Overview / Machine learning

Ml::Neural

Beta

Inference of small networks (MLP, convolutions, LSTM and GRU) inside the binary, from an in-house format converted from ONNX by the <code>etl-neural</code> tool. The client never reads ONNX.

Optional module: turn it on with -DETHEREAL_ML_NEURAL=ONInclude #include <ethereal/cpp/ml/neural/neural_attrs.hpp>C layer

neural_attrs.hpp

#include <ethereal/cpp/ml/neural/neural_attrs.hpp>

Attributes of each kernel, as stored in the ATTRS section.

Every attribute block is made of 32 bit words. The converter writes them with the shapes already resolved. The loader checks each one against the tensors of the step (everything the kernel reads and writes must fit) before the plan exists.

Weight layouts (the converter writes them this way, the kernel never shuffles):

  • GEMM float (B, K x N): panels of 16 columns. Panel p, then k, then the 16 columns (p*16 .. p*16+15, zero after N). ceil(N/16) K 16 floats.
  • GEMM int8 (B, K x N): panels of 16 columns with K in groups of four. Panel p, group q, column j, then the 4 k (q*4 .. q*4+3) in a row. ceil(N/16) ceil(K/4) 64 bytes.
  • Conv (W, M x C/g x kH x kW): per group, the transpose of W_g (K x M/g, K = C/g kH kW), packed as the GEMM B (float or int8). The convolution is the GEMM im2col^T (pixels x K) . W_g^T, with the output written directly in NCHW.
  • Depthwise (W, C x 1 x kH x kW): exactly as in ONNX.
const

NEURAL_GEMM_NR

Ethereal::Ml::Neural#
constexpr ETL_UINT32 NEURAL_GEMM_NR = 16u;

Columns in one GEMM panel.

const

NEURAL_QGEMM_KQ

Ethereal::Ml::Neural#
constexpr ETL_UINT32 NEURAL_QGEMM_KQ = 4u;

Values of k in one int8 group.

struct

SGemmAttr

Ethereal::Ml::Neural#
C++
struct   SGemmAttr   final
{
    /// @brief  Rows of A, columns of B and the inner dimension.
    ETL_UINT32    uM, uN, uK;

    /// @brief  1 when A is stored transposed (K x M).
    ETL_UINT32    uTransA;

    /// @brief  Fused EActivation and its two parameters.
    ETL_UINT32    eAct;
    float        fAct0, fAct1;

    /// @brief  Scale of A . B.
    float        fAlpha;

    /// @brief  1 when the bias input is present.
    ETL_UINT32    uHasBias;

    /// @brief  Reserved, zero.
    ETL_UINT32    aReserved[ 3 ];
};

eGemm attributes.

Inputs: A (float, M x K, or K x M with uTransA), B packed, bias (N) optional. Output: Y (M x N). Y = act( fAlpha * A . B + bias ).

struct

SMatMulAttr

Ethereal::Ml::Neural#
C++
struct   SMatMulAttr   final
{
    /// @brief  Rows of A, columns of B and the inner dimension.
    ETL_UINT32    uM, uN, uK;

    /// @brief  Number of batch dimensions.
    ETL_UINT32    uBatchRank;

    /// @brief  Batch dimensions of the output.
    ETL_UINT32    aOutBatch[ 4 ];

    /// @brief  Batch dimensions of A. Each one is 1 or the one in aOutBatch.
    ETL_UINT32    aABatch[ 4 ];

    /// @brief  Batch dimensions of B. Each one is 1 or the one in aOutBatch.
    ETL_UINT32    aBBatch[ 4 ];
};

eMatMul attributes (both sides dynamic).

Inputs: A (batches x M x K) and B (batches x K x N). Batches broadcast as in numpy: up to 4 batch dimensions, aligned to the right.

enum

EBinaryOp

Ethereal::Ml::Neural#
C++
enum class   EBinaryOp : ETL_UINT32
{
    /// @brief  A + B.
    eAdd = 0,

    /// @brief  A - B.
    eSub,

    /// @brief  A * B.
    eMul,

    /// @brief  A / B.
    eDiv
};

Operation of an eBinary step.

struct

SBinaryAttr

Ethereal::Ml::Neural#
C++
struct   SBinaryAttr   final
{
    /// @brief  EBinaryOp.
    ETL_UINT32    eOp;

    /// @brief  Fused EActivation and its two parameters.
    ETL_UINT32    eAct;
    float        fAct0, fAct1;

    /// @brief  Number of dimensions.
    ETL_UINT32    uRank;

    /// @brief  Output shape.
    ETL_UINT32    aOut[ NEURAL_MAX_RANK ];

    /// @brief  Shape of A.
    ETL_UINT32    aA[ NEURAL_MAX_RANK ];

    /// @brief  Shape of B.
    ETL_UINT32    aB[ NEURAL_MAX_RANK ];
};

eBinary attributes.

Shapes are aligned to the right in uRank dimensions. Each dimension of A and of B is 1 or the output one (numpy broadcasting).

struct

