Pidoku

Embeddings and Rerankers at Scale

Module 26 Lesson 26.g 1h Difficulty 3/5

Prerequisites 26.a, 10.f, 12.b, 20.d


Before you start: words you need#

WordPlain meaning
EmbeddingA fixed-length list of numbers that represents the meaning of a text (or image). Similar meanings give nearby vectors (10.f).
Bi-encoderEncodes the query and each document separately; relevance is the similarity of the two vectors. Documents can be embedded in advance.
Cross-encoder (reranker)Reads the query and one document together and outputs a relevance score. More accurate, but must run for every pair at query time.
Late interactionKeeps one vector per token for query and document and scores with “MaxSim” (ColBERT style). Between the two above in cost and quality.
PoolingHow per-token outputs become one vector: the first token (CLS), the average (mean), or the last token.
Matryoshka (MRL)Training that makes the first N numbers of an embedding useful on their own, so you can truncate vectors to save space.
PaddingFiller tokens added so inputs in a batch have equal length. Computed, then thrown away.
Vector indexA data structure (HNSW, IVF and others) that finds the nearest vectors quickly among millions.

1. What is it?#

Retrieval-augmented generation (RAG), semantic search, recommendations, deduplication and classification all run on pooling models: models that read an input once and return a vector or a score instead of generating text. Two kinds dominate:

  • Embedding models (bi-encoders), used twice: offline to embed the whole corpus, online to embed each query.
  • Rerankers (cross-encoders), used online to rescore the top few dozen to few hundred candidates that vector search returns.

The models are small to mid-sized (0.1B to 8B parameters), but the volume is huge: billions of documents to embed, and every search or agent tool call to serve with a tight latency budget. Facts checked on 13 November 2026 against vLLM v0.32.0, Text Embeddings Inference (TEI) v1.9.4 and Infinity.


2. Why does it matter?#

  • Every RAG answer waits for retrieval. Query embedding plus vector search plus reranking sits before the LLM’s prefill, adding directly to time to first token.
  • The bottleneck is not where LLM engineers look. No decode, no KV cache. Padding, tokenization, request overhead and batching policy decide throughput.
  • Corpus embedding is a large batch job. Re-embedding a billion chunks after a model change can cost more GPU-hours than a month of query traffic, and the index must be rebuilt.
  • Index memory is a hardware bill. Vector dimension and precision decide whether the index fits in RAM on a few machines or needs a cluster.

3. Simple analogy#

A library. The embedding model writes a short index card for every book once, so a librarian can find the 100 cards most similar to your question in seconds. The reranker is the expert who then actually reads your question beside each of those 100 books and puts them in order. You cannot ask the expert to read the whole library for every visitor, and you would not trust the index cards alone for the final order.


4. Tiny example: one RAG query#

query              "how do I rotate my API key?"                     12 tokens
embed query        0.6B bi-encoder, one pass                          ~2-5 ms on a GPU
vector search      top 100 of 50 million chunks (HNSW)                 ~5-20 ms on CPU
rerank             100 pairs x (12 + 250) tokens through a cross-encoder   ~20-60 ms
keep top 5         5 x 250 tokens -> prompt of the LLM
LLM                prefill + decode (Module 12)

The reranker pushes 100 times more tokens through a model than the query embedding did. It is usually the most expensive part of retrieval.


5. Technical explanation#

Three scoring designs#

DesignQuery-time costStorageQuality
Bi-encoder (embedding)One pass over the query, then vector searchOne vector per chunkGood
Late interaction (ColBERT-style)One pass over the query, MaxSim against stored token vectorsOne vector per token (10–100x more)Better
Cross-encoder (reranker)One pass per (query, candidate) pairNoneBest

Production systems combine them: bi-encoder (often plus keyword search) for recall, cross-encoder on the top-k for precision.

Models in 2026#

Decoder-LLM-based embedders now lead quality leaderboards: the Qwen3-Embedding family (0.6B, 4B and 8B; 1,024, 2,560 and 4,096 dimensions; 32K context; Matryoshka output dimensions from 32 to 4,096; instruction-aware) and matching Qwen3-Reranker models. These use last-token pooling: the hidden state of the final token is the embedding. Older BERT-style models (BGE, GTE, E5, mxbai) use CLS or mean pooling and stay popular because they are 10–50x cheaper. BGE-M3 produces dense, sparse and ColBERT-style outputs from one model. Multimodal embedders (Qwen3-VL-Embedding, SigLIP, CLIP) embed images and text in one space; their image side has the VLM encoder costs of 26.b.

Serving engines#

Text Embeddings Inference (TEI), Hugging Face’s Rust server (v1.9.4, 15 September 2026): token-based dynamic batching, FlashAttention, Candle and cuBLASLt kernels, ONNX and Safetensors loading, SPLADE pooling and rerankers. Key flags:

