Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Embeddings: Snowflake Arctic and the parity contract

Source: written from pkgs/atlas-search/crates/atlas-embed/src/lib.rs, pkgs/atlas-search/crates/atlas-core/src/embed.rs, pkgs/atlas-search/crates/atlas-core/src/types.rs, pkgs/atlas-search/crates/atlas-core/src/shards/mod.rs, pkgs/atlas-search/fixtures/embed-probes.json, and pkgs/atlas-search/atlas_search.py under https://github.com/developing-today/code/blob/main/pkgs/atlas-search/ — provenance only; this chapter is complete without following it.

An embedding is a list of numbers that stands in for a piece of text, placed so that texts with similar meaning sit near each other. Atlas search compares a query’s embedding with every chunk’s embedding; that comparison is one of the two branches described in Retrieval: hybrid full-text and vector search. This chapter is about the one embedding space production Atlas actually uses, why the Rust embedder is held to a bit-for-bit contract against the Python pipeline that built the corpus, and what other spaces exist at the edges.

The production model

The production model is Snowflake’s snowflake-arctic-embed-m-v2.0, a text embedding model. Every production chunk vector and every production query vector lives in its space. The stored width is 768 dimensions, full width, in 32-bit floats. The vector table is named for exactly that: vec_snowflake_m_v2_768_f32. That table name is the default everywhere the table is configurable, through --vec-table or the ATLAS_VEC_TABLE environment variable, and the model is likewise configurable through --model or ATLAS_SEARCH_MODEL — but naming another model on the Rust search surface does not create another working space. For vector and hybrid modes the Rust binary refuses any model other than the default Snowflake model; the alternatives live only in the Python reference, described below.

The pinned snapshot matters as much as the name. The model revision is 95c2741480856aa9666782eb4afe11959938017f. The loader expects tokenizer.json at the model directory root and the fp32 graph at onnx/model.onnx. atlas-search fetch-model downloads that revision into ~/.local/state/atlas-search/model/<rev>/ — the model is data, not code, and is not provisioned into the Nix store — verifies both files’ recorded SHA-256 hashes, and refuses the install on a mismatch; an already-verifying snapshot is a no-op. A missing or mismatched model is a loud error on any path that needs to embed. Full-text-only search and get-chunk keep working with no model present.

Three spellings of one model

The same model appears under three spellings in the tree, and they are not interchangeable strings. The book uses each spelling only where it is operative:

SpellingWhere it is operative
Snowflake/snowflake-arctic-embed-m-v2.0The Hugging Face identity: DEFAULT_MODEL in atlas-core, the default in atlas-proto, the Worker’s pinned model value, and the Python reference’s model constant. This is the spelling a --model flag carries.
snowflake-arctic-embed-m-v2.0The shard and staging identity: EMBEDDING_MODEL_ID in the shards module. This exact string is stamped into shard manifests and staging-database manifests, and it is the string discovery and fan-out compare against.
Snowflake arctic-embed-m-v2.0A shortened display spelling in the fleet CLI’s help text. It names the same model for a human reader and is not compared against anything.

A shard stamped by the aggregator can therefore never string-equal DEFAULT_MODEL, and no code converts between the spellings. Each subsystem compares only within its own spelling. That is a recorded wart, not a design feature: it works because the comparisons never cross, and any future code that compares across subsystems must normalise first or it will refuse every shard it is handed.

How a vector is made

The embedder is the crate atlas-embed: a native Rust implementation running the model’s ONNX graph — ONNX is the portable model format the graph is shipped in — with no Python and no sentence-transformers process in the path. Tokenization (splitting text into the model’s input units) uses the model’s own tokenizer.json: a SentencePiece Unigram tokenizer with a Metaspace pre-tokenizer, not BERT WordPiece. Getting this right is not a detail; a different tokenizer produces different input ids and therefore a different vector for the same text.

The steps, in order, are the parity contract:

  1. Tokenize with special tokens added, no truncation, no padding at this stage. The shipped tokenizer configuration carries a 512-token truncation default; the loader explicitly turns truncation off, because the model’s real context is 8192 tokens (MODEL_CONTEXT = 8192). An input longer than 8192 tokens is a loud TooLong error, never a silent cut.
  2. Batch with manual right-padding: pad token id 0, attention mask 0 for padded positions. Batch composition never changes a vector — the same text embedded alone and embedded in a batch produces the same result. Batch validation runs before any tensor is built: an empty batch is an error, and an empty entry in a batch is an error naming its index, because an empty entry previously returned, by accident of padding, a fabricated unit-norm embedding.
  3. Run the ONNX session with inputs input_ids and attention_mask. The output must have shape batch by sequence by 768 or the run fails with a shape error.
  4. Pool by CLS: take the hidden state at position 0, the model’s classification token, as the text’s vector. This follows the model’s shipped pooling configuration.
  5. L2-normalise in f32: divide the vector by its length, so cosine comparisons reduce to dot products. The sum of squares inside the norm replicates NumPy’s pairwise summation order exactly, through a helper that mirrors its block size and unrolled accumulators — because floating-point addition is not associative, a differently ordered sum can differ in the last bits, and the parity gate grants no tolerance for that.