SUnaryAttr

Ethereal::Ml::Neural#
C++
struct   SUnaryAttr   final
{
    /// @brief  EActivation and its two parameters.
    ETL_UINT32    eAct;
    float        fAct0, fAct1;

    /// @brief  Number of elements.
    ETL_UINT32    uCount;
};

eUnary attributes: uCount elements and the activation eAct (Relu, LeakyRelu, Sigmoid, Tanh or Clip).

struct

SSoftmaxAttr

Ethereal::Ml::Neural#
C++
struct   SSoftmaxAttr   final
{
    /// @brief  Outer, axis and inner sizes.
    ETL_UINT32    uOuter, uAxis, uInner;

    /// @brief  Reserved, zero.
    ETL_UINT32    uReserved;
};

eSoftmax attributes. Softmax over the middle axis of [uOuter, uAxis, uInner].

struct

SStridedAttr

Ethereal::Ml::Neural#
C++
struct   SStridedAttr   final
{
    /// @brief  Number of dimensions.
    ETL_UINT32    uRank;

    /// @brief  Output shape.
    ETL_UINT32    aOut[ NEURAL_MAX_RANK ];

    /// @brief  Input stride of each output dimension, in elements.
    ETL_INT32    aStride[ NEURAL_MAX_RANK ];

    /// @brief  Input index of the first output element.
    ETL_INT32    iBase;
};

eStrided attributes (Transpose, Slice).

output[o] = input[ iBase + sum( o_d * aStride[d] ) ]. Strides can be negative (Slice with a negative step).

struct

SConcatAttr

Ethereal::Ml::Neural#
C++
struct   SConcatAttr   final
{
    /// @brief  Outer and inner sizes.
    ETL_UINT32    uOuter, uInner;

    /// @brief  Number of inputs.
    ETL_UINT32    uCount;

    /// @brief  Size of each input along the axis.
    ETL_UINT32    aSizes[ NEURAL_MAX_STEP_INPUTS ];
};

eConcat attributes. uCount inputs along the middle axis of [uOuter, sum, uInner].

struct

SGatherAttr

Ethereal::Ml::Neural#
C++
struct   SGatherAttr   final
{
    /// @brief  Outer size, size of the gathered axis and inner size.
    ETL_UINT32    uOuter, uAxisDim, uInner;

    /// @brief  Number of indices.
    ETL_UINT32    uIndexCount;
};

eGather attributes.

Data [uOuter, uAxisDim, uInner], indices (int32 or int64, uIndexCount), output [uOuter, uIndexCount, uInner]. An index out of [-uAxisDim, uAxisDim) returns eInvalidArgument at run time (ONNX Runtime refuses it too).

enum

EReduceOp

Ethereal::Ml::Neural#
C++
enum class   EReduceOp : ETL_UINT32
{
    /// @brief  ReduceSum.
    eSum = 0,

    /// @brief  ReduceMean.
    eMean
};

Operation of an eReduce step.

struct

SReduceAttr

Ethereal::Ml::Neural#
C++
struct   SReduceAttr   final
{
    /// @brief  EReduceOp.
    ETL_UINT32    eOp;

    /// @brief  Number of dimensions.
    ETL_UINT32    uRank;

    /// @brief  Input shape.
    ETL_UINT32    aIn[ NEURAL_MAX_RANK ];

    /// @brief  Reduced axes, one bit per axis.
    ETL_UINT32    uMask;

    /// @brief  Reserved, zero.
    ETL_UINT32    uReserved;
};

eReduce attributes. The input [aIn] is reduced over the axes in uMask (bit d). The output has 1 in those axes.

struct

SCopyAttr

Ethereal::Ml::Neural#
C++
struct   SCopyAttr   final
{
    /// @brief  Low and high words of the byte count.
    ETL_UINT32    uBytesLo, uBytesHi;
};

eCopy attributes: uBytes copied.

struct

SConvAttr

Ethereal::Ml::Neural#
C++
struct   SConvAttr   final
{
    /// @brief  Input shape (N x C x H x W).
    ETL_UINT32    uN, uC, uH, uW;

    /// @brief  Output channels and kernel size.
    ETL_UINT32    uM, uKH, uKW;

    /// @brief  Strides.
    ETL_UINT32    uSH, uSW;

    /// @brief  Padding: top, left, bottom and right.
    ETL_UINT32    uPT, uPL, uPB, uPR;

    /// @brief  Dilations.
    ETL_UINT32    uDH, uDW;

    /// @brief  Number of groups.
    ETL_UINT32    uGroup;

    /// @brief  Output height and width.
    ETL_UINT32    uOH, uOW;

    /// @brief  Fused EActivation and its two parameters.
    ETL_UINT32    eAct;
    float        fAct0, fAct1;

    /// @brief  1 when the bias input is present.
    ETL_UINT32    uHasBias;
};

eConv, eDepthwise and eQConv attributes.

Inputs: X (N x C x H x W), W and bias (M) optional. Conv1d is uH = uKH = 1.

enum

