Ai::Embed

Beta

Embedding models that run locally on the CPU, offline, with scalar and AVX2 kernels, int8 quantization and GGUF files from llama.cpp. Multilingual, including Portuguese.

Optional module: turn it on with -DETHEREAL_AI_EMBED=ONInclude #include <ethereal/cpp/ai/embed/embed_inc.hpp>C layer

embed_inc.hpp

#include <ethereal/cpp/ai/embed/embed_inc.hpp>

The whole of Ai::Embed.

embed_model.hpp

#include <ethereal/cpp/ai/embed/embed_model.hpp>

Ai::Embed: local CPU inference of text embedding models (BERT and XLM-RoBERTa encoders), offline, with no dependency.

C++
Embed::SModelConfig Config;
Embed::CModel Model;
Embed::CModel::LoadEtlemb( "minilm.etlemb", Config, &Model );
Embed::CSession Session;                    /// one per thread
Session.Init( Model );                      /// the only allocation
float aVector[ 384 ];
Model.Embed( "query: how do I reset it?", Session, aVector );

A model is immutable once loaded and is shared by every thread. The weights of an .etlemb are mapped read only, so several processes share them. A session is the workspace of one thread: sized once for the longest text and the largest batch, and no call allocates after its first one.

The pipeline: the tokenizer of the model (Ai::Tokenizer), the word, position and type embeddings, the encoder layers (attention, residual, LayerNorm, feed forward with GELU), the pooling (mean or the first token), and the L2 normalization. Instruction prefixes ("query: " and "passage: " for E5, the instruction of BGE for queries) are part of the text the caller gives: the Ai::Embed page of the SDK documentation (docs/modules/ai-embed.md) lists them per model.

Determinism: the same text, instruction set and model give the same bits, whatever the number of threads and whether the text is embedded alone or in a batch.

class

CModel

Ethereal::Ai::Embed#

A loaded model: immutable, shared by every thread.

class CModel
constructor

CModel

#
CModel() noexcept = default;
function

LoadSafetensors

#
static EStatus LoadSafetensors( std::string_view sModelDir, const SModelConfig & Config, CModel * pOut ) noexcept;

Loads a model folder as Hugging Face publishes it: config.json, model.safetensors and tokenizer.json, with the files of sentence-transformers when present (sentence_bert_config.json, modules.json, 1_Pooling/config.json).

The weights are packed for the kernels (a copy in memory). With SModelConfig::ePrecision eInt8 they are quantized here.

eOk, eInvalidArgument, eIoError, eFormatError, eUnsupported, eTokenizerError, eOutOfMemory, eNotLicensed.
function

LoadEtlemb

#
static EStatus LoadEtlemb( std::string_view sPath, const SModelConfig & Config, CModel * pOut ) noexcept;

Loads an .etlemb (ConvertToEtlemb): the file is mapped read only, its checksum and every tensor are checked, and the weights are used where they are (already packed).

eOk, eInvalidArgument, eIoError, eFormatError, eChecksumMismatch, eUnsupported, eTokenizerError, eOutOfMemory, eNotLicensed.
function

LoadGguf

#
static EStatus LoadGguf( std::string_view sPath, const SModelConfig & Config, CModel * pOut ) noexcept;

Loads a GGUF file (llama.cpp) of the "bert" architecture: BERT encoders and the XLM-RoBERTa ones as convert_hf_to_gguf.py writes them.

The tensors may be F32, F16, BF16, Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, Q2_K, Q3_K, Q4_K, Q5_K or Q6_K. They are decoded with the arithmetic of ggml and packed as LoadSafetensors packs them (SModelConfig::ePrecision applies, eInt8 calibrates the smoothing on the decoded weights). The token table stays in the mapped file: F32 and F16 as they are, the quantized types decoded one row at a time.

The tokenizer is rebuilt from the metadata: "bert" becomes WordPiece (the phantom space of the converter turned back into "##"), "t5" becomes the Unigram of SentencePiece with its compiled character map.