One asymmetry is deliberate. Documents — the chunks that make up the corpus, whose provenance is covered in The corpus: provenance and content addressing — are embedded prompt-free, exactly as the production corpus was built. Queries pass through one extra step in atlas-core, not in atlas-embed: the string prefix "query: " is prepended before tokenization. That prefix is the prompt the model’s sentence-transformers configuration applies for queries under the name query; the Rust search layer replicates it as the constant QUERY_PROMPT. A query embedded without the prefix is a valid vector in the same space but a measurably worse search, and a document embedded with it would not match the stored corpus.

Width selection is a caller concern. The crate always produces the full 768 dimensions. A caller may truncate a query vector to fewer dimensions — Matryoshka truncation, using the model’s property that a prefix of the vector is itself a usable, coarser embedding — and then renormalise; --trunc 384 is the form the evaluation lineage uses. The stored table stays 768 wide regardless. Truncation happens after the raw query vector is produced, which is also why the query-embedding cache stores the raw full-dimension vector and applies truncation per request on both hits and misses.

A resident session is expensive: about 1.6 GB of memory, held for the session’s lifetime. Serve mode therefore holds one embedder, or a small pool, behind a mutex and shares it across searches; ONNX sessions take a mutable reference, so concurrent embedding through one session is not possible. Thread counts default to the recorded corpus-pass values: 8 intra-op threads and 2 inter-op threads.

Gate A: bit-identical parity

The corpus was embedded by a Python pipeline. If the Rust embedder produced vectors that differed even slightly, every Rust query vector would be compared against Python-made document vectors across an invisible seam, and no search-quality measurement could separate embedder drift from ranking behaviour. So the contract, called Gate A, is exact: atlas-embed must reproduce the production Python pipeline (~/atlas/v3/embed_onnx.py) bit-identically — token ids equal, output vectors with delta 0.0, singly and batched.

The reference is a fixture file, fixtures/embed-probes.json: 11 probes covering ordinary prose, a query-prefixed probe, a single character, Japanese text, an empty input, three real corpus chunks referenced by chunk id only, and a long probe past 512 tokens that exists specifically to catch the tokenizer truncation trap. The fixture records its own provenance: the model and revision above, the ONNX and tokenizer file hashes, ONNX Runtime 1.31.1, and the thread counts.

Gate A is version-matched, and this qualification is load-bearing. The gate reads the runtime version from the loaded library’s versioned name and refuses to render a verdict against a different runtime version: it fails as NOT APPLICABLE rather than reporting a parity failure or a pass. A different runtime build — the Nix closure’s 1.27.1 is the recorded example — produces deltas around 1e-7 on most components of every probe. That is numerical noise between builds of the same library, but Gate A grants no tolerance, so the honest answer against the wrong runtime is “not measured”, not “close enough”. The gate test is accordingly ignored in ordinary CI, which lacks the pinned snapshot and runtime; it runs where ATLAS_MODEL_DIR and ATLAS_ORT_LIB point at the pinned pair.

One recorded curiosity belongs here because a future maintainer will otherwise “fix” it: the tokenizer’s own configuration declares pad token id 1, and one neighbouring implementation pads with 1. The corpus pipeline pads with 0, so atlas-embed hard-codes pad id 0. A recorded diagnostic shows the two choices are bit-identical on this fp32 graph, including on a 1,272-token chunk, because masked positions never reach the CLS row that pooling reads. The proof is about this graph; a different graph voids it.

The ONNX Runtime loader lesson

ONNX Runtime is loaded dynamically, from a library path the caller supplies, through the ort crate built with its load-dynamic feature and default features off. Nothing is downloaded at build time or at run time. The default behaviour of the ort crate — fetching a prebuilt runtime — is forbidden in the Nix sandbox and is a reproducibility hole anywhere else: the runtime that produced the corpus is part of the parity contract, so the runtime must be a pinned input, not a network fetch.