EPoolKind

Ethereal::Ml::Neural#
C++
enum class   EPoolKind : ETL_UINT32
{
    /// @brief  MaxPool.
    eMax = 0,

    /// @brief  AveragePool.
    eAverage,

    /// @brief  GlobalAveragePool.
    eGlobalAverage
};

Kind of an ePool step.

struct

SPoolAttr

Ethereal::Ml::Neural#
C++
struct   SPoolAttr   final
{
    /// @brief  EPoolKind.
    ETL_UINT32    eKind;

    /// @brief  Input shape (N x C x H x W).
    ETL_UINT32    uN, uC, uH, uW;

    /// @brief  Window size.
    ETL_UINT32    uKH, uKW;

    /// @brief  Strides.
    ETL_UINT32    uSH, uSW;

    /// @brief  Padding: top, left, bottom and right.
    ETL_UINT32    uPT, uPL, uPB, uPR;

    /// @brief  Dilations.
    ETL_UINT32    uDH, uDW;

    /// @brief  Output height and width.
    ETL_UINT32    uOH, uOW;

    /// @brief  1 when the average counts the padding (count_include_pad).
    ETL_UINT32    uCountIncludePad;
};

ePool attributes (NCHW). There is no ceil mode field: the converter applies ONNX 'ceil_mode' to uOH and uOW, so the last windows can go past the padding (as in ONNX).

enum

EPadMode

Ethereal::Ml::Neural#
C++
enum class   EPadMode : ETL_UINT32
{
    /// @brief  Fills with fValue.
    eConstant = 0,

    /// @brief  Mirrors the data without repeating the edge.
    eReflect,

    /// @brief  Repeats the edge value.
    eEdge
};

Mode of an ePad step.

struct

SPadAttr

Ethereal::Ml::Neural#
C++
struct   SPadAttr   final
{
    /// @brief  EPadMode.
    ETL_UINT32    eMode;

    /// @brief  Number of dimensions.
    ETL_UINT32    uRank;

    /// @brief  Input shape.
    ETL_UINT32    aIn[ NEURAL_MAX_RANK ];

    /// @brief  Padding before each axis.
    ETL_UINT32    aBefore[ NEURAL_MAX_RANK ];

    /// @brief  Padding after each axis.
    ETL_UINT32    aAfter[ NEURAL_MAX_RANK ];

    /// @brief  Fill value of eConstant.
    float        fValue;
};

ePad attributes. Each axis gets aBefore elements before and aAfter after (not negative).

enum

EResizeMode

Ethereal::Ml::Neural#
C++
enum class   EResizeMode : ETL_UINT32
{
    /// @brief  Nearest neighbour.
    eNearest = 0,

    /// @brief  Bilinear.
    eLinear
};

Mode of an eResize step.

struct

SResizeAttr

Ethereal::Ml::Neural#
C++
struct   SResizeAttr   final
{
    /// @brief  EResizeMode.
    ETL_UINT32    eMode;

    /// @brief  Input shape (N x C x H x W).
    ETL_UINT32    uN, uC, uH, uW;

    /// @brief  Output height and width.
    ETL_UINT32    uOH, uOW;

    /// @brief  Reserved, zero.
    ETL_UINT32    uReserved;
};

eResize attributes (NCHW, H and W only).

Input 1 is the table (weights) the converter computed. Nearest: one u32 source per output row (uOH) and per output column (uOW). Linear: per row (u32 y0, u32 y1, float weight of y1), and the same per column.

struct

SRnnAttr

Ethereal::Ml::Neural#
C++
struct   SRnnAttr   final
{
    /// @brief  Sequence length, batch, input size and hidden size.
    ETL_UINT32    uT, uB, uI, uH;

    /// @brief  1 or 2.
    ETL_UINT32    uDirections;

    /// @brief  With one direction: 1 for 'reverse'.
    ETL_UINT32    uReverse;

    /// @brief  GRU 'linear_before_reset'.
    ETL_UINT32    uLinearBeforeReset;

    /// @brief  Clip of the activation inputs. 0 means no clip.
    float        fClip;
};

eLstm and eGru attributes (ONNX semantics, one layer).

Inputs: X [T, B, I], W, R, bias [D, 2*G*H] (the ONNX one), sequence_lens [B] (int32), initial_h [D, B, H], initial_c [D, B, H] (LSTM) and P [D, 3*H] (LSTM). Outputs: Y [T, D, B, H], Y_h [D, B, H] and Y_c [D, B, H] (LSTM). G = 4 gates (iofc) or 3 (zrh).

W and R are packed as the GEMM B, per direction: W (I x G*HP) and R (H x G*HP), with each gate starting on a panel (HP = H rounded up to 16), so one gate alone is a single GEMM.

struct

SLayerNormAttr

Ethereal::Ml::Neural#
C++
struct   SLayerNormAttr   final
{
    /// @brief  Number of rows and row length.
    ETL_UINT32    uOuter, uN;

    /// @brief  Epsilon added to the variance.
    float        fEpsilon;

