Mental model
Client-side embedding generation maps a text passage to a numeric vector in the browser so a local or remote index can compare its meaning with other vectors. A useful vector depends on the full recipe: model weights and tokenizer, truncation, pooling, normalization, and dimension. Store that recipe beside the vector, because changing one part changes its coordinate space.
Learning outcomes
- Trace text tokenization, transformer hidden states, pooling, and optional L2 normalization.
- Estimate browser memory for a vector collection and compare storage formats.
- Keep queries and indexed passages in the same model space and evaluate nearest-neighbor recall.
Theory
A transformer produces contextual hidden states for the input tokens. Sentence-BERT-style retrieval models are trained so that pooled sentence representations can be compared by a similarity function. A feature-extraction pipeline exposes token-level features; mean pooling reduces the sequence dimension to one vector per input, and L2 normalization scales its length to one. For a 384-coordinate MiniLM model, the output should be one vector with 384 finite values per passage, but the application must confirm the loaded model card and output shape rather than infer those properties from a filename.
The vector is meaningful only within its embedding space. Use the same model revision, tokenizer files, text preprocessing, pooling mode, normalization rule, and query/document prompts for both sides of a search. Changing the encoder or pooling operation can rotate or distort the space; existing vectors then cannot be safely compared to freshly generated queries. Version an index and rebuild it when the vector recipe changes.
The browser may run the model through WebAssembly or a hardware execution provider. The backend changes latency, supported operators, precision, and numerical results; it does not change the semantic contract. A quantized model can reduce download size and compute, but check retrieval metrics against the unquantized baseline. Local execution keeps raw text on-device during encoding, yet an embedding can still reveal semantic information and is not an anonymized substitute for the text.
Similarity model and worked example
For a query vector and passage vector , cosine similarity is the normalized dot product:
Vert_2lVert d Vert_2}$$ Each vector has $D$ dimensionless coordinates; the score is dimensionless and lies from $-1$ to \$1$. When both vectors were normalized by the same pipeline, $s(q,d)=q^\top d$. Keep the score’s meaning tied to a model and evaluation set; a value such as 0.74 is not a universal confidence probability. Suppose a local handbook index has 10,000 passages and the encoder produces 384 float32 values per passage. Raw coordinate storage is (10{,}000 imes 384 imes 4 = 15{,}360{,}000) bytes, about 14.65 MiB before IDs and index overhead. Int8 storage uses 3,840,000 bytes, about 3.66 MiB. If a 500-query benchmark changes recall@10 from 0.86 to 0.82 after quantization, the smaller representation saves about 11 MiB but misses more relevant passages. Keep both the byte count and a task metric in the device decision. <ConceptDiagram sourceIds="sentence-bert,hf-transformers-js-docs,onnx-runtime-web-docs" steps="Normalize text inputs|Tokenize with the pinned encoder|Run browser inference|Pool and normalize each vector|Validate shape and index under the recipe version" /> ## Trade-offs Client encoding can avoid a round trip when users search personal notes offline or when text must stay on the device during the model pass. It pays an initial model download, browser storage, CPU/GPU time, and thermal cost. Generate only the passages that need indexing, batch small requests to amortize dispatch overhead, and move sustained inference off the UI thread. A server encoder is easier to update centrally and can keep a large corpus in one space, but it receives source text and adds network latency. Float32 is straightforward and faithful to the pipeline output, at four bytes per coordinate. Int8 or binary vectors use less space and can improve cache locality, but require a compatible search implementation and may change rankings. A WebGPU path can accelerate supported operators on some machines; WASM is a broad fallback, while unsupported graph operations may prevent one backend from loading. Select the backend by capability detection and measured device coverage, not by assuming every browser exposes the same GPU. ## Failure modes and misconceptions - Embedding the query with a new model and comparing it against an index built by an older model. Model IDs alone may not capture changes; pin the revision and preprocessing metadata. - Silently truncating long passages. The vector then represents only a prefix, so split passages at meaningful boundaries or reject text beyond the encoder’s maximum sequence length. - Averaging padding tokens into a sentence vector. Use the pipeline’s mask-aware pooling or verify that the model’s pooling implementation excludes padding. - Treating cosine similarity as calibrated confidence. A high score can still retrieve a stale or irrelevant passage; measure precision and recall at the actual rank cutoff. - Accepting an empty, NaN, zero-norm, or wrong-length tensor. Validate the batch count, each dimension, finite values, and normalization before persisting. - Assuming local embeddings contain no sensitive information. They encode semantic structure and still need access control, retention limits, and explicit handling if synchronized. - Reindexing only new documents after a model upgrade. Old and new coordinates no longer share a guaranteed space; rebuild the corpus or retain separate versioned indexes. ## Decision scenario A support application wants offline search across 10,000 downloaded manuals. The float32 index needs about 14.65 MiB for coordinates, while the device budget allows 5 MiB before index metadata. An int8 build fits at about 3.66 MiB, but recall@10 drops from 0.86 to 0.82 on the 500-query evaluation. If 0.84 is the product’s minimum, the compact model cannot ship as configured. Test a higher-quality quantization or a smaller candidate subset, then rerun recall, latency, and memory checks on low-end devices. The storage constraint does not justify silently weakening retrieval quality. ## Implementation pattern Transformers.js can return pooled and normalized feature-extraction vectors for one text or a batch. The guard below checks the expected batch count, 384-dimensional output, finite coordinates, and unit norm before the application writes vectors to a versioned index. ```typescript import { pipeline } from "@huggingface/transformers"; const modelId = "onnx-community/all-MiniLM-L6-v2-ONNX"; const dimensions = 384; const extractor = await pipeline("feature-extraction", modelId); export async function embedBatch(texts: string[]): Promise<Float32Array[]> { if (texts.length === 0 || texts.length > 16) throw new RangeError("batch size must be 1–16"); if (texts.some((text) => !text.trim())) throw new Error("empty passages cannot be embedded"); const output = await extractor(texts, { pooling: "mean", normalize: true }); const rows = output.tolist() as number[][]; if (rows.length !== texts.length) throw new Error("encoder returned the wrong batch size"); return rows.map((row) => { if (row.length !== dimensions || row.some((value) => !Number.isFinite(value))) { throw new Error("encoder returned an invalid vector"); } const vector = Float32Array.from(row); const norm = Math.hypot(...vector); if (Math.abs(norm - 1) > 0.02) throw new Error("normalized vector is outside tolerance"); return vector; }); } ``` Persist the model revision, tokenizer revision, pooling mode, normalization flag, and dimension with every index version. Before switching a cohort to another encoder, compare recall@k, p95 latency, and peak memory on representative mobile hardware, then rebuild query and document vectors together. <KnowledgeCheck assessmentId="client-side-embeddings-generation-assessment" />