technical
Generative Retrieval: Tokenizers and Semantic IDs
A practical guide to residual quantization, RQ-KMeans, RQ-VAE, codebook balancing, and the design and evaluation of semantic IDs for generative retrieval.
The big picture
Motivation / intuition
In classical retrieval, an embedding model outputs a query vector and retrieves items through nearest-neighbor search. In generative retrieval, a sequence model predicts an item’s Semantic ID (SID) autoregressively:
item metadata / behavior -> item encoder -> embedding x
|
v
SID tokenizer
|
v
(c1, c2, ..., cL)
|
index: SID -> item(s)
query + context -> generative model -> predicted SID -> retrieved item(s)
A useful SID should balance four sometimes-conflicting goals:
- Semantic organization: related items should often share a prefix.
- Distinctiveness: different items should not collide excessively.
- Vocabulary utilization: avoid dead codes and pathological concentration.
- Conditional predictability: codes should be learnable from query/user context, not just reconstructable from the item embedding.
Important: low quantization MSE is a surrogate objective, not the end-to-end retrieval objective.
Shared notation
- : item embedding (from a frozen or separately learned item representation model).
- : number of quantization levels; : codebook size at level .
- : level- codebook.
- : selected token at level .
- .
The levels use shared level-wise codebooks: level 2 does not normally train a different codebook for every level-1 cluster. RQ is therefore not the same as a hierarchical K-Means tree.
Residual Quantization (RQ)
Motivation / intuition
One codeword may capture the broad content of an item but miss fine detail. Rather than quantize once, repeatedly quantize what is left unexplained.
Formulation
For a vector (either or an encoded latent ), initialize . At level :
After levels:
The code sequence is . Later levels often tend to encode finer residual information, but a rigid semantic hierarchy is not mathematically guaranteed.
# Shared RQ encoding logic; codebooks must already be fitted/trained.
r = vector
sid = []
quantized = 0
for codebook in codebooks:
k = squared_l2(r, codebook).argmin()
e = codebook[k]
sid.append(k)
quantized += e
r = r - e
The key difference between RQ-KMeans and RQ-VAE is primarily how codebooks and (possibly) the quantization space are learned, not this basic nearest-codeword recurrence.
RQ-KMeans
Motivation / intuition
If the input embedding space is already good, fit centroids directly in that space. K-Means alternates between assigning points to centers and recomputing the best centers. No neural encoder, decoder, STE, or optimizer is required for standard batch K-Means.
Ordinary K-Means, one level
Given training vectors , minimize within-cluster squared distance:
Two alternating steps:
Assignment (fixed centers)
Update (fixed assignments)
Why the mean? For a fixed cluster , differentiating with respect to , setting the derivative to zero, yields the arithmetic mean. This derivation uses calculus, but the algorithm does not use gradient descent.
Toy example: with . Starting centers , assignments form groups and ; updating produces centers . The next assignment does not change, so the algorithm converges.
Extending K-Means to RQ
For each level, fit a fresh K-Means to the current residuals of all items; subtract assigned centers; proceed to the next level.
residuals = item_embeddings.copy()
codebooks, sid_columns = [], []
for K in [4096, 1024, 512]:
km = KMeans(n_clusters=K, n_init=10) # illustrative API
ids = km.fit_predict(residuals) # complete K-Means at this level
centers = km.cluster_centers_
codebooks.append(centers)
sid_columns.append(ids)
residuals = residuals - centers[ids]
sids = stack(sid_columns, axis=1)
Two nested loops: inner assignment/update until convergence; outer fit residual level 1, then 2, then 3. Earlier codebooks are typically frozen when training later levels. The method is greedy, initialization-sensitive, and not globally optimal across all levels. Practical systems may employ K-Means++, restarts, mini-batches, or approximate assignment for scale.
Pros: simple; deterministic given data/seed/implementation; no quantizer backprop; convenient diagnostics. Cons: cannot directly reshape the representation space; greedy residual fitting; no guarantee of balanced clusters or globally best SID geometry.
RQ-VAE
Motivation / intuition
The original embedding space may not be ideal for compact discrete encoding. RQ-VAE adds a trainable encoder and decoder so that the representation can adapt to quantization.
Here , and RQ operates in the latent space. The decoder reconstructs the original input embedding .
Formulation and loss
A TIGER-style objective is
(stop gradient) is identity in forward, but contributes zero gradient in backward.
Intuition of each component
- Reconstruction: keep the quantized representation informative enough to reconstruct .
- Codebook loss: bring selected codewords toward the current residuals; gradients update selected codewords.
- Commitment loss: encourage encoder residuals to stay near their selected codewords; gradients update the encoder-side path.
- STE: enable the reconstruction gradient to reach the encoder despite hard quantization.
In a multi-level implementation, residual dependencies and detach placement require care; the gradient statements above describe the principal intended paths, not every possible cross-level path in arbitrary code.
Hard assignment is not differentiable
For fixed scalar codewords :
The true derivative is zero almost everywhere and undefined at the decision boundary. Merely differentiating through will not provide a useful learning signal for the encoder.
Identity Straight-Through Estimator (STE)
# z: encoder output; z_q: selected (hard) codebook vector
z_st = z + (z_q - z).detach()
Forward: .
Backward: because the parenthesized term is detached.
This does not make argmin mathematically differentiable. STE replaces its unusable true derivative with a surrogate Jacobian (identity). It is a biased estimator of the gradient of the original discrete computation and is not guaranteed to be a descent direction.
In this standard identity-STE branch, reconstruction gradient reaches the encoder, but not the codebook through that branch. The separate codebook loss supplies selected-codeword updates.
Where does z_st enter the total loss?
Motivation / intuition
STE is not an additional loss term. It changes the tensor passed to the decoder when computing reconstruction loss. The forward value remains the hard-quantized representation, but the backward path to the encoder uses a surrogate gradient.
For a single-level VQ-VAE, let and let be the selected codeword. Define
The implemented loss is then
Forward: since numerically, the reconstruction loss is exactly the same value as .
Backward: autograd sees and . Thus reconstruction gradients update the decoder normally and reach the encoder through identity STE, but do not update the codebook through this reconstruction branch.
A single-level implementation:
z = encoder(x)
idx = ((z[:, None, :] - codebook[None, :, :]) ** 2).sum(-1).argmin(-1)
z_q = codebook[idx] # hard nearest-codeword lookup
z_st = z + (z_q - z).detach() # forward = z_q, backward to z = identity
x_hat = decoder(z_st)
loss_recon = F.mse_loss(x_hat, x)
loss_codebook = F.mse_loss(z_q, z.detach())
loss_commit = beta * F.mse_loss(z, z_q.detach())
loss = loss_recon + loss_codebook + loss_commit
loss.backward()
Gradient routing: which loss updates which parameters?
For z_st = z + (z_q - z).detach(), the STE branch has and .
| Loss | Encoder | Selected codeword | Decoder |
|---|---|---|---|
| Reconstruction loss | ✅ Through identity STE | ❌ Not through this STE path | ✅ |
| Codebook loss | ❌ | ✅ | ❌ |
| Commitment loss | ✅ | ❌ | ❌ |
Rule of thumb: Reconstruction + Commitment → Encoder; Codebook Loss → Selected Codewords. Reconstruction also trains the Decoder. This table describes the single-level VQ-VAE implementation above; multi-level RQ-VAE cross-level gradients may depend on how residuals and stop-gradients are constructed.
Extending the implementation to RQ-VAE (multiple levels)
In RQ-VAE, each level quantizes a residual, and the decoder receives the sum of all selected codewords. The STE is applied to that final summed quantized representation. A simplified PyTorch training step is:
import torch
import torch.nn.functional as F
def rqvae_loss(x, encoder, decoder, codebooks, beta=0.25):
# x: [batch, input_dim]
# codebooks: iterable of trainable tensors [K_l, latent_dim]
z = encoder(x) # [batch, latent_dim]
z_q = torch.zeros_like(z)
codebook_loss = z.new_zeros(())
commit_loss = z.new_zeros(())
sid = []
for codebook in codebooks:
# Residual for this level. Detach previous quantized sums
# to isolate local codebook/commitment loss paths.
residual = z - z_q.detach()
dist = ((residual[:, None, :] -
codebook[None, :, :]) ** 2).sum(dim=-1)
idx = dist.argmin(dim=-1) # discrete, no gradient
e = codebook[idx] # selected codeword IS trainable
sid.append(idx)
codebook_loss = codebook_loss + F.mse_loss(
e, residual.detach()
)
commit_loss = commit_loss + beta * F.mse_loss(
residual, e.detach()
)
z_q = z_q + e # sum selected vectors
# The decoder sees the hard quantized sum in forward.
# Reconstruction gradients pass to z through identity STE.
z_st = z + (z_q - z).detach()
x_hat = decoder(z_st)
recon_loss = F.mse_loss(x_hat, x)
total = recon_loss + codebook_loss + commit_loss
return total, {
"recon": recon_loss,
"codebook": codebook_loss,
"commit": commit_loss,
"sid": torch.stack(sid, dim=-1),
}
loss, metrics = rqvae_loss(x, encoder, decoder, codebooks)
loss.backward()
optimizer.step()
This is a gradient-routing illustration, not a verbatim reproduction of TIGER’s training code. In particular, detaching the previously accumulated quantized sum when defining each level’s residual prevents local codebook/commitment losses from propagating into earlier selected codewords; alternative implementations can choose different cross-level gradient behavior.
Why papers often omit z_st from their written loss: the mathematical objective describes the forward loss value, for which . The surrogate backward rule is an implementation/training convention, not a separate scalar regularizer.
Why an indexed codeword still receives gradients
idx = squared_l2(z, codebook).argmin(dim=-1) # no derivative through idx
z_q = codebook[idx] # differentiable wrt selected rows
loss_cb = ((z_q - z.detach()) ** 2).mean()
loss_cb.backward()
The index decision is nondifferentiable, but the values selected by that index are trainable. This distinction is crucial.
Intuition: a discrete selection can define a piecewise differentiable scalar objective. We do not need to differentiate the chosen integer index to update the continuous codewords.
For a fixed encoder output , consider the nearest-codeword squared error:
Suppose one codeword is the unique nearest center. In a sufficiently small neighborhood of the current codebook parameters, that same center remains selected. Locally, the objective is simply
Its derivatives with respect to the codewords are
Thus, the selected codeword can be updated by ordinary gradient descent even though the index is discrete. After that update, a new forward pass recomputes the nearest center, and the selected index may change.
Boundary case: when two or more centers tie for the minimum, the objective is generally non-differentiable at the switching boundary. Away from such ties, it is locally a smooth squared-distance function.
Do not confuse two gradient paths: This observation explains why the codebook loss can train selected codewords. It does not solve the separate problem of passing the decoder’s reconstruction gradient through hard quantization to the encoder; that is where STE is used.
Takeaway: Non-differentiable selection does not imply the resulting scalar loss has no gradients with respect to its continuous parameters.
Pros: can learn nonlinear, quantization-friendly latents and add task-aware auxiliary losses. Cons: more complex training; surrogate-gradient bias; codebook collapse/underuse; harder debugging and retraining stability.
Soft assignment vs hard assignment vs STE
Guiding question: Why do we need STE?
Motivation / intuition
A VQ-VAE tokenizer needs two things at once:
- A genuinely discrete forward representation: each item should select a codeword (and eventually obtain a discrete SID).
- A useful training signal: the decoder’s reconstruction loss must reach the encoder across the quantization step.
This creates the central tension:
- Hard assignment preserves discrete codes, but nearest-codeword selection blocks useful reconstruction gradients to the encoder.
- Soft assignment makes the quantization path differentiable, but a weighted average of codewords is not the same representation as a single hard codeword.
- Straight-Through Estimation (STE) keeps the hard forward computation while supplying a surrogate gradient in backward.
The rest of this section compares these choices. It is a motivation for STE, not a claim that soft assignment always fails or that there are only two possible estimators.
Hard assignment: correct discrete forward, no useful encoder gradient
For residual and codebook vectors :
Example: let , with codewords and . The selected codeword is ; changing slightly does not change the selection.
With these fixed codewords:
The true derivative is zero almost everywhere and undefined at the boundary. Thus, directly using in reconstruction loss does not provide a useful gradient through the hard quantizer to the encoder.
Nuance: after the index is selected, the value remains differentiable with respect to that selected codeword. This does not make the index-selection operation differentiable.
Soft assignment: restore differentiability, but change the forward representation
Instead of choosing one index immediately, turn the negative squared distances into weights:
Here is the temperature. Construct a soft quantized vector:
For , , , and :
Unlike the hard output , the soft output is a weighted average. The path
is differentiable: gradients reach the encoder through the distance computation and softmax.
Trade-off: if training feeds to the decoder but inference uses one hard codeword, the model may experience a training-inference mismatch. Lowering can make the weights sharper, but does not guarantee a perfect substitute for hard quantization.
Language-model analogy: in ordinary teacher-forcing cross-entropy, training differentiates through the complete probability distribution rather than through greedy decoding. The difference here is that soft quantization also uses the probabilities to construct the decoder’s input vector.
STE: hard forward, surrogate backward
STE addresses the tension by separating the forward values from the backward rule. It does not make hard mathematically differentiable; it defines a useful approximate gradient.
Variant A: Identity STE (the classic VQ-VAE choice)
Forward computation path
Where STE acts: at the quantized embedding level, combining the hard vector with the encoder output via . The backward surrogate goes directly to , not through index .
# z: encoder output; z_q: selected hard quantized vector
z_st = z + (z_q - z).detach()
x_hat = decoder(z_st)
loss_recon = F.mse_loss(x_hat, x)
Forward: , so the decoder sees an actual hard codeword.
Backward: , so the reconstruction gradient reaches the encoder as if the quantizer were the identity. In this exact implementation, the reconstruction branch does not update the codebook; a separate codebook loss handles selected-codeword updates.
This is the mechanism used in the earlier Where does z_st enter the total loss? section.
Variant B: Softmax STE (hard forward, softmax-shaped gradient)
Forward computation path
Where STE acts: at the assignment-weight level: and . The STE constructs from the hard one-hot assignment and soft probabilities; it does not differentiate through the integer index.
Start from soft probabilities but replace their forward value by a hard one-hot vector :
Quantize with :
probs = torch.softmax(-distances / tau, dim=-1)
index = probs.argmax(dim=-1)
hard = F.one_hot(index, num_classes=probs.shape[-1]).to(probs.dtype)
weights = hard - probs.detach() + probs
z_st = weights @ codebook
Forward: , so the output is a selected codeword rather than a soft average.
Backward: the hard one-hot and detached term do not contribute gradients. The assignment-dependent gradient passes through , using the differentiable softmax path back to distances and the encoder. The multiplication by the codebook also gives a direct gradient path to selected codeword values.
Unlike identity STE, the gradient to the encoder depends on the softmax probabilities, temperature, distances, and codebook geometry.
Summary: which forward and backward behavior do we want?
| Method | Forward to decoder | Backward to encoder |
|---|---|---|
| Hard assignment | Single codeword | No useful gradient through |
| Soft assignment | Weighted average of codewords | True softmax-path gradient |
| Identity STE | Single codeword | Identity surrogate gradient |
| Softmax STE | Single codeword | Softmax-derived surrogate gradient |
For TIGER-style RQ-VAE: focus first on hard nearest-neighbor quantization + identity STE. Softmax STE is an alternative gradient-estimation design, not an additional step required by TIGER. Neither STE is guaranteed to match the true discrete gradient.
Connection to codebook balancing: the main quantization path can still use hard assignment + identity STE, while a separate, differentiable auxiliary balance loss uses soft assignment probabilities. These mechanisms can coexist because they serve different purposes.
Collapse, imbalance, and how to address them
Motivation / intuition
Two distinct problems can look similar:
- Collapse / dead codes: many codewords are never used.
- Imbalance: all or most codewords are used, but a small subset dominates assignments.
Let be number of items mapped to code at level and .
High utilization does not imply high normalized entropy. Also, marginal balance per level does not imply diversity of full SID sequences, because level assignments are correlated.
Balanced RQ-KMeans: constrain assignment size
Standard K-Means minimizes distance alone. Balanced K-Means adds a cardinality constraint, e.g. for divisible :
The update step can still use cluster means. The assignment step is now coupled across samples (not independent nearest-centroid lookups). Practical solutions include greedy capacity filling or more costly capacity-constrained assignment/transport solvers. Strict balance may degrade semantic neighborhoods; balance is not automatically desirable at every RQ level.
OneSearch observation: balancing only RQ level 3 worked better than the tested all-level balancing configuration. For the reported 4096-1024-512 + keywords configuration, adding L3 balancing increased total code-space utilization from 1.64% to 7.03% and ICR from 43.32% to 68.08%. This is a specific system ablation; the all-level-balanced row does not isolate every other factor equally.
RQ-VAE: prevent collapse or encourage balancing
Different interventions target different stages:
| Intervention | Where it acts | What it changes | Caution |
|---|---|---|---|
| K-Means initialization (TIGER) | Initialization | Start codewords near observed vectors | Not a balance guarantee |
| Dead-code reset | Codebook maintenance | Revive persistently inactive entries | Changes codeword semantics |
| EMA codebook updates | Centroid update | Moving-average alternative to gradient updating | Still does not enforce equal usage |
| Diversity / contrastive regularization (LETTER) | Loss and codeword geometry | Separate codewords, counteract redundant geometry | Geometric spread != uniform usage |
| Entropy regularization | Auxiliary differentiable loss | Encourage higher average assignment entropy | Depends on soft assignment and batch quality |
| Frequency-aware routing (S²GR / CoBa RQ-VAE) | Hard selection distances | Penalize overused codes; favor underused ones | Soft balancing, not strict capacity |
| Optimal transport / Sinkhorn (OptVQ) | Assignment solver | Couple batch assignments and balance masses | Extra computation; batch-size constraints |
| Invertible distribution transform (CARD / NU-RQ-VAE) | Representation space | Make skewed latents more quantization-friendly | May alter semantic geometry |
A differentiable balance objective (generic design, not TIGER’s loss)
For soft assignments , define . Encourage aggregate usage to approach uniform:
Optionally penalize per-example entropy to favor confident individual assignments while preserving globally varied code usage. Do not maximize each sample’s entropy unless you actually want diffuse per-item assignments. Since is soft, this auxiliary loss differentiates through distances to codebook embeddings and encoder outputs; final hard counts are not guaranteed equal.
LETTER: why K-Means grouping does not need differentiable K-Means
LETTER applies constrained K-Means to the codebook vectors, yielding discrete groups. It then selects a positive codeword from the same group and uses a continuous codeword-similarity loss.
Its published Eq. (4) is written as a negative unlogged softmax-like ratio:
Do not silently rewrite the paper’s equation as standard negative-log InfoNCE: a negative ratio and a negative log-ratio give different gradients. The paper also adds a collaborative regularizer aligning quantized embeddings to behavior-based CF embeddings.
Gradient logic:
with torch.no_grad():
groups = constrained_kmeans(codebook.detach()) # discrete, frozen for this step
anchor_idx, pos_idx = choose_pairs(groups)
loss_div = diversity_loss(codebook[anchor_idx], codebook[pos_idx], codebook)
loss_div.backward() # updates continuous codeword vectors
The group assignment does not receive gradients, but the continuous selected codeword embeddings do. This is analogous to hard-negative mining: non-differentiable selection can define a differentiable objective. Regroup periodically if desired. The publication does not give enough detail to treat the illustrative pseudocode as its exact implementation.
S²GR / CoBa RQ-VAE: frequency-aware selection
For codeword usage count and mean usage , define a bounded adjustment (positive for underused codes, negative for overused codes), and change the routing distance:
Underused codes become artificially closer; overused codes become farther. This influences future assignment and gradient coverage without requiring a differentiable hard index. This is soft load balancing, not exact equipartition.
Sinkhorn / optimal-transport assignment (intuition)
Rather than assigning each residual independently, solve for nonnegative assignment weights with row masses summing to 1 and approximately equal column masses :
Sinkhorn scaling efficiently approximates the entropy-regularized transport solution. A later hardening step may be required; independently taking argmax of each row does not strictly preserve column capacities. This is a general VQ approach, not the TIGER default.
CARD / NU-RQ-VAE: change the distribution before quantization
Learn an invertible mapping so that has a distribution more amenable to RQ; use after quantization for decoding. Rather than forcing assignment counts, this targets the geometry/statistics that cause skewed usage. Invertibility preserves information in the transformation itself, but does not make the later quantizer lossless.
PQ, OPQ, and RQ-OPQ
Motivation / intuition
RQ encodes successive full-dimensional residuals. Product Quantization (PQ) instead splits a vector into subspaces, encodes each subspace separately, then concatenates subspace reconstructions. OPQ improves PQ by learning a rotation before splitting dimensions.
PQ vs RQ
For :
RQ reconstructs via sum of full-dimensional codewords; PQ reconstructs via concatenation of subspace codewords.
OPQ = optimized rotation + PQ
Let . Rotate , then quantize its subspaces. The idealized objective is:
The inverse reconstruction is . An orthogonal transform preserves Euclidean distances before quantization, while redistributing information across chosen PQ subspaces. Classical OPQ learns its transform/codebooks by alternating optimization; it does not require the nonlinear encoder/decoder of RQ-VAE.
OneSearch: RQ first, OPQ on the final residual
input item embedding x
-> RQ-KMeans L1 (4096 codes)
-> RQ-KMeans L2 (1024 codes)
-> RQ-KMeans L3 ( 512 codes; balanced in the selected setup)
-> residual r3 = x - sum(selected RQ codewords)
-> OPQ(r3): two 256-entry PQ sub-codebooks
-> SID = (RQ1, RQ2, RQ3, OPQ1, OPQ2)
An idealized reconstruction is
Interpretation: the early RQ prefix captures shared semantic structure; the OPQ suffix increases discrimination among items with similar prefixes by representing previously discarded residual information. This does not mean every suffix distinction is predictable from the query.
OneSearch’s reported tokenizer comparison (Table 3, real click pairs):
| Tokenizer | ICR | Recall@10 | MRR@10 |
|---|---|---|---|
| RQ-VAE | 38.83% | 0.2171 | 0.0689 |
| RQ-KMeans | 68.08% | 0.2844 | 0.1038 |
| RQ-OPQ | 91.91% | 0.3369 | 0.1194 |
This is evidence in one industrial experimental setup, not a universal proof that RQ-OPQ is always better. More suffix tokens increase coding capacity and generation length/difficulty; OneSearch reports that four OPQ suffix tokens performed worse than two.
Evaluation: what is a good SID tokenizer?
Motivation / intuition
A tokenizer may have very low reconstruction error and very high full-ID uniqueness yet encode details that a query cannot predict. Conversely, a highly predictable SID may collapse too many distinct target items. Evaluate multiple axes independently.
| Axis | Useful metrics / tests | Diagnostic question |
|---|---|---|
| Quantization | Original-space reconstruction MSE, residual norms by level | How much information was lost? |
| Utilization | Per-level active codes, normalized entropy, top-k code mass | Is capacity actually being used? |
| Full SID | Distinct SID count, collision rate, SID bucket-size distribution | How many items share an ID? |
| Semantics | Nearest-neighbor preservation, prefix purity, attribute agreement | Do shared prefixes mean anything useful? |
| Predictability | Per-level SID cross-entropy / accuracy conditioned on query and user | Can the generator infer these codes? |
| Retrieval | Recall@K, HR@K, MRR@K, NDCG@K, head/tail & cold-start | Does the final system improve? |
| Operations | Encoding stability across retraining, new-item drift, serving cost | Can the IDs be maintained? |
For items, define a convenient independent-code ratio as a diagnostic definition; check each paper’s exact ICR convention rather than assuming all papers compute it identically. Collision metrics may need a separate tie-breaking/item-ID disambiguation policy for inference.