Skip to content
Skip to lesson
Back to Topics
LearnApplied LLM Engineering & RAGEmbedding Similarity & Quantization
MediumEmbeddings & Vector Search15 min read

Embedding Similarity & Quantization

Master cosine vs dot vs L2 geometry, dimensionality reduction with Matryoshka prefixes, PCA, and Johnson-Lindenstrauss projections, the 2D-map trap, and INT8/binary quantization.

On this page

A developer asks, "How does FlashAttention fuse softmax into tiled SRAM passes?" Your retriever embeds that query and scans stored passages. One similarity rule puts flash-attention-v2 first; another favors a longer embedding from a draft note; compressing vectors to fit RAM shuffles the shortlist again. Separating similarity geometry from dimensionality reduction and quantization isolates which step changed the rank.

Contrastive training pulls semantically similar passages together in vector space and pushes unrelated passages apart (covered in Sentence Embeddings & Contrastive Loss). Here the encoder stays fixed while we dissect searching that vector space at scale: similarity metrics, Matryoshka prefixes, , Johnson-Lindenstrauss projections, the 2D-map trap, and INT8/1-bit quantization.

Three ways to measure closeness

An maps text to a vector in Rd\mathbb{R}^d. Three rulers answer different versions of "how close are two vectors?"

RulerFormulaRangeSensitive to positive length scaling?
A⋅B∥A∥∥B∥\frac{\mathbf{A} \cdot \mathbf{B}}{\|\mathbf{A}\| \|\mathbf{B}\|}[−1,1][-1, 1]No
∑i=1daibi\sum_{i=1}^d a_i b_i(−∞,+∞)(-\infty, +\infty)Yes
Euclidean (L2) distance∥A−B∥2\|\mathbf{A} - \mathbf{B}\|_2[0,+∞)[0, +\infty)Yes

Check flash-attention-v2 at A=[3,4]\mathbf{A} = [3, 4] and tiled-softmax-notes at B=[4,3]\mathbf{B} = [4, 3]. Both have norm 5: dot product is 24, cosine is 24 / 25 = 0.96, and L2 distance is 2≈1.41\sqrt{2} \approx 1.41. Stretching A\mathbf{A} tenfold to [30, 40] multiplies dot product tenfold to 240 and expands L2 distance, while cosine stays locked at 0.96.

Top panels plot equal-length vectors A = (3, 4) and B = (4, 3) with norm 5, dot product 24, cosine 0.96, and Euclidean distance 1.414. Bottom AxisPlot scales A by k from 1 to 10: normalized dot product rises linearly to 10x while normalized cosine stays flat at 1.0.
Top: equal-length vectors A = (3, 4) and B = (4, 3) have cosine 0.96 and dot product 24. Bottom: scaling A by k keeps cosine flat at 1.0x while dot product climbs linearly to 10x.

When all three rulers agree

When every stored vector and query is L2-normalized (∥A∥2=∥B∥2=1\|\mathbf{A}\|_2 = \|\mathbf{B}\|_2 = 1), cosine equals dot product and squared L2 is a strictly decreasing linear function of it:

cos⁡(A,B)=A⋅B=1−∥A−B∥222\cos(\mathbf{A}, \mathbf{B}) = \mathbf{A} \cdot \mathbf{B} = 1 - \frac{\|\mathbf{A} - \mathbf{B}\|_2^2}{2}

On the unit hypersphere, descending cosine, descending dot product, and ascending squared L2 induce the exact same ranking. Normalize rows once at ingestion and queries once at search time, then score with a fast inner-product multiply.[1] Reject zero vectors explicitly, and rescale by max(abs(v)) before dividing by the norm so tiny nonzero values like 1e-308 do not underflow to zero. Use raw dot product only for maximum inner product search (MIPS) models trained to store learned priors in magnitude.

metric-equivalence-and-norm-trap.py
import numpy as np

def l2_normalize(v: np.ndarray) -> np.ndarray:
    arr = np.asarray(v, dtype=np.float64)
    scale = float(np.max(np.abs(arr)))
    if scale == 0.0 or not np.all(np.isfinite(arr)):
        raise ValueError("need a finite nonzero vector")
    scaled = arr / scale
    return scaled / np.linalg.norm(scaled)

