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, PCA, Johnson-Lindenstrauss projections, the 2D-map trap, and INT8/1-bit quantization.
Three ways to measure closeness
An embedding maps text to a vector in . Three rulers answer different versions of "how close are two vectors?"
| Ruler | Formula | Range | Sensitive to positive length scaling? |
|---|---|---|---|
| Cosine similarity | No | ||
| Dot product | Yes | ||
| Euclidean (L2) distance | Yes |
Check flash-attention-v2 at and tiled-softmax-notes at . Both have norm 5: dot product is 24, cosine is 24 / 25 = 0.96, and L2 distance is . Stretching tenfold to [30, 40] multiplies dot product tenfold to 240 and expands L2 distance, while cosine stays locked at 0.96.

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 (), cosine equals dot product and squared L2 is a strictly decreasing linear function of it:
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 matrix 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.
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)raw dot winner: linear-attn-draft | unit winner: flash-attention-v2
unit dot == 1 - L2^2/2: TrueShrinking dimensions: Matryoshka, PCA, and random projection
Every float32 coordinate costs 4 bytes and one multiply-add per candidate ( 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 before quantization starts.
Matryoshka prefixes (MRL)
Matryoshka Representation Learning (MRL) trains an encoder with nested losses at multiple prefix widths , 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).](https://assets.leetllm.com/v1/561d61e29746/fundamentals/embeddings-cosine-dot-product-quantization/illustrations/_generated/matryoshka_dimensions_dark.png)
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 to get and take its thin SVD (avoiding , which squares the condition number):[4][5]
Project every document and live query through the same persisted basis , 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 from held-out Recall@K, not a fixed variance cutoff:
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}")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.867Johnson-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 (Gaussian or sparse Achlioptas entries with probabilities ).[6]
The Johnson-Lindenstrauss (JL) lemma proves that for any points and distortion , a linear map exists keeping all pairwise squared Euclidean distances inside whenever:[7][8]
Crucially, scales only as , independent of ambient dimension . Yet the worst-case bound is conservative: at and , it asks for (over 4x wider than ), and overlapping intervals can still swap close neighbors. Low-rank real embeddings often tolerate , while isotropic unstructured vectors drop sharply:
import numpy as npfrom 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}")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.367Persist 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:
- t-SNE converts high-dimensional distances into Gaussian neighbor probabilities (tuned via
perplexity), uses a heavy-tailed Student- (Cauchy) kernel in 2D to relieve crowding, and minimizes KL divergence .[9] Classic t-SNE cannot project unseen live queries. - UMAP builds a local -NN graph with fuzzy union edge weights and optimizes 2D weights via stochastic fuzzy cross-entropy (balancing attraction against negative-sampled repulsion).[10][11]
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.
| Goal | Primary metric | Best methods |
|---|---|---|
| Inspect clusters or drift | 1-NN / -NN overlap + manual inspection | PCA, t-SNE, UMAP (plots only) |
| Shrink dimensions for serving | Recall@K, RAM, latency | MRL prefix, PCA, random projection |
| Shrink bytes per coordinate | Compressed Recall@K + rescored accuracy | SQ8, binary (1-bit), PQ |
Memory sizing and scalar quantization (SQ8)
When shrinking still overflows RAM, quantization cuts bytes per coordinate. Raw coordinate payload for 1,536-dimensional vectors (before graph links, metadata, or retained FP32 copies):
| Representation | Per vector | 1M vectors | 100M vectors | Raw cut |
|---|---|---|---|---|
| FP32 (4 B/dim) | 6,144 B | 5.72 GiB | 572 GiB | 1x |
| INT8 SQ (1 B/dim) | 1,536 B | 1.43 GiB | 143 GiB | 4x |
| Binary (1 bit/dim) | 192 B | 183.1 MiB | 17.9 GiB | 32x |
| PQ-96 (96 one-byte IDs) | 96 B | 91.6 MiB | 8.94 GiB | 64x (+1.5 MiB codebooks) |

Scalar quantization (SQ8) maps each float32 coordinate to one byte (4x payload cut). Symmetric signed INT8 calibrates per dimension:
Range-offset codecs (such as Qdrant's uint8) instead map calibrated intervals to 0..255 via , .[12][13] Freeze calibration ranges once across ingestion and serving, and watch three bugs that wreck SQ8 recall:
- Dropping per-dimension scales: Scoring unscaled integer codes lets narrow-range dimensions overpower wide-range ones and reverses rank.
- Narrow
int8overflow: In NumPy,int8 @ int8wraps in 8 bits; widen operands toint32before multiplying.[14] - Outlier-stretched ranges: One outlier at
25.0stretches step width to0.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.](https://assets.leetllm.com/v1/89f4a3e4eda3/fundamentals/embeddings-cosine-dot-product-quantization/illustrations/_generated/scalar_calibration_dark.png)
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.import numpy as np
# 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()) == 1unscaled winner: 1 | scaled winner: 0
INT8 wrap=[2, 4] | INT32=[32258, 32004]
MAE bound=25: 0.0483 | bound=1: 0.0019Binary quantization and coarse-to-fine rescoring
Binary quantization (BQ) keeps only each coordinate's sign bit (1 if , 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 isotropic random hyperplanes, expected normalized Hamming distance matches vector angle:[15]
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- shortlist while evaluating metadata filters inline so disqualified rows never crowd out valid hits, (2) rescore those 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).](https://assets.leetllm.com/v1/d8961587191d/fundamentals/embeddings-cosine-dot-product-quantization/illustrations/_generated/hamming_vs_precise_dark.png)
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.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"hamming: [0, 0, 2] | post-filter K=1: None
rescore K=2: flash-attention-v2 | pre-filter K=1: flash-attention-v2Rescoring 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 subvectors, clusters each subspace into 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.](https://assets.leetllm.com/v1/b7a0928d9bc4/fundamentals/embeddings-cosine-dot-product-quantization/illustrations/_generated/product_quantization_flow_dark.png)
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 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
int8toint32before 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-.