RiptideRiptide
Download Riptide SDKInstall Riptorch
Menu
Riptorch docs · Guide

Exact vector search for RAG

Why float16 and bfloat16 search reorders top-10s, and the pipeline that returns the same ranking every time.

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 changesMiniLM-L6bge-base
embeddings computed in bfloat1645–46% of queries50.5%
embeddings computed in float165.7–6.5%7.1%
embeddings with TF32 matmuls4.2–4.3%5.1%
embeddings in float320%0%
search: float16 matmul on float32 vectors11.4%33.0%
search: bfloat16 matmul67.6%92.3%
search: float16 cosine on stored int8 / int16 vectors14.2–14.4% / 11.0%30.7% / 32.3%
search: Riptorch exact, int8 / int160% / 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:

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.

  1. 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.
  2. Normalise in float32 (or float64: it costs nothing next to the model).
  3. 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.
  4. 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.

Example
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)
Output, recorded on an Apple M1 Pro (CPU)
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 search returns are recomputed in float64 from the vectors; use the indices for the ranking.