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.
Defined as empty because onnx-light does not require explicit
__declspec(dllexport)or__attribute__((visibility("default")))annotations — visibility is controlled at the shared-library level. The macro is provided so that vendored ONNX headers that decorate their declarations withONNX_APIcompile without modification.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
-
class Attention : public onnx_light::onnx_kernels::kernel::KernelBase#
- #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
-
Tensor operator()(const Tensor &Q, const Tensor &K, const Tensor &V) 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) const#
Explicit
scaleoverload, no mask.
-
Tensor operator()(const Tensor &Q, const Tensor &K, const Tensor &V, float scale, const Tensor &attn_mask) 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) 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.
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
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.
-
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 onnx_light::onnx_kernels::kernel::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
-
Tensor operator()(const Tensor &x, const std::vector<int64_t> &kernel_shape, const std::vector<int64_t> &strides = {}, const std::vector<int64_t> &pads = {}, bool ceil_mode = false, bool count_include_pad = false, const std::vector<int64_t> &dilations = {}, const std::string &auto_pad = "NOTSET") 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).
-
void operator()(const Tensor &x, const std::vector<int64_t> &kernel_shape, const std::vector<int64_t> &strides, const std::vector<int64_t> &pads, bool ceil_mode, bool count_include_pad, Tensor &output, const std::vector<int64_t> &dilations = {}, const std::string &auto_pad = "NOTSET") const#
-
inline explicit KernelBase(const KernelContext &ctx)#
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.
-
Tensor operator()(const Tensor &x, const std::vector<int64_t> &kernel_shape, const std::vector<int64_t> &strides = {}, const std::vector<int64_t> &pads = {}, bool ceil_mode = false, bool count_include_pad = false, const std::vector<int64_t> &dilations = {}, const std::string &auto_pad = "NOTSET") const#
-
class BatchNormalization : public onnx_light::onnx_kernels::kernel::KernelBase#
- #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
-
Tensor operator()(const Tensor &x, const Tensor &scale, const Tensor &bias, const Tensor &input_mean, const Tensor &input_var, float epsilon = 1e-5f) 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) 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) 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.
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output
Yhas the same shape asXso the output buffer may alias the inputXbuffer.
-
Tensor operator()(const Tensor &x, const Tensor &scale, const Tensor &bias, const Tensor &input_mean, const Tensor &input_var, float epsilon = 1e-5f) const#
-
class CausalConvWithState : public onnx_light::onnx_kernels::kernel::KernelBase#
- #include <include_nn_kernels.h>
Reference implementation of
ai.onnx::CausalConvWithState(v27).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); when absent the carry is implicitly zero-padding.output: same shape asinputpresent_state:(batch_size, channels, k - 1)containing the lastk - 1values of the padded sequence ([past_state, input]) along the causal axis.
Public Functions
-
std::pair<Tensor, Tensor> operator()(const Tensor &input, const Tensor &weight, const Tensor &bias, const Tensor &past_state, const Attributes &attrs) const#
Returning overload.
biasandpast_statemay be default-constructed (empty-shape)Tensorvalues to indicate the optional inputs are missing.
-
void operator()(const Tensor &input, const Tensor &weight, const Tensor *bias, const Tensor *past_state, const Attributes &attrs, Tensor &output, Tensor &present_state) const#
In-place overload writing into caller-allocated output tensors.
biasandpast_statemay benullptrfor the optional inputs.
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
-
struct Attributes#
- #include <include_nn_kernels.h>
Attributes carried by the
CausalConvWithStateoperator.
-
class Col2Im : public onnx_light::onnx_kernels::kernel::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
-
Tensor operator()(const Tensor &input, const Tensor &image_shape, const Tensor &block_shape, const Attributes &attrs) const#
-
void operator()(const Tensor &input, const Tensor &image_shape, const Tensor &block_shape, const Attributes &attrs, Tensor &output) const#
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape differs from input shape, so storage cannot be shared.
-
struct Attributes#
- #include <include_nn_kernels.h>
Attributes carried by the ONNX
Col2Imoperator.
-
class Conv : public onnx_light::onnx_kernels::kernel::KernelBase#
- #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
-
Tensor operator()(const Tensor &x, const Tensor &w, const Tensor &b, const Attributes &attrs) const#
Returning overload.
Bmay be a default-constructed (empty-shape)Tensorto indicate the optional bias is missing.
-
void operator()(const Tensor &x, const Tensor &w, const Tensor &b, const Attributes &attrs, Tensor &output) const#
In-place overload writing into a caller-allocated FLOAT
output.
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape generally differs from the input, so storage cannot be shared.
-
struct Attributes#
- #include <include_nn_kernels.h>
Attributes carried by the ONNX
Convoperator.Public Members
-
int64_t group = 1#
Number of conv groups.
-
int64_t group = 1#
-
Tensor operator()(const Tensor &x, const Tensor &w, const Tensor &b, const Attributes &attrs) const#
-
class ConvInteger : public onnx_light::onnx_kernels::kernel::KernelBase#
- #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
-
Tensor operator()(const Tensor &x, const Tensor &w, const Tensor &x_zero_point, const Tensor &w_zero_point, const Attributes &attrs) const#
Returning overload.
-
void operator()(const Tensor &x, const Tensor &w, const Tensor &x_zero_point, const Tensor &w_zero_point, const Attributes &attrs, Tensor &output) const#
In-place overload writing into a caller-allocated INT32
output.
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output dtype differs from input dtype, so storage cannot be shared.
-
struct Attributes#
- #include <include_nn_kernels.h>
Attributes carried by the ONNX
ConvIntegeroperator.
-
Tensor operator()(const Tensor &x, const Tensor &w, const Tensor &x_zero_point, const Tensor &w_zero_point, const Attributes &attrs) const#
-
class ConvTranspose : public onnx_light::onnx_kernels::kernel::KernelBase#
- #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
-
Tensor operator()(const Tensor &x, const Tensor &w, const Tensor &b, const Attributes &attrs) const#
Returning overload.
-
void operator()(const Tensor &x, const Tensor &w, const Tensor &b, const Attributes &attrs, Tensor &output) const#
In-place overload writing into a caller-allocated FLOAT
output.
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape generally differs from the input, so storage cannot be shared.
-
struct Attributes#
- #include <include_nn_kernels.h>
Attributes carried by the ONNX
ConvTransposeoperator.
-
Tensor operator()(const Tensor &x, const Tensor &w, const Tensor &b, const Attributes &attrs) const#
-
class DeformConv : public onnx_light::onnx_kernels::kernel::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
-
Tensor operator()(const Tensor &x, const Tensor &w, const Tensor &offset, const Tensor &b, const Tensor &mask, const Attributes &attrs) const#
-
void operator()(const Tensor &x, const Tensor &w, const Tensor &offset, const Tensor &b, const Tensor &mask, const Attributes &attrs, Tensor &output) const#
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape differs from any input, so storage cannot be shared.
-
struct Attributes#
- #include <include_nn_kernels.h>
Attributes carried by the ONNX
DeformConvoperator. Defaults match the upstream schema (since opset 19).
-
class Dropout : public onnx_light::onnx_kernels::kernel::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
-
std::pair<Tensor, Tensor> operator()(const Tensor &data, float ratio = 0.5f, bool training_mode = false, int64_t seed = kNoSeed) const#
-
Tensor operator()(const Tensor &data, float ratio, bool training_mode, Tensor &mask, int64_t seed = kNoSeed) const#
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Public Static Attributes
-
static constexpr int64_t kNoSeed = -1#
-
std::pair<Tensor, Tensor> operator()(const Tensor &data, float ratio = 0.5f, bool training_mode = false, int64_t seed = kNoSeed) const#
-
class Flatten : public onnx_light::onnx_kernels::kernel::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
-
Tensor operator()(const Tensor &input, int64_t axis = 1) const#
Returns the 2-D output tensor.
axisfollows ONNX semantics.
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output element count equals the input element count, so storage can be shared in-place.
-
Tensor operator()(const Tensor &input, int64_t axis = 1) const#
-
class GlobalAveragePool : public onnx_light::onnx_kernels::kernel::KernelBase#
- #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
-
Tensor operator()(const Tensor &x) const#
Returns a FLOAT output tensor of shape
(N, C, 1, 1, ..., 1).
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape differs from the input shape, so storage cannot be shared.
-
Tensor operator()(const Tensor &x) const#
-
class GlobalLpPool : public onnx_light::onnx_kernels::kernel::KernelBase#
- #include <include_nn_kernels.h>
Global Lp 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 Lp norm over all elements in that dimension. The default value ofpis 2 (L2 norm). Whenp == 1this is L1 pooling;p == 2(default) gives the RMS/L2 pooling defined by ONNX.Public Functions
-
Tensor operator()(const Tensor &x, int64_t p = 2) const#
Returns a FLOAT output tensor of shape
(N, C, 1, 1, ..., 1).pis the Lp norm exponent (default 2).
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape differs from the input shape, so storage cannot be shared.
-
Tensor operator()(const Tensor &x, int64_t p = 2) const#
-
class GlobalMaxPool : public onnx_light::onnx_kernels::kernel::KernelBase#
- #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
-
Tensor operator()(const Tensor &x) const#
Returns a FLOAT output tensor of shape
(N, C, 1, 1, ..., 1).
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape differs from the input shape, so storage cannot be shared.
-
Tensor operator()(const Tensor &x) const#
-
class GroupNormalization : public onnx_light::onnx_kernels::kernel::KernelBase#
- #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
-
Tensor operator()(const Tensor &x, const Tensor &scale, const Tensor &bias, int64_t num_groups, float epsilon = 1e-5f) const#
Returns the output
Y.epsilondefaults to 1e-5f, the upstream default.
-
void operator()(const Tensor &x, const Tensor &scale, const Tensor &bias, int64_t num_groups, Tensor &output, float epsilon = 1e-5f) const#
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output
Yhas the same shape asXso the output buffer may alias the inputXbuffer.
-
Tensor operator()(const Tensor &x, const Tensor &scale, const Tensor &bias, int64_t num_groups, float epsilon = 1e-5f) const#
-
class GRU : public onnx_light::onnx_kernels::kernel::KernelBase#
- #include <include_nn_kernels.h>
Single-direction (
"forward") one-layer GRU on FLOAT tensors using the defaultSigmoid/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 = [1, batch_size, hidden_size]) andlayout=1(X.shape = [batch_size, seq_length, input_size]; optionalinitial_h.shape = [batch_size, 1, hidden_size]).W.shape = [1, 3 * hidden_size, input_size];R.shape = [1, 3 * hidden_size, hidden_size]; optionalB.shape = [1, 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);activations,clipand non-forwarddirectionare not supported.The two outputs are produced together: for
layout=0,Yhas shape[seq_length, 1, batch_size, hidden_size]and is the concatenation of every per-time-step hidden state;Y_hhas shape[1, batch_size, hidden_size]and equals the last time step ofY. Forlayout=1the corresponding shapes are[batch_size, seq_length, 1, hidden_size]and[batch_size, 1, hidden_size].Public Functions
-
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#
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).
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape generally differs from the input shape, so storage cannot in general be shared.
-
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#
-
class InstanceNormalization : public onnx_light::onnx_kernels::kernel::KernelBase#
- #include <include_nn_kernels.h>
Reference implementation of
InstanceNormalization(opset 1, 6, 22).Normalizes a FLOAT 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 FLOAT tensors of lengthC.Public Functions
-
Tensor operator()(const Tensor &x, const Tensor &scale, const Tensor &bias, float epsilon = 1e-5f) const#
Returns the output
Y.epsilondefaults to 1e-5f, the upstream default.
-
void operator()(const Tensor &x, const Tensor &scale, const Tensor &bias, Tensor &output, float epsilon = 1e-5f) const#
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output
Yhas the same shape asXso the output buffer may alias the inputXbuffer.
-
Tensor operator()(const Tensor &x, const Tensor &scale, const Tensor &bias, float epsilon = 1e-5f) const#
-
class LayerNormalization : public onnx_light::onnx_kernels::kernel::KernelBase#
- #include <include_nn_kernels.h>
Reference implementation of
LayerNormalization(opset 17).Normalizes a FLOAT 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.Public Functions
-
std::tuple<Tensor, Tensor, Tensor> operator()(const Tensor &x, const Tensor &scale, const Tensor &b, int64_t axis = -1, float epsilon = 1e-5f) 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.
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output
Yhas the same shape asXso the output buffer may alias the inputXbuffer.
-
std::tuple<Tensor, Tensor, Tensor> operator()(const Tensor &x, const Tensor &scale, const Tensor &b, int64_t axis = -1, float epsilon = 1e-5f) const#
-
class LinearAttention : public onnx_light::onnx_kernels::kernel::KernelBase#
- #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
-
Tensor operator()(const Tensor &query, const Tensor &key, const Tensor &value) const#
Default-attribute overload (update_rule=”linear”, scale=auto).
-
Result operator()(const Tensor &query, const Tensor &key, const Tensor &value, const Attributes &attrs, const Tensor *past_state = nullptr, const Tensor *decay = nullptr, const Tensor *beta = nullptr) const#
Comprehensive overload covering every supported feature.
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
-
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.
-
Tensor operator()(const Tensor &query, const Tensor &key, const Tensor &value) const#
-
class LpNormalization : public onnx_light::onnx_kernels::kernel::KernelBase#
- #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
-
Tensor operator()(const Tensor &x, int64_t axis = -1, int64_t p = 2) const#
Returns a FLOAT output tensor whose shape matches
x.
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape matches input shape, so storage may alias the input buffer.
-
Tensor operator()(const Tensor &x, int64_t axis = -1, int64_t p = 2) const#
-
class LpPool : public onnx_light::onnx_kernels::kernel::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
-
Tensor operator()(const Tensor &x, const std::vector<int64_t> &kernel_shape, const std::vector<int64_t> &strides = {}, const std::vector<int64_t> &pads = {}, int64_t p = 2, bool ceil_mode = false, const std::vector<int64_t> &dilations = {}, const std::string &auto_pad = "NOTSET") 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).
-
inline explicit KernelBase(const KernelContext &ctx)#
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.
-
Tensor operator()(const Tensor &x, const std::vector<int64_t> &kernel_shape, const std::vector<int64_t> &strides = {}, const std::vector<int64_t> &pads = {}, int64_t p = 2, bool ceil_mode = false, const std::vector<int64_t> &dilations = {}, const std::string &auto_pad = "NOTSET") const#
-
class LRN : public onnx_light::onnx_kernels::kernel::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 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 matches the input shape.Public Functions
-
Tensor operator()(const Tensor &x, int64_t size, float alpha = 0.0001f, float beta = 0.75f, float bias = 1.0f) const#
Returns a FLOAT output tensor whose shape matches
x.
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape matches input shape, so storage may alias the input buffer.
-
Tensor operator()(const Tensor &x, int64_t size, float alpha = 0.0001f, float beta = 0.75f, float bias = 1.0f) const#
-
class LSTM : public onnx_light::onnx_kernels::kernel::KernelBase#
- #include <include_nn_kernels.h>
Single-direction (
"forward") one-layer LSTM on FLOAT tensors using the defaultSigmoid/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 = [1, 4 * hidden_size, input_size];R.shape = [1, 4 * hidden_size, hidden_size]; optionalB.shape = [1, 8 * hidden_size]([Wb, Rb]each with 4 gate blocks in the ONNX gate orderi, o, f, c); optionalP.shape = [1, 3 * hidden_size](peephole weights in gate orderi, o, f).sequence_lensis not supported (every batch must share the same sequence length);activations,clip,input_forgetand non-forwarddirectionare not supported.Both
layoutvalues defined by ONNX are supported:layout == 0(default):X.shape = [seq_length, batch_size, input_size]; optionalinitial_h.shape = initial_c.shape = [1, batch_size, hidden_size];Y.shape = [seq_length, 1, batch_size, hidden_size];Y_h.shape = [1, batch_size, hidden_size].layout == 1:X.shape = [batch_size, seq_length, input_size]; optionalinitial_h.shape = initial_c.shape = [batch_size, 1, hidden_size];Y.shape = [batch_size, seq_length, 1, hidden_size];Y_h.shape = [batch_size, 1, hidden_size].
The two outputs are produced together:
Yis the concatenation of every per-time-step hidden state andY_hequals the last time step ofY. The optional third outputY_cis not produced by this overload.Public Functions
-
std::pair<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#
Returns the pair
(Y, Y_h).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.
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape generally differs from the input shape, so storage cannot in general be shared.
-
class MaxPool : public onnx_light::onnx_kernels::kernel::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
-
Tensor operator()(const Tensor &x, const std::vector<int64_t> &kernel_shape, const std::vector<int64_t> &strides = {}, const std::vector<int64_t> &pads = {}, bool ceil_mode = false, const std::vector<int64_t> &dilations = {}, int64_t storage_order = 0, const std::string &auto_pad = "NOTSET") const#
Returns the primary output
Y(tensor of the pooled values; same element type asx).
-
std::pair<Tensor, Tensor> WithIndices(const Tensor &x, const std::vector<int64_t> &kernel_shape, const std::vector<int64_t> &strides = {}, const std::vector<int64_t> &pads = {}, bool ceil_mode = false, const std::vector<int64_t> &dilations = {}, int64_t storage_order = 0, const std::string &auto_pad = "NOTSET") 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).
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape generally differs from the input shape.
-
Tensor operator()(const Tensor &x, const std::vector<int64_t> &kernel_shape, const std::vector<int64_t> &strides = {}, const std::vector<int64_t> &pads = {}, bool ceil_mode = false, const std::vector<int64_t> &dilations = {}, int64_t storage_order = 0, const std::string &auto_pad = "NOTSET") const#
-
class MaxRoiPool : public onnx_light::onnx_kernels::kernel::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
-
Tensor operator()(const Tensor &x, const Tensor &rois, const Attributes &attrs) 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.
-
inline explicit KernelBase(const KernelContext &ctx)#
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.
-
struct Attributes#
- #include <include_nn_kernels.h>
Attributes carried by the ONNX
MaxRoiPooloperator.
-
Tensor operator()(const Tensor &x, const Tensor &rois, const Attributes &attrs) const#
-
class MaxUnpool : public onnx_light::onnx_kernels::kernel::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
-
Tensor operator()(const Tensor &x, const Tensor &indices, const std::vector<int64_t> &kernel_shape, const std::vector<int64_t> &strides = {}, const std::vector<int64_t> &pads = {}) 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 std::vector<int64_t> &kernel_shape, const std::vector<int64_t> &strides = {}, const std::vector<int64_t> &pads = {}) const#
Three-input form:
output_shapeis a rank-1int64tensor giving the full output shape(N, C, D1, ..., Dk).
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape differs from input shape.
-
Tensor operator()(const Tensor &x, const Tensor &indices, const std::vector<int64_t> &kernel_shape, const std::vector<int64_t> &strides = {}, const std::vector<int64_t> &pads = {}) const#
-
class MeanVarianceNormalization : public onnx_light::onnx_kernels::kernel::KernelBase#
- #include <include_nn_kernels.h>
Reference implementation of
MeanVarianceNormalization(opset 9, 13).Normalizes each element as
Y = (X - mean(X, axes)) / sqrt(mean((X - mean(X, axes))^2, axes)). The default axes are[0, 2, 3].Public Functions
-
void operator()(const Tensor &x, Tensor &output, const std::vector<int64_t> &axes = {0, 2, 3}) const#
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output
Yhas the same shape asXso the output buffer may alias the inputXbuffer.
-
void operator()(const Tensor &x, Tensor &output, const std::vector<int64_t> &axes = {0, 2, 3}) const#
-
class RMSNormalization : public onnx_light::onnx_kernels::kernel::KernelBase#
- #include <include_nn_kernels.h>
Reference implementation of
RMSNormalization(opset 23).Normalizes a FLOAT 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:]).Public Functions
-
Tensor operator()(const Tensor &x, const Tensor &scale, int64_t axis = -1, float epsilon = 1e-5f) const#
Returns the output
Y.axisdefaults to-1andepsilonto1e-5fto match the upstream defaults.
-
void operator()(const Tensor &x, const Tensor &scale, Tensor &output, int64_t axis = -1, float epsilon = 1e-5f) const#
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output
Yhas the same shape asXso the output buffer may alias the inputXbuffer.
-
Tensor operator()(const Tensor &x, const Tensor &scale, int64_t axis = -1, float epsilon = 1e-5f) const#
-
class RNN : public onnx_light::onnx_kernels::kernel::KernelBase#
- #include <include_nn_kernels.h>
Single-direction (
"forward") one-layer RNN on FLOAT tensors using theTanhactivation. 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 = [1, hidden_size, input_size];R.shape = [1, hidden_size, hidden_size]; optionalB.shape = [1, 2 * hidden_size]([Wb, Rb]); optionalinitial_h.shape = [1, 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";directionmust be"forward"(the default);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, 1, batch_size, hidden_size]and is the concatenation of every per-time-step hidden state;Y_hhas shape[1, batch_size, hidden_size]and equals the last time step ofY.Public Functions
-
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#
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.
-
inline explicit KernelBase(const KernelContext &ctx)#
Public Static Functions
-
static inline constexpr bool CanRunInPlace() noexcept#
Output shape generally differs from the input shape, so storage cannot in general be shared.
-
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#
-
class RotaryEmbedding : public onnx_light::onnx_kernels::kernel::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
-
Tensor operator()(const Tensor &X, const Tensor &cos_cache, const Tensor &sin_cache, const Tensor &position_ids, const Attributes &attrs) const#
Returning overload.
position_idsmay be a default-constructed (empty-shape)Tensorto indicate the optional input is missing.
-
void operator()(const Tensor &X, const Tensor &cos_cache, const Tensor &sin_cache, const Tensor *position_ids, const Attributes &attrs, Tensor &output) const#
In-place overload writing into a caller-allocated output of the same shape and dtype as
X.
-
inline explicit KernelBase(const KernelContext &ctx)#
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.
-
struct Attributes#
- #include <include_nn_kernels.h>
Attributes carried by the ONNX
RotaryEmbeddingoperator. All defaults match the upstream schema.
-
Tensor operator()(const Tensor &X, const Tensor &cos_cache, const Tensor &sin_cache, const Tensor &position_ids, const Attributes &attrs) const#
-
class Attention : public onnx_light::onnx_kernels::kernel::KernelBase#
-
namespace kernel
-
namespace onnx_kernels