Part I — Representation contracts
What the encoding must preserve
A representation is a numerical interface between an input and a later computation. An encoder produces that interface. It need not retain enough information to reconstruct the input; it needs to expose distinctions that a permitted downstream operation can use. A representation of support tickets might preserve issue type while ignoring punctuation. A representation used to reproduce exact quotations cannot safely ignore the same variation.
Preservation is therefore operational. Let an encoder map an input to . A downstream function that turns into a task output is called a readout. A distinction is preserved for task when an appropriate readout can recover the required output on new cases. The claim therefore depends on the input population, the allowed readout, and the decision—not merely on whether two vectors look separated in a plot. Training receives pressure from a computable objective, which may reward only some distinctions.
Every representation is selective. An autoencoder constrained by a bottleneck or regularization must prioritize information useful for its reconstruction criterion, but low reconstruction error does not establish useful semantic neighborhoods. Conversely, a retrieval encoder can rank relevant passages without preserving exact wording. Fixed-width compression can also discard a distinction that a later, unforeseen query needs. That is why no embedding is universally semantic.
Useful invariance and harmful information loss are the same structural event judged against different tasks: changing the input causes little or no useful change in its representation. Ignoring capitalization may help topic retrieval; it may corrupt a task that must preserve legal names exactly. State the decision first, then decide which transformations should leave the representation stable.
The task decides whether invariance is useful
ExampleOne capitalization-insensitive representation can preserve issue type while discarding the exact-name distinction required by another readout.
Read the diagram as text
- “ACME refund failed”. Original support-ticket text with capitalization preserved.
- “Acme refund failed”. A controlled variant changes capitalization but keeps the issue description.
- Capitalization-insensitive encoder. Maps both variants to the same task-facing representation.
- Shared representation. Issue information remains accessible; capitalization does not.
- Issue-routing readout. Uses the preserved issue distinction to select the refund queue.
- Refund queue. The task decision remains stable across the controlled transformation.
- Exact-name readout. Attempts to recover the original capitalization from the representation.
- Exact form unavailable. The representation no longer distinguishes “ACME” from “Acme.”
- “ACME refund failed” → Capitalization-insensitive encoder: data: original text.
- “Acme refund failed” → Capitalization-insensitive encoder: data: capitalization variant.
- Capitalization-insensitive encoder → Shared representation: produces the same encoding.
- Shared representation → Issue-routing readout: readout uses issue features.
- Issue-routing readout → Refund queue: selects queue.
- Shared representation → Exact-name readout: readout attempts exact recovery.
- Exact-name readout → Exact form unavailable: returns an underdetermined form.
Which object the vector represents
A vector is an ordered numerical array; its width is its dimension. Equal length makes two arrays structurally compatible, not necessarily comparable.
For text, keep several levels distinct. A token is a vocabulary unit. Its token ID is an integer name. An embedding table stores one learned row per vocabulary entry, so the ID selects a vector; the numerical size of the ID carries no semantic magnitude. A transformer then combines that initial vector with position and surrounding context, producing an occurrence-specific contextual state. The arrays and their parameters develops the shapes used in that computation.
| Representation | Represents | Constructed by | What is no longer directly available |
|---|---|---|---|
| Token ID | Vocabulary entry | Tokenizer lookup | Meaningful coordinate geometry |
| Embedding-table row | Token type | Learned lookup table | Occurrence-specific context |
| Contextual token state | One token occurrence | Sequence layers using surrounding input | A context-independent word vector |
| Pooled sequence vector | A selected span or document | Mean, maximum, special-state, or learned pooling | Separate token states and some order detail |
| User, item, image, or region vector | The unit selected by its encoder | Domain-specific features and aggregation | Input detail not retained by that contract |
Even within one model family, the contract can include role prefixes, maximum input length, pooling, normalization, precision, and output truncation. E5-base-v2, for example, documents query and passage prefixes, 768-dimensional outputs, average pooling, normalization, and a 512-token limit. A vector detached from those conventions is incomplete application data.
Part II — Development
Turning points in reusable representations
Modern embeddings combine several lines of work that made different relationships computable. In 1954, Zellig Harris described words through the environments in which they occur, treating distribution as evidence about meaning rather than a complete definition of it. A 1974 vector-space retrieval report represented documents with weighted term coordinates and compared their directions. Latent semantic indexing, published in 1990 by Deerwester and colleagues, then compressed term–document associations into lower-dimensional factors, helping retrieval bridge vocabulary mismatch without assigning a human meaning to every coordinate.
Learning made the comparison rule part of fitting. The 1993 Siamese signature network trained shared encoders from labeled signature pairs. Bengio and colleagues’ 2003 neural language model learned word vectors jointly with next-word prediction, and word2vec’s 2013 continuous bag-of-words and skip-gram objectives scaled context-based learning of static word representations. Count-based and predictive methods remained related alternatives rather than successive replacements; their objective-level connection is developed later in the chapter.
The next turning points changed what an encoded object could depend on. ELMo, introduced in 2018, produced occurrence-specific word representations from surrounding text. BERT, posted in 2018 and published in 2019, used masked-token prediction to learn deeply contextual token states. In 2021, CLIP trained separate image and text encoders from paired examples, making cross-modal comparison reusable. These approaches coexist because distributional association, prediction, pair supervision, context, and cross-modal alignment preserve different relationships.
Turning points in reusable representations
1954Zellig HarrisWord environments become observable evidence about differences in meaning.
Contributors: Zellig Harris
What changed: Established a distributional framing while distinguishing occurrence patterns from truth or a complete definition of meaning.
1974Vector-space retrievalWeighted term coordinates make document direction directly comparable.
Contributors: Gerard Salton, A. Wong, and C. S. Yang
What changed: Turned document retrieval into geometric comparison while keeping the representation dependent on selected terms and weights.
1990Latent semantic indexingLower-dimensional factors connect terms and documents across vocabulary mismatch.
Contributors: Scott Deerwester and colleagues
What changed: Compressed term–document associations so related material could compare closely without sharing every term or assigning a human meaning to each coordinate.
1993Siamese signature networkShared encoders learn compatibility from labeled signature pairs.
Contributors: Jane Bromley, Isabelle Guyon, Yann LeCun, Eduard Säckinger, and Roopak Shah
What changed: Made the comparison rule trainable: genuine pairs were rewarded for small angles and forgery pairs for large angles.
2003Bengio neural language modelWord vectors are learned jointly with next-word prediction.
Contributors: Yoshua Bengio and colleagues
What changed: Allowed related word representations to support generalization beyond exact sequences observed during training.
2013word2vecCBOW and skip-gram scale predictive learning of static word vectors.
Contributors: word2vec paper authors
What changed: Made context-based word learning efficient through objectives that predict a word from context or context from a word.
2018ELMoA word occurrence receives a representation derived from its surrounding text.
Contributors: Matthew Peters and colleagues
What changed: Changed the represented object from a context-independent word type to an occurrence-specific state assembled from a bidirectional language model.
2018 preprint; 2019 publicationBERTMasked prediction learns deeply contextual token states from both directions.
Contributors: Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova
What changed: Separated input embeddings from contextual states and made one pretrained checkpoint adaptable to multiple downstream tasks.
2021CLIPPaired image and text encoders learn a reusable cross-modal score.
Contributors: CLIP research team
What changed: Enabled image–text retrieval and zero-shot classification while leaving the score dependent on paired data, candidate descriptions, and the training objective.
Part III — Scores and neighborhoods
Three ways to compare vectors
A comparison rule maps two vectors to a scalar. The dot product reflects alignment and magnitude, Euclidean distance measures separation, and cosine similarity measures angular alignment for nonzero vectors.
A worked comparison
| Candidate | Vector | Dot product | Cosine | Euclidean distance |
|---|---|---|---|---|
| A | (2, 2) | 2 | 0.707 | 2.236 |
| B | (1, 0) | 1 | 1 | 0 |
| C | (0, 1) | 0 | 0 | 1.414 |
| Ranking | A, B, C | B, A, C | B, C, A |
One query, three different rankings
ExampleDot product favors A; cosine favors B; Euclidean distance ranks C ahead of A.
Vectors from the origin
Arrows show magnitude and direction.
- 1. Query q
- 2. Candidate A
- 3. Candidate B
- 4. Candidate C
Read coordinates and regions as data
X: -0.5–2.5 dimensionless; Y: -0.5–2.5 dimensionless, increasing up. Equal scale on both axes.
(0, 0); (1, 0)
(0, 0); (2, 2)
(0, 0); (1, 0)
(0, 0); (0, 1)
q and B: (1.1, 0.08)
A: (2.08, 2.08)
C: (0.08, 1.08)
Dot product favors A’s magnitude; cosine favors B’s matching direction; Euclidean distance favors B, then C. The task determines whether magnitude belongs in the score. Validate thresholds for the exact encoder and population because some contrastively trained spaces concentrate cosine scores in a narrow, high range.
What a nearest neighborhood means
A nearest-neighbor result is relative to a collection, representation, comparison rule, and selection policy. A -nearest query returns a fixed count even when every candidate is poor; a radius query can return none or many. Ties at a boundary can make results depend on ordering. “Nearest” therefore means best among the supplied candidates under a declared rule, not relevant in an application sense.
High-dimensional geometry needs diagnostics rather than folklore. Anisotropy is directional concentration: random items can share a large background cosine because much of the space points along common directions. Hubness is different: a hub appears unusually often in other points’ neighbor lists. Distance concentration concerns relative distance spread. These effects depend on the learned distribution and metric; high dimension alone does not prove any of them.
| Field | Question answered |
|---|---|
| Candidate ID and source | What object was compared? |
| Raw score and rank | What did the named metric return? |
| Tie and boundary status | Could ordering change at the cutoff? |
| Neighbor occurrence count | Does this item act as a hub? |
| Human or task relevance | Was geometric proximity useful? |
Two-dimensional projections are inspection aids, not evidence about the original space. t-SNE layouts can change with perplexity, optimization, and random runs; displayed cluster distances and apparent density can be misleading. UMAP can introduce apparent tears and responds to neighborhood and packing parameters. Always compute authoritative neighbors in the original representation, then label any projection as a separate derived representation.
Axes are fragile interpretations: rotations can change coordinates while preserving comparisons. Some objectives also permit prediction-preserving reparameterizations that alter cosine geometry. Naming a coordinate requires separate evidence.
Part IV — Learning geometry
The objective chooses rewarded distinctions
A representation’s geometry emerges from what fitting rewards. A predictive objective preserves features useful for predicting context or successors. A reconstruction objective preserves detail that reduces reconstruction loss. Classification rewards boundaries useful for supplied labels. Metric and contrastive objectives directly compare selected examples. These labels describe pressure, not a complete geometry: architecture, data, capacity, augmentation, regularization, and optimization also matter.
| Objective family | Training relationship | What it directly rewards |
|---|---|---|
| Context prediction | Word and surrounding words | Features useful for predicting observed contexts |
| Masked prediction | Visible input and hidden target | Features useful for recovering selected missing content |
| Reconstruction | Input and reconstruction | Information favored by the loss and bottleneck |
| Classification | Input and supplied label | Features supporting the trained decision boundary |
| Metric or contrastive | Anchor, related items, alternatives | Relative compatibility under declared pairs |
The historical divide between count and prediction can be overstated. Skip-gram with negative sampling admits a matrix-factorization interpretation under stated assumptions, and controlled work transferring smoothing and context choices between count-based and predictive representations found no consistently superior family across its tested tasks. Preprocessing and evaluation choices can explain apparent family-level advantages.
Pairs, negatives, and contrastive pressure
In contrastive learning, the training procedure declares a positive pair related for the task and supplies competing alternatives, often called negatives. The names describe training roles, not objective truth. Two augmented views of one image may be positive for object recognition, while two camera views must remain distinguishable for a viewpoint-estimation task.
From pair declarations to pressure
Illustrative pseudocode
Python-like pseudocodeA margin or triplet loss asks an anchor–positive distance to beat an anchor–negative distance by a margin. InfoNCE-style losses compare a positive with many sampled alternatives. In-batch negatives are efficient because another pair’s positive can serve as a competitor, but the shortcut is only valid when those items are genuinely negative for the intended relation. Same-class or otherwise compatible examples create false negatives, teaching the model to separate things the application wants together.
A false negative turns efficient batching into harmful pressure
ExampleAn in-batch item can be relevant under the application relation yet still be pushed away because the loss assigned it the role of competitor.
The anchor has one declared positive. Every other candidate is treated as a competitor, including a second document that is relevant under the application relation.
Read the diagram as text
- Anchor: password reset. A query seeking instructions for resetting an account password.
- Declared positive. The labeled password-reset guide paired with the anchor.
- Valid competitor. An unrelated billing-address article from another pair.
- False negative. A relevant account-recovery guide that appears as another pair’s positive.
- Intended task relation. Both recovery documents are useful answers for the anchor.
- In-batch contrastive loss. Rewards the declared positive relative to every other candidate in the batch.
- Pull declared pair together. Training raises the declared positive’s score relative to competitors.
- Push valid competitor away. Lower compatibility agrees with the intended retrieval relation.
- Push relevant item away. Lower compatibility conflicts with the intended retrieval relation.
- Anchor: password reset → Declared positive: batch declares positive.
- Anchor: password reset → Valid competitor: batch supplies competitor.
- Anchor: password reset → False negative: batch supplies competitor.
- Anchor: password reset → Intended task relation: task asks for recovery help.
- Declared positive → Intended task relation: satisfies intended relation.
- False negative → Intended task relation: also satisfies intended relation.
- Declared positive → In-batch contrastive loss: occupies positive slot.
- Valid competitor → In-batch contrastive loss: enters denominator.
- False negative → In-batch contrastive loss: enters denominator.
- In-batch contrastive loss → Pull declared pair together: raises relative score.
- In-batch contrastive loss → Push valid competitor away: lowers relative score.
- In-batch contrastive loss → Push relevant item away: lowers relative score.
- Declare batch roles. The anchor has one declared positive. Every other candidate is treated as a competitor, including a second document that is relevant under the application relation. Active: Anchor: password reset, Declared positive, Valid competitor, False negative, Intended task relation. New: Anchor: password reset, Declared positive, Valid competitor, False negative, Intended task relation.
- Apply relative-score pressure. The loss pulls the declared pair together and pushes both competitors down. That pressure is appropriate for the billing article but conflicts with the task relation for the account-recovery guide. Active: Anchor: password reset, Declared positive, Valid competitor, False negative, Intended task relation, In-batch contrastive loss, Pull declared pair together, Push valid competitor away, Push relevant item away. New: In-batch contrastive loss, Pull declared pair together, Push valid competitor away, Push relevant item away.
Hard-negative mining concentrates training on high-scoring confusions, but “hard” should mean confusable and still incorrect. An unlabeled relevant item is not a useful negative merely because the current model scores it highly. Pair construction, sampling, and augmentation jointly define the relation the space is trained to expose.
Useful invariance without collapse
Invariance means a task-approved transformation leaves the relevant representation or decision effectively stable. Equivariance means the representation changes in a predictable corresponding way. Translating an image might preserve its category while shifting a spatial feature map. Cropping an image and segmentation target at the same coordinates preserves their relationship; cropping only the image corrupts it.
The required behavior depends on the task. A local descriptor used for correspondence must retain enough spatial variation to distinguish locations, while a category representation may benefit from ignoring small position changes. Local features and correspondence gives the concrete visual case. Augmentation is thus a proposed task contract, not a universally harmless way to create more data.
A contrastive agreement objective has a trivial solution if every input maps to the same vector. This is representation collapse: intended positives agree, but no inputs remain distinguishable. VICReg separates three pressures: match paired views, maintain variation across examples in each coordinate, and reduce redundant covariance across coordinates. The construction distinguishes constant-output collapse from repeated information across dimensions.
Avoiding collapse is necessary but insufficient. Nonzero variance does not show that the space preserves identity, negation, relevance, or any other required relation. Test the desired invariances and separations directly on held-out transformations, including changes that should remain stable and nearby changes that must alter the decision.
Part V — Inspection and comparison
What a readout can recover
A readout maps a representation to a task output. Neighbor inspection asks whether nearby examples look useful. A linear probe fits a weighted-sum classifier while keeping the encoder frozen. A nonlinear probe permits a richer decision boundary. Fine-tuning changes the representation itself and therefore answers a different question; adapting reusable features develops those choices.
Held-out linear-probe success supports a bounded claim: the tested distinction is accessible to that linear predictor on that population under that training procedure. It does not prove that each coordinate has a human meaning, that the original model uses the distinction, or that the same boundary survives distribution shift. Successive network layers can improve linear separability without adding information about the original input.
The readout changes what is accessible
ExampleA straight boundary solves one target on fixed points, while an XOR-like target needs a richer readout; neither layout alone proves causal use by the encoder.
Target A: linearly accessible
Positive examples lie to the right of the dashed linear boundary.
- 1. Target A positive
- 2. Target A negative
- 3. Linear boundary
Read coordinates and regions as data
X: -2–2 dimensionless; Y: -2–2 dimensionless, increasing up. Equal scale on both axes.
(1, 1); (1, -1)
(-1, 1); (-1, -1)
(0, -1.8); (0, 1.8)
Target B: richer readout needed
Diagonal positives form an XOR-like target that one line cannot separate.
- 1. Target B positive
- 2. Target B negative
Read coordinates and regions as data
X: -2–2 dimensionless; Y: -2–2 dimensionless, increasing up. Equal scale on both axes.
(1, 1); (-1, -1)
(-1, 1); (1, -1)
A powerful probe complicates interpretation because it can learn substantial task logic itself. Conversely, probe failure does not prove absence; another readout may recover the property. Attribute-recovery studies also show why testing one weak attacker is inadequate: demographic information remained recoverable from some text representations even after the training adversary approached chance. Probe capacity, train/test separation, baselines, and overfitting checks belong in the claim.
A decoder is another readout. Linus Lee demonstrated a custom text autoencoder whose decoder approximately reconstructed text from a pooled representation, and a learned adapter enabled approximate recovery from another model’s embeddings. That does not make arbitrary embedding APIs invertible, but it illustrates that vectors can retain details beyond the application’s intended use. Stored embeddings should therefore be included in sensitive-data inventories.
A task-matched comparison
Choosing a representation is an evaluation problem. Begin by specifying the represented unit, intended population, query or readout operation, frozen or adapted parameters, preprocessing, pooling, normalization, metric, baselines, held-out split, resource limits, and consequential slices. Generalization requires new cases from the intended setting; matched comparisons keep cases aligned across candidates.
| Evidence | What it supports | What it does not establish |
|---|---|---|
| Annotated pair similarity | Fit to the benchmark’s relation | Retrieval, classification, or product value |
| Frozen linear probe | Linear accessibility on held-out cases | Causal use or nonlinear absence |
| Recall at k | Coverage of labeled relevant items | Precision, answer quality, or index latency |
| End-to-end task result | Behavior of the complete tested system | Attribution to one changed component |
| Operational measurements | Cost, latency, and reliability under a workload | Semantic fitness outside that workload |
MTEB deliberately evaluates several readouts, including classification on frozen vectors, clustering, pair scoring, and retrieval. Its original results were strongly task-dependent: strength on semantic textual similarity did not guarantee strength on retrieval. BEIR likewise found dense retrievers strong on some domains and below BM25 on others. A public aggregate is useful evidence about its stated tasks, not a portable ordering for every application.
A 2025 Weights & Biases chatbot evaluation illustrates the decision rule. Four embedding models were compared with recall at ten on logged queries and generated queries. The desired validation was not only similar scores but preservation of model ordering. In that application, the reported winner differed from what public English MTEB standing or the incumbent model might have suggested. Exact scores, sample size, and uncertainty were not supplied, so the lesson is the comparison design rather than a current model ranking.
Retrieval metrics can also trade off. In a fifty-task code experiment, windowed reads plus semantic search reportedly improved precision, while broader default exploration retained better file recall and the two windowed conditions had similar recall. Because windowing itself changed behavior, only the matched windowed conditions isolate the incremental semantic-search question. Neither precision nor recall alone established downstream solution quality.
Part VI — Larger systems
Candidate retrieval, not complete search
A dense retriever factorizes candidate comparison. Corpus units are encoded and indexed before requests. A new query is encoded at request time, then its vector is compared with compatible corpus vectors. Dense Passage Retrieval used separate question and passage encoders with dot-product scoring; training contrasted relevant passages with negatives. This makes broad candidate generation efficient because passage computation is reused.
Separate encoders can learn asymmetric roles: a query asks for information while a document supplies it. Some libraries therefore distinguish query and document encoding methods or prefixes. Shared vector width and callable APIs do not prove role compatibility; preprocessing and training conventions must match the stored corpus.
The embedding component stops at candidates. Similarity is not a probability that a passage proves an answer, and fixed top-k retrieval has no built-in rejection criterion. Lexical matching can outperform dense retrieval under some shifts, while metadata constraints, permissions, freshness, hybrid retrieval, reranking, and answer construction remain separate responsibilities developed in Search and Retrieval.
A bi-encoder also moves repeated work outside the request path. Pinterest described computing pin embeddings offline and query embeddings online, refreshing a pin only when its inputs meaningfully changed. This scales differently from a cross-encoder that jointly processes each query–document pair. A common pattern is broad bi-encoder retrieval followed by a cross-encoder reranker over a much smaller set.
Dense retrieval ends at candidates
Corpus encoding is reusable offline work; query encoding and comparison happen online, while relevance, permissions, and answer decisions remain downstream.
Read the diagram as text
- Corpus units. Documents, chunks, images, or other explicitly selected candidate units.
- Document encoder. Applies the versioned candidate-side representation contract.
- Vector index. Stores candidate vectors with identifiers and source metadata.
- Incoming query. The current information request.
- Query encoder. Applies the compatible query-side role and preprocessing.
- Scored candidates. Nearest or highest-scoring items under the configured metric.
- Search decision stages. Lexical signals, metadata, permissions, reranking, rejection, and response logic.
- Corpus units → Document encoder: data: candidate content.
- Document encoder → Vector index: data: vectors and IDs.
- Incoming query → Query encoder: data: request text.
- Query encoder → Vector index: control: search with query vector.
- Vector index → Scored candidates: data: scores and IDs.
- Scored candidates → Search decision stages: data: candidate set.
User–item compatibility is not generic similarity
Recommendation systems can learn user and item embeddings from interaction data. In matrix factorization, their dot product approximates observed feedback. Missing entries in the interaction matrix are not automatically dislikes: fitting only positives admits trivial behavior, while treating every missing entry equally as negative can overwhelm the observed signal. The objective determines what compatibility means.
Content-based recommendation answers a different question. It places item attributes and user preferences in a shared feature space, allowing a new item to be scored through its properties before it has extensive interaction history. Collaborative representations instead learn from behavioral structure. Systems often combine them because item-ID embeddings alone struggle with cold-start items.
| Comparison | Question | Typical evidence |
|---|---|---|
| Item ↔ item | Which items resemble or co-occur with this item? | Content features, graph structure, co-purchases |
| User ↔ item | Which items are compatible with this user state? | Interactions, preferences, context |
| Query ↔ item | Which items match this request? | Query–item logs, content, request context |
Magnitude can carry an objective-dependent signal; cosine normalization removes it. A high user–item score does not mean an item resembles a person. Exposure, exploration, long-term satisfaction, and product value belong to Recommendation Systems.
Alignment across modalities
Cross-modal embeddings make different input types comparable by learning the relationship, not by declaring their vectors the same width. CLIP uses separate image and text encoders and trains matched image–caption pairs to score above mismatches. At inference, text descriptions can be compared with an image for retrieval or zero-shot classification. The score expresses learned correspondence under the paired data and objective, not a symbolic inventory of visual facts.
This distinction matters operationally. A drawing game used CLIP cosine similarity to rank images against arbitrary prompts, enabling open-set comparisons beyond a fixed class list. Developers also reported that players could score well by writing prompt words in the image, prompting a handwriting-related penalty. The representation had learned a correspondence useful for the score but different from the application’s intended notion of a good drawing.
Cross-modal retrieval can preserve coarse subject alignment while missing order, attribute binding, and relations. ARO evaluates captions that retain constituent words but reverse relations, reassign attributes, or reorder content; tested image–text models showed weaknesses even when ordinary retrieval remained strong. Success at finding a broadly related image does not establish who did what to whom.
Some systems encode screenshots containing text, images, and layout, but the retrieved vector is still only an index key. The application must resolve the stored image and pass the actual visual content to a multimodal model for interpretation. Detailed modality fusion belongs to Multimodal Models and Applications, while visual representation mechanisms belong to Computer Vision.
Part VII — Failure boundaries
Nearby can still be wrong
Semantic similarity fails when the representation exposes a relation different from the decision the application needs. Common mechanisms include objective mismatch, missing context, wrong represented unit, lossy pooling, false negatives, domain or language shift, role-format mismatch, hubs, and unstable cutoff neighbors. Diagnose the mechanism instead of treating every bad result as a vague embedding-quality problem.
| Change | Why vectors may remain close | What the application can get wrong |
|---|---|---|
| Synonym ↔ antonym | Opposites often occur in similar contexts | Approved versus denied, strong versus weak |
| Affirmation ↔ negation | Most tokens and topic remain shared | Supported versus rejected claim |
| Number replacement | Sentence structure and vocabulary remain similar | Quantity, date, or dosage |
| Relation or attribute reassignment | Objects and attributes remain present | Who owns, wears, or acts on what |
| Associated ↔ genuinely similar | Related words co-occur without being substitutable | Category or equivalence decision |
| Same topic ↔ entailment | A hypothesis can mention the same entities without following from the text | Whether evidence supports a conclusion |
Many application relations are directional or structured. “Answers this question,” “newer than,” “caused by,” and “permitted for” cannot be established by an undirected proximity score alone. Graph traversal can start from a semantic match and then follow stored ownership or other edges, but the relationship must exist and be queried explicitly. Current permission requires an authority check, as explained in Enforce current authority.
Similarity is also not identity. Near-duplicate candidates can be proposed geometrically, but merging records requires an identity rule and provenance. Duplicates depend on identity develops that decision. Likewise, a memory fact can be topically close yet operationally irrelevant: a dog named Melody may match a request about favorite tunes without expressing any listening preference.
Test these failures with minimal pairs and slices. Change one entity, number, negation, relation, language, domain, or input convention while holding other content fixed. Measure both aggregate task performance and the decision-sensitive slice. A model improved for negation can still become worse on another category, so one repaired distinction does not certify general semantic fidelity.
Part VIII — Operations
Version, migrate, and revalidate the space
Once vectors are stored, an embedding becomes a versioned data dependency. The contract includes encoder checkpoint, tokenizer and preprocessing, query or document role instructions, represented unit, truncation, pooling, output layer, dimension, precision, normalization, similarity metric, source revision, and index schema. Pinning only the model name or checking array shape leaves important behavior unspecified.
Equal dimensions do not align independently trained spaces. Google explicitly documents that vectors from gemini-embedding-001 and gemini-embedding-2 cannot be compared directly and that migration requires re-embedding stored data. Switching only the online query encoder can therefore silently compare a new query space with old candidate vectors, producing structurally valid but meaningless rankings.
A safe migration coordinates the whole serving bundle.
- Preserve sources — Keep source records and lineage needed to generate the new vectors; old vectors alone cannot be re-encoded.
- Build separately — Create a new collection or named-vector generation with its own dimension, metric, identifiers, and metadata.
- Catch up changes — Coordinate concurrent upserts, partial updates, and deletions so validation does not compare a stale generation.
- Evaluate matched work — Run old and new bundles on the same held-out queries, failure slices, and operational workload; choose workload-specific acceptance criteria.
- Cut over together — Switch the query encoder, preprocessing, scoring rule, and candidate index as one compatible release. If an alias performs the index switch, remove the old target and add the new target in one aliases request, inspect every action result, and use
must_existwhere appropriate so a failed removal cannot leave an unintended target. - Retain rollback — Keep the prior compatible bundle until rollback safety, writes, deletions, and permission changes have been reconciled.
A migration keeps two spaces separate until cutover
Source records produce versioned candidate spaces; the query encoder and serving target switch to the compatible generation only after catch-up and matched validation.
The stable alias has one intended target, the v1 index, and online queries use encoder v1.
Read the diagram as text
- Preserved source records. Versioned content and lineage from which vectors can be regenerated.
- Old vector generation. Candidate vectors produced by encoder contract v1.
- New vector generation. Candidate vectors produced separately by encoder contract v2.
- Query encoder v1. Online query path compatible with the old generation.
- Query encoder v2. Online query path compatible with the new generation.
- Stable serving alias. Application-facing name with exactly one intended active generation.
- Alias → v1 serving. The alias and query encoder v1 form the active compatible bundle.
- v2 building, not serving. Backfill and concurrent updates are still being applied.
- v2 validated, not serving. Matched task, slice, operational, and update-completeness checks passed.
- Alias → v2 serving. The alias and query encoder v2 switched as one compatible release.
- v1 bundle retained. The prior compatible bundle remains available while rollback is safe.
- Preserved source records → Old vector generation: data: encode with v1.
- Preserved source records → New vector generation: data: encode with v2.
- Query encoder v1 → Old vector generation: compatible comparisons.
- Query encoder v2 → New vector generation: compatible comparisons.
- Serve the old bundle. The stable alias has one intended target, the v1 index, and online queries use encoder v1. Active: Preserved source records, Old vector generation, Query encoder v1, Stable serving alias, Alias → v1 serving. New: Preserved source records, Old vector generation, Query encoder v1, Stable serving alias, Alias → v1 serving.
- Build and catch up v2. Preserved sources and concurrent changes populate a separate v2 generation without cross-version scoring or serving it through the alias. Active: Preserved source records, Old vector generation, New vector generation, Query encoder v1, Query encoder v2, Stable serving alias, Alias → v1 serving, v2 building, not serving. New: New vector generation, Query encoder v2, v2 building, not serving.
- Validate matched work. The v2 query encoder and v2 index are evaluated together on held-out tasks, failure slices, latency, and update completeness while v1 remains the sole serving target. Active: Preserved source records, Old vector generation, New vector generation, Query encoder v1, Query encoder v2, Stable serving alias, Alias → v1 serving, v2 validated, not serving. New: v2 validated, not serving.
- Cut over together. One aliases request removes v1 and adds v2; action failures are inspected and `must_exist` is used where appropriate. Online preprocessing and the query encoder switch to v2 in the coordinated release, while the complete v1 bundle remains available for rollback. Active: Preserved source records, Old vector generation, New vector generation, Query encoder v1, Query encoder v2, Stable serving alias, Alias → v2 serving, v1 bundle retained. New: Alias → v2 serving, v1 bundle retained.
An alias can give the application a stable index name. Removing the old target and adding the rebuilt target in one aliases request can switch that name atomically, but the caller must inspect action failures and use must_exist where appropriate to prevent an unintended partial action list. Alias atomicity still does not transact an external query encoder, caches, or configuration, so release orchestration must coordinate those artifacts. After cutover, monitor task metrics and important slices rather than vector statistics alone; distribution and traffic changes can invalidate an earlier acceptance result.
The governing rule is simple: an embedding is not merely an array. It is a task-shaped measurement produced by a versioned procedure. Its geometry becomes useful only when the represented object, training relationship, comparison rule, and downstream evidence remain compatible.
Open questions
Can representation objectives be compared under genuinely controlled conditions—holding architecture, data, augmentations, capacity, and optimization fixed—so engineers can isolate which objective creates a useful distinction rather than attributing a whole-system difference to the loss name?
How can a system detect that a deployed embedding space has lost a consequential relation before aggregate retrieval metrics move? Progress would combine maintained minimal-pair slices, traffic coverage, neighbor diagnostics, and downstream decision outcomes without treating vector drift alone as failure.
How should contrastive systems discover false negatives at production scale when relevance is incomplete or changes by user and task? Useful progress would identify mislabeled competitors without collapsing hard-negative training into expensive universal pairwise judgment.
How can representation migrations preserve continuous updates, deletions, permissions, and rollback across indexes, encoders, caches, and external configuration? Existing blue–green and alias mechanisms cover important pieces, but acceptance thresholds and cross-system transactions remain workload-specific.
What privacy controls are appropriate for embeddings whose source text may be partly reconstructable? Progress would measure recovery risk for the exact encoder and access model, then connect retention, access, deletion, and incident response to both vectors and their source lineage.



