    /// @brief  1 when the bias input is present.
    ETL_UINT32    uHasBias;
};

eLayerNorm attributes. Normalizes the last uN positions of each of the uOuter rows.

struct

SQGemmAttr

Ethereal::Ml::Neural#
C++
struct   SQGemmAttr   final
{
    /// @brief  Rows of A, columns of B and the inner dimension.
    ETL_UINT32    uM, uN, uK;

    /// @brief  Fused EActivation and its two parameters.
    ETL_UINT32    eAct;
    float        fAct0, fAct1;

    /// @brief  Input scale and zero point.
    float        fInScale;
    ETL_INT32    iInZero;

    /// @brief  0: u8 input [0, 255]. 1: s8 input [-128, 127].
    ETL_UINT32    uInSigned;

    /// @brief  1 for per channel weight scales.
    ETL_UINT32    uPerChannel;

    /// @brief  1 when the bias input is present.
    ETL_UINT32    uHasBias;

    /// @brief  1 when all weights are in [-64, 63].
    ETL_UINT32    uWeights7;

    /// @brief  1 to requantize the output.
    ETL_UINT32    uRequantize;

    /// @brief  Output scale and zero point (uRequantize).
    float        fOutScale;
    ETL_INT32    iOutZero;

    /// @brief  0: u8 output. 1: s8 output.
    ETL_UINT32    uOutSigned;
};

eQGemm attributes.

A is float, quantized on input with a fixed scale and zero point (from calibration). The weights are symmetric int8 packed in groups of four, per tensor or per channel (N scales). Inputs: A, B int8, the scales (float, 1 or N), the column sums of B (int32, N) and bias (N) optional. With uRequantize the output goes through Q and DQ (as ONNX Runtime does in a QDQ model): y = (clamp(round(y/fOutScale) + iOutZero) - iOutZero) * fOutScale. uWeights7: all weights in [-64, 63] (the fast kernel, checked on load).

struct

SQConvAttr

Ethereal::Ml::Neural#
C++
struct   SQConvAttr   final
{
    /// @brief  Convolution shape.
    SConvAttr    Conv;

    /// @brief  Input scale and zero point.
    float        fInScale;
    ETL_INT32    iInZero;

    /// @brief  0: u8 input. 1: s8 input.
    ETL_UINT32    uInSigned;

    /// @brief  1 for per channel weight scales.
    ETL_UINT32    uPerChannel;

    /// @brief  1 when all weights are in [-64, 63].
    ETL_UINT32    uWeights7;

    /// @brief  1 to requantize the output.
    ETL_UINT32    uRequantize;

    /// @brief  Output scale and zero point (uRequantize).
    float        fOutScale;
    ETL_INT32    iOutZero;

    /// @brief  0: u8 output. 1: s8 output.
    ETL_UINT32    uOutSigned;

    /// @brief  Reserved, zero.
    ETL_UINT32    uReserved;
};

eQConv attributes.

The Conv with the input quantized (as in eQGemm) and symmetric int8 weights, per group W_g^T (K x M/g) packed as the eQGemm B. Inputs: X, W, the scales, the column sums and bias optional.

neural_format.hpp

#include <ethereal/cpp/ml/neural/neural_format.hpp>

File format of a neural model ('.etlnn').

Fixed width and little-endian, so the file is mapped and used as is. Layout: the header (128 bytes), the section table (24 bytes per section), then the sections, each aligned to 64 bytes.

Sections:

  • TENSORS: one SNeuralTensor (64 bytes) per tensor.
  • STEPS: one SNeuralStep (64 bytes) per plan step, in execution order.
  • ATTRS: step attributes, 32 bit words, one block per step.
  • WEIGHTS: the weights, each tensor aligned to 64 bytes and already in the layout the kernel expects.
  • IO: u32 input tensors, then u32 output tensors.
  • STRINGS: the names (UTF-8, no terminator). Each tensor points to its name by (offset, size).

All graph analysis belongs to the converter ('etl-neural', offline): shapes, constant folding, fusion, kernel choice and the arena plan. The client never reads ONNX. ONNX is protobuf, and a protobuf parser over hostile data is a liability in a security product. The loader only validates: each step must read and write inside its tensors, and each tensor must lie inside the arena, the weights or the caller's buffer.

The arena plan (lifetime of each tensor, reuse by size) also comes from the converter. The arena is a single allocation, made in the context, with the exact size from the header.

const

NEURAL_MAGIC

Ethereal::Ml::Neural#
constexpr ETL_UINT32 NEURAL_MAGIC = 0x4E4C5445u;

File magic, 'ETLN' in little-endian.

const

NEURAL_FORMAT_VERSION

Ethereal::Ml::Neural#
constexpr ETL_UINT16 NEURAL_FORMAT_VERSION = 1u;

Format version written and accepted by this build.

const

NEURAL_HEADER_SIZE

Ethereal::Ml::Neural#
constexpr ETL_UINT32 NEURAL_HEADER_SIZE = 128u;

Size of the file header, in bytes.