Shell
text-embeddings-router --model-id Qwen/Qwen3-Embedding-0.6B \
  --max-batch-tokens 16384 --max-client-batch-size 64 \
  --tokenization-workers 8 --auto-truncate

--max-batch-tokens caps the tokens in one forward pass rather than the number of requests, which is the right unit when lengths vary.

Infinity (Michael Feil): rewritten in October 2026 as a native Rust server on LibTorch (v3) for embeddings, reranking (/rerank) and classification; the Python v2 line added multi-model and multimodal serving.

vLLM pooling models (v0.32.0): --runner pooling (usually auto-detected), --convert embed or --convert classify to adapt a generative checkpoint, and --pooler-config to override pooling. Endpoints: /v1/embeddings (OpenAI), /v2/embed (Cohere), /v1/rerank and /v2/rerank (Cohere rerank), /score, /classify and /pooling. Scoring supports three types: cross-encoder, bi-encoder (cosine) and late-interaction (MaxSim over token_embed outputs). Matryoshka models accept a dimensions field per request; models without Matryoshka training reject it. Some rerankers need overrides; for Qwen3-Reranker the docs give:

Shell
vllm serve Qwen/Qwen3-Reranker-0.6B --hf_overrides \
  '{"architectures": ["Qwen3ForSequenceClassification"],"classifier_from_token": ["no", "yes"],"is_original_qwen3_reranker": true}'

vLLM brings its scheduler, prefix caching and multi-GPU support to large (4–8B) embedders; for small BERT-class models a dedicated server like TEI is often simpler and as fast.

Where the time goes#

  • Padding: the classic waste (section 6). Fix it with length bucketing, token-budget batching or variable-length (“unpadded”) attention kernels.
  • Tokenization: on the CPU, per request. For a small model on a big GPU, tokenizing can take longer than the forward pass. Scale tokenizer workers with cores.
  • Request overhead: HTTP parsing and JSON serialising 4,096 floats per input. Batch inputs per request (--max-client-batch-size) and consider binary or base64 output.
  • The forward pass itself is prefill-shaped and compute-bound for medium inputs; FP8 or INT8 works well for embedders, but always re-check retrieval quality.

6. Under the hood: padding, reranking and index memory#

The program measures three costs: padding waste for 10,000 inputs with a long-tailed length distribution, the tokens a reranker processes per query, and the memory of a 100-million-vector index.

Go
package main

import (
	"fmt"
	"math/rand"
	"sort"
)

// Part 1: padding waste. Padded batches cost (batch size x longest input) tokens.
func paddedCost(lengths []int, batch int) (useful, paid int) {
	for i := 0; i < len(lengths); i += batch {
		end := min(i+batch, len(lengths))
		longest := 0
		for _, l := range lengths[i:end] {
			useful += l
			longest = max(longest, l)
		}
		paid += longest * (end - i)
	}
	return
}

func main() {
	r := rand.New(rand.NewSource(1))
	lengths := make([]int, 10000)
	for i := range lengths {
		// mostly short queries and chunks, a long tail of big passages
		l := 8 + int(r.ExpFloat64()*90)
		lengths[i] = min(l, 2048)
	}

	useful, arrival := paddedCost(lengths, 32)
	sorted := append([]int(nil), lengths...)
	sort.Ints(sorted)
	_, bucketed := paddedCost(sorted, 32)
	fmt.Println("10,000 inputs, batches of 32")
	fmt.Printf("  useful tokens:            %9d\n", useful)
	fmt.Printf("  padded, arrival order:    %9d  (%.1fx)\n", arrival, float64(arrival)/float64(useful))
	fmt.Printf("  padded, sorted by length: %9d  (%.2fx)\n", bucketed, float64(bucketed)/float64(useful))
	fmt.Printf("  unpadded (varlen kernels):%9d  (1.00x)\n", useful)

	// Part 2: what one reranked query costs.
	fmt.Println("\nrerank top-k for one query (query 30 tokens, passages 250 tokens)")
	for _, k := range []int{20, 100, 400} {
		tokens := k * (30 + 250)
		fmt.Printf("  k=%3d: %6d tokens through the cross-encoder = %4.0fx an embedding of the query\n",
			k, tokens, float64(tokens)/30)
	}

	// Part 3: index memory for 100 million passages.
	fmt.Println("\nvector index, 100 million passages (vectors only, no graph overhead)")
	const n = 100e6
	for _, c := range []struct {
		dims  int
		bytes float64
		name  string
	}{
		{4096, 4, "4096-d float32"},
		{4096, 2, "4096-d float16"},
		{1024, 2, "1024-d float16 (Matryoshka)"},
		{1024, 1, "1024-d int8"},
		{1024, 1.0 / 8, "1024-d binary"},
	} {
		gb := n * float64(c.dims) * c.bytes / 1e9
		fmt.Printf("  %-28s %8.0f GB\n", c.name, gb)
	}
}