Packaging mechanises the lesson. Since a 2026-11-08 ruling, the package vendors its own ONNX Runtime in-tree at pkgs/atlas-search/onnxruntime/ rather than taking whatever the ambient package set offers, compiles in a default library path pointing at that vendored libonnxruntime.so, and runs a smoke check at install time. The closure must also carry libstdc++.so.6 and libz.so.1; a packaged server without them fails loudly, so the packaging step verifies with closure inspection and a smoke run — one full-text-only query and one embedded query against a fixture database — instead of assuming. Callers resolve the library in a chain: the ATLAS_ORT_LIB environment variable first, then state-directory and local fallbacks, then the compiled-in default. atlas-embed itself reads no environment variables; resolution is always the caller’s job.

Vectors as plain BLOBs

In SQLite-shaped stores — the local publish files and the core scan shards described in Ingest today: staging, classification, promotion — a vector is stored as a plain binary blob: a table of chunk id and vec BLOB, the blob being the 768 f32 values in little-endian order, chunk after chunk. There is no index structure attached to that column in the shard schema the aggregator writes.

That storage shape decides which query primitives exist. vector_top_k is libSQL’s approximate-nearest-neighbour lookup, and it operates on a libSQL vector index — an index object built over a vector column. A bare blob column has no such index, so vector_top_k has nothing to query against the vectors as stored: it does not work on them. The working primitive is an explicit cosine computation over the blob values, vector_distance_cos on the hosted backend or an in-process cosine scan over a loaded matrix on the local backend. That is the Scan strategy of Retrieval: hybrid full-text and vector search: exact, and priced at a full pass over the allowed vectors. The index-based strategies exist in the code for stores that do carry the index; the plain-blob stores are why they are not the default.

The same plainness has an upside the local backend depends on. Because a vector is just bytes keyed by a chunk id in its own store, vector side stores can be joined to a corpus by content hash when their chunk-id spaces differ — and they do differ, which is why an id join would silently attach the wrong vectors to thousands of chunks. Content hash is the identity; the blob is interchangeable cargo.

The dormant BGE-small space

One other space exists in the publish: vec_bge_small_384_f32, 384 dimensions, from the model BAAI/bge-small-en-v1.5 through the fastembed embedder. It is the pre-Snowflake fallback, kept in the publish as a dormant set. Dormant means dormant: no Rust code names that table — the string appears only in the Python reference, atlas_search.py, which is the sole surface that can still query it, using the BGE query prefix "Represent this sentence for searching relevant passages: " in place of "query: ". Local side-store files from that era are still probed by the local backend when it looks for a configured vector table, joined by content hash like any other side store. The Cloudflare Worker states the boundary from the other side: it validates embeddings against the pinned Snowflake space and refuses a 384-dimension BGE-small vector as not comparable with the corpus. Nothing new is embedded into the BGE space, and no plan re-embeds it; it survives so the fallback publish remains readable, not as a second production option.

Model-versioned vectors, and the open second-embedder question

Vectors from different embedding models are not comparable — a cosine distance between a Snowflake vector and a vector from any other model is a number without meaning. Atlas therefore treats model identity as part of a vector’s provenance, and enforces it at the boundaries:

  • A shard’s manifest records its embedding model. Discovery refuses, in strict mode, a shard with no recorded model, and refuses a shard whose recorded model disagrees with the consumer’s expected identity. A fan-out over shards with mixed recorded models is a fatal error, with that reason stated.
  • Promotion from staging is gated on the same contract, as Ingest today: staging, classification, promotion describes.
  • Query traces record the embedding model of the query and, per candidate, the model recorded by the shard that produced it; two or more distinct candidate models in one search set a breach flag on the trace.
  • The query-embedding cache keys on model identity and revision together with the normalised query text, so a model change changes every key — there is no cache invalidation to forget.
  • The standing decision behind all of this, from 2026-11-08, is one embedding model for every Atlas tier, so cross-tier comparisons are comparable by construction.

Whether that remains one model forever is an open question, deliberately. Issue #9092 requires evaluating a second embedding approach alongside Snowflake — the candidates named there, explicitly not pre-picked, include BGE-M3, Voyage, OpenAI’s text-embedding-3, and Workers AI models — judged on evaluation-set quality, cost, and self-hostability, using the harness described in Evaluation: golden sets and gates. The requirement that makes it hard is also stated there: a second space must be supported without a flag-day re-embed of the corpus, which means per-corpus model identity everywhere a vector is stored or compared, tracked separately as #8623. Until that evaluation runs and lands, the shipped behaviour is the single Snowflake space above, and any chapter or tool that presents a second production embedder is describing a plan, not the system.