include_nn_kernels.h#
-
namespace onnx_light
Alias that makes onnx-light headers compatible with code that references
ONNX_LIGHT_NAMESPACE(the macro used in the standard onnx package).Set to
ONNX_LIGHT_NAMESPACEso both names resolve to the same namespace.Symbol-visibility attribute for the public onnx-light C++ API.
Maps the upstream compatibility macro to onnx-light’s explicit proto ABI annotation. This keeps declarations from vendored ONNX headers visible when
lib_onnx_protouses hidden visibility by default.Namespace alias so that ONNX C++ code (and consumers such as onnxruntime) that refers to the literal
onnxnamespace — rather than theONNX_NAMESPACEmacro — resolves to the onnx-light namespace. The standard onnx package lives innamespace onnx; onnx-light usesonnx_light(via ONNX_LIGHT_NAMESPACE), so this alias keeps onnx-light a true drop-in. It is only introduced when the onnx-light namespace differs fromonnx.-
namespace onnx_kernels
-
namespace kernel
Functions
-
core::shapes::PeakMemoryEstimate ComputePeakMemoryAttention(core::symbolic::Device device, const std::vector<core::symbolic::SymShape> &input_shapes)#
Estimates the peak scratch memory (in bytes) required to evaluate an
Attentionnode through a shape-only convenience overload. It takes the :cpp:enum:Devicethe operator runs on followed by the shapes of the node’s inputs.Bounds all supported dtypes and executors: one FLOAT32 score row per possible concurrent batch/head task, half-precision promotions and intermediate results, and temporary caches. Declared final outputs are excluded. This overload assumes all four outputs are returned and supports rank-4 Q/K/V; packed inputs require the node-aware overload. Symbolic dimensions remain in the byte expression. Missing shapes yield an unresolved bound.
- Parameters:
device – Device on which the operator executes (currently does not affect the estimate).
input_shapes – Shapes of the node’s inputs, in order;
input_shapes[0]isQ, followed byK,Vand optional inputs.
- Throws:
std::invalid_argument – if a contributing dimension is negative or the scratch allocation exceeds
int64_t.- Returns:
A conservative worst-case bound without an inferred average.
-
core::shapes::PeakMemoryEstimate ComputePeakMemoryAttention(core::symbolic::Device device, const NodeProto &node, const std::vector<core::symbolic::SymShape> &input_shapes)#
Bounds portable Attention workspace for rank-3 or rank-4 inputs. The packed rank-3 layout uses the node’s positive
q_num_headsandkv_num_headsattributes; without them the worst-case bound is unresolved. Score scratch is bounded by4 * batch * q_num_heads * (kv_seq + past_seq)bytes, with no scratch for empty batches or queries. Also includes half-precision promotions, intermediate FLOAT32 results, packed-layout reordering and temporary caches. Declared final outputs are excluded; an omitted qk output is neither allocated nor estimated. Symbolic dimensions remain in the byte expression. Missing estimation information produces an unresolved worst-case bound without an average. Negative dimensions, invalid head counts and arithmetic overflow raisestd::invalid_argument.- Parameters:
device – Device on which the operator executes.
node – Attention node, including head attributes and optional cache input names.
input_shapes – Input shapes in node input order, including empty optional slots.
- Returns:
A conservative worst-case bound without an inferred average.
-
core::shapes::PeakMemoryEstimate ComputePeakMemoryLinearAttention(core::symbolic::Device device, const std::vector<core::symbolic::SymShape> &input_shapes)#
Estimates peak scratch memory for a
LinearAttentionnode.Includes half-precision promotions and intermediate results, plus one reusable FLOAT32 auxiliary vector for delta update rules. Without node attributes this overload conservatively bounds head geometry using packed hidden dimensions. A zero or symbolic query width cannot bound missing query heads and produces an unresolved bound. Returned final outputs are excluded. Other symbolic dimensions are preserved; missing shapes produce an unresolved bound.
- Parameters:
device – Device on which the operator executes.
input_shapes – Shapes of query, key, value, and optional inputs.
- Throws:
std::invalid_argument – if a contributing dimension is negative or the scratch allocation exceeds
int64_t.- Returns:
A conservative worst-case bound without an inferred average.
-
core::shapes::PeakMemoryEstimate ComputePeakMemoryLinearAttention(core::symbolic::Device device, const NodeProto &node, const std::vector<core::symbolic::SymShape> &input_shapes)#
Estimates portable LinearAttention workspace using head attributes and declared outputs.
-
core::shapes::PeakMemoryEstimate ComputePeakMemoryRMSNormalization(core::symbolic::Device device, const NodeProto &node, const std::vector<core::symbolic::SymShape> &inputs)#
Bounds the portable RMSNormalization kernel’s additional workspace, excluding declared outputs.
-
Tensor DecodePagedCachePayload(const RuntimeValue &value, int64_t length, const StructTypeCatalogue &catalogue = {}, RawBufferAllocator *allocator = nullptr)#
Decodes the valid prefix of one dense or affine paged-cache payload to FLOAT.
- Parameters:
value – Payload stored in a page’s key or value field.
length – Number of valid leading rows to decode.
catalogue – Structured-type catalogue used to validate encoded values.
allocator – Optional destination allocator.
- Returns:
Owned FLOAT tensor with shape
[batch,heads,length,width].
-
class Attention : public onnx_light::onnx_kernels::tuning::ParallelTunableKernel#
- #include <include_nn_kernels.h>
Reference implementation of
ai.onnx::Attention(v23 / v24).Computes scaled dot-product attention. The baseline computation is
Y = Softmax((Q @ K^T) * scale + attn_bias, axis=-1) @ Vwhere
attn_biasis derived from the optionalattn_maskinput (and/or theis_causalattribute) as described below.Both rank-4 layouts
(batch, num_heads, seq, head_size)and rank-3 “fused” layouts(batch, seq, num_heads * head_size)are accepted. When rank-3 inputs are used theq_num_headsandkv_num_headsattributes must be set andYis returned with the same rank-3 layout as the inputs.Supported features (mirroring the upstream operator):
scaleattribute — when unset the implementation uses1 / sqrt(head_size).is_causalattribute — applies an upper-triangular-infmask aligned to the upper-left corner of the(q_seq_len, total_kv_seq_len)score matrix (accounting for any cached KV).softcapattribute — when> 0, the pre-softmax scores are scaled bysoftcap * tanh(s / softcap).qk_matmul_output_modeattribute (0/1/2/3) — selects which stage of the QK pipeline is exposed in the auxiliaryqk_matmuloutput (0: raw(Q @ K^T) * scale; 1: with bias; 2: after softcap; 3: after softmax).Grouped Query Attention (
q_num_headsmultiple ofkv_num_heads).Optional
attn_maskinput: FLOAT (rank 2-4, broadcasted to(batch, q_num_heads, q_seq_len, total_kv_seq_len)and added as a bias) or BOOL (rank 2-4,truemeans “attend”;falsebecomes-inf). When the mask’s last dimension is shorter thantotal_kv_seq_lenit is padded with-inf/false.Optional
past_key/past_valuerank-4 FLOAT inputs that are concatenated along the sequence axis withK/Vto form thepresent_key/present_valueoutputs.Optional
nonpad_kv_seqlenINT64 input (v24): a 1-D tensor of lengthbatch_sizegiving the number of non-padding key/value positions per batch. Positionsj >= nonpad_kv_seqlen[b]are masked out with-inf.
Not modeled: the
softmax_precisionattribute.Public Functions
-
explicit Attention(const KernelContext &ctx)#
-
void Run(RuntimeContext &rt) override#
-
Tensor operator()(const Tensor &Q, const Tensor &K, const Tensor &V, RuntimeContext *rt = nullptr) const#
Default-attribute overload.
scale = 1 / sqrt(head_size), no mask, no causal, no softcap, no past KV.
-
Tensor operator()(const Tensor &Q, const Tensor &K, const Tensor &V, float scale, RuntimeContext *rt = nullptr) const#
Explicit
scaleoverload, no mask.
-
Tensor operator()(const Tensor &Q, const Tensor &K, const Tensor &V, float scale, const Tensor &attn_mask, RuntimeContext *rt = nullptr) const#
Explicit
scaleplus an optional FLOAT attention bias whose shape must broadcast to(batch, q_num_heads, q_seq_len, kv_seq_len). A default-constructedTensoromits the mask.
-
void operator()(const Tensor &Q, const Tensor &K, const Tensor &V, float scale, const Tensor *attn_mask, Tensor &output) const#
In-place overload writing into a caller-allocated
outputtensor.outputmust already be FLOAT and shape(batch, q_num_heads, q_seq_len, v_head_size).
-
Result operator()(const Tensor &Q, const Tensor &K, const Tensor &V, const Attributes &attrs, const Tensor *attn_mask = nullptr, const Tensor *past_key = nullptr, const Tensor *past_value = nullptr, const Tensor *nonpad_kv_seqlen = nullptr, RuntimeContext *rt = nullptr) const#
Comprehensive overload covering every supported feature.
attn_mask,past_key,past_valueandnonpad_kv_seqlenmay benullptrto mean “absent”.nonpad_kv_seqlenis a 1-D INT64 tensor of lengthbatch_sizemasking out trailing (padding) key/value positions.
Public Static Functions
-
static void RegisterTuningSchemas()#
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:Attention"#
-
struct Attributes#
- #include <include_nn_kernels.h>
Bundles every optional scalar/string attribute of the upstream
ai.onnx::Attentionoperator.has_scalecontrols whetherscaleoverrides the default1 / sqrt(head_size). When the inputs are rank-3 (fused layout),q_num_headsandkv_num_headsmust both be positive; otherwise both default to0(auto-detected from the rank-4 input shapes).Public Members
-
bool has_scale = false#
When true,
scaleoverrides the default.
-
float scale = 0.0f#
Multiplier applied to the
Q @ K^Tdot product before the optional bias and softmax. Whenhas_scaleis false the kernel uses1 / sqrt(head_size)instead.
-
bool is_causal = false#
When true, applies a causal upper-triangular
-infmask.
-
float softcap = 0.0f#
When
> 0, appliessoftcap * tanh(s / softcap).
-
int qk_matmul_output_mode = 0#
0: raw; 1: + bias; 2: after softcap; 3: after softmax.
-
int64_t q_num_heads = 0#
Required when inputs are rank-3.
-
int64_t kv_num_heads = 0#
Required when inputs are rank-3.
-
int64_t left_window_size = -1#
-1 is unbounded; otherwise includes this many left keys.
-
int64_t right_window_size = -1#
-1 is unbounded; otherwise includes this many right keys.
-
bool has_scale = false#
-
struct Result#
- #include <include_nn_kernels.h>
Bundles every output produced by the kernel.
Yis always populated;present_key/present_valuemirror the upstream optional outputs and equalK/V(or their concatenation with the past tensors when those were supplied).qk_matmul_outputreflects the chosenqk_matmul_output_modeand is always rank-4 FLOAT(batch, q_num_heads, q_seq_len, total_kv_seq_len).
-
class AveragePool : public KernelBase#
- #include <include_nn_kernels.h>
N-D average pooling on a FLOAT tensor laid out as
(N, C, D1, ..., Dk).kernel_shapemust havekentries;strides,padsanddilations(lengthsk,2 * kandkrespectively) default to all-ones / all-zeros / all-ones when omitted.auto_paddefaults toNOTSET(use explicitpads); when set toSAME_UPPER,SAME_LOWERorVALIDthepadsargument must be empty and the begin/end padding is computed from the input shape.Public Functions
-
void Run(RuntimeContext &rt) override#
-
Tensor operator()(const Tensor &x, const Shape &kernel_shape, const Shape &strides = {}, const Shape &pads = {}, bool ceil_mode = false, bool count_include_pad = false, const Shape &dilations = {}, AutoPad auto_pad = AutoPad::kNotSet, RuntimeContext *rt = nullptr) const#
All attributes explicit.
stridesmay be empty (treated as all 1),padsmay be empty (treated as all 0) anddilationsmay be empty (treated as all 1).
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape generally differs from the input shape, so the output buffer cannot in general alias the input buffer.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:AveragePool"#
-
void Run(RuntimeContext &rt) override#
-
class BatchNormalization : public onnx_light::onnx_kernels::tuning::ParallelTunableKernel#
- #include <include_nn_kernels.h>
Inference-mode BatchNormalization on a FLOAT input laid out as
(N, C, D1, ..., Dk)(any rank >= 2; rank 1 is also accepted withCtreated as 1). All four extra inputs (scale,B,input_mean,input_var) must be 1-D FLOAT tensors of lengthC. The kernel implements the inference formulaY = (X - input_mean) / sqrt(input_var + epsilon) * scale + Busing NumPy-style broadcasting along the channel axis. Training mode (training_mode = 1, opset 14+) is also supported viaTrainingForward: it normalizesXwith the per-channel batch statistics and returns the updated running mean / variance.Public Functions
-
void Run(RuntimeContext &rt) override#
-
explicit BatchNormalization(const KernelContext &ctx)#
-
Tensor operator()(const Tensor &x, const Tensor &scale, const Tensor &bias, const Tensor &input_mean, const Tensor &input_var, float epsilon = 1e-5f, RuntimeContext *rt = nullptr) const#
Returns the inference-mode primary output
Y.epsilondefaults to 1e-5f, the upstream default.
-
void operator()(const Tensor &x, const Tensor &scale, const Tensor &bias, const Tensor &input_mean, const Tensor &input_var, Tensor &output, float epsilon = 1e-5f, RuntimeContext *rt = nullptr) const#
-
std::tuple<Tensor, Tensor, Tensor> TrainingForward(const Tensor &x, const Tensor &scale, const Tensor &bias, const Tensor &input_mean, const Tensor &input_var, float epsilon = 1e-5f, float momentum = 0.9f, RuntimeContext *rt = nullptr) const#
Returns the training-mode outputs
(Y, running_mean, running_var)fortraining_mode = 1(opset 14+). The per-channel batchmeanand (population)varare computed over every axis except the channel axis,Yis normalized with those batch statistics, and the running estimates are updated asrunning = input * momentum + saved * (1 - momentum).momentumdefaults to 0.9f andepsilonto 1e-5f, the upstream defaults.
Public Static Functions
-
static void RegisterTuningSchemas()#
-
static inline constexpr bool CanRunInPlace() noexcept#
Output
Yhas the same shape asXso the output buffer may alias the inputXbuffer.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:BatchNormalization"#
-
void Run(RuntimeContext &rt) override#
-
class CausalConvWithState : public KernelBase#
- #include <include_nn_kernels.h>
Reference implementation of
ai.onnx::CausalConvWithState(v27 and v29).Stateful causal 1D depthwise convolution used by Gated DeltaNet (Qwen3.5) and Mamba (Jamba, FalconMamba). Replaces the
Concat + Conv + Slicepattern with a single fused operation that also supports an optional fused SiLU/Swish activation.Tensors are rank-3:
input:(batch_size, channels, length)weight:(channels, 1, k)(depthwise:group = channels)bias(optional):(channels)past_state(optional):(batch_size, channels, (k - 1) * dilation); when absent the carry is implicitly zero-padding.output: same shape asinputpresent_state:(batch_size, channels, (k - 1) * dilation)containing the last(k - 1) * dilationconsecutive raw values of the padded sequence ([past_state, input]) along the causal axis.
Public Functions
-
void Run(RuntimeContext &rt) override#
-
std::pair<Tensor, Tensor> operator()(const Tensor &input, const Tensor &weight, const Tensor &bias, const Tensor &past_state, const Attributes &attrs, RuntimeContext *rt = nullptr) const#
Returning overload.
biasandpast_statemay be default-constructed (empty-shape)Tensorvalues to indicate the optional inputs are missing.
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:CausalConvWithState"#
-
struct Attributes#
- #include <include_nn_kernels.h>
Attributes carried by the
CausalConvWithStateoperator.
-
class Col2Im : public KernelBase#
- #include <include_nn_kernels.h>
Reference N-D
Col2Imkernel restricted to FLOAT tensors. Implements the upstreamai.onnx::Col2Imoperator (since opset 18), rearranging column blocks back into a multi-dimensional batched image.Inputs:
input— FLOAT rank-3 tensor of shape(N, C * product(block_shape), L)whereLis the number of blocks enumerated in lexicographic order.image_shape— INT64 1-D tensor of lengthn_spatialgiving the spatial dimensions(d_1, ..., d_n)of the output image.block_shape— INT64 1-D tensor of lengthn_spatialgiving the (un-dilated) block shape.
Attributes mirror the ONNX schema:
dilations(optional, defaults to all ones).pads(optional, defaults to all zeros, length2 * n_spatialin[d1_begin, ..., dn_begin, d1_end, ..., dn_end]order).strides(optional, defaults to all ones).
Output: FLOAT rank-
2 + n_spatialtensor of shape(N, C, image_shape[0], ..., image_shape[n_spatial - 1]). Overlapping block contributions are summed (matching PyTorch’sfold).Public Functions
-
void Run(RuntimeContext &rt) override#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape differs from input shape, so storage cannot be shared.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:Col2Im"#
-
struct Attributes#
- #include <include_nn_kernels.h>
Attributes carried by the ONNX
Col2Imoperator.
-
class Conv : public onnx_light::onnx_kernels::tuning::ParallelTunableKernel#
- #include <include_nn_kernels.h>
Reference N-D
Convkernel restricted to FLOAT tensors.Implements the standard convolution defined by the upstream
ai.onnx::Convoperator. Inputs are laid out asX.shape = (N, C, D1, ..., Dk),W.shape = (M, C/group, k1, ..., kk); output shape is(N, M, oD1, ..., oDk). Supports thekernel_shape,strides,pads,dilations,groupandauto_padattributes (NOTSET,SAME_UPPER,SAME_LOWER,VALID).Public Functions
-
explicit Conv(const KernelContext &ctx)#
-
void Run(RuntimeContext &rt) override#
Public Static Functions
-
static void RegisterTuningSchemas()#
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape generally differs from the input, so storage cannot be shared.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:Conv"#
-
struct Attributes#
- #include <include_nn_kernels.h>
Attributes carried by the ONNX
Convoperator.
-
explicit Conv(const KernelContext &ctx)#
-
class ConvInteger : public onnx_light::onnx_kernels::tuning::ParallelTunableKernel#
- #include <include_nn_kernels.h>
Reference N-D
ConvIntegerkernel.Inputs
xandware 8-bit integer tensors (int8oruint8) and the outputyisint32. The optionalx_zero_pointmust be a scalar with the same dtype asx; the optionalw_zero_pointmay be a scalar or a 1-D length-Mtensor (per-output-channel) with the same dtype asw. Empty-shapeTensorindicates absence.Public Functions
-
explicit ConvInteger(const KernelContext &ctx)#
-
void Run(RuntimeContext &rt) override#
Public Static Functions
-
static void RegisterTuningSchemas()#
-
static inline constexpr bool CanRunInPlace() noexcept#
Output dtype differs from input dtype, so storage cannot be shared.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:ConvInteger"#
-
struct Attributes#
- #include <include_nn_kernels.h>
Attributes carried by the ONNX
ConvIntegeroperator.
-
explicit ConvInteger(const KernelContext &ctx)#
-
class ConvTranspose : public onnx_light::onnx_kernels::tuning::ParallelTunableKernel#
- #include <include_nn_kernels.h>
Reference N-D
ConvTransposekernel restricted to FLOAT tensors.Implements the upstream
ai.onnx::ConvTranspose. Input layout isX.shape = (N, C, D1, ..., Dk)andW.shape = (C, M/group, k1, ..., kk). Whenoutput_shapeis provided the per-axis padding is derived per the upstream spec; otherwise the output spatial dim isstride[i] * (iD[i] - 1) + output_padding[i] + ((k[i]-1)*dil[i]+1) - pads[start] - pads[end].Public Functions
-
explicit ConvTranspose(const KernelContext &ctx)#
-
void Run(RuntimeContext &rt) override#
Public Static Functions
-
static void RegisterTuningSchemas()#
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape generally differs from the input, so storage cannot be shared.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:ConvTranspose"#
-
struct Attributes#
- #include <include_nn_kernels.h>
Attributes carried by the ONNX
ConvTransposeoperator.
-
explicit ConvTranspose(const KernelContext &ctx)#
-
class DeformConv : public KernelBase#
- #include <include_nn_kernels.h>
Reference 2-D
DeformConvkernel restricted to FLOAT tensors.Implements the deformable convolution defined in https://arxiv.org/abs/1703.06211 and https://arxiv.org/abs/1811.11168, matching the upstream
ai.onnx::DeformConvoperator (since opset 19; the opset 22 update only widensTto also acceptbfloat16— not modeled here). Only the rank-4 (2-D image) caseX.shape = (N, C, H, W)is supported.Attributes mirror the ONNX schema:
kernel_shape(optional): inferred fromW.shape[2:]when omitted.strides/dilations(optional, default all ones).pads(optional, default all zeros, length2 * spatial_rankin[h_begin, w_begin, h_end, w_end]order).group(default 1) — channels grouped alongC/oC.offset_group(default 1) — number of offset groups;Cmust be divisible byoffset_group.
Inputs:
x— FLOAT rank-4(N, C, H, W).w— FLOAT rank-4(oC, C/group, kH, kW).offset— FLOAT rank-4(N, offset_group * kH * kW * 2, oH, oW); the inner2channels are stored(y, x).b— Optional 1-D FLOAT bias of lengthoC; an empty-shapeTensorindicates absence (treated as zeros).mask— Optional FLOAT rank-4 mask(N, offset_group * kH * kW, oH, oW); an empty-shapeTensorindicates absence (treated as ones).
Public Functions
-
void Run(RuntimeContext &rt) override#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape differs from any input, so storage cannot be shared.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:DeformConv"#
-
struct Attributes#
- #include <include_nn_kernels.h>
Attributes carried by the ONNX
DeformConvoperator. Defaults match the upstream schema (since opset 19).
-
class Dropout : public KernelBase#
- #include <include_nn_kernels.h>
Reference implementation of
Dropout(opset 12+ behavior).Dropouttakes an input tensordataand optional scalarratio/training_modecontrols. In inference mode (training_mode=false),outputis a copy ofdataandmask(when requested) is all ones. In training mode, each element is kept with probability1-ratioand scaled by1/(1-ratio).This backend test kernel currently supports FLOAT and DOUBLE tensors for
data.ratiomust be in[0, 1).Public Functions
-
void Run(RuntimeContext &rt) override#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
-
void Run(RuntimeContext &rt) override#
-
class Flatten : public KernelBase#
- #include <include_nn_kernels.h>
Flattens an input tensor of any element type into a 2-D matrix. Given an input of shape
(d_0, d_1, ..., d_n)and integer attributeaxis, the output has shape(d_0 * d_1 * ... * d_(axis-1), d_axis * ... * d_n).axisdefaults to 1 and may be negative (counted from the back). Whenaxis == 0the outer dimension is 1 and the inner dimension is the product of every input dimension. Whenaxis == rankthe outer dimension is the product of every input dimension and the inner dimension is 1.The output reuses the input data buffer byte-for-byte (Flatten is a pure view operation), so every element type supported by :cpp:func:
PackedByteSizeis accepted. The output dtype always matches the input dtype.Public Functions
-
void Run(RuntimeContext &rt) override#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output element count equals the input element count, so storage can be shared in-place.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:Flatten"#
-
void Run(RuntimeContext &rt) override#
-
class GlobalAveragePool : public onnx_light::onnx_kernels::tuning::ParallelTunableKernel#
- #include <include_nn_kernels.h>
Global average pooling on a FLOAT tensor laid out as
(N, C, D1, ..., Dk). The output shape is(N, C, 1, 1, ..., 1)— each spatial dimension is reduced to 1 by computing the mean over all elements in that dimension.Public Functions
-
void Run(RuntimeContext &rt) override#
-
explicit GlobalAveragePool(const KernelContext &ctx)#
Public Static Functions
-
static void RegisterTuningSchemas()#
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape differs from the input shape, so storage cannot be shared.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:GlobalAveragePool"#
-
void Run(RuntimeContext &rt) override#
-
class GlobalLpPool : public onnx_light::onnx_kernels::tuning::ParallelTunableKernel#
- #include <include_nn_kernels.h>
Global Lp pooling on a FLOAT, DOUBLE, FLOAT16, or BFLOAT16 tensor laid out as
(N, C, D1, ..., Dk). The output shape is(N, C, 1, 1, ..., 1)— each spatial dimension is reduced to 1 by computing the Lp norm over all elements in that dimension. The default value ofpis 2 (L2 norm). Whenp == 1this is L1 pooling;p == 2(default) gives L2 pooling (without averaging).Public Functions
-
void Run(RuntimeContext &rt) override#
-
explicit GlobalLpPool(const KernelContext &ctx)#
-
Tensor operator()(const Tensor &x, double p = 2, RuntimeContext *rt = nullptr) const#
Returns an output tensor of shape
(N, C, 1, 1, ..., 1)with the input dtype.pis a finite positive exponent (default 2); opset 1 allows fractional values. Computes in the log domain to avoid intermediate overflow and underflow. Empty spatial dimensions produce zeros.
Public Static Functions
-
static void RegisterTuningSchemas()#
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape differs from the input shape, so storage cannot be shared.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:GlobalLpPool"#
-
void Run(RuntimeContext &rt) override#
-
class GlobalMaxPool : public onnx_light::onnx_kernels::tuning::ParallelTunableKernel#
- #include <include_nn_kernels.h>
Global max pooling on a FLOAT tensor laid out as
(N, C, D1, ..., Dk). The output shape is(N, C, 1, 1, ..., 1)— each spatial dimension is reduced to 1 by computing the maximum over all elements in that dimension.Public Functions
-
void Run(RuntimeContext &rt) override#
-
explicit GlobalMaxPool(const KernelContext &ctx)#
Public Static Functions
-
static void RegisterTuningSchemas()#
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape differs from the input shape, so storage cannot be shared.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:GlobalMaxPool"#
-
void Run(RuntimeContext &rt) override#
-
class GroupNormalization : public onnx_light::onnx_kernels::tuning::ParallelTunableKernel#
- #include <include_nn_kernels.h>
Reference implementation of
GroupNormalization(opset 18, 21).Groups the
Cchannel dimension of a FLOAT inputXof shape(N, C, D1, ..., Dk)(rank >= 2) intonum_groupsequal-sized groups, normalizes each(n, group)block over its channels and spatial dims, then applies a per-channel affinescale * x + bias:Y = scale * (X - mean) / sqrt(var + epsilon) + biasThe kernel implements the opset-21 contract where
scaleandbiasare 1-D FLOAT tensors of lengthC.num_groupsmust divideC.Public Functions
-
void Run(RuntimeContext &rt) override#
-
explicit GroupNormalization(const KernelContext &ctx)#
Public Static Functions
-
static void RegisterTuningSchemas()#
-
static inline constexpr bool CanRunInPlace() noexcept#
Output
Yhas the same shape asXso the output buffer may alias the inputXbuffer.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:GroupNormalization"#
-
void Run(RuntimeContext &rt) override#
-
class GRU : public KernelBase#
- #include <include_nn_kernels.h>
One-layer GRU on FLOAT tensors using the default
Sigmoid/Tanhactivations. Implements the upstream ONNXGRUformulaz_t = sigmoid(X_t @ Wz^T + H_{t-1} @ Rz^T + Wbz + Rbz)r_t = sigmoid(X_t @ Wr^T + H_{t-1} @ Rr^T + Wbr + Rbr)h_t = tanh (X_t @ Wh^T + (r_t (.) H_{t-1}) @ Rh^T + Wbh + Rbh)(linear_before_reset == 0, the default)h_t = tanh (X_t @ Wh^T + r_t (.) (H_{t-1} @ Rh^T + Rbh) + Wbh)(linear_before_reset != 0)H_t = (1 - z_t) (.) h_t + z_t (.) H_{t-1}for both
layout=0(X.shape = [seq_length, batch_size, input_size]; optionalinitial_h.shape = [num_directions, batch_size, hidden_size]) andlayout=1(X.shape = [batch_size, seq_length, input_size]; optionalinitial_h.shape = [batch_size, num_directions, hidden_size]).W.shape = [num_directions, 3 * hidden_size, input_size];R.shape = [num_directions, 3 * hidden_size, hidden_size]; optionalB.shape = [num_directions, 6 * hidden_size]([Wb, Rb]each with 3 gate blocks in the ONNX gate orderz, r, h);initial_hdefaults to zeros.sequence_lensis not supported (every batch must share the same sequence length);activationsandclipare not supported.directionmay be"forward","reverse"or"bidirectional"(num_directionsis2for the last,1otherwise).The two outputs are produced together: for
layout=0,Yhas shape[seq_length, num_directions, batch_size, hidden_size]and is the concatenation of every per-time-step hidden state;Y_hhas shape[num_directions, batch_size, hidden_size]and equals the last time step ofY. Forlayout=1the corresponding shapes are[batch_size, seq_length, num_directions, hidden_size]and[batch_size, num_directions, hidden_size].Public Functions
-
void Run(RuntimeContext &rt) override#
-
std::pair<Tensor, Tensor> operator()(const Tensor &x, const Tensor &w, const Tensor &r, const Tensor &b = Tensor{}, const Tensor &initial_h = Tensor{}, int64_t linear_before_reset = 0, int64_t layout = 0, const std::string &direction = "forward", RuntimeContext *rt = nullptr) const#
Returns the pair
(Y, Y_h).bmay be a default-constructed (empty-shape)Tensorto indicate the optionalBinput is missing; same convention forinitial_h.linear_before_resetmatches the ONNX attribute of the same name (default0).layoutmatches the ONNX attribute of the same name (default0).directionmay be"forward","reverse"or"bidirectional".
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape generally differs from the input shape, so storage cannot in general be shared.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:GRU"#
-
void Run(RuntimeContext &rt) override#
-
class InstanceNormalization : public onnx_light::onnx_kernels::tuning::ParallelTunableKernel#
- #include <include_nn_kernels.h>
Reference implementation of
InstanceNormalization(opset 1, 6, 22).Normalizes a FLOAT, FLOAT16 or BFLOAT16 input
Xof shape(N, C, D1, ..., Dk)(rank >= 2) per-instance, per-channel:Y = scale * (X - mean) / sqrt(var + epsilon) + Bwhere
meanandvarare computed over the spatial dimensionsD1, ..., Dkfor every(n, c)pair.scaleandBare 1-D tensors of lengthCwith the same element type asX. Half-precision inputs are decoded to float32 before computing the statistics and affine transform.Public Functions
-
void Run(RuntimeContext &rt) override#
-
explicit InstanceNormalization(const KernelContext &ctx)#
Public Static Functions
-
static void RegisterTuningSchemas()#
-
static inline constexpr bool CanRunInPlace() noexcept#
Output
Yhas the same shape asXso the output buffer may alias the inputXbuffer.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:InstanceNormalization"#
-
void Run(RuntimeContext &rt) override#
-
class LayerNormalization : public onnx_light::onnx_kernels::tuning::ParallelTunableKernel#
- #include <include_nn_kernels.h>
Reference implementation of
LayerNormalization(opset 17).Normalizes a FLOAT, FLOAT16 or BFLOAT16 input
Xof arbitrary rankralong the lastr - axisdimensions, then applies a per-element affine transform usingScaleand the optionalB(both broadcastable to the normalized shapeX.shape[axis:]):Mean = ReduceMean(X, axes=[axis,...,r-1])Var = ReduceMean((X - Mean)^2, axes=[axis,...,r-1])InvStdDev = 1 / sqrt(Var + epsilon)Y = (X - Mean) * InvStdDev * Scale + BIn addition to the normalized output
Y, the kernel also returns the per-rowMeanandInvStdDevtensors. Their shape mirrorsXwith the trailingr - axisdimensions collapsed to 1. Both statistics use FLOAT stash precision. Half inputs are promoted before normalization, then rounded back to the input dtype before the affine stage.Public Functions
-
void Run(RuntimeContext &rt) override#
-
explicit LayerNormalization(const KernelContext &ctx)#
-
std::tuple<Tensor, Tensor, Tensor> operator()(const Tensor &x, const Tensor &scale, const Tensor &b, int64_t axis = -1, float epsilon = 1e-5f, RuntimeContext *rt = nullptr) const#
Returns the tuple
(Y, Mean, InvStdDev).axisdefaults to-1andepsilonto1e-5fto match the upstream defaults.bmay be a default-constructedTensor{}to indicate that the bias is absent.
-
void operator()(const Tensor &x, const Tensor &scale, const Tensor &b, Tensor &y, Tensor &mean, Tensor &inv_std_dev, int64_t axis = -1, float epsilon = 1e-5f) const#
In-place overload.
ymust have the same shape and dtype asx.meanandinv_std_devmust havex’s outer shape (i.e.x.shape[:axis]) padded with 1s up tox’s rank.
Public Static Functions
-
static void RegisterTuningSchemas()#
-
static inline constexpr bool CanRunInPlace() noexcept#
Output
Yhas the same shape asXso the output buffer may alias the inputXbuffer.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:LayerNormalization"#
-
void Run(RuntimeContext &rt) override#
-
class LinearAttention : public onnx_light::onnx_kernels::tuning::ParallelTunableKernel#
- #include <include_nn_kernels.h>
Reference
LinearAttentionkernel for FLOAT, FLOAT16 and BFLOAT16 tensors.Implements the unified linear attention recurrence defined by the upstream
ai.onnx::LinearAttentionoperator (since opset 27). Supports fourupdate_rulevariants:"linear","gated","delta", and"gated_delta". Inputs use 3D packed format(B, T, H*D); the recurrent state is 4D(B, H_kv, d_k, d_v). Group-query attention (GQA) is supported whenq_num_headsis a positive multiple ofkv_num_heads. Half-precision (FLOAT16/BFLOAT16) activations are promoted to FLOAT32 for the recurrence and the outputs are demoted back.Public Functions
-
explicit LinearAttention(const KernelContext &ctx)#
-
void Run(RuntimeContext &rt) override#
Public Static Functions
-
static void RegisterTuningSchemas()#
-
static inline constexpr bool CanRunInPlace() noexcept#
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:LinearAttention"#
-
struct Attributes#
- #include <include_nn_kernels.h>
Attributes carried by the ONNX
LinearAttentionoperator.Public Members
-
bool has_scale = false#
When true,
scaleoverrides the default.
-
float scale = 0.0f#
Output scaling factor; 0 means 1/sqrt(d_k).
-
int64_t q_num_heads = 0#
Number of query heads (required).
-
int64_t kv_num_heads = 0#
Number of key/value heads (required).
-
int64_t chunk_size = 64#
Chunk size hint (not used in reference impl).
-
bool has_scale = false#
-
struct Result#
- #include <include_nn_kernels.h>
Bundles every output produced by the kernel.
-
explicit LinearAttention(const KernelContext &ctx)#
-
class LpNormalization : public onnx_light::onnx_kernels::tuning::ParallelTunableKernel#
- #include <include_nn_kernels.h>
Reference implementation of
LpNormalization.Computes
output = input / Lp_norm(input, axis)element-wise along the givenaxis(negative values count from the end). When the Lp norm along a slice is zero, the corresponding output slice is set to zero to avoid division by zero.The kernel accepts FLOAT inputs of any rank
>= 1.axisdefaults to-1(the last axis).pmust be either1(L1 norm) or2(L2 norm) and defaults to2. The output shape matches the input shape.Public Functions
-
void Run(RuntimeContext &rt) override#
-
explicit LpNormalization(const KernelContext &ctx)#
Public Static Functions
-
static void RegisterTuningSchemas()#
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape matches input shape, so storage may alias the input buffer.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:LpNormalization"#
-
void Run(RuntimeContext &rt) override#
-
class LpPool : public KernelBase#
- #include <include_nn_kernels.h>
N-D Lp pooling on a FLOAT tensor laid out as
(N, C, D1, ..., Dk). Implements the ONNXLpPooloperator: for every output position, the kernel computes(sum |x_i|^p)^(1/p)over the input values inside the pooling window. Positions outside[0, in_dim)(i.e. in the padded region) contribute0to the sum (matching the upstream ONNX reference, where the input is zero-padded before pooling).kernel_shapemust havekentries;strides,padsanddilations(lengthsk,2 * kandkrespectively) default to all-ones / all-zeros / all-ones when omitted.auto_paddefaults toNOTSET(use explicitpads); when set toSAME_UPPER,SAME_LOWERorVALIDthepadsargument must be empty and the begin/end padding is computed from the input shape.pdefaults to2(L2 norm).Public Functions
-
void Run(RuntimeContext &rt) override#
-
Tensor operator()(const Tensor &x, const Shape &kernel_shape, const Shape &strides = {}, const Shape &pads = {}, int64_t p = 2, bool ceil_mode = false, const Shape &dilations = {}, AutoPad auto_pad = AutoPad::kNotSet, RuntimeContext *rt = nullptr) const#
All attributes explicit.
stridesmay be empty (treated as all 1),padsmay be empty (treated as all 0) anddilationsmay be empty (treated as all 1).
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape generally differs from the input shape, so the output buffer cannot in general alias the input buffer.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:LpPool"#
-
void Run(RuntimeContext &rt) override#
-
class LRN : public KernelBase#
- #include <include_nn_kernels.h>
Reference implementation of
LRN(Local Response Normalization).Implements
Y[n, c, d1, ..., dk] = X[n, c, d1, ..., dk] /(bias + alpha / size * square_sum[n, c, d1, ..., dk]) ** betawhere
square_sum[n, c, d1, ..., dk]is the sum of squares over the channel windowi in [max(0, c - floor((size-1)/2)), min(C-1, c + ceil((size-1)/2))].The kernel accepts FLOAT, FLOAT16 or BFLOAT16 inputs of rank
>= 2laid out as(N, C, D1, ..., Dk).sizemust be a strictly positive integer.alphadefaults to0.0001,betato0.75andbiasto1.0(the ONNX defaults). The output shape and dtype match the input. Half-precision inputs are decoded to float32 before computing the sum of squares.Public Functions
-
void Run(RuntimeContext &rt) override#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape matches input shape, so storage may alias the input buffer.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:LRN"#
-
void Run(RuntimeContext &rt) override#
-
class LSTM : public KernelBase#
- #include <include_nn_kernels.h>
One-layer LSTM on FLOAT tensors using the default
Sigmoid/Tanh/Tanhactivations. Implements the upstream ONNXLSTMformulait = sigmoid(Xt @ Wi^T + Ht-1 @ Ri^T + Pi (.) Ct-1 + Wbi + Rbi)ft = sigmoid(Xt @ Wf^T + Ht-1 @ Rf^T + Pf (.) Ct-1 + Wbf + Rbf)ct = tanh (Xt @ Wc^T + Ht-1 @ Rc^T + Wbc + Rbc)Ct = ft (.) Ct-1 + it (.) ctot = sigmoid(Xt @ Wo^T + Ht-1 @ Ro^T + Po (.) Ct + Wbo + Rbo)Ht = ot (.) tanh(Ct)for
W.shape = [num_directions, 4 * hidden_size, input_size];R.shape = [num_directions, 4 * hidden_size, hidden_size]; optionalB.shape = [num_directions, 8 * hidden_size]([Wb, Rb]each with 4 gate blocks in the ONNX gate orderi, o, f, c); optionalP.shape = [num_directions, 3 * hidden_size](peephole weights in gate orderi, o, f).sequence_lensis not supported (every batch must share the same sequence length);activations,clipandinput_forgetare not supported.directionmay be"forward","reverse"or"bidirectional"(num_directionsis2for the last,1otherwise).Both
layoutvalues defined by ONNX are supported:layout == 0(default):X.shape = [seq_length, batch_size, input_size]; optionalinitial_h.shape = initial_c.shape = [num_directions, batch_size, hidden_size];Y.shape = [seq_length, num_directions, batch_size, hidden_size];Y_h.shape = Y_c.shape = [num_directions, batch_size, hidden_size].layout == 1:X.shape = [batch_size, seq_length, input_size]; optionalinitial_h.shape = initial_c.shape = [batch_size, num_directions, hidden_size];Y.shape = [batch_size, seq_length, num_directions, hidden_size];Y_h.shape = Y_c.shape = [batch_size, num_directions, hidden_size].
The three outputs are produced together:
Yis the concatenation of every per-time-step hidden state,Y_hequals the last time step ofYandY_cis the final cell state.Public Functions
-
void Run(RuntimeContext &rt) override#
-
std::tuple<Tensor, Tensor, Tensor> operator()(const Tensor &x, const Tensor &w, const Tensor &r, const Tensor &b = Tensor{}, const Tensor &initial_h = Tensor{}, const Tensor &initial_c = Tensor{}, const Tensor &p = Tensor{}, int64_t layout = 0, const std::string &direction = "forward", RuntimeContext *rt = nullptr) const#
Returns the tuple
(Y, Y_h, Y_c).b,initial_h,initial_candpmay each be a default-constructed (empty-shape)Tensorto indicate that the corresponding optional input is missing.layoutselects between the two ONNX layouts (0or1); any other value is rejected.directionmay be"forward","reverse"or"bidirectional".
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape generally differs from the input shape, so storage cannot in general be shared.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:LSTM"#
-
class MaxPool : public KernelBase#
- #include <include_nn_kernels.h>
N-D max pooling on a numeric tensor laid out as
(N, C, D1, ..., Dk). Supported element types areFLOAT,DOUBLE,INT8andUINT8; the output type matches the input type. Implements the ONNXMaxPooloperator restricted tostorage_order=0(row-major).kernel_shapemust havekentries;strides,padsanddilations(lengthsk,2 * kandkrespectively) default to all-ones / all-zeros / all-ones when omitted.auto_paddefaults toNOTSET(use explicitpads); when set toSAME_UPPER,SAME_LOWERorVALIDthepadsargument must be empty and the begin/end padding is computed from the input shape.The :cpp:func:
operator()overload returns only the primary outputY. :cpp:func:WithIndicesadditionally produces the optionalIndicestensor (int64flat indices into the un-padded input buffer, mirroring the upstream ONNX semantics).Public Functions
-
void Run(RuntimeContext &rt) override#
-
Tensor operator()(const Tensor &x, const Shape &kernel_shape, const Shape &strides = {}, const Shape &pads = {}, bool ceil_mode = false, const Shape &dilations = {}, int64_t storage_order = 0, AutoPad auto_pad = AutoPad::kNotSet, RuntimeContext *rt = nullptr) const#
Returns the primary output
Y(tensor of the pooled values; same element type asx).
-
std::pair<Tensor, Tensor> WithIndices(const Tensor &x, const Shape &kernel_shape, const Shape &strides = {}, const Shape &pads = {}, bool ceil_mode = false, const Shape &dilations = {}, int64_t storage_order = 0, AutoPad auto_pad = AutoPad::kNotSet, RuntimeContext *rt = nullptr) const#
Returns
(Y, Indices)whereIndicesis anint64tensor with the same shape asYcontaining the flat indices into the un-padded input(N, C, D1, ..., Dk)buffer.storage_orderselects the flattening of the selected spatial coordinate:0(row major) or1(column major).
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape generally differs from the input shape.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:MaxPool"#
-
void Run(RuntimeContext &rt) override#
-
class MaxRoiPool : public KernelBase#
- #include <include_nn_kernels.h>
2-D
MaxRoiPoolkernel restricted to FLOAT inputs/outputs. Implements the ONNXMaxRoiPooloperator: for each RoI[batch_id, x1, y1, x2, y2]the kernel scales the corner coordinates byspatial_scale, rounds them to the nearest integer feature-map cell, divides the resulting region into apooled_shape[0] x pooled_shape[1]grid of bins, and produces one max value per (channel, bin) pair. Empty bins (e.g. when the scaled RoI is smaller than the requested pooled output) emit0— mirroring the upstream reference implementation inonnx/reference/ops/op_max_roi_pool.py.Public Functions
-
void Run(RuntimeContext &rt) override#
-
Tensor operator()(const Tensor &x, const Tensor &rois, const Attributes &attrs, RuntimeContext *rt = nullptr) const#
Returns the pooled output
Yof shape(num_rois, C, pooled_shape[0], pooled_shape[1]).
-
void operator()(const Tensor &x, const Tensor &rois, const Attributes &attrs, Tensor &output) const#
In-place variant that writes into a pre-allocated
outputtensor of the expected shape and FLOAT dtype.
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output element layout (num_rois, C, pooled_shape[0], pooled_shape[1]) differs from any input, so storage cannot be shared.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:MaxRoiPool"#
-
struct Attributes#
- #include <include_nn_kernels.h>
Attributes carried by the ONNX
MaxRoiPooloperator.
-
void Run(RuntimeContext &rt) override#
-
class MaxUnpool : public KernelBase#
- #include <include_nn_kernels.h>
N-D
MaxUnpoolon a FLOAT tensor withint64indices. Implements the ONNXMaxUnpooloperator: each value ofxis scattered into a zero-initialized output buffer at the linear index given byindices(interpreted as the flat(N, C, D1, ..., Dk)offset of the output).Two overloads are provided: one that derives the output shape from the
kernel_shape,stridesandpadsattributes, and one that takes an explicit rank-1int64output_shapetensor (if specified, thepadsattribute is ignored, matching the ONNX spec).Public Functions
-
void Run(RuntimeContext &rt) override#
-
Tensor operator()(const Tensor &x, const Tensor &indices, const Shape &kernel_shape, const Shape &strides = {}, const Shape &pads = {}, RuntimeContext *rt = nullptr) const#
Two-input form: derives the output shape from
kernel_shape,stridesandpads(defaults: 1 and 0).
-
Tensor operator()(const Tensor &x, const Tensor &indices, const Tensor &output_shape, const Shape &kernel_shape, const Shape &strides = {}, const Shape &pads = {}, RuntimeContext *rt = nullptr) const#
Three-input form:
output_shapeis a rank-1int64tensor giving the full output shape(N, C, D1, ..., Dk).
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape differs from input shape.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:MaxUnpool"#
-
void Run(RuntimeContext &rt) override#
-
class MeanVarianceNormalization : public onnx_light::onnx_kernels::tuning::ParallelTunableKernel#
- #include <include_nn_kernels.h>
Reference implementation of
MeanVarianceNormalization(opset 9, 13, 29).Normalizes each element as
Y = (X - mean(X, axes)) / sqrt(mean((X - mean(X, axes))^2, axes)). The default axes are[0, 2, 3]. Opset 29 addsepsilonafter the standard deviation and promotes half-precision inputs to FLOAT.Public Functions
-
void Run(RuntimeContext &rt) override#
-
explicit MeanVarianceNormalization(const KernelContext &ctx)#
Public Static Functions
-
static void RegisterTuningSchemas()#
-
static inline constexpr bool CanRunInPlace() noexcept#
Output
Yhas the same shape asXso the output buffer may alias the inputXbuffer.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:MeanVarianceNormalization"#
-
void Run(RuntimeContext &rt) override#
-
class PagedAttention : public KernelBase#
- #include <include_nn_kernels.h>
Computes opt-in paged attention for finite FLOAT/FLOAT16/BFLOAT16 Q/K/V of shape [batch,heads,L,D], including grouped-query attention.
Registers through RuntimeContext::RegisterKernelFn in domain
ai.rtasPagedAttention; it does not replace ONNX Attention. Q and new K/V have equal sequence lengths. Prior pages remain immutable, including partial pages. Dense FLOAT/FLOAT16/BFLOAT16 and inline INT8/UINT8/INT4/UINT4/INT2/UINT2 affine pages may coexist. Affine decoding supports scalar, per-axis and blocked FLOAT scales; other scale types, external payloads and structured encodings are rejected. Prior dense pages require owner-retaining storage (RuntimeValue::Retain).Public Types
Public Functions
-
explicit PagedAttention(const KernelContext &context)#
-
PagedAttention(const KernelContext &context, FormatSelector format_selector)#
Constructs a kernel whose policy selects the appended page formats for every execution.
-
Result operator()(const Tensor &q, const Tensor &k, const Tensor &v, const RuntimeValue &past, const Options &options, RuntimeContext *rt = nullptr) const#
Appends independently formatted pages and computes bounded-workspace attention.
-
void Run(RuntimeContext &rt) override#
Executes four inputs and publishes Y/present only after successful computation.
Public Static Functions
-
static RuntimeValue EmptyCache()#
Returns an empty cache ready for a first append.
-
static inline constexpr bool CanRunInPlace() noexcept#
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.rt:PagedAttention"#
-
struct Format#
- #include <include_nn_kernels.h>
-
struct Formats#
- #include <include_nn_kernels.h>
-
struct Options#
- #include <include_nn_kernels.h>
-
struct Result#
- #include <include_nn_kernels.h>
-
struct Statistics#
- #include <include_nn_kernels.h>
Reports one successful direct invocation; Run publishes only Y and present, not statistics.
Public Members
-
uint64_t copied_bytes = 0#
Counts new stored payload bytes written by copying or conversion, excluding metadata/Y.
-
uint64_t dequantized_bytes = 0#
Counts FLOAT bytes decoded for attended tokens, counting repeated queries separately.
-
uint64_t peak_workspace_bytes = 0#
Counts peak numerical scratch bytes, excluding outputs, cache payloads and metadata.
-
uint64_t validated_pages = 0#
Counts pages whose immutable metadata is validated rather than reused.
-
uint64_t copied_bytes = 0#
-
explicit PagedAttention(const KernelContext &context)#
-
class QuantizePagedCache : public KernelBase#
- #include <include_nn_kernels.h>
Quantizes selected paged-cache blocks with independent scalar K/V parameters.
block_indicesis a rank-one INT64 tensor of unique zero-based block indices. Scales are positive scalar FLOAT tensors. Each scalar zero point selects its output storage type. INT8, UINT8, INT4, UINT4, INT2 and UINT2 produce affine pages; FLOAT, FLOAT16 and BFLOAT16 produce dense pages. Selected dense or affine blocks are decoded and converted; unselected immutable blocks retain their existing storage.Public Functions
-
void Run(RuntimeContext &rt) override#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.rt:QuantizePagedCache"#
-
void Run(RuntimeContext &rt) override#
-
class RMSNormalization : public onnx_light::onnx_kernels::tuning::ParallelTunableKernel#
- #include <include_nn_kernels.h>
Reference implementation of
RMSNormalization(opset 23).Normalizes a FLOAT, FLOAT16 or BFLOAT16 input
Xof arbitrary rankrby dividing it by the root-mean-square computed over the lastr - axisdimensions, then multiplies the normalized result byscale(with unidirectional broadcasting):Y = X / sqrt(mean(X * X, axes=normalized_axes) + epsilon) * scalewhere
normalized_axes = [axis, ..., r - 1].scalemust be broadcastable to the normalized shape (i.e.X.shape[axis:]). Half inputs are promoted to FLOAT before normalization, then rounded back to the input dtype before multiplying byscale.Public Functions
-
void Run(RuntimeContext &rt) override#
-
explicit RMSNormalization(const KernelContext &ctx)#
Public Static Functions
-
static void RegisterTuningSchemas()#
-
static inline constexpr bool CanRunInPlace() noexcept#
Output
Yhas the same shape asXso the output buffer may alias the inputXbuffer.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:RMSNormalization"#
-
void Run(RuntimeContext &rt) override#
-
class RNN : public KernelBase#
- #include <include_nn_kernels.h>
One-layer RNN on FLOAT tensors using the
Tanhactivation. Implements the upstream ONNXRNNformulaH_t = tanh(X_t @ W^T + W_b + H_{t-1} @ R^T + R_b)for
layout=0, withX.shape = [seq_length, batch_size, input_size];W.shape = [num_directions, hidden_size, input_size];R.shape = [num_directions, hidden_size, hidden_size]; optionalB.shape = [num_directions, 2 * hidden_size]([Wb, Rb]); optionalinitial_h.shape = [num_directions, batch_size, hidden_size], defaulting to zeros.layout=1(batch-major) is also supported: the kernel transposesX/initial_hon entry and the outputs on exit so the core time-major loop is unchanged. Theactivationsattribute, if present, must be either empty or the single value"Tanh";directionmay be"forward","reverse"or"bidirectional"(num_directionsis2for the last,1otherwise);sequence_lensis not supported (every batch must share the same sequence length);clipis not supported.The two outputs are produced together:
Yhas shape[seq_length, num_directions, batch_size, hidden_size]and is the concatenation of every per-time-step hidden state;Y_hhas shape[num_directions, batch_size, hidden_size]and equals the last time step ofY.Public Functions
-
void Run(RuntimeContext &rt) override#
-
std::pair<Tensor, Tensor> operator()(const Tensor &x, const Tensor &w, const Tensor &r, const Tensor &b = Tensor{}, const Tensor &initial_h = Tensor{}, int64_t layout = 0, const std::string &direction = "forward", RuntimeContext *rt = nullptr) const#
Returns the pair
(Y, Y_h).bmay be a default-constructed (empty-shape)Tensorto indicate the optionalBinput is missing; same convention forinitial_h.layoutmay be0(time-major, the default) or1(batch-major); forlayout=1the kernel transposesX/initial_hon entry and the outputs on exit so the core time-major loop is unchanged.directionmay be"forward","reverse"or"bidirectional".
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape generally differs from the input shape, so storage cannot in general be shared.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:RNN"#
-
void Run(RuntimeContext &rt) override#
-
class RotaryEmbedding : public KernelBase#
- #include <include_nn_kernels.h>
Reference implementation of
ai.onnx::RotaryEmbedding(v23).Applies the rotary positional embedding (RoPE) defined in https://arxiv.org/pdf/2104.09864 to the input tensor
X. The kernel accepts both the rank-3 layout(batch_size, sequence_length, hidden_size)(in which casenum_headsmust be provided andhidden_size = num_heads * head_size) and the rank-4 layout(batch_size, num_heads, sequence_length, head_size). The output has the same shape and dtype asX.cos_cacheandsin_cacheare either rank-2(max_position_id_plus_1, head_size / 2)tables indexed by the optionalposition_idsinput or rank-3(batch_size, sequence_length, head_size / 2)tensors used directly whenposition_idsis omitted. Whenrotary_embedding_dimis non-zero the last dimension of the caches must equalrotary_embedding_dim / 2and rotation is applied only to the firstrotary_embedding_dimchannels of each head; the remaining channels are passed through unchanged.When
interleavedis true, even/odd channels of each head are paired instead of the (default) splitting into two contiguous halves.Public Functions
-
void Run(RuntimeContext &rt) override#
-
Tensor operator()(const Tensor &X, const Tensor &cos_cache, const Tensor &sin_cache, const Tensor &position_ids, const Attributes &attrs, RuntimeContext *rt = nullptr) const#
Returning overload.
position_idsmay be a default-constructed (empty-shape)Tensorto indicate the optional input is missing.
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape matches input shape; storage could theoretically alias
Xbut the in-place overload above does not exploit it.
Public Static Attributes
-
static constexpr const char *name = "onnx_kernels:CPU:ai.onnx:RotaryEmbedding"#
-
struct Attributes#
- #include <include_nn_kernels.h>
Attributes carried by the ONNX
RotaryEmbeddingoperator. All defaults match the upstream schema.
-
void Run(RuntimeContext &rt) override#
-
core::shapes::PeakMemoryEstimate ComputePeakMemoryAttention(core::symbolic::Device device, const std::vector<core::symbolic::SymShape> &input_shapes)#
-
namespace kernel
-
namespace onnx_kernels