const

NEURAL_SECTION_ENTRY_SIZE

Ethereal::Ml::Neural#
constexpr ETL_UINT32 NEURAL_SECTION_ENTRY_SIZE = 24u;

Size of one section table entry, in bytes.

const

NEURAL_ALIGN

Ethereal::Ml::Neural#
constexpr ETL_UINT32 NEURAL_ALIGN = 64u;

Alignment of the sections, the weights and the arena tensors.

const

NEURAL_MAX_RANK

Ethereal::Ml::Neural#
constexpr ETL_UINT32 NEURAL_MAX_RANK = 6u;

Maximum rank of a tensor.

const

NEURAL_MAX_STEP_INPUTS

Ethereal::Ml::Neural#
constexpr ETL_UINT32 NEURAL_MAX_STEP_INPUTS = 8u;

Maximum number of inputs of a step.

const

NEURAL_MAX_STEP_OUTPUTS

Ethereal::Ml::Neural#
constexpr ETL_UINT32 NEURAL_MAX_STEP_OUTPUTS = 3u;

Maximum number of outputs of a step.

const

NEURAL_NO_TENSOR

Ethereal::Ml::Neural#
constexpr ETL_UINT32 NEURAL_NO_TENSOR = 0xFFFFFFFFu;

Marks an optional input or output that is absent.

enum

EDataType

Ethereal::Ml::Neural#
C++
enum class   EDataType : ETL_UINT8
{
    /// @brief  32 bit float.
    eFloat32 = 1,

    /// @brief  Unsigned 8 bit integer.
    eUInt8 = 2,

    /// @brief  Signed 8 bit integer.
    eInt8 = 3,

    /// @brief  Signed 32 bit integer.
    eInt32 = 4,

    /// @brief  16 bit float. Weights only, converted to float32 on load.
    eFloat16 = 5,

    /// @brief  Signed 64 bit integer. Indices only (Gather).
    eInt64 = 6
};

Element type of a tensor.

enum

EPlace

Ethereal::Ml::Neural#
C++
enum class   EPlace : ETL_UINT8
{
    /// @brief  At 'uOffset' inside the context arena.
    eArena = 0,

    /// @brief  At 'uOffset' inside the WEIGHTS section.
    eWeight = 1,

    /// @brief  In the caller's buffer. 'uIo' is the input number.
    eInput = 2,

    /// @brief  In the caller's buffer. 'uIo' is the output number.
    eOutput = 3
};

Where a tensor lives.

enum

EKernel

Ethereal::Ml::Neural#
C++
enum class   EKernel : ETL_UINT32
{
    /// Phase A: tabular and MLP.

    /// @brief  Y = act( A . B + bias ), with B weights already packed.
    eGemm = 1,

    /// @brief  A . B, both dynamic, with batch broadcasting.
    eMatMul = 2,

    /// @brief  Add, Sub, Mul or Div with numpy broadcasting.
    eBinary = 3,

    /// @brief  Relu, LeakyRelu, Sigmoid, Tanh or Clip.
    eUnary = 4,

    /// @brief  Softmax over one axis.
    eSoftmax = 5,

    /// @brief  Transpose and Slice: a strided copy.
    eStrided = 6,

    /// @brief  Concatenation along one axis.
    eConcat = 7,

    /// @brief  Gather, which is also the embedding lookup.
    eGather = 8,

    /// @brief  ReduceMean or ReduceSum.
    eReduce = 9,

    /// @brief  A Reshape that ends in an output.
    eCopy = 10,

    /// Phase B: convolution.

    /// @brief  Conv1d or Conv2d (im2col + GEMM), groups, folded BatchNorm.
    eConv = 20,

    /// @brief  Depthwise convolution.
    eDepthwise = 21,

    /// @brief  MaxPool, AveragePool or GlobalAveragePool.
    ePool = 22,

    /// @brief  Pad.
    ePad = 23,

    /// @brief  Resize.
    eResize = 24,

    /// Phase C: sequences.

    /// @brief  LSTM, one layer.
    eLstm = 30,

    /// @brief  GRU, one layer.
    eGru = 31,

    /// @brief  Layer normalization.
    eLayerNorm = 32,

    /// Quantized (int8).

    /// @brief  Int8 GEMM.
    eQGemm = 40,

    /// @brief  Int8 convolution.
    eQConv = 41
};

The kernels. Each one has its attribute block (neural_attrs.hpp) and its validator.

enum

EActivation

Ethereal::Ml::Neural#
C++
enum class   EActivation : ETL_UINT32
{
    /// @brief  No activation.
    eNone = 0,

    /// @brief  ReLU.
    eRelu,

    /// @brief  Leaky ReLU. fParam0 is the slope.
    eLeakyRelu,

    /// @brief  Sigmoid.
    eSigmoid,

    /// @brief  Hyperbolic tangent.
    eTanh,

    /// @brief  Clip. fParam0 and fParam1 are the minimum and the maximum.
    eClip,