What a GGUF does not say: the activation is the exact GELU (as the Hugging Face model, where llama.cpp uses the tanh one), the vectors are normalized (the llama.cpp default, ENormalize::eOff turns it off), and the maximum length is bert.context_length (the max_seq_length of sentence-transformers is lost: SModelConfig::uMaxSeqLen sets it).

eOk, eInvalidArgument, eIoError, eFormatError, eUnsupported (another architecture, a tensor type outside the list, a big-endian file), eTokenizerError, eOutOfMemory, eNotLicensed.
function

LoadGgufFromMemory

#
static EStatus LoadGgufFromMemory( const void * pData, std::size_t uSize, const SModelConfig & Config, CModel * pOut ) noexcept;

A GGUF in memory. The bytes must outlive the model (the token table and the aligned F32 vectors are used where they are).

function

LoadEtlembFromMemory

#
static EStatus LoadEtlembFromMemory( const void * pData, std::size_t uSize, const SModelConfig & Config, CModel * pOut ) noexcept;

An .etlemb in memory. The bytes must outlive the model (they are not copied) and be aligned to 64.

function

Unload

#
void Unload( void ) noexcept;

Frees the model (the sessions made from it must be gone).

function

IsLoaded

#
bool IsLoaded( void ) const noexcept
function

Dimensions

#
ETL_UINT32 Dimensions( void ) const noexcept;

The dimensions of the vectors (zero when not loaded).

function

Info

#
const SModelInfo & Info( void ) const noexcept;
function

Isa

#
EIsa Isa( void ) const noexcept;

The instruction set the kernels use.

function

GetTokenizer

#
const Tokenizer::CTokenizer & GetTokenizer( void ) const noexcept;

The tokenizer of the model.

function

OwnedBytes

#
std::size_t OwnedBytes( void ) const noexcept;

Bytes the model allocated (the packed weights). The mapped file is not counted.

function

Embed

#
EStatus Embed( std::string_view sText, CSession & Session, float * pOut ) const noexcept;

The vector of one text: Dimensions() floats in pOut.

eOk, eInvalidArgument (a session of another model, a null), eLimitExceeded (a text over the limit with ETruncation::eError), eTokenizerError.
function

EmbedBatch

#
EStatus EmbedBatch( const std::string_view * pTexts, std::size_t uCount, CSession & Session, float * pOut ) const noexcept;

The vectors of uCount texts, in their order: uCount x Dimensions() floats in pOut. The texts are packed with no padding, and each vector is the one Embed gives for that text, bit for bit.

As Embed, and eLimitExceeded for more texts than SModelConfig::uMaxBatch.
function

EmbedTokens

#
EStatus EmbedTokens( const ETL_UINT32 * pIds, std::size_t uCount, CSession & Session, float * pOut ) const noexcept;

The vector of a text already tokenized (the special tokens included, at most the maximum length).

function

Tokenize

#
EStatus Tokenize( std::string_view sText, CSession & Session, const ETL_UINT32 ** ppIds, std::size_t * pCount ) const noexcept;

The ids the model sees for a text (truncated, with the special tokens). The view lives until the next call with Session.

function

TraceLayers

#
EStatus TraceLayers( std::string_view sText, CSession & Session, float * pOut, std::size_t uCapacity, std::size_t * pTokens ) const noexcept;

The hidden states of one text after the embeddings and after each layer, for the tests that find where a model diverges: (layers + 1) x tokens x Dimensions() floats in pOut.

uCapacity
Floats that fit in pOut.
pTokens
Receives the tokens of the text.
eOk, eBufferTooSmall (pTokens says the tokens), and as Embed.
class

CSession

Ethereal::Ai::Embed#

The workspace of one thread for one model.

class CSession
constructor

CSession

#
CSession() noexcept = default;
function

Init

#
EStatus Init( const CModel & Model ) noexcept;

Sizes the workspace for Model (its longest text and largest batch). The model must outlive the session.

eOk, eInvalidArgument (a model not loaded), eOutOfMemory.
function

ReservedBytes

#
std::size_t ReservedBytes( void ) const noexcept;

Bytes of the workspace.

function

ConvertToEtlemb

Ethereal::Ai::Embed#
EStatus ConvertToEtlemb( std::string_view sModelDir, EPrecision ePrecision, std::string_view sOutPath ) noexcept;

Converts a model folder (as LoadSafetensors reads it), or a path ending in ".gguf" (as LoadGguf reads it), to one .etlemb file: the tokenizer, the configuration and the packed weights in ePrecision, aligned to 64, with a version and a CRC-32C. The file is written next to the destination and renamed over it, so a failure leaves no half file.

eOk, and the errors of LoadSafetensors and eIoError.
function

SaveEtlemb

Ethereal::Ai::Embed#
EStatus SaveEtlemb( const CModel & Model, EPrecision ePrecision, std::string_view sOutPath ) noexcept;

Writes a loaded model as an .etlemb. A model loaded in int8 can only be written in int8 (eUnsupported otherwise).

embed_types.hpp

#include <ethereal/cpp/ai/embed/embed_types.hpp>

Types of Ai::Embed: the status codes, the precisions, the pooling, the instruction sets, and the configuration and description of a model.

enum

EStatus

Ethereal::Ai::Embed#
C++
enum class   EStatus : ETL_UINT8
{
    eOk = 0,
    eInvalidArgument,        /// A null, an empty text where one is needed, a value out of range.
    eOutOfMemory,
    eNotLicensed,
    eIoError,                /// A file could not be opened, read, mapped or written.
    eFormatError,            /// A file that is not what it says (a bad header, a missing tensor, a wrong shape).
    eChecksumMismatch,        /// An .etlemb whose content does not match its checksum.
    eUnsupported,            /// A model the module does not run (an architecture, an activation, a dtype).
    eLimitExceeded,            /// More texts than the session holds, or a text over the limit with ETruncation::eError.
    eBufferTooSmall,
    eTokenizerError            /// The tokenizer refused the text (invalid UTF-8 included).
};

The result of the functions of the module.

function

StatusName

Ethereal::Ai::Embed#
const char * StatusName( EStatus eStatus ) noexcept;

The name of a status, in English.

enum

EPrecision

Ethereal::Ai::Embed#
C++
enum class   EPrecision : ETL_UINT8
{
    eFp32 = 0,        /// The reference.
    eInt8,            /// Weights int8 per output channel (symmetric), activations int8 per row, int32 sums.
    eFp16            /// Storage only (.etlemb): the weights are widened to fp32 when the model loads.
};

The precision of the weights of the linear layers.

enum

EPooling

Ethereal::Ai::Embed#
C++
enum class   EPooling : ETL_UINT8
{
    eMean = 0,        /// The mean of the tokens of the text (the special ones included).
    eCls            /// The vector of the first token.
};

How the token vectors become the text vector.

enum

EActivation

Ethereal::Ai::Embed#
C++
enum class   EActivation : ETL_UINT8
{
    eGelu = 0,        /// The exact one, with erf ("gelu").
    eGeluTanh        /// The tanh approximation ("gelu_new", "gelu_pytorch_tanh").
};

The activation of the feed forward layers.

enum

EArchitecture

Ethereal::Ai::Embed#
C++
enum class   EArchitecture : ETL_UINT8
{
    eBert = 0,
    eXlmRoberta
};

The encoder family. They differ in the positions (XLM-RoBERTa starts after the padding id).

enum

EIsa

Ethereal::Ai::Embed#
C++
enum class   EIsa : ETL_UINT8
{
    eScalar = 0,
    eAvx2,            /// AVX2 and FMA.
    eAvx512,        /// AVX-512 F, BW, DQ and VL.
    eAvx512Vnni,    /// The above and VNNI (the int8 sums).
    eNeon,
    eNeonDot        /// NEON and SDOT (the int8 sums).
};

The instruction sets of the kernels, from the simplest. EIsa::eScalar is always compiled and is the oracle of the others.

function

IsaName

Ethereal::Ai::Embed#
const char * IsaName( EIsa eIsa ) noexcept;

The name of an instruction set ("avx2").

function

BestIsa

Ethereal::Ai::Embed#
EIsa BestIsa( EIsa eCap = EIsa::eNeonDot ) noexcept;

The best instruction set this machine runs, capped by eCap.

enum

ETruncation

Ethereal::Ai::Embed#
C++
enum class   ETruncation : ETL_UINT8
{
    eTruncate = 0,    /// Cut at the maximum length (the special tokens kept), as sentence-transformers.
    eError            /// Refused with EStatus::eLimitExceeded.
};

What happens to a text longer than the maximum length.

enum

ENormalize

Ethereal::Ai::Embed#
C++
enum class   ENormalize : ETL_UINT8
{
    eModel = 0,        /// As the model says (the Normalize module of sentence-transformers).
    eOn,
    eOff
};

Whether the text vector is normalized (L2).

struct

SModelConfig

Ethereal::Ai::Embed#
C++
struct   SModelConfig
{
    /// @brief  LoadSafetensors: eInt8 quantizes the weights while loading. LoadEtlemb
    ///             ignores it (the file says).
    EPrecision                ePrecision = EPrecision::eFp32;

    /// @brief  LoadSafetensors with eInt8: the migration strength of the smoothing
    ///             (SmoothQuant), from 0 to 1. Each input channel of each linear layer gets a
    ///             power of two s, the weights are multiplied by s and the activations divided
    ///             by it before the row quantization, which keeps the outlier channels from
    ///             taking the whole range of a row. s comes from a fixed calibration run of
    ///             the model in fp32 at load time. Zero turns it off. The .etlemb keeps the
    ///             factors, so LoadEtlemb ignores this field.
    float                    fSmoothAlpha = 0.5f;

    /// @brief  The longest text, in tokens (the special ones included). Zero takes the
    ///             one of the model (the max_seq_length of sentence-transformers, or the
    ///             positions of the model).
    ETL_UINT32                uMaxSeqLen = 0u;

    /// @brief  The most texts of one EmbedBatch.
    ETL_UINT32                uMaxBatch = 32u;

    /// @brief  The most tokens one forward pass holds (the size of the workspace of a
    ///             session). A batch with more is run in several passes, with the same
    ///             bits. Zero is 8 times the maximum length.
    ETL_UINT32                uMaxBatchTokens = 0u;

    /// @brief  The threads of the job system for the calls. Null runs on the calling
    ///             thread. The module never creates threads.
    Job::IParallelFor *        pParallel = nullptr;

    /// @brief  The best instruction set the kernels may use (tests force the others).
    EIsa                    eMaxIsa = EIsa::eNeonDot;

    ETruncation                eTruncation = ETruncation::eTruncate;
    ENormalize                eNormalize = ENormalize::eModel;

    /// @brief  The allocator of the weights and of the workspaces. Null is the default.
    Memory::IAllocator *    pAlloc = nullptr;
};

How a model is loaded and run.

struct

SModelInfo

Ethereal::Ai::Embed#
C++
struct   SModelInfo
{
    EArchitecture    eArchitecture = EArchitecture::eBert;
    EPrecision        ePrecision = EPrecision::eFp32;
    EActivation        eActivation = EActivation::eGelu;
    EPooling        ePooling = EPooling::eMean;
    bool            bNormalize = true;        /// The model's own choice (see ENormalize).
    bool            bLowerCase = false;        /// The text is lowercased first (do_lower_case).
    ETL_UINT32        uHidden = 0u;            /// The dimensions of the vectors.
    ETL_UINT32        uLayers = 0u;
    ETL_UINT32        uHeads = 0u;
    ETL_UINT32        uIntermediate = 0u;
    ETL_UINT32        uVocab = 0u;
    ETL_UINT32        uMaxPositions = 0u;
    ETL_UINT32        uTypeVocab = 0u;
    ETL_UINT32        uPadId = 0u;
    ETL_UINT32        uMaxSeqLen = 0u;        /// The one in use (see SModelConfig::uMaxSeqLen).
    float            fLayerNormEps = 1e-12f;
};

What a loaded model is.