Swap the encoder behind 4.2 million stored vectors and recall can fall from 0.86 to 0.11 while every dashboard stays green. How you ship the new encoder decides what users see.
Pick a way to ship v2, then press Run the migration. Watch recall and memory from the first chunk to the last. Then we build, piece by piece, why spaces do not transfer, the migration bill, compatible training, fingerprints, drift, the release gate and the semantic cache.
You need to know that an embedding model turns text into a list of numbers and that cosine similarity ranks neighbours (see Vector Embeddings). We build the rest from zero.
Illustrative scenario: 4.2 million chunks of 768 float32 numbers plus a graph index, on a 32 GB box. Chapter 2 computes the memory. We made up the recall values for this page; the mixed curve is the linear blend of Chapter 3.
Chapter 0
Watch a one-line model change return confident, wrong answers with no error anywhere
You run search for a documentation product. It holds 4.2 million text chunks of about 380 tokens each. An encoder (the embedding model) turned each chunk into 768 numbers, and an index stores them. A question goes through the same encoder, and the index returns the 8 nearest chunks.
Your golden set is a fixed list of test queries with known right chunks. On it, recall@8 (the share of right chunks that reach the top 8) is 0.86. Then your vendor ships v2: also 768 wide, and better on public benchmarks. You change one line at 09:40. Nothing errors. By 14:00 someone reruns the golden set: recall@8 is 0.11.
Put three documents on a circle and describe each by its angle. Encoder v1 puts "cat" at 0°, "kitten" at 15° and "truck" at 90°. For unit vectors, cosine similarity is the cosine of the angle between them. A v1 query for "feline" lands at 10°:
Encoder v2 lays out the same meanings turned by 70°. Inside v2 nothing is wrong. But the index still holds v1 vectors, so the search compares a v2 query at 80° with v1 documents:
Blue arrows are the stored v1 documents. Orange is the v2 query. Turn the rotation and find where "truck" wins. Then switch on the v1 query to see the healthy system.
A two-dimensional toy. Real encoders differ by more than a rotation (Chapter 1), but the rotation alone is enough to break the search.
Truck wins with 0.985, as high as a perfect match. So a similarity threshold cannot save you: it removes low scores, and this wrong answer has a high score.
Why 0.11 and not zero? A random pick of 8 from 4.2 million finds the right chunk with chance 8 / 4,200,000 = 0.0000019. So the two encoders share some coarse structure. That makes the outage worse. A team rolls back a system at 0.00 by lunch. A system at 0.11 looks like a mild quality drop and can run for weeks.
The failure. Symptom: fluent answers built on the wrong chunks, with every shape check passing. Measure: rerun the golden set, and compare the top 8 before and after the change. Fix: record which encoder made each vector and refuse to compare across encoders (Chapter 4).
Chapter 1
Prove that training cannot see a rotation, then test two encoders in thirty seconds
Train the same encoder twice and change only the random seed. You get two spaces whose coordinates do not match. The reason is two lines of algebra.
Text encoders train on a contrastive loss: pull a query toward its matching passage and push it away from the others. Every term of that loss is an inner product: multiply two vectors element by element, then add. The loss never looks at one coordinate alone.
An orthogonal matrix is a rotation or a reflection: it keeps every length and every angle. Call it R. Call two embeddings a and b, and rotate both:
R-a dot R-b equals a dot b.
Rotate every embedding by the same R. Each inner product stays the same, so the loss stays the same. Training cannot prefer one R, so the seed picks it.
Rotate by 70°: a = [1, 0] becomes [0.342, 0.940], and b = [0.966, 0.259] becomes [0.087, 0.996]. Before: a · b = 0.966. After: 0.342 × 0.087 + 0.940 × 0.996 = 0.966. Every coordinate moved; the angle did not.
Blue shows run A and orange shows run B, five documents each. Turn the rotation, add some new knowledge, then switch on the bridge.
Toy in two dimensions. "New knowledge" moves each document by its own fixed share of the angle; no rotation can undo that part.
If the gap were only a rotation, you could undo it. Embed the same texts with both encoders and fit the best rotation between them. This is the orthogonal Procrustes problem, and one SVD solves it.
The bridge recovers the rotation but not what v2 learned that is new. Applying it costs 2 × 768 × 768 = 1.18 million operations per vector. Re-embedding a 380-token chunk with a 110-million-parameter encoder costs about 71,000 times more. Use it as a stopgap during an incident.
Embed the same 20 strings through both paths and take the cosine of each string with itself. One space gives 1.000. Two unrelated spaces give random unit vectors, and in 768 dimensions their cosine scatters around 0 with a spread of 1/√768 = 0.036. Three spreads is 0.108.
| Mean self-cosine | Reading |
|---|---|
| above 0.999 | same space; look for the bug elsewhere |
| 0.11 to 0.999 | related but different spaces: this is the outage |
| below 0.11 | no better than unrelated random vectors |
The failure. Symptom: two services return different neighbours for the same query. Measure: run the probe across both. Fix: find the pipeline step that differs (Chapter 4), and keep the source text so you can always rebuild the vectors.
Chapter 2
Price a full re-embed in tokens, hours, dollars and bytes, and find the line that breaks first
The honest fix is to re-embed every chunk with v2. Most teams guess this cost wrong. The compute is cheap. The memory and the moving corpus are not.
Now the memory. Call the number of stored vectors N, the width d and the bytes per number b.
S equals N times d times b.
Multiply N by d by b, then add the index graph. A shadow index holds both versions, so double the total.
4,200,000 × 768 × 4 = 12.9 GB. A graph index with 64 neighbour ids of 4 bytes per vector adds 1.08 GB. Both versions: 2 × (12.9 + 1.08) = 28.0 GB on a 32 GB box.
| Precision | Bytes per vector | 4.2M vectors | Cosine to float32 |
|---|---|---|---|
| float32 | 3,072 | 12.9 GB | 1 |
| float16 | 1,536 | 6.45 GB | 0.99999998 |
| int8 | 768 | 3.23 GB | 0.99997 |
| 1 bit (sign) | 96 | 0.40 GB | 0.80 |
Smaller numbers make room for the shadow copy. One-bit codes change scores a lot, so measure recall on the golden set and record the precision in the fingerprint.
Each bar is one line of the bill against its limit. Raise the corpus size and see which bar turns red first.
Assumed: 380 tokens per chunk, 250 chunks a second per GPU, $1 per GPU-hour, a graph of 256 bytes per vector, a 32 GB box. Limits (24 hours, 5% stale, $1,000) are illustrative. We measured the cosine column on 2,000 random unit vectors.
The backfill takes 16,800 seconds, and the corpus keeps changing. At 30 writes a second: 30 × 16,800 = 504,000 writes, up to 12% of the corpus. Those are the newest chunks, which users ask about most. Dual write fixes it: during the window, every write goes through both encoders into both indexes. A watermark sweep afterwards re-embeds anything changed since the start, to catch failed dual writes.
At 900 million chunks, the same arithmetic gives 1,000 GPU-hours: 42 days on one GPU, 15.6 hours on 64. The shadow copy needs 1.38 TB of float16 vectors. Then the question becomes how to avoid a backfill.
The failure. Symptom: the golden set looks fine while users report missing recent content. Measure: count rows per encoder version, grouped by document age. Fix: run the watermark sweep, then turn on dual write.
Chapter 3
Train v2 to answer against the old index, and price the leash
What if v2 learns to put its vectors where v1 put them? Then v2 queries can search the old index on day one. This is backward-compatible training (BCT), from Shen et al. (CVPR 2020), first built for face-recognition galleries. It needs one thing: you train v2 yourself.
| Query | Index | Meaning | Recall@8 |
|---|---|---|---|
| v1 | v1 | today | 0.860 |
| v2 | v2 | after a full backfill | 0.905 |
| v2 | v1 | compatibility, without BCT | 0.110 |
Shen et al. push the new features through the old model's frozen classifier. A text encoder has no classifier, so a common version anchors each new vector to the old vector of the same text. Call the new encoder φ-new, the old one φ-old, and the anchor weight λ.
L equals L-task plus lambda times the mean over x of one minus the cosine of phi-new of x and phi-old of x.
Embed each text x with both encoders. Score how far apart the two vectors point as one minus their cosine. Average, multiply by lambda, add to L-task.
A new vector 70° from its old twin adds 1 − cos 70° = 0.66 to the bracket; at 0° it adds 0. At 180° it adds 2, yet the pull is zero, because the pull along the sphere scales with sin of the angle.
Grey is v2 without the anchor. Orange is v2 at your lambda. The dashed line is today. Find the lambda where orange stays above the line and its right end stays high.
Illustrative sweep, made up for this page: the shape (compatibility rises, the ceiling falls) is the real trade. Measure your own sweep before you pick lambda.
Call the share of the index already re-embedded m. A first estimate of recall during the backfill blends two numbers:
R of m equals m times R-new, plus one minus m times R-mix.
Weight R-new by the share done and R-mix by the share left, then add.
Without BCT at m = 0.5: 0.5 × 0.905 + 0.5 × 0.110 = 0.51, far below today's 0.86. With the illustrative BCT numbers at lambda 1: 0.5 × 0.884 + 0.5 × 0.845 = 0.86. It clears 0.86 from m = 0.38.
The failure. Symptom: a half-migrated index serves worse than the blend says. Measure: score v1 rows and v2 rows of equal relevance against v2 queries; the v1 rows score lower and lose top-8 slots. Fix: serve one version at a time and switch at once.
Chapter 4
Hash the whole text-to-vector path and make the search refuse a mismatch
A model name is not a version. The same name gives a different space when any step between the text and the vector changes.
| What changed | Model name | Space |
|---|---|---|
| pooling, first token to mean | same | different |
| query prefix added | same | different |
| normalized at write, not at query | same | scores stop being cosines |
| chunker 512 to 256 tokens | same | different corpus |
| stored as float16 | same | same, cosine 0.99999998 |
| new upstream revision, same tag | same | anything |
The prefix row bites often. The BGE retrieval models, for example, document a query instruction ("Represent this sentence for searching relevant passages: "). Two services that disagree on it get different vectors from the same weights.
So hash every setting that can change the output. The hash is the fingerprint. Twelve hex characters hold 48 bits, so a chance collision becomes likely only after about 20 million different specs.
pythonimport hashlib, json SPEC = {"model_id": "BAAI/bge-base-en-v1.5", "revision": "<pinned commit>", "pooling": "cls", "normalize": True, "max_seq_len": 512, "query_prefix": "Represent this sentence for searching relevant passages: ", "chunker": {"size": 512, "overlap": 64}, "dtype": "float32", "dim": 768} def fingerprint(spec): blob = json.dumps(spec, sort_keys=True, separators=(",", ":")) # order-free return hashlib.sha256(blob.encode()).hexdigest()[:12] def search(index, qvec, qfp, k=8): if qfp != index.manifest["fingerprint"]: # first, and it raises raise RuntimeError(f"query fp {qfp} != index fp; refusing") return index.knn(qvec, k)
The fingerprint lives in five places: every vector row, each index manifest, the query in flight, every cache key, and an append-only registry. The registry maps each fingerprint to its full spec.
The index uses the base spec. Switch on a change to the query path and read the two fingerprints. Then switch the refusal off.
This page hashes the spec with a fast 48-bit FNV hash so it runs in the browser; use SHA-256 in production. Which changes move the space follows the table above.
Refusing makes a loud outage: found in minutes, reverted with one flag. Degrading makes weeks of confident wrong answers. A contract test in CI adds a second guard. It embeds 20 fixed phrases, compares them with stored vectors, and fails if any cosine is below 0.9999. Its message says "bump the spec", not "loosen the threshold".
The failure. Symptom: two services disagree on one query. Measure: send one string through both; below 0.999 means different paths. Fix: move the differing step into the fingerprinted spec.
Chapter 5
Measure the world moving under a frozen encoder, against a noise floor you compute first
Change nothing for six weeks. Retrieval still gets worse. Content drift is the corpus moving, such as a launch that adds 40,000 chunks of new words. Query drift is the users moving, such as a renamed feature. The golden set is a photo of old traffic, so its score stays flat while live quality falls.
Average one day of query vectors into a centroid and compare it, by cosine, with the four-week centroid. What move is real? Text embeddings sit in a cone, so the mean of many unit vectors has a length well above zero. Call that length μ and the day's query count n.
One minus cosine theta is about one minus mu squared, over two n mu squared.
One query scatters around the mean by one minus mu squared. Averaging n queries divides that by n. Divide by mu squared for an angle, then halve.
With an assumed mu = 0.42 and n = 50,000: (1 − 0.1764) / (2 × 50,000 × 0.1764) = 0.000047. The noise floor is cos = 0.99995. A reading of 0.9971 is 62 times further from 1: a real shift.
Turn each query into one number, such as its best similarity to the corpus. Cut the baseline into 10 bins of 10% each. Call the baseline share of bin i e-i and this week's share a-i.
PSI equals the sum over i of a-i minus e-i, times the natural log of a-i over e-i.
For each bin, multiply a-i minus e-i by the log of a-i over e-i. Both factors share a sign, so each term is positive. Add the ten terms.
With made-up shares 0.04, 0.05, 0.07, 0.09, 0.10, 0.11, 0.12, 0.13, 0.14 and 0.15, bin 1 adds (−0.06) × ln 0.4 = 0.055. All ten give PSI = 0.148: moderate, on the usual bands of 0.10 and 0.25.
An empty bin makes ln(0) infinite. Floor each share at 0.5 / n: one emptied bin then adds 0.92. Signal 3 is the share of queries whose best match falls below the baseline's 5th percentile. It starts at 5%, and at 50,000 queries a day 5.3% is already three standard errors up.
A new product line lands in week 5. Set the wave size and scrub the weeks. Note which signal fires first.
Illustrative simulation. The alarm lines are the ones derived here: centroid 10 times its floor (cosine 0.9995), PSI 0.10, rate 5.29%.
The failure. Symptom: quality decays for two months with no deploy and matching fingerprints. Measure: centroid cosine below its floor, PSI above 0.10. Fix: refresh the golden set and recalibrate every threshold; roll nothing back.
Chapter 6
Measure change without labels, then size the golden set so the gate can see the regression it guards
A candidate encoder scores nDCG 0.941 on 200 golden queries. Production scores 0.951. Ship or block? First ask whether a one-point gap is bigger than the noise.
Gate on recall@k at the k you send downstream: a chunk outside the top 8 never reaches the language model. Watch overlap@k too, which needs no labels: the share of the top k that two systems share. If v1 returns a to h and v2 returns a, c, e and five new chunks, overlap@8 = 3 / 8 = 0.375. Below 0.20, suspect a version mismatch before an upgrade. Chapter 0's outage would show near zero within a minute.
Per-query nDCG spreads widely, with a standard deviation near 0.25. Over 200 queries the standard error is 0.25 / √200 = 0.018, larger than the gap. Pair the systems on the same queries and study the per-query differences. Their spread is smaller, say 0.08, so the error is 0.0057. The gap is 1.77 standard errors: still undecided.
So state the gate as non-inferiority: ship if v2 is not worse by more than a margin δ. Call the observed drop d and the spread of paired differences s.
n is at least one point nine six times s, over delta minus d, all squared.
Subtract d from delta to get the room left. Divide 1.96 times s by that room and square it. With that many queries, the interval's top end stays under delta.
s = 0.08, delta = 0.010, d = 0.004: 1.96 × 0.08 / 0.006 = 26.1, and 26.1 squared is 683 queries, not 200.
Teal is the observed drop, purple its 95% interval, pink the margin. Grow n until the interval's right end clears the margin.
The margin is fixed at 0.010 nDCG. Normal approximation; the numbers are the chapter's made-up example.
Gate the data, not only the code. Build the v2 index on the same corpus snapshot and shadow 5% of queries. Then serve 1%, 5%, 25% and 100%, and recheck each gate at each step. Soak 7 days to cover a weekly cycle. Gate latency, memory and cost too.
The failure. Symptom: the gate passes a candidate that users find worse. Measure: compare the interval width with delta. Fix: grow the set toward n, or admit the gate cannot see one-point drops and widen delta.
Chapter 7
Pick a cache threshold by capping wrong answers, and add a verifier when no threshold works
A semantic cache embeds a new question and finds the nearest stored question. If the cosine is above a threshold τ (tau), it returns the stored answer and skips the language model. A retriever's mistakes get a second look downstream. A cache's mistakes go straight to the user.
Model it with made-up bells. 22% of traffic repeats a cached question, and its best match scores around 0.93 (spread 0.04). The rest find only a related question, around 0.70 (spread 0.08). A false hit is a cached answer to a different question.
| τ | Hit rate | Wrong answers per million |
|---|---|---|
| 0.95 | 6.9% | 693 |
| 0.90 | 17.5% | 4,844 |
| 0.85 | 23.9% | 23,709 |
Going from 0.95 to 0.85 multiplies hits by 3.5 and wrong answers by 34. Now price it. Call the saving per hit ΔC, the loss per wrong answer L, and the false share of all hits f.
f must be less than delta-C over L.
Every hit saves delta-C. Every false hit also loses L. The cache pays only while the false share f stays under delta-C over L. The hit rate does not appear.
An illustrative call of 4,000 input tokens at $3 per million plus 500 output tokens at $15 per million costs $0.0195, so delta-C is about $0.02. With L = $0.50 the limit is 4%. At tau 0.90, f = 2.8%: +$1,078 per million queries. At tau 0.85, f = 9.9%: −$7,080.
Teal: questions that repeat a cached one. Purple: related but different. The cache serves everything right of the pink line. The red area is wrong answers. Raise the cost of a wrong answer until no threshold pays, then switch on the verifier.
Illustrative bells and prices. The verifier costs $0.001 per hit, rejects 90% of false hits and 2% of true hits. Saving per hit $0.02.
Raise L to $5 and the limit becomes 0.4%. Even at tau 0.99, f = 0.76%. No threshold works, so add a stage. A cheap verifier asks "does this stored answer answer this question?" With it, tau 0.90 earns +$2,927 per million at L = $0.50, and +$748 at L = $5 instead of −$20,718.
Put the fingerprint in every cache key. A version bump then gives a cold cache, a cost you can see, in place of old-space answers to new-space questions.
The failure. Symptom: users get answers to questions they did not ask. Measure: sample cache hits and read them; check the cache namespace against the current fingerprint. Fix: namespace by fingerprint, cap f, add a verifier if L is high.
Chapter 8
Run an encoder change as a state machine where rollback stays a flag until the last step
One rule shapes every phase: rollback must stay free until the last possible moment. Free means a config flag, not a restore. Do not start without these:
Most migrations run on five independent flags: dual write, backfill running, shadow share, v2 traffic share, v1 index loaded. Five on/off flags make 25 = 32 combinations. Only a few are safe. "v2 traffic while the backfill is at 40%" is one flag away. It serves the mixed index of Chapter 3.
So keep one state field with legal moves. A dangerous combination is then a move that does not exist, not a flag someone can set at 3 a.m. The state is one string in one place, so a status page can show where the migration stands.
Step through the phases. Watch memory and the rollback cost. Press Serve v2 now early and see the machine refuse.
Memory uses the Chapter 2 scenario: 14.0 GB for one float32 copy with its graph, 28.0 GB for two.
| Phase | Exit when | Rollback |
|---|---|---|
| Version the reads | a planted mismatch in staging raises | revert one commit |
| Dual write | v2 writes succeed 99.9% for 24 h | turn off the v2 branch |
| Backfill, newest first | row counts per fingerprint match | stop the job |
| Reconcile | a second sweep finds nothing | run it again |
| Shadow read | overlap@8 between 0.5 and 0.9 | stop sampling |
| Canary, ramp | every gate passes at every step | routing flag |
| Soak 7 days | a full week with no breach | routing flag; v1 still loaded |
| Decommission | v1 dropped, fingerprint kept forever | none |
After the switch, every number tuned on v1 is stale. That list holds the cache threshold, the duplicate cutoff, the out-of-range cutoff, cluster ids, drift baselines and reranker weights. Re-measure each in the new space, because score scales differ between encoders even when both are cosines.
The failure. Symptom: a problem after the ramp needs a full rebuild. Mechanism: "ramp to 100%" and "drop v1" shipped in one change. Fix: drop v1 on a separate day, after the soak.
Chapter 9
Keep the strategies, the numbers, the checks and the code in one place
An embedding is a coordinate, and a coordinate means nothing without the encoder that made it. Everything on this page keeps that link visible.
| Strategy | Ship time | Quality kept | Needs |
|---|---|---|---|
| Full re-embed | hours to weeks | all of it | source text, 2× memory, dual write |
| BCT | day one | most (97.7% in the toy sweep) | you train v2, and decide before training |
| Procrustes bridge | minutes | part | texts embedded by both encoders |
| Do nothing, monitor | none | what drift leaves | drift signals |
| Tool | Formula | Number from this page |
|---|---|---|
| Rotation | (R a) · (R b) = a · b | 0.966 before and after 70° |
| Probe floor | 1 / √d | 0.036 at d = 768 |
| Storage | N × d × b | 12.9 GB; 28.0 GB with a shadow |
| Anchor loss | Ltask + λ · mean(1 − cos) | 0.66 for a 70° gap |
| Blend | m Rnew + (1 − m) Rmix | 0.51 at halfway without BCT |
| Centroid floor | (1 − μ²) / (2nμ²) | cos 0.99995 at n = 50,000 |
| PSI | Σ (a − e) ln(a/e) | 0.148, moderate |
| Gate size | (1.96 s / (δ − d))² | 683 queries |
| Cache | f < ΔC / L | 4% at $0.02 and $0.50 |
pythonimport numpy as np, math def probe(a, b): # a, b: [20, d] unit rows from two paths same = (a * b).sum(-1).mean() return "same" if same > 0.999 else "different" if same > 3 / math.sqrt(a.shape[1]) else "unrelated" def bridge(X_old, Y_new): # [N, d] each: the best rotation, Procrustes U, _, Vt = np.linalg.svd(X_old.T @ Y_new) return U @ Vt # apply as X_old @ R, then renormalize def psi(a, e=0.1, n=50_000): a = np.maximum(np.asarray(a), 0.5 / n) # the ln(0) guard return float(((a - e) * np.log(a / e)).sum()) def gate_size(s, delta, d): return math.ceil((1.96 * s / (delta - d)) ** 2) print(4_200_000 * 768 * 4 / 1e9) # 12.9 GB print(psi([.04,.05,.07,.09,.10,.11,.12,.13,.14,.15])) # 0.148 print(gate_size(0.08, 0.010, 0.004)) # 683
RAG · Text Chunking · On-Device Embeddings · The Statistics of Evaluation · Regression Testing for ML · Storage and Retrieval · Caching and CDNs
Papers: Shen, Xiong, Xia, Soatto, Towards Backward-Compatible Representation Learning (CVPR 2020); Ramanujan et al., Forward Compatible Training for Large-Scale Embedding Retrieval Systems (CVPR 2022); Kornblith et al., Similarity of Neural Network Representations Revisited (ICML 2019); Schönemann, "A generalized solution of the orthogonal Procrustes problem" (Psychometrika, 1966); Malkov and Yashunin, HNSW (2016); Kusupati et al., Matryoshka Representation Learning (NeurIPS 2022).
Now press Present or Teach and explain four things from memory. Why can training not see a rotation? What does a migration cost in memory? How does BCT trade ceiling for compatibility? Why does a cache threshold come from f < ΔC / L? Then go back to the hero and say why the mixed backfill dips to 0.51 at halfway.