    /// @brief  The QuantizeLinear -> DequantizeLinear pair of a QDQ model, in u8.
    ///             fParam0 is the scale and fParam1 the zero point:
    ///             (clamp(round(x / s) + z) - z) * s.
    eQuantDequantU8,

    /// @brief  Same as eQuantDequantU8, in s8.
    eQuantDequantS8
};

Activation fused into a Gemm, a Conv or a Binary.

enum

ESection

Ethereal::Ml::Neural#
C++
enum class   ESection : ETL_UINT32
{
    /// @brief  Tensor table.
    eTensors = 1,

    /// @brief  Plan steps.
    eSteps = 2,

    /// @brief  Step attributes.
    eAttrs = 3,

    /// @brief  Weights.
    eWeights = 4,

    /// @brief  Model inputs and outputs.
    eIo = 5,

    /// @brief  Tensor names.
    eStrings = 6
};

Section identifiers.

const

NEURAL_SECTION_REQUIRED

Ethereal::Ml::Neural#
constexpr ETL_UINT32 NEURAL_SECTION_REQUIRED = 1u;

Section flag: a loader that does not know the section must refuse the file.

enum

EQuantScheme

Ethereal::Ml::Neural#
C++
enum class   EQuantScheme : ETL_UINT32
{
    /// @brief  Everything in float32.
    eFloat32 = 0,

    /// @brief  Int8 quantized.
    eInt8 = 1,

    /// @brief  Float16 weights, float32 compute.
    eFloat16Weights = 2,

    /// @brief  Mixed precision.
    eMixed = 3
};

Quantization scheme of the model. Informative only, each step states its own.

struct

SNeuralFileHeader

Ethereal::Ml::Neural#
C++
struct   SNeuralFileHeader   final
{
    /// @brief  NEURAL_MAGIC.
    ETL_UINT32    uMagic;

    /// @brief  NEURAL_FORMAT_VERSION.
    ETL_UINT16    uFormatVersion;

    /// @brief  NEURAL_HEADER_SIZE.
    ETL_UINT16    uHeaderSize;

    /// @brief  ONNX opset the model came from.
    ETL_UINT32    uOpset;

    /// @brief  EQuantScheme.
    ETL_UINT32    eQuantScheme;

    /// @brief  FNV-1a of TENSORS, STEPS, ATTRS and IO, checked on load.
    ETL_UINT64    uGraphHash;

    /// @brief  Number of tensors, steps, inputs and outputs.
    ETL_UINT32    uTensorCount;
    ETL_UINT32    uStepCount;
    ETL_UINT32    uInputCount;
    ETL_UINT32    uOutputCount;

    /// @brief  Exact arena size (the converter's plan).
    ETL_UINT64    uArenaBytes;

    /// @brief  Kernel scratch (packing, im2col), per thread.
    ETL_UINT64    uScratchBytes;

    /// @brief  Number of entries in the section table.
    ETL_UINT32    uSectionCount;

    /// @brief  Reserved, zero.
    ETL_UINT32    uReserved0;

    /// @brief  Offset of the section table.
    ETL_UINT64    uSectionTableOffset;

    /// @brief  Size of the whole file.
    ETL_UINT64    uFileSize;

    /// @brief  Hash of the feature spec (Ml::Features). Zero when there is none.
    ETL_UINT64    uSpecHash;

    /// @brief  Reserved, zero.
    ETL_UINT8    aReserved[ 40 ];
};

File header, 128 bytes.

struct

SNeuralSectionEntry

Ethereal::Ml::Neural#
C++
struct   SNeuralSectionEntry   final
{
    /// @brief  ESection.
    ETL_UINT32    uId;

    /// @brief  Flags (NEURAL_SECTION_REQUIRED).
    ETL_UINT32    uFlags;

    /// @brief  Offset of the section in the file.
    ETL_UINT64    uOffset;

    /// @brief  Size of the section, in bytes.
    ETL_UINT64    uSize;
};

One entry of the section table, 24 bytes.

enum

EQuant

Ethereal::Ml::Neural#
C++
enum class   EQuant : ETL_UINT8
{
    /// @brief  Not quantized.
    eNone = 0,

    /// @brief  One scale (fScale) and one zero point (iZeroPoint).
    ePerTensor = 1,

    /// @brief  Per channel. The loader accepts the value and no kernel reads it: the
    ///             per channel scales of QGemm and QConv are separate weight tensors
    ///             (the '::escalas' and '::somas' inputs of the step).
    ePerChannel = 2
};

Quantization of a tensor.

struct

SNeuralTensor

Ethereal::Ml::Neural#
C++
struct   SNeuralTensor   final
{
    /// @brief  EDataType.
    ETL_UINT8    eType;

    /// @brief  Number of dimensions.
    ETL_UINT8    uRank;

    /// @brief  EPlace.
    ETL_UINT8    ePlace;

    /// @brief  EQuant.
    ETL_UINT8    eQuant;

    /// @brief  Input or output number (eInput or eOutput).
    ETL_UINT32    uIo;

