The problem: the same query, a different top-10
Retrieval-augmented generation (RAG) puts the top results of a vector search in front of the model. If the search returns a different top-10 when the precision changes, the model sees different passages and gives a different answer. That happens far more often than leaderboards suggest, because nDCG barely moves when two near-equal passages swap places, while every user who asks the same question twice notices.
We measured how often the usual settings change the top-10 order against a float64 reference (the same model in float64, scored in float64, ties broken by the lowest index), on BEIR FiQA (57,638 passages, 648 queries) with all-MiniLM-L6 and bge-base:
| what changes | MiniLM-L6 | bge-base |
|---|---|---|
| embeddings computed in bfloat16 | 45–46% of queries | 50.5% |
| embeddings computed in float16 | 5.7–6.5% | 7.1% |
| embeddings with TF32 matmuls | 4.2–4.3% | 5.1% |
| embeddings in float32 | 0% | 0% |
| search: float16 matmul on float32 vectors | 11.4% | 33.0% |
| search: bfloat16 matmul | 67.6% | 92.3% |
| search: float16 cosine on stored int8 / int16 vectors | 14.2–14.4% / 11.0% | 30.7% / 32.3% |
| search: Riptorch exact, int8 / int16 | 0% / 0% | 0% / 0% |
Two things stand out. The model’s precision matters more than people expect: bfloat16 embeddings put a different top-10 in front of about half the queries. And the search step adds its own drift on top: scoring perfectly good float32 vectors with a float16 matmul (the fastest brute force in PyTorch) reorders 11–33% of the top-10s.
Why float16 and bfloat16 reorder results
A float16 number keeps 11 significant bits, so near 0.9 its values are about 0.0005 apart; bfloat16 keeps 8 bits, about 0.004 apart. The neighbours in a top-10 are often closer to each other than that. Rounding never reverses two scores, but it merges close ones into ties, and with float inputs the rounding of the vectors themselves moves each score by a different amount, which does swap neighbours. Which document wins a tie then depends on the kernel, the batch size and the device.
A small run shows it on 20,000 vectors. The exact index matches the float64 ranking on every query; the float16 path changes some top-10s and ties scores inside others:
import json
import numpy as np
import riptorch as torch
# 20,000 unit vectors (stand-ins for normalised embeddings) and 32 queries near some of them
rng = np.random.default_rng(7)
docs = rng.standard_normal((20000, 384)).astype(np.float32)
docs /= np.linalg.norm(docs, axis=1, keepdims=True)
queries = docs[:32] + 0.6 * rng.standard_normal((32, 384)).astype(np.float32) / np.sqrt(384)
queries /= np.linalg.norm(queries, axis=1, keepdims=True)
# Store as symmetric int16: one global scale, no offset
scale = 32767 / max(np.abs(docs).max(), np.abs(queries).max())
d16 = np.round(docs * scale).astype(np.int16)
q16 = np.round(queries * scale).astype(np.int16)
index = torch.SimilarityIndex(torch.from_numpy(d16), metric="cross", exact=True)
values, indices = index.search(torch.from_numpy(q16), 10)
print(index)
print("query 0, top 5:", indices[0, :5].tolist())
def top10(scores): # best first, ties by lowest index
return np.lexsort((np.arange(scores.shape[1])[None, :].repeat(len(scores), 0), -scores), axis=1)[:, :10]
# Reference: the same int16 vectors scored in float64 (cosine)
D, Q = d16.astype(np.float64), q16.astype(np.float64)
ref = top10((Q @ D.T) / np.linalg.norm(Q, axis=1)[:, None] / np.linalg.norm(D, axis=1)[None, :])
same = (indices.numpy() == ref).all(axis=1)
print(f"exact search: top-10 order equals float64 on {same.sum()} of {len(same)} queries")
# The usual fast path: float16 inputs, float32 accumulation, float16 scores
f16 = (queries.astype(np.float16).astype(np.float32) @ docs.astype(np.float16).astype(np.float32).T).astype(np.float16)
fast = top10(f16.astype(np.float64))
diff = (fast != ref).any(axis=1)
print(f"float16 search: top-10 order differs on {diff.sum()} of {len(diff)} queries")
print("float16 scores tied inside a top-10:", int(sum(len(set(f16[i, fast[i]])) < 10 for i in range(len(fast)))), "queries")SimilarityIndex(20000 x 384, metric='cross', exact=True) query 0, top 5: [0, 18704, 7367, 19552, 7832] exact search: top-10 order equals float64 on 32 of 32 queries float16 search: top-10 order differs on 3 of 32 queries float16 scores tied inside a top-10: 5 queries
Exact search with Riptorch
SimilarityIndex(keys, metric="cross", exact=True) stores whole-number vectors (int8 or int16) and scores them exactly:
- every dot product is an exact integer;
- the ranking compares exact fractions, so nothing is rounded before the order is decided;
- ties go to the lowest index.
The result is the same top-k on every CPU and GPU and at every batch size. metric="cross" ranks exactly as cosine similarity does (it is cos θ · |cos θ|; see How the exact maths works). For one-off searches, torch.similarity_topk(queries, keys, k, metric="cross", exact=True) does the same without keeping an index.
The recommended pipeline
- Embed with your model in PyTorch or ONNX Runtime, in float16 (with float32 accumulation) or float32. Don’t use bfloat16 for retrieval: it is the one setting that moves half the rankings.
- Normalise in float32 (or float64: it costs nothing next to the model).
- Store symmetric int16 (2 bytes per dimension, keeps the float ranking) or symmetric int8 (4× smaller than float32, exact for what is stored). One scale for the whole corpus, no offsets: see Storing embeddings in int8 and int16.
- Score exactly with
SimilarityIndex(..., metric="cross", exact=True).
Here it is end to end. embed() is a stand-in so the example runs anywhere; replace it with your model.
import hashlib
import numpy as np
import riptorch as torch
passages = [
"Riptorch runs PyTorch code with one changed import.",
"Integer matrix multiplies in Riptorch are exact.",
"Float16 search can reorder the top results.",
"Symmetric int16 storage keeps the float ranking.",
"The Raya language compiles to native shared libraries.",
"A bfloat16 embedding changes many rankings.",
]
def embed(texts, dim=256):
"""Stand-in for your embedding model (sentence-transformers, ONNX Runtime, ...): run the model in float16
or float32, never bfloat16 for retrieval. Here: hashed words through a fixed random projection."""
rng = np.random.default_rng(0)
proj = rng.standard_normal((4096, dim)).astype(np.float32)
out = np.zeros((len(texts), dim), dtype=np.float32)
for i, t in enumerate(texts):
for w in t.lower().replace(".", "").split():
out[i] += proj[int(hashlib.md5(w.encode()).hexdigest(), 16) % 4096]
return out
# 1. embed (your model), 2. normalise in float32
emb = embed(passages)
emb /= np.linalg.norm(emb, axis=1, keepdims=True)
# 3. store symmetric int16: one scale for the whole corpus, kept with the index
SCALE = 32767.0
store = np.round(emb * SCALE).astype(np.int16)
# 4. score exactly
index = torch.SimilarityIndex(torch.from_numpy(store), metric="cross", exact=True)
def search(question, k=3):
q = embed([question])
q /= np.linalg.norm(q, axis=1, keepdims=True)
q16 = torch.from_numpy(np.round(q * SCALE).astype(np.int16))
values, indices = index.search(q16, k)
return [(round(v, 4), passages[i]) for v, i in zip(values[0].tolist(), indices[0].tolist())]
for score, text in search("are integer matrix multiplies exact"):
print(score, text)0.7224 Integer matrix multiplies in Riptorch are exact. 0.001 Riptorch runs PyTorch code with one changed import. 0.0005 A bfloat16 embedding changes many rankings.
On FiQA, symmetric int16 with exact scoring gave the same top-10 as the float32 vectors’ float64 ranking for 99.5–99.8% of queries (the rest differ in order only: recall@10 was 1.0000 and nDCG@10 unchanged), at half the memory of float32. The common int8 recipe, per-dimension calibrated codes scored by the raw dot product, changed every top-10 and cost 8–12% nDCG@10.
Tips
- Pad batches to a few fixed lengths (multiples of 32 tokens, for example) when embedding. Fewer shapes means fewer compiled programs, on every library.
- Keep the scale with the index. Queries must be quantised with the same scale as the corpus.
- The values
searchreturns are recomputed in float64 from the vectors; use the indices for the ranking.