Output:

10,000 inputs, batches of 32
  useful tokens:               974783
  padded, arrival order:      3647568  (3.7x)
  padded, sorted by length:    988480  (1.01x)
  unpadded (varlen kernels):   974783  (1.00x)

rerank top-k for one query (query 30 tokens, passages 250 tokens)
  k= 20:   5600 tokens through the cross-encoder =  187x an embedding of the query
  k=100:  28000 tokens through the cross-encoder =  933x an embedding of the query
  k=400: 112000 tokens through the cross-encoder = 3733x an embedding of the query

vector index, 100 million passages (vectors only, no graph overhead)
  4096-d float32                   1638 GB
  4096-d float16                    819 GB
  1024-d float16 (Matryoshka)       205 GB
  1024-d int8                       102 GB
  1024-d binary                      13 GB

How to read it:

  • Padding in arrival order wasted 73% of the compute (3.7x the useful tokens) because one long passage in a batch of 32 short ones pads all of them. Sorting by length, or batching by a token budget with unpadded kernels, recovers almost all of it. This one change often beats any kernel optimisation.
  • Reranking dominates retrieval compute. k = 100 sends over 900 times the query’s tokens through the reranker. Choose k from measured recall, use a small reranker, cap passage length, and cache scores for repeated (query, passage) pairs where traffic allows.
  • Dimensions and precision decide the index bill. Truncating a Matryoshka embedding to 1,024 dimensions and storing int8 shrinks 1.6 TB to about 100 GB. Binary vectors with a float rescoring pass are another 8x. Always measure recall at each step.

7. Performance implications#

  • Two traffic shapes, two deployments. Online queries: short, latency-sensitive, small batches. Corpus embedding: long, throughput-bound, huge batches. Run them separately or give online traffic strict priority (20.k).
  • Small models need many replicas, not big GPUs. A 0.1–0.6B model rarely uses an H100 well; share GPUs (MIG, MPS, 21.d), use cheaper GPUs, or run on CPUs with ONNX for low volumes.
  • Large embedders behave like LLM prefill. 4–8B embedders benefit from FP8, FlashAttention and the token-budget batching of 12.j; vLLM’s pooling runner gives you these.
  • Instructions and prefixes repeat. Instruction-aware models prepend the same task instruction to every query; prefix caching in vLLM can skip it.
  • Truncation is a quality decision. --auto-truncate (TEI) or truncate_prompt_tokens (vLLM) silently cut long inputs. Chunk documents deliberately instead.

8. Production implications#

  • The embedding model is a schema. Vectors from different models (or versions, or dimensions) are not comparable. A model upgrade means re-embedding the corpus and rebuilding the index, then switching atomically (dual-write and backfill, then cut over).
  • Version everything: model, revision, pooling, normalisation, instruction text, dimension, chunking rules. A changed instruction string is a silent quality regression.
  • Budget the backfill. Corpus tokens ÷ throughput per GPU = GPU-hours; schedule on spare or spot capacity.
  • Monitor retrieval quality, not just latency: recall@k on a labelled set, and the share of LLM answers that cite retrieved passages.
  • An outage here breaks every RAG product. Embedding services need the same redundancy as the LLM tier, and a cache for hot queries.

9. Common mistakes#

  1. Batching by request count with padding. Use token budgets or sort by length.
  2. Mixing embeddings from two model versions in one index.
  3. Reranking 1,000 candidates because “more is better”. Measure where recall stops improving.
  4. Running a 0.1B model on a dedicated H100.
  5. Truncating dimensions on a model without Matryoshka training. vLLM rejects it; other stacks may silently return poor vectors.

10. Hands-on exercise#

  1. Run the program. Change the batch size to 128. What happens to the waste in arrival order?
  2. Add a “token budget” batcher: fill each batch with sorted inputs until the padded size would exceed 16,384 tokens. How many forward passes does it need?
  3. Estimate the GPU-hours to embed 2 billion 300-token chunks with a 0.6B model at an assumed 150,000 tokens per second per GPU, and with an 8B model at 15,000.
  4. Serve the same small embedding model with TEI and with vllm serve --runner pooling; compare p50 and p99 latency for single short queries and throughput for 64-input batches.

11. Interview questions#

  1. Compare bi-encoders, cross-encoders and late interaction on query cost, storage and quality.
  2. Why is padding a bigger problem for embedding servers than for LLM decode?
  3. How would you upgrade the embedding model behind a 1-billion-chunk index without downtime?
  4. What does Matryoshka training buy you, and how do you choose the dimension?
  5. Retrieval latency p99 doubled after a new data source was added. What do you suspect first?

12. Further reading#

Checked on 13 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in