    /// @brief  Dimensions. Unused ones are zero.
    ETL_UINT32    aDims[ NEURAL_MAX_RANK ];

    /// @brief  Offset in the arena or in the weights.
    ETL_UINT64    uOffset;

    /// @brief  Product of the dimensions times the type size (checked).
    ETL_UINT64    uBytes;

    /// @brief  Quantization scale.
    float        fScale;

    /// @brief  Quantization zero point.
    ETL_INT32    iZeroPoint;

    /// @brief  Offset of the name in STRINGS.
    ETL_UINT32    uNameOffset;

    /// @brief  Size of the name, in bytes.
    ETL_UINT32    uNameSize;
};

A tensor, 64 bytes.

struct

SNeuralStep

Ethereal::Ml::Neural#
C++
struct   SNeuralStep   final
{
    /// @brief  EKernel.
    ETL_UINT32    eKernel;

    /// @brief  Offset of the attributes in ATTRS, in words.
    ETL_UINT32    uAttrOffset;

    /// @brief  Size of the attributes, in words.
    ETL_UINT32    uAttrWords;

    /// @brief  Number of inputs and outputs.
    ETL_UINT8    uInputs;
    ETL_UINT8    uOutputs;

    /// @brief  Reserved, zero.
    ETL_UINT16    uReserved;

    /// @brief  Input tensors. NEURAL_NO_TENSOR marks an absent optional input.
    ETL_UINT32    aIn[ NEURAL_MAX_STEP_INPUTS ];

    /// @brief  Output tensors.
    ETL_UINT32    aOut[ NEURAL_MAX_STEP_OUTPUTS ];

    /// @brief  Reserved, zero.
    ETL_UINT32    uReserved2;
};

A plan step, 64 bytes.

neural_model.hpp

#include <ethereal/cpp/ml/neural/neural_model.hpp>

Ml::Neural: inference of small networks, inside the binary, with no dependencies (spec 33).

Scope: tabular models, MLPs, small convolutional networks, LSTM and GRU, with little memory, a small binary footprint and hardened loading. It does not run large language models and does not compete with ONNX Runtime in coverage. The operator set is fixed, and a missing operator is a converter error that names it, never a surprise at run time.

The model is converted offline from ONNX ('etl-neural convert'). The client only reads the native format (neural_format.hpp), mapped and validated, with no parsing.

No allocations during inference. The graph is static and so is the arena plan (made by the converter). CNeuralContext allocates the arena, the scratch and the pointer table once, and Run allocates nothing. Use one context per thread that runs inferences at the same time. The model is read only and can be shared.

The plan is a flat table of function pointers with the argument block of each step, built once on load (the SIMD path is also chosen once). There is no virtual dispatch per operator per inference.

struct

IParallelFor

Ethereal::Ml::Neural#
C++
struct   IParallelFor
{
    /// @brief  Number of workers available.
    ///
    virtual ETL_UINT32 Workers() const ETL_NOEXCEPT = 0;


    ///
    /// Run
    ///
    /// @brief  Runs pFn for every task and waits for all of them.
    ///
    /// @param uTasks    Number of tasks.
    /// @param pFn        Task function, called with pCtx and the task index.
    /// @param pCtx        Context passed to every call.
    ///
    virtual void Run( ETL_UINT32 uTasks, void ( *pFn )( void * pCtx, ETL_UINT32 uTask ) ETL_NOEXCEPT, void * pCtx ) ETL_NOEXCEPT = 0;


    /// @brief  Destructor.
    ///
    virtual ~IParallelFor() = default;
};

Thread seam. The integrator spreads the tasks over its own threads.

The module never creates threads. Run only returns when all tasks are done.

enum

EKernelPath

Ethereal::Ml::Neural#
C++
enum class   EKernelPath : ETL_UINT32
{
    /// @brief  Portable scalar code.
    eScalar = 0,

    /// @brief  SSE4.1.
    eSse41,

    /// @brief  AVX2 with FMA.
    eAvx2
};

SIMD path chosen by the plan.

struct

STensorInfo

Ethereal::Ml::Neural#
C++
struct   STensorInfo   final
{
    /// @brief  Tensor name.
    std::string_view    sName;

    /// @brief  Element type.
    EDataType            eType = EDataType::eFloat32;

    /// @brief  Number of dimensions.
    ETL_UINT32            uRank = 0u;

    /// @brief  Dimensions. Unused ones are zero.
    ETL_UINT32            aDims[ NEURAL_MAX_RANK ] = {};

    /// @brief  Size in bytes.
    ETL_UINT64            uBytes = 0u;

    /// @brief  Scale of a tensor quantized at the boundary.
    float                fScale = 0.0f;

    /// @brief  Zero point of a tensor quantized at the boundary.
    ETL_INT32            iZeroPoint = 0;
};

Description of a model input, output or tensor.

class

CNeuralModel

Ethereal::Ml::Neural#

A loaded and validated '.etlnn' model. Read only after load.

class CNeuralModel final
constructor

CNeuralModel

#
CNeuralModel() noexcept;

