Embedding Ops

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.

Ship v2 four ways

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

The Silent Outage

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.

Two dimensions show the whole failure

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°:

kitten cos 5° = 0.996 · cat cos 10° = 0.985 · truck cos 80° = 0.174

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:

cat cos 80° = 0.174 · kitten cos 65° = 0.423 · truck cos 10° = 0.985

Turn the new encoder, watch the winner change

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.

70°

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).

The road

  1. Spaces do not transfer: training cannot see rotations, so two runs disagree.
  2. The migration bill: tokens, hours, dollars, bytes and the stale window.
  3. Backward-compatible training: keep v2 in v1's space, and the cost of that leash.
  4. Versioning discipline: fingerprint the pipeline and refuse a mismatch.
  5. Drift with no model change: centroid, PSI and the out-of-range rate.
  6. The release gate: overlap, paired tests and the size of the golden set.
  7. The semantic cache: a threshold, a break-even and a verifier.
  8. The runbook: phases, exit criteria and rollbacks.
  9. Field guide: terms, numbers, code and links.
After the v2 deploy, the top result for a billing question is an unrelated chunk with cosine 0.985. What does that score tell you?

Chapter 1

Why Spaces Do Not Transfer

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:

Say it aloud

R-a dot R-b equals a dot b.

R a
R-a vector a after the rotation R, a 768 by 768 matrix.
·
dot the inner product.
a
a one embedding, 768 numbers.
b
b another embedding.
In plain words

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.

With numbers

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.

Rotate run B, then try to undo it

Blue shows run A and orange shows run B, five documents each. Turn the rotation, add some new knowledge, then switch on the bridge.

70°
15°

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.

The thirty-second probe

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-cosineReading
above 0.999same space; look for the bug elsewhere
0.11 to 0.999related but different spaces: this is the outage
below 0.11no 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.

The probe gives a mean self-cosine of 0.31 between two services. What does that mean?

Chapter 2

The Migration Bill

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.

  1. Tokens: 4,200,000 chunks × 380 tokens = 1.6 billion tokens.
  2. A hosted API at an illustrative $0.02 per million tokens: about $32. At a rate limit of 1 million tokens a minute: 26.6 hours.
  3. One GPU at an assumed 250 chunks a second: 4,200,000 / 250 = 16,800 s = 4.7 hours, or $4.70 at an illustrative $1 an hour.

Now the memory. Call the number of stored vectors N, the width d and the bytes per number b.

Say it aloud

S equals N times d times b.

S
S storage for the raw vectors, in bytes.
N
N the number of vectors, here 4.2 million.
d
d numbers per vector, here 768.
b
b bytes per number: 4 for float32, 2 for float16, 1 for int8, one eighth for one bit.
In plain words

Multiply N by d by b, then add the index graph. A shadow index holds both versions, so double the total.

With numbers

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.

PrecisionBytes per vector4.2M vectorsCosine to float32
float323,07212.9 GB1
float161,5366.45 GB0.99999998
int87683.23 GB0.99997
1 bit (sign)960.40 GB0.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.

Push the corpus until a line breaks

Each bar is one line of the bill against its limit. Raise the corpus size and see which bar turns red first.

4.2M
1
30

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.

The backfill takes 4.7 hours at 30 writes a second, and you skip dual write. What do users most likely see?

Chapter 3

Backward-Compatible Training

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.

QueryIndexMeaningRecall@8
v1v1today0.860
v2v2after a full backfill0.905
v2v1compatibility, without BCT0.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 λ.

Say it aloud

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.

L
L the total loss v2 trains on.
Ltask
L-task v2's normal contrastive loss.
λ
lambda the anchor weight, 0 or more.
meanx
the mean over x the average over a batch of texts x.
cos
the cosine of the cosine of the angle between two vectors.
φnew(x)
phi-new of x v2's vector for text x; training changes it.
φold(x)
phi-old of x v1's vector for the same text, frozen.
In plain words

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.

With numbers

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.

Tighten the leash, watch both ends move

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.

1

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:

Say it aloud

R of m equals m times R-new, plus one minus m times R-mix.

R(m)
R of m recall when share m is re-embedded.
m
m the share done, from 0 to 1.
Rnew
R-new recall of v2 queries on v2 vectors.
Rmix
R-mix recall of v2 queries on v1 vectors.
In plain words

Weight R-new by the share done and R-mix by the share left, then add.

With numbers

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.

Lambda 3 gives v2-on-v1 recall 0.858 and a ceiling of 0.861. Lambda 1 gives 0.845 and 0.884. Which do you ship?

Chapter 4

Versioning Discipline

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 changedModel nameSpace
pooling, first token to meansamedifferent
query prefix addedsamedifferent
normalized at write, not at querysamescores stop being cosines
chunker 512 to 256 tokenssamedifferent corpus
stored as float16samesame, cosine 0.99999998
new upstream revision, same tagsameanything

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.

Change one setting, see who notices

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.

