What it does
- Runs locally on the CPU, offline
- Scalar and AVX2 kernels, plus AVX-512 and NEON ones that are compiled and not yet measured
- int8 quantization
- Loads GGUF files from llama.cpp, quantized types included
- Multilingual models, including Portuguese
Measured
- fp32 against PyTorch: cosine of at least 0.99999
- int8 against fp32 on four models: mean cosine of at least 0.9979, minimum of at least 0.9923
- GGUF: decoding bit-identical to ggml, and F32 gives the same bits as the Hugging Face folder
Known limits
- BERT and XLM-RoBERTa encoders only. No GPU, no generative models, no cross-encoders
- The AVX-512, VNNI, SDOT and NEON kernels are compiled and were never run on the measurement machine
- The int8 vector is not bit-identical across instruction sets
Ethereal::Ai::Embed · off by default
Local inference of text embedding models on the CPU, offline and with no external dependency. The module runs the whole pipeline of a BERT family encoder: the model's own tokenizer (through [Ai::Tokenizer](ai-tokenizer.md)), the word, position and type embeddings, the encoder layers (attention, LayerNorm, feed forward with GELU), the pooling and the L2 normalization. Weights run in fp32 or int8, on scalar, AVX2, AVX-512 (and VNNI) and NEON (and SDOT) kernels, chosen at run time from what the CPU supports.
A model loads from three sources: a Hugging Face model folder, the library's own .etlemb file (produced by the etl-embed tool), or a GGUF file of the llama.cpp bert architecture. Model files are not part of the SDK. You supply the model.
The module is optional: -DETHEREAL_AI_EMBED=ON, which requires ETHEREAL_AI_TOKENIZER. CMake stops with the reason when the tokenizer is off.
#include <ethereal/cpp/ai/embed/embed_inc.hpp>
namespace Embed = Ethereal::Ai::Embed;
Embed::SModelConfig Config; // fp32, up to 32 texts per batch, best kernels
Embed::CModel Model;
if( Embed::CModel::LoadEtlemb( "minilm.etlemb", Config, &Model ) != Embed::EStatus::eOk )
return 1; // or LoadSafetensors( "models/all-MiniLM-L6-v2", ... )
Embed::CSession Session; // one per thread: the workspace, the only allocation
Session.Init( Model );
std::vector< float > v( Model.Dimensions() );
Model.Embed( "how do I reset the password?", Session, v.data() );
std::string_view aTexts[] = { "first passage", "second passage" };
std::vector< float > m( 2 * Model.Dimensions() );
Model.EmbedBatch( aTexts, 2, Session, m.data() ); // the same bits as two calls to EmbedAlways include embed_inc.hpp: it brings in the module in the right order.
---
Models
| Item | Supported |
|---|---|
| Architectures | BERT and XLM-RoBERTa encoders (EArchitecture::eBert, eXlmRoberta) |
| Activation | exact GELU (gelu) and the tanh approximation (gelu_new, gelu_pytorch_tanh) |
| Pooling | mean of the tokens or the first token (EPooling::eMean, eCls) |
| Tokenizers | WordPiece and SentencePiece Unigram, as Ai::Tokenizer reads them |
| Precision | fp32, int8, and fp16 as storage only |
Four published models are measured against their PyTorch reference (see "Accuracy"). The instruction prefixes are part of the text you pass. A wrong prefix changes the vector without any error, so they are not added for you:
| Model | Query prefix | Document prefix |
|---|---|---|
| all-MiniLM-L6-v2 | none | none |
| bge-small-en-v1.5 | Represent this sentence for searching relevant passages: | none |
| e5-small-v2, multilingual-e5-small | query: | passage: |
Not supported: GPU, generative models, cross-encoders.
---
The API
| Piece | What it does |
|---|---|
CModel::LoadSafetensors( dir, Config, &Model ) | a Hugging Face folder: config.json, model.safetensors, tokenizer.json, plus sentence_bert_config.json, modules.json and 1_Pooling/config.json when present. The weights are packed for the kernels (a copy in memory) |
CModel::LoadEtlemb( path, Config, &Model ) | an .etlemb, mapped read only, checksum and every tensor checked, weights used in place |
CModel::LoadGguf( path, Config, &Model ) | a GGUF file (see "GGUF") |
LoadEtlembFromMemory / LoadGgufFromMemory | the same from a buffer that outlives the model (an .etlemb buffer aligned to 64) |
Embed( text, Session, pOut ) | the vector of one text: Dimensions() floats |
EmbedBatch( pTexts, uCount, Session, pOut ) | uCount vectors in order. Each one is bit for bit what Embed gives for that text |
EmbedTokens( pIds, uCount, Session, pOut ) | the vector of text already tokenized (special tokens included) |
Tokenize( text, Session, &pIds, &uCount ) | the ids the model sees, truncated, with the special tokens |
TraceLayers( ... ) | the hidden states after the embeddings and after each layer, to find where a model diverges |
Dimensions(), Info(), Isa(), GetTokenizer(), OwnedBytes(), IsLoaded(), Unload() | description of the loaded model |
CSession::Init( Model ) / ReservedBytes() | sizes the workspace of one thread for one model |
ConvertToEtlemb( dir or .gguf, ePrecision, out ) | writes an .etlemb from a folder or a GGUF |
SaveEtlemb( Model, ePrecision, out ) | writes a loaded model as an .etlemb. A model loaded in int8 can only be written in int8 |
BestIsa( cap ), IsaName( isa ), StatusName( status ) | the best kernels of this machine, readable names |
SModelConfig, all fields with defaults:
| Field | Default | Meaning |
|---|---|---|
ePrecision | eFp32 | eInt8 quantizes the weights at load (folder and GGUF). An .etlemb says its own |
fSmoothAlpha | 0.5 | int8 smoothing strength, 0 to 1, zero turns it off (see "Precision") |
uMaxSeqLen | 0 | longest text in tokens, special tokens included. Zero takes the model's |
uMaxBatch | 32 | most texts in one EmbedBatch |
uMaxBatchTokens | 0 | tokens per forward pass (the session size). Zero is 8 times the maximum length |
pParallel | null | a Job::IParallelFor (for example Job::CJobParallelFor). Null runs on the calling thread |
eMaxIsa | eNeonDot | the best kernel set allowed |
eTruncation | eTruncate | cut long text, or refuse it with eError |
eNormalize | eModel | as the model says, or force eOn / eOff |
pAlloc | null | allocator of the weights and workspaces |
Status codes (EStatus): eOk, eInvalidArgument, eOutOfMemory, eNotLicensed, eIoError (open, read, map or write), eFormatError (bad header, missing tensor, wrong shape), eChecksumMismatch (an .etlemb that does not match its CRC), eUnsupported (an architecture, activation or tensor type the module does not run), eLimitExceeded (more texts than the session holds, or a long text with eTruncation = eError), eBufferTooSmall, eTokenizerError (the tokenizer refused the text, invalid UTF-8 included).
---
Behavior
- Threads. A model is immutable once loaded and is shared by every thread. A session belongs to one thread. Inside one call, the work spreads over the
IParallelForyou give. The module never creates threads. - Determinism. The same text, model and kernel set give the same bits with any number of threads, and alone or in a batch. A batch is packed with no padding: the cost is that of the real tokens.
- Memory.
CSession::Initis the only allocation. No call allocates after it. - Truncation. As sentence-transformers: the text becomes at most the maximum length minus the special tokens, and the special tokens are kept around it.
- Lowercase. A model with
do_lower_case(bge) lowercases the text first, except special tokens written in it. - Shared memory. An
.etlembis mapped read only, so several processes running the same model share its pages.OwnedBytes()does not count the mapped file.
---
The .etlemb file
One file with the tokenizer, the configuration and the weights already packed for the kernels, aligned to 64 bytes, with a version and a CRC-32C. The packing is the same for every kernel set, so one file serves every machine. It can be fp32, int8 or fp16 (fp16 is storage only: the weights are widened to fp32 at load). The int8 file also stores the smoothing factors. ConvertToEtlemb writes next to the destination and renames over it, so a failure leaves no half file.
---
GGUF
Embed::SModelConfig Config;
Config.uMaxSeqLen = 256; // the sentence-transformers max_seq_length is not in a GGUF
Embed::CModel Model;
Embed::CModel::LoadGguf( "all-MiniLM-L6-v2-q8_0.gguf", Config, &Model );- The
bertarchitecture as llama.cpp'sconvert_hf_to_gguf.pywrites it (BERT, and the XLM-RoBERTa encoders), GGUF versions 2 and 3, little-endian. - Tensor types: F32, F16, BF16, Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, Q2_K, Q3_K, Q4_K, Q5_K and Q6_K. They are decoded to fp32 at load with the arithmetic of ggml and packed like a folder's weights, so
ePrecisionapplies (eInt8quantizes again, with the smoothing calibrated 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 when looked up.
- The tokenizer is rebuilt from the metadata:
bertbecomes WordPiece,t5becomes the SentencePiece Unigram. - What a GGUF does not say: the activation is taken as the exact GELU (that of the trained model, where llama.cpp uses the tanh one), the vector is normalized (
ENormalize::eOffturns it off), and the maximum length isbert.context_length. SetuMaxSeqLento the model's own limit. - Refused with
eUnsupported: the IQ, TQ and MXFP4 types, other architectures (nomic-bert, jina-bert, modern-bert), big-endian files. - At the tested llama.cpp revision, the stock converter does not convert multilingual-e5-small (a BERT model with a SentencePiece tokenizer). Its reference GGUF was produced with an adjusted converter.
---
Precision
- fp32 is the reference.
- int8: weights symmetric per output channel, activations quantized per row at run time, exact int32 sums. Loaded from a folder or a GGUF, the weights get calibrated smoothing (SmoothQuant style): at load, the model runs a fixed calibration set in fp32 on the scalar kernels and one thread, and each input channel of each linear layer gets a power-of-two factor. The calibration is the same on every machine, so a folder and its int8
.etlembgive the same bits. The int8 GEMM gives the same bits on every kernel set, but the final int8 vector does not: the last bit of the vectorized GELU becomes a different rounding in the next quantization. Measured on all-MiniLM-L6-v2, scalar against AVX2, the lowest cosine was 0.9960. To compare int8 vectors from different machines, allow for that or seteMaxIsato a set both have. - fp16: storage only, in the
.etlemb.
---
The etl-embed tool
Ships in bin/. Exit code 0 on success, 1 on a model error, 2 on bad arguments.
etl-embed convert --in <model folder | file.gguf> --out <file.etlemb> [--precision fp32|int8|fp16]
etl-embed inspect <file.etlemb | file.gguf | model folder>
etl-embed embed <file.etlemb | file.gguf | model folder> <text> [--isa scalar|avx2|avx512|avx512-vnni|neon|neon-dot]inspect prints the architecture, precision, dimensions, layers, heads, vocabulary, maximum length, activation, pooling, normalization, lowercase, the kernels in use and the owned memory. embed prints the first values of the vector and the time of the first call.
---
C layer
Header ethereal/c/ai/embed.h, 12 functions. ETLC_EmbedConfigDefault, the loaders ETLC_EmbedModelLoadSafetensors, ETLC_EmbedModelLoadEtlemb and ETLC_EmbedModelLoadGguf, ETLC_EmbedModelInfo, ETLC_EmbedModelDestroy, ETLC_EmbedSessionCreate and ETLC_EmbedSessionDestroy, ETLC_Embed, ETLC_EmbedBatch, ETLC_EmbedConvert (folder or .gguf to .etlemb) and ETLC_EmbedIsaName. The model and the session are opaque handles with the same thread rules as in C++. Texts are UTF-8 with a length, or ETLC_EMBED_NUL_TERMINATED.
Every call runs on the calling thread: the job system is not exposed in C. In ETLC_EmbedConfig, zero in a field means its default, **except iMaxIsa, where zero is the scalar kernel**. Start from ETLC_EmbedConfigDefault (or pass NULL) to get the best kernels. The status codes map to the common ETLC_ERR_* codes, plus ETLC_AI_EMBED_TOKENIZER (-5815) for a text the tokenizer refuses.
Left out of C: loading from memory, Tokenize, EmbedTokens, TraceLayers and SaveEtlemb.
---
Accuracy
Against PyTorch (sentence-transformers) on 2,000 texts per model in several languages:
- Tokenization: the same ids as Hugging Face on every text of every model.
- fp32: cosine 1.0 on every model and every language group, with the scalar and AVX2 kernels, on GCC and MSVC. The criterion was a cosine of at least 0.99999 and at most 1e-4 per dimension. The XLM-RoBERTa path (its positions, the tanh GELU, no normalization) is checked with a small model of random weights, since the four published models declare
bert. - int8 against fp32 (target: mean at least 0.995, minimum at least 0.99, met):
| Model | Mean cosine | Lowest cosine | nDCG@10 on NFCorpus, fp32 to int8 |
|---|---|---|---|
| all-MiniLM-L6-v2 | 0.9979 | 0.9923 | 0.3173 to 0.3165 |
| bge-small-en-v1.5 | 0.9991 | 0.9925 | drop of 0.0006 |
| e5-small-v2 | 0.9993 | 0.9975 | gain of 0.0002 |
| multilingual-e5-small | 0.9995 | 0.9937 | drop of 0.0015 |
Without smoothing (fSmoothAlpha = 0), all-MiniLM-L6-v2 falls below 0.99 on very short texts (lowest 0.9768, on "."). Among the strengths tried on that model (0.3, 0.5, 0.65, 0.8), 0.5 was the best, which is why it is the default.
- GGUF: the 13 decoders give the same bits as ggml's reference (gguf-py) on random blocks of each type. Against the Hugging Face folder of the same model, with the same maximum length (ids and F32 on the 2,000 texts, the cosines on 500 of them):
| Model | F32 | F16 lowest cosine | BF16 lowest cosine | Q8_0 lowest cosine |
|---|---|---|---|---|
| all-MiniLM-L6-v2 | same bits | 1.000000 | 0.999981 | 0.999617 |
| bge-small-en-v1.5 | same bits | 1.000000 | 0.999992 | 0.999876 |
| e5-small-v2 | same bits | 1.000000 | 0.999994 | 0.999897 |
| multilingual-e5-small | same bits | 1.000000 | 0.999995 | 0.999931 |
An int8 load of an F32 GGUF gives the same bits as an int8 load of the folder. The Q4 to Q6 and K types are checked on a small synthetic model (the same output as that model with its weights decoded to F32 beforehand), not against published models.
Kernels not run on hardware. The vendor's test machine (Intel i7-6700, AVX2) cannot run the AVX-512, AVX-512 VNNI, NEON and NEON SDOT kernels. They are compiled (NEON with Clang for AArch64) but unverified on hardware. The SDOT path is only used when the whole library is built with dotprod.
---
Speed
Intel i7-6700 (4 cores / 8 logical), GCC 15.2 on WSL2, AVX2 kernels. A short query (up to 16 tokens, one thread, median of 2,000 calls) and a batch of 32 texts of 128 tokens (median of 30). The ONNX Runtime 1.31.0 figures are from the same machine (optimizations on, int8 by dynamic quantization). The Ethereal times include tokenization, pooling and normalization. The ONNX Runtime times are the encoder only.
| Model | Precision | Short query (ms) | ONNX Runtime | Batch, 1 thread (ms) | 4 threads | 8 threads | ONNX Runtime, 8 threads |
|---|---|---|---|---|---|---|---|
| all-MiniLM-L6-v2 | fp32 | 4.714 | 3.890 | 2314.7 | 880.8 | 710.7 | 430.1 |
| all-MiniLM-L6-v2 | int8 | 5.185 | 2.044 | 3078.3 | 1184.1 | 951.3 | 299.4 |
| bge-small-en-v1.5 | fp32 | 9.434 | 7.747 | 4601.9 | 1753.8 | 1417.3 | 838.4 |
| bge-small-en-v1.5 | int8 | 10.404 | 4.116 | 6048.0 | 2309.9 | 1832.9 | 612.2 |
| e5-small-v2 | fp32 | 9.470 | 7.897 | 4606.4 | 1773.9 | 1404.7 | 853.4 |
| e5-small-v2 | int8 | 10.673 | 4.180 | 6081.6 | 2327.7 | 1834.1 | 607.5 |
| multilingual-e5-small | fp32 | 9.427 | 7.959 | 4617.3 | 1698.2 | 1355.6 | 873.0 |
| multilingual-e5-small | int8 | 10.375 | 4.217 | 6004.5 | 2272.2 | 1804.8 | 604.5 |
Targets not met. The targets were a short query 1.5 times faster than ONNX Runtime, and with 8 threads a batch at 0.9 times its speed in fp32 and at its speed in int8. Measured: the short query is 0.82 to 0.84 times its speed in fp32 and 0.39 to 0.41 times in int8, and the batch with 8 threads is 0.59 to 0.64 times in fp32 and 0.31 to 0.34 times in int8.
On AVX2, int8 is slower than fp32 here: about 10 percent on a short query and about 30 percent in a batch. Choose int8 for a smaller file, not for speed on an AVX2 machine. The VNNI and SDOT int8 paths are the ones meant to be faster, and they are unverified (see above).
No MSVC timings are published for this module.