Default constructor. The model is empty until Load or LoadFile.

constructor

CNeuralModel

#
CNeuralModel( CNeuralModel && Other ) noexcept;

Move constructor. Other is left empty.

operator

operator=

#
CNeuralModel & operator=( CNeuralModel && Other ) noexcept;

Move assignment. Other is left empty.

function

Load

#
static EStatus Load( std::span< const ETL_UINT8 > Bytes, CNeuralModel * pOut );

Validates and prepares a model that is already in memory (the ModelGuard one, for example).

Bytes
The model. Must outlive the model and is never written. Aligned to 64.
pOut
Receives the model.
eOk, eInvalidArgument, eOutOfMemory or the validation error. EStatus::eNotLicensed when the library is not licensed.
function

LoadFile

#
static EStatus LoadFile( std::string_view sPath, CNeuralModel * pOut );

Maps the file read only, then validates it as Load does.

sPath
File path.
pOut
Receives the model.
eOk, eInvalidArgument, eIoError, eOutOfMemory or the validation error. EStatus::eNotLicensed when the library is not licensed.
function

IsLoaded

#
bool IsLoaded() const noexcept;

true when a model is loaded.

function

InputCount

#
ETL_UINT32 InputCount() const noexcept;

Number of model inputs.

function

OutputCount

#
ETL_UINT32 OutputCount() const noexcept;

Number of model outputs.

function

Input

#
EStatus Input( ETL_UINT32 u, STensorInfo * pOut ) const noexcept;

Describes one model input.

u
Input number.
pOut
Receives the description.
eOk, eNotLoaded or eInvalidArgument.
function

Output

#
EStatus Output( ETL_UINT32 u, STensorInfo * pOut ) const noexcept;

Describes one model output.

u
Output number.
pOut
Receives the description.
eOk, eNotLoaded or eInvalidArgument.
function

ArenaBytes

#
ETL_UINT64 ArenaBytes() const noexcept;

Exact arena size (the converter's plan), per context.

function

ScratchBytes

#
ETL_UINT64 ScratchBytes() const noexcept;

Scratch size, per context.

function

StepCount

#
ETL_UINT32 StepCount() const noexcept;

Number of steps of the built plan (for inspection).

function

StepKernel

#
EKernel StepKernel( ETL_UINT32 u ) const noexcept;

Kernel of step u of the plan.

function

Path

#
EKernelPath Path() const noexcept;

SIMD path chosen on load.

function

GraphHash

#
ETL_UINT64 GraphHash() const noexcept;

Graph hash (the header one, checked on load).

function

SpecHash

#
ETL_UINT64 SpecHash() const noexcept;

Hash of the feature spec. Zero when there is none.

struct

IStepObserver

Ethereal::Ml::Neural#
C++
struct   IStepObserver
{
    ///
    /// AfterStep
    ///
    /// @brief  Called after each step of Run.
    ///
    /// @param uStep    Step that just ran.
    /// @param Ctx        Context. TensorData and TensorInfo are valid during the call.
    ///
    virtual void AfterStep( ETL_UINT32 uStep, const CNeuralContext & Ctx ) ETL_NOEXCEPT = 0;


    /// @brief  Destructor.
    ///
    virtual ~IStepObserver() = default;
};

Observer used by the converter to calibrate. Called after each step, with the tensors of that step.

class

CNeuralContext

Ethereal::Ml::Neural#

Runs inferences of a model. One context per thread.

class CNeuralContext final
constructor

CNeuralContext

#
CNeuralContext() noexcept;

Default constructor. Call Init before use.

function

Init

#
EStatus Init( const CNeuralModel & Model, IParallelFor * pParallel = nullptr );

Allocates the arena, the scratch and the pointer table.

Model
The model. Must outlive the context.
pParallel
Thread seam, one scratch per task. May be null.
eOk, eNotLoaded or eOutOfMemory. EStatus::eNotLicensed when the library is not licensed.
function

Run

#
EStatus Run( std::span< const void * const > Inputs, std::span< void * const > Outputs ) noexcept;

Runs one inference. Allocates nothing.

Inputs
Input buffers in signature order, each with the bytes it declares.
Outputs
Output buffers in signature order, each with the bytes it declares.
eOk, eNotLoaded, eInvalidArgument or the error of a kernel.
function

SetObserver

#
void SetObserver( IStepObserver * pObserver ) noexcept;

Sets an observer called after each step (to calibrate). Null removes it.

pObserver
The observer, or null.
function

TensorData

#
const void * TensorData( ETL_UINT32 uTensor ) const noexcept;

Data of tensor uTensor. Valid during AfterStep.

function

TensorInfo

#
EStatus TensorInfo( ETL_UINT32 uTensor, STensorInfo * pOut ) const noexcept;

Describes tensor uTensor.

uTensor
Tensor index.
pOut
Receives the description.
eOk, eNotLoaded or eInvalidArgument.
function

MemoryUsage

#
std::size_t MemoryUsage() const noexcept;

Bytes allocated by the context.