Two services use the same pinned model, pooling and normalization. One adds the query prefix and one does not. What should the fingerprint do?

Chapter 5

Drift With No Model Change

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.

Signal 1: the centroid

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.

Say it aloud

One minus cosine theta is about one minus mu squared, over two n mu squared.

1 − cos θ
one minus cosine theta how far noise alone moves the day's centroid from the true one.
≈
is about an estimate for large n.
μ
mu the length of the mean query vector, between 0 and 1.
n
n queries in one day.
In plain words

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 numbers

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.

Signal 2: PSI

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.

Say it aloud

PSI equals the sum over i of a-i minus e-i, times the natural log of a-i over e-i.

PSI
P-S-I the population stability index: how far the shares moved.
Σi
the sum over i add one term per bin, 10 bins.
ai
a-i this week's share in bin i.
ei
e-i the baseline share, 0.10.
ln
the natural log of negative when a bin shrinks.
In plain words

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 numbers

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.

Launch a product, watch three alarms

A new product line lands in week 5. Set the wave size and scrub the weeks. Note which signal fires first.

0.60
8

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.

Today's query centroid has cosine 0.9971 against the baseline, over 50,000 queries. The noise floor is 0.99995. What is it?

Chapter 6

The Release Gate

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.

Say it aloud

n is at least one point nine six times s, over delta minus d, all squared.

n
n paired golden queries needed.
≥
is at least fewer queries cannot show it.
1.96
one point nine six the multiplier for a 95% interval.
s
s the standard deviation of per-query differences.
δ
delta the largest drop you accept.
d
d the drop you observe.
In plain words

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.

With numbers

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.

Size the golden set

Teal is the observed drop, purple its 95% interval, pink the margin. Grow n until the interval's right end clears the margin.

200
0.08
0.004

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.

A candidate scores 0.010 nDCG below production on 200 paired queries, with paired s = 0.08. What is the right call?

Chapter 7

The Semantic Cache

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 rateWrong answers per million
0.956.9%693
0.9017.5%4,844
0.8523.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.

Say it aloud

f must be less than delta-C over L.

f
f false hits divided by all hits.
<
must be less than the condition for the cache to pay.
ΔC
delta-C dollars saved by one skipped model call.
L
L dollars lost on one wrong answer.
In plain words

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.

With numbers

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.

Find the operating point

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.

0.900
$0.50
0.22

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.

A hit saves $0.02 and a wrong answer costs $0.50. At tau 0.85 the hit rate is 23.9% and 10% of hits are wrong. What do you do?

Chapter 8

The Runbook

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:

  1. You keep the source text of every vector, readable.
  2. Every row carries a fingerprint; every index has a manifest.
  3. The search refuses a fingerprint mismatch.
  4. The golden set fits your margin (683 queries for one nDCG point in Chapter 6).
  5. Drift signals run, so a baseline exists before the change.
  6. Memory fits two full copies: 28 GB of 32 in Chapter 2.

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.

Walk the migration, try a shortcut

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.

PhaseExit whenRollback
Version the readsa planted mismatch in staging raisesrevert one commit
Dual writev2 writes succeed 99.9% for 24 hturn off the v2 branch
Backfill, newest firstrow counts per fingerprint matchstop the job
Reconcilea second sweep finds nothingrun it again
Shadow readoverlap@8 between 0.5 and 0.9stop sampling
Canary, rampevery gate passes at every steprouting flag
Soak 7 daysa full week with no breachrouting flag; v1 still loaded
Decommissionv1 dropped, fingerprint kept forevernone

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.

v2 has served 100% of traffic for two hours and every gate is green. What should you not do today?

Chapter 9

Field Guide

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.

StrategyShip timeQuality keptNeeds
Full re-embedhours to weeksall of itsource text, 2× memory, dual write
BCTday onemost (97.7% in the toy sweep)you train v2, and decide before training
Procrustes bridgeminutesparttexts embedded by both encoders
Do nothing, monitornonewhat drift leavesdrift signals
ToolFormulaNumber from this page
Rotation(R a) · (R b) = a · b0.966 before and after 70°
Probe floor1 / √d0.036 at d = 768
StorageN × d × b12.9 GB; 28.0 GB with a shadow
Anchor lossLtask + λ · mean(1 − cos)0.66 for a 70° gap
Blendm Rnew + (1 − m) Rmix0.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
Cachef < ΔC / L4% at $0.02 and $0.50

Checklist

  1. Keep the source text for every vector.
  2. Fingerprint the whole text-to-vector path, not the model name.
  3. Refuse on a mismatch; never fall through to a search.
  4. Compute the noise floor before you read any monitor.
  5. Size the golden set from the margin.
  6. Namespace caches by fingerprint and cap the false share.
  7. Drop the old index on a separate day, after the soak.

The core in code

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

The embedding family

Keep going

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).

The takeaway. When a space changes, make the system lose speed or money, never truth. A cold cache is a line on a dashboard; a stale cache is an incident nobody sees.

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.

Embedding Ops
The embedding family · Back to Gleams