labels = ["flash-attention-v2", "linear-attn-draft", "rope-encoding"]
docs = np.array([[0.95, 0.05], [8.00, 6.00], [0.20, 0.90]])
query = np.array([1.0, 0.0])

unit_docs = np.vstack([l2_normalize(r) for r in docs])
unit_q = l2_normalize(query)
unit_dot = unit_docs @ unit_q
sq_l2 = np.sum((unit_docs - unit_q) ** 2, axis=1)

print("raw dot winner:", labels[int(np.argmax(docs @ query))], "| unit winner:", labels[int(np.argmax(unit_dot))])
print("unit dot == 1 - L2^2/2:", np.allclose(unit_dot, 1.0 - sq_l2 / 2.0))
assert np.allclose(sq_l2, 2.0 - 2.0 * unit_dot, atol=1e-12)
Output
raw dot winner: linear-attn-draft | unit winner: flash-attention-v2
unit dot == 1 - L2^2/2: True

Shrinking dimensions: Matryoshka, PCA, and random projection

Every float32 coordinate costs 4 bytes and one multiply-add per candidate (O(d)O(d) work). One million 1,536-dimensional FP32 vectors already take 5.72 GiB (6.14 GB) before graph links or metadata. Three linear methods cut dd before quantization starts.

Matryoshka prefixes (MRL)

trains an encoder with nested losses at multiple prefix widths d∈Dd \in \mathcal{D}, packing broad semantics into leading coordinates so you can slice a vector to 256 or 512 dimensions on demand.[2][3] Always re-normalize sliced prefixes for both documents and queries. Renormalization restores unit norm, yet it cannot recover distinctions stored only in truncated tail coordinates:

Three-stage visual of Matryoshka 4d-to-2d prefix truncation. Left: four 4d vectors split into Head [d0, d1] and Tail [d2, d3] show query q [1,0|0,1], flash-attn [1,0|0,1], and sparse-attn [1,0|1,0] share identical heads while rope-enc is [0,1|0,1]. Center: 2d prefix space (d0, d1) collapses flash-attn and sparse-attn onto ray (1, 0) at cosine 1.00. Right: paired 2d vs 4d cosine bars show full 4d rescoring separates flash-attn (1.00) from sparse-attn (0.50).
Keeping only head coordinates collapses flash-attn and sparse-attn onto prefix ray (1, 0) at cosine 1.00. Returning a shortlist K > 1 lets full 4d rescoring separate flash-attn (1.00) from sparse-attn (0.50).

PCA: learn a shorter linear basis

When an encoder lacks MRL training, Principal Component Analysis (PCA) learns an orthogonal rotation aligned with the corpus's top variance directions. Subtract column means μ=1N1TX\mu = \frac{1}{N}\mathbf{1}^T X to get Xc=X−μX_c = X - \mu and take its thin (avoiding XcTXcX_c^T X_c, which squares the condition number):[4][5]

Xc=UΣVT,C=1N−1VΣ2VTX_c = U \Sigma V^T, \qquad C = \frac{1}{N - 1} V \Sigma^2 V^T

Project every document and live query through the same persisted basis z=(x−μ)Vkz = (x - \mu) V_k, then L2-normalize before cosine search. Watch the central pitfall: explained variance is not search relevance. High-variance axes often track length or prose-vs-code formatting while fine retrieval distinctions sit in lower-variance components. Always pick kk from held-out Recall@K, not a fixed variance cutoff:

prefix-and-pca-recall-sweep.py
from sklearn.decomposition import PCA

# 1. MRL prefix slicing loses tail distinctions until full-width rescoring.
mrl_docs = np.array([[1.0, 0.0, 1.0, 0.0], [1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0]])
mrl_q = np.array([1.0, 0.0, 0.0, 1.0])
mrl_names = ["sparse-attn", "flash-attn", "rope-enc"]
pick = lambda w: mrl_names[int(np.argmax(np.vstack([l2_normalize(r[:w]) for r in mrl_docs]) @ l2_normalize(mrl_q[:w])))]
print(f"MRL 4d winner={pick(4)} | 2d prefix tie winner={pick(2)}")

# 2. PCA sweep: Recall@3 hits 1.000 at k=8 with only 0.716 explained variance.
rng = np.random.default_rng(21)
norm_rows = lambda x: x / np.linalg.norm(x, axis=1, keepdims=True)
topics = norm_rows(rng.normal(0, 1, size=(20, 24)))
docs = np.vstack([t + rng.normal(0, 0.11, size=(3, 24)) for t in topics])
queries = np.vstack([t + rng.normal(0, 0.03, size=(1, 24)) for t in topics])
relevant = [set(range(3 * i, 3 * i + 3)) for i in range(20)]

def recall3(q: np.ndarray, d: np.ndarray) -> float:
    topk = np.argsort(-(norm_rows(q) @ norm_rows(d).T), axis=1, kind="stable")[:, :3]
    return float(np.mean([len(rel & set(row)) / 3 for rel, row in zip(relevant, topk)]))

for k in [2, 4, 8, 12]:
    pca = PCA(n_components=k).fit(docs)
    print(f"PCA k={k:>2}: recall@3={recall3(pca.transform(queries), pca.transform(docs)):.3f}, var={pca.explained_variance_ratio_.sum():.3f}")
Output
MRL 4d winner=flash-attn | 2d prefix tie winner=sparse-attn
PCA k= 2: recall@3=0.433, var=0.264
PCA k= 4: recall@3=0.900, var=0.452
PCA k= 8: recall@3=1.000, var=0.716
PCA k=12: recall@3=1.000, var=0.867

Johnson-Lindenstrauss random projection

When streaming corpora shift continuously and refitting PCA across replicas is impractical, random projection multiplies every vector by one fixed zero-mean matrix R∈Rd×kR \in \mathbb{R}^{d \times k} (Gaussian Rij∼N(0,1/k)R_{ij} \sim \mathcal{N}(0, 1/k) or sparse Achlioptas entries {−3/k,0,+3/k}\{-\sqrt{3/k}, 0, +\sqrt{3/k}\} with probabilities {1/6,2/3,1/6}\{1/6, 2/3, 1/6\}).[6]

The proves that for any N≥2N \ge 2 points and distortion 0<ϵ<10 < \epsilon < 1, a linear map RR exists keeping all pairwise squared Euclidean distances inside (1±ϵ)(1 \pm \epsilon) whenever:[7][8]

k≥4ln⁡Nϵ2/2−ϵ3/3,(1−ϵ)∥u−v∥2≤∥uR−vR∥2≤(1+ϵ)∥u−v∥2k \ge \frac{4 \ln N}{\epsilon^2 / 2 - \epsilon^3 / 3}, \qquad (1 - \epsilon)\|u - v\|^2 \le \|uR - vR\|^2 \le (1 + \epsilon)\|u - v\|^2

Crucially, kk scales only as O(ln⁡N/ϵ2)\mathcal{O}(\ln N / \epsilon^2), independent of ambient dimension dd. Yet the worst-case bound is conservative: at N=107N = 10^7 and ϵ=0.15\epsilon = 0.15, it asks for k≥6,368k \ge 6{,}368 (over 4x wider than d=1,536d = 1{,}536), and overlapping (1±ϵ)(1 \pm \epsilon) intervals can still swap close neighbors. Low-rank real embeddings often tolerate k=256k = 256, while isotropic unstructured vectors drop sharply:

jl-budget-and-projection.py
from sklearn.random_projection import GaussianRandomProjection

for eps in [0.15, 0.25, 0.50]:
    k_min = int(np.ceil(4 * np.log(10_000_000) / (eps**2 / 2 - eps**3 / 3)))
    print(f"JL bound (N=10M, eps={eps:.2f}): k >= {k_min}")

rng = np.random.default_rng(33)
docs = rng.normal(0, 1, size=(180, 48))
queries = docs[:12] + rng.normal(0, 0.03, size=(12, 48))
top5 = lambda q, d: np.argsort(-((q / np.linalg.norm(q, axis=1, keepdims=True)) @ (d / np.linalg.norm(d, axis=1, keepdims=True)).T), axis=1, kind="stable")[:, :5]

rp = GaussianRandomProjection(n_components=16, random_state=0).fit(docs)
overlap = np.mean([len(set(g) & set(p)) / 5 for g, p in zip(top5(queries, docs), top5(rp.transform(queries), rp.transform(docs)))])
print(f"48d -> 16d isotropic Gaussian RP top-5 cosine overlap: {overlap:.3f}")
Output
JL bound (N=10M, eps=0.15): k >= 6368
JL bound (N=10M, eps=0.25): k >= 2476
JL bound (N=10M, eps=0.50): k >= 774
48d -> 16d isotropic Gaussian RP top-5 cosine overlap: 0.367

Persist rp.components_ beside the index so every serving replica applies the identical transform.

The 2D-map trap: t-SNE and UMAP

Linear projections compress vectors for search. Nonlinear 2D maps do a completely different job: exploratory visual debugging to spot drift or anomalies before checking the original high-dimensional vectors.

Projecting hundreds of orthogonal axes onto a 2D plane triggers the crowding problem: volume grows exponentially with dimension, so moderate high-dimensional distances cannot all fit on a flat sheet. Two standard nonlinear methods trade global geometry to preserve local neighborhoods:

Always measure nearest-neighbor overlap (the fraction of points keeping their exact high-dimensional nearest neighbor in 2D) and confirm visual patterns directly in the full embedding space.

GoalPrimary metricBest methods
Inspect clusters or drift1-NN / kk-NN overlap + manual inspectionPCA, t-SNE, UMAP (plots only)
Shrink dimensions for servingRecall@K, RAM, latencyMRL prefix, PCA, random projection
Shrink bytes per coordinateCompressed Recall@K + rescored accuracySQ8, binary (1-bit), PQ

Memory sizing and scalar quantization (SQ8)

When shrinking dd still overflows RAM, quantization cuts bytes per coordinate. Raw coordinate payload for 1,536-dimensional vectors (before graph links, metadata, or retained FP32 copies):

RepresentationPer vector1M vectors100M vectorsRaw cut
FP32 (4 B/dim)6,144 B5.72 GiB572 GiB1x
INT8 SQ (1 B/dim)1,536 B1.43 GiB143 GiB4x
Binary (1 bit/dim)192 B183.1 MiB17.9 GiB32x
PQ-96 (96 one-byte IDs)96 B91.6 MiB8.94 GiB64x (+1.5 MiB codebooks)
Side-by-side comparison of 1,536-dimensional embedding storage across FP32, INT8, Binary, and PQ-96. Left: calibrated log-scale bars show exact bytes per vector and 1M-row RAM dropping from 6,144 B (5.72 GiB) for FP32 to 1,536 B (1.43 GiB) for INT8, 192 B (183.1 MiB) for Binary, and 96 B (91.6 MiB) for PQ-96. Right: linear compression ratio bars climb from 1x (32 b/d) to 4x (8 b/d), 32x (1 b/d), and 64x (0.5 b/d).
Compression ratio climbs 64x from FP32 to 96-subspace PQ across one million 1,536d rows. Shared codebooks, graph links, metadata, and optional full-precision rescore copies add to total RAM.

Scalar quantization (SQ8) maps each float32 coordinate to one byte (4x payload cut). Symmetric signed INT8 calibrates sj=max⁡(∣xj∣)/127s_j = \max(|x_j|) / 127 per dimension:

xq,j=clip⁡ ⁣(round⁡ ⁣(xjsj),−127,127),x^j=sjxq,jx_{q, j} = \operatorname{clip}\!\left(\operatorname{round}\!\left(\frac{x_j}{s_j}\right), -127, 127\right), \qquad \hat{x}_j = s_j x_{q, j}

Range-offset codecs (such as Qdrant's uint8) instead map calibrated intervals [a,b][a, b] to 0..255 via s=(b−a)/255s = (b - a)/255, x^=a+sc\hat{x} = a + s c.[12][13] Freeze calibration ranges once across ingestion and serving, and watch three bugs that wreck SQ8 recall:

  1. Dropping per-dimension scales: Scoring unscaled integer codes lets narrow-range dimensions overpower wide-range ones and reverses rank.
  2. Narrow int8 overflow: In NumPy, int8 @ int8 wraps in 8 bits; widen operands to int32 before multiplying.[14]
  3. Outlier-stretched ranges: One outlier at 25.0 stretches step width to 0.197, crushing ordinary coordinates in [-1, 1]. Quantile clipping (e.g., 99.9th percentile) shrinks ordinary MAE 25x while saturating the rare outlier.
AxisPlot over [-1, 1] shows how signed INT8 calibration with bound 25 creates coarse 0.197 quantization steps compared with clipped bound 1 at step 0.0079 closely tracking y = x. A ProgressList reports ordinary-range mean absolute error dropping from 0.0483 to 0.0019 (25x finer), while clipping saturates the single outlier 25 at 1.00.
Calibrating signed INT8 to max(|v|) = 25 stretches steps to 0.197 across [-1, 1]. Clipping to bound 1 shrinks ordinary MAE 25x (0.0483 to 0.0019) while saturating the outlier at 1.00.
sq8-scales-overflow-and-outliers.py
# 1. Per-dimension scales preserve dot order.
scales = np.array([10.0, 1.0], dtype=np.float32) / 127.0
db = np.array([[8.0, 0.0], [0.0, 1.0]], dtype=np.float32)
q = np.array([1.0, 1.0], dtype=np.float32)
codes = np.clip(np.rint(db / scales), -127, 127).astype(np.int8)
print("unscaled winner:", int(np.argmax(codes.astype(np.float32) @ q)), "| scaled winner:", int(np.argmax((codes.astype(np.float32) * scales) @ q)))

# 2. Narrow INT8 matmul wraps; widen to INT32 before multiplying.
q8, d8 = np.array([127, 127], dtype=np.int8), np.array([[127, 127], [126, 126]], dtype=np.int8)
wrapped, wide = d8 @ q8, d8.astype(np.int32) @ q8.astype(np.int32)
print(f"INT8 wrap={wrapped.tolist()} | INT32={wide.tolist()}")

# 3. Quantile clipping cuts ordinary MAE 25x.
ordinary = np.linspace(-1.0, 1.0, 101)
quant = lambda v, b: np.clip(np.rint(v / (b / 127.0)), -127, 127) * (b / 127.0)
print(f"MAE bound=25: {np.mean(np.abs(ordinary - quant(ordinary, 25.0))):.4f} | bound=1: {np.mean(np.abs(ordinary - quant(ordinary, 1.0))):.4f}")
assert int(wide.argmax()) == 0 and int(wrapped.argmax()) == 1
Output
unscaled winner: 1 | scaled winner: 0
INT8 wrap=[2, 4] | INT32=[32258, 32004]
MAE bound=25: 0.0483 | bound=1: 0.0019

Binary quantization and coarse-to-fine rescoring

Binary quantization (BQ) keeps only each coordinate's sign bit (1 if xj>0x_j > 0, else 0), cutting payload 32x relative to FP32. Packed into machine words, two binary codes compare via bitwise XOR and CPU popcount (AVX-512 VPOPCNTDQ processes 512 bits per instruction), computing Hamming distance with zero floating-point math.

For bb isotropic random hyperplanes, expected normalized Hamming distance matches vector angle:[15]

Erandom hyperplanes ⁣[DH(h(u),h(v))b]=θπ=arccos⁡(cos⁡(u,v))π\mathbb{E}_{\text{random hyperplanes}}\!\left[\frac{D_H(h(\mathbf{u}), h(\mathbf{v}))}{b}\right] = \frac{\theta}{\pi} = \frac{\arccos(\cos(\mathbf{u}, \mathbf{v}))}{\pi}

Raw coordinate signs are not random hyperplanes, however: nearly orthogonal vectors [1.0, 0.01, -1.0, -0.01] and [0.01, 1.0, -0.01, -1.0] (cosine = 0.020) share identical sign bits and tie at Hamming 0. Pair binary codes (best on high-dimensional, centered embeddings, or 1.5/2-bit rotated variants)[13] with a coarse-to-fine funnel: (1) scan 1-bit codes for a generous top-KK shortlist while evaluating metadata filters inline so disqualified rows never crowd out valid hits, (2) rescore those KK survivors with retained FP32 or SQ8 vectors, and (3) optionally rerank the top shortlist with a cross-encoder.

Two-stage retrieval funnel from coarse 1-bit Hamming filtering to exact FP32 cosine rescoring. Stage 1 compares query q = [0.8, -0.4, 0.6, -0.2] (sign bits 1010) against three candidates: linear-attn-draft (1010) and flash-attention-v2 (1010) tie in the Hamming 0 bucket (shortlist K=2), while adamw-decay (1100, Hamming 2, exact cos -0.435) is pruned. Stage 2 rescores the Hamming 0 shortlist in FP32, cleanly separating flash-attention-v2 (1.000) from linear-attn-draft (0.410).
Both linear-attn-draft and flash-attention-v2 tie at Hamming 0 against the query even though exact cosines are 0.410 vs 1.000. Shortlisting K = 2 plus FP32 rescoring (or inline metadata filtering) recovers flash-attention-v2.
binary-pack-shortlist-and-rescore.py
labels = ["linear-attn-draft", "flash-attention-v2", "adamw-decay"]
verified = np.array([False, True, True])
docs = np.array([[0.05, -2.00, 0.05, -2.00], [0.78, -0.38, 0.58, -0.22], [0.10, 0.60, -0.40, -0.20]])
query = np.array([0.80, -0.40, 0.60, -0.20])

pack = lambda v: int.from_bytes(np.packbits((v > 0).astype(np.uint8), bitorder="little").tobytes(), "little")
q_code = pack(query)
hamming = [(pack(row) ^ q_code).bit_count() for row in docs]
unit_q = l2_normalize(query)

pick_top = lambda ids: max([i for i in ids if verified[i]], key=lambda i: float(np.dot(l2_normalize(docs[i]), unit_q)), default=None)
k1 = sorted(range(3), key=lambda i: (hamming[i], i))[:1]
k2 = sorted(range(3), key=lambda i: (hamming[i], i))[:2]
prefilter_k1 = sorted([i for i in range(3) if verified[i]], key=lambda i: (hamming[i], i))[:1]

print("hamming:", hamming, "| post-filter K=1:", pick_top(k1))
print("rescore K=2:", labels[pick_top(k2)], "| pre-filter K=1:", labels[pick_top(prefilter_k1)])
assert pick_top(k1) is None and labels[pick_top(k2)] == "flash-attention-v2"
Output
hamming: [0, 0, 2] | post-filter K=1: None
rescore K=2: flash-attention-v2 | pre-filter K=1: flash-attention-v2

Rescoring only reorders shortlisted survivors; it cannot recover a document missed in stage one.

Product quantization and HNSW indexes

Quantization shrinks bytes per vector, while approximate nearest neighbor (ANN) indexes reduce how many vectors each query visits. When SQ8 still exceeds RAM, Product Quantization (PQ) splits each vector into MM subvectors, clusters each subspace into KK centroids offline (storing one byte ID per subspace for 32x–64x cuts), and scores unquantized queries via Asymmetric Distance Computation (ADC) lookup tables without decompressing database rows.[16] Production engines combine those codes with multi-layer HNSW graphs or inverted-file partitions (IVF), where graph links often rival the compressed code payload in RAM.[17] Continue to Vector Database Internals: HNSW & IVF for full PQ/ADC math, IVF residuals, OPQ rotations, and HNSW construction and search tuning (M, ef_construction, ef_search).

Product quantization and asymmetric distance computation (ADC) across four 2d subspaces s1 through s4. Top: four mini 2d Voronoi plots show unquantized query subvectors qs sitting close to centroid ID 1 (distance 0.02 each) and far from centroid ID 0 (distances 12.10, 4.49, 30.28, 9.70). Middle: aligned 2x4 ADC lookup table T[id][s] stores those squared distances. Bottom: scoring stored 4-byte PQ codes reduces to four table additions, with FlashAttn [1,1,1,1] summing to 0.08 while LayerNorm [0,0,0,0] sums to 56.57.
PQ stores compact subspace centroid IDs and scores unquantized queries via a small per-query lookup table; see Vector Database Internals: HNSW & IVF for full PQ/ADC and HNSW internals.

Common pitfalls

  • Metric mismatch: Scoring unnormalized vectors with dot product lets long rows beat closer angles. Store model ID, width, normalization rule, and codec settings in one versioned index header.
  • Tuning PCA by variance alone: High variance can live on formatting axes; pick kk by held-out Recall@K.
  • Trusting 2D maps: t-SNE and UMAP distort global distances; verify patterns with neighbor overlap in full space.
  • SQ8 scale and overflow bugs: Include per-dimension scales, widen int8 to int32 before multiplying, and clip outliers with quantiles.
  • Post-filter starvation: Apply selective metadata predicates inline during ANN or binary search rather than after taking a narrow top-KK.
Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 5 answered
1.Query is [0, 2]; document A is [3, 4] and document B is [0, 3]. Which winners do raw dot product and cosine select?
2.A PCA projection keeps 95% of corpus explained variance yet drops a target passage outside top-5 on held-out queries. Why, and what is the fix?
3.At N = 10M and epsilon = 0.15, the Johnson-Lindenstrauss bound asks for k >= 6,368 even though embeddings have d = 1,536. What follows?
4.For query [1, 2], INT8 rows are A = [50, 0] and B = [0, 80] with scales [0.1, 0.01]. Separately, int8 [120, 120] @ [120, 120] wraps to -128 in NumPy. Which scores and fix are right?
5.Vectors [1.0, 0.01, -1.0, -0.01] and [0.01, 1.0, -0.01, -1.0] have cosine 0.020 yet share identical sign bits (Hamming 0). How do you prevent this collision from breaking retrieval?

5 questions remaining.

References

MetricType and distances

Meta/Faiss Contributors · 2026

https://github.com/facebookresearch/faiss/wiki/MetricType-and-distances

Matryoshka Representation Learning.

Kusupati, A., et al. · 2022 · NeurIPS 2022

https://arxiv.org/abs/2205.13147

Vector embeddings

OpenAI · 2024

https://developers.openai.com/api/docs/guides/embeddings

Numerical Linear Algebra.

Trefethen, L. N., & Bau, D. · 1997 · SIAM

https://people.maths.ox.ac.uk/trefethen/books.html

sklearn.decomposition.PCA

Scikit-learn Developers · 2026 · Official documentation

https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html

Random Projection

scikit-learn Developers · 2026

https://scikit-learn.org/stable/modules/random_projection.html

Extensions of Lipschitz mappings into a Hilbert space.

Johnson, W. B. & Lindenstrauss, J. · 1984 · Contemporary Mathematics, 26

https://web.stanford.edu/class/cs114/readings/JL-Johnson.pdf

An elementary proof of a theorem of Johnson and Lindenstrauss

Dasgupta, S., & Gupta, A. · 2003 · Random Structures & Algorithms

https://cseweb.ucsd.edu/~dasgupta/papers/jl.pdf

Visualizing Data using t-SNE.

van der Maaten, L. & Hinton, G. · 2008

https://jmlr.org/papers/v9/vandermaaten08a.html

UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction.

McInnes, L., Healy, J., & Melville, J. · 2018

https://arxiv.org/abs/1802.03426

On UMAP's True Loss Function

Damrich, S., & Hamprecht, F. A. · 2021

https://arxiv.org/abs/2103.14608

Embedding Quantization

Sentence Transformers · 2026

https://www.sbert.net/examples/sentence_transformer/applications/embedding-quantization/README.html

Qdrant Quantization Guide

Qdrant. · 2026

https://qdrant.tech/documentation/manage-data/quantization/

numpy.matmul

NumPy Developers · 2026

https://numpy.org/doc/stable/reference/generated/numpy.matmul.html

Similarity Estimation Techniques from Rounding Algorithms

Charikar, M. S. · 2002 · STOC 2002

https://www.cs.princeton.edu/courses/archive/spring04/cos598B/bib/CharikarEstim.pdf

Product Quantization for Nearest Neighbor Search.

Jégou, H., Douze, M., & Schmid, C. · 2011 · IEEE TPAMI 2011

https://doi.org/10.1109/TPAMI.2010.57

Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs

Malkov, Y. A., & Yashunin, D. A. · 2018 · IEEE Transactions on Pattern Analysis and Machine Intelligence

https://arxiv.org/abs/1603.09320

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.