← All writing

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:

  1. Semantic organization: related items should often share a prefix.
  2. Distinctiveness: different items should not collide excessively.
  3. Vocabulary utilization: avoid dead codes and pathological concentration.
  4. 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

  • xi∈RDx_i\in\mathbb R^D: item embedding (from a frozen or separately learned item representation model).
  • LL: number of quantization levels; KlK_l: codebook size at level ll.
  • El={el,1,…,el,Kl}E_l=\{e_{l,1},\ldots,e_{l,K_l}\}: level-ll codebook.
  • ci,l∈{1,…,Kl}c_{i,l}\in\{1,\dots,K_l\}: selected token at level ll.
  • SID(i)=(ci,1,…,ci,L)\mathrm{SID}(i)=(c_{i,1},\ldots,c_{i,L}).

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 xx once, repeatedly quantize what is left unexplained.

Formulation

For a vector vv (either xx or an encoded latent zz), initialize r0=vr_0=v. At level ll:

cl=arg⁡min⁡k∥rl−1−el,k∥22,rl=rl−1−el,cl.\begin{aligned} c_l &= \arg\min_k \|r_{l-1}-e_{l,k}\|_2^2,\\ r_l &= r_{l-1}-e_{l,c_l}. \end{aligned}

After LL levels:

v^=∑l=1Lel,cl,rL=v−v^.\hat v=\sum_{l=1}^L e_{l,c_l},\qquad r_L=v-\hat v.

The code sequence is SID(v)=(c1,…,cL)\mathrm{SID}(v)=(c_1,\ldots,c_L). 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 y1,…,yNy_1,\ldots,y_N, minimize within-cluster squared distance:

min⁡a1,…,aN,μ1,…,μK ∑i=1N∥yi−μai∥2.\min_{a_1,\ldots,a_N,\mu_1,\ldots,\mu_K}\ \sum_{i=1}^N\|y_i-\mu_{a_i}\|^2.

Two alternating steps:

Assignment (fixed centers)

ai←arg⁡min⁡k∥yi−μk∥2.a_i\leftarrow\arg\min_k\|y_i-\mu_k\|^2.

Update (fixed assignments)

μk←1∣Ck∣∑i:ai=kyi.\mu_k\leftarrow\frac{1}{|C_k|}\sum_{i:a_i=k}y_i.

Why the mean? For a fixed cluster CkC_k, differentiating ∑i∈Ck∥yi−μk∥2\sum_{i\in C_k}\|y_i-\mu_k\|^2 with respect to μk\mu_k, setting the derivative to zero, yields the arithmetic mean. This derivation uses calculus, but the algorithm does not use gradient descent.

Toy example: [0,1,2,8,9,10][0,1,2,8,9,10] with K=2K=2. Starting centers 0,100,10, assignments form groups [0,1,2][0,1,2] and [8,9,10][8,9,10]; updating produces centers 1,91,9. 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.

x→fθz→RQz^→gϕx^.x\xrightarrow{f_\theta}z\xrightarrow{\mathrm{RQ}}\hat z\xrightarrow{g_\phi}\hat x.

Here r0=zr_0=z, and RQ operates in the latent space. The decoder reconstructs the original input embedding xx.

Formulation and loss

A TIGER-style objective is

L=∥x−gϕ(z^)∥22⏟Lrecon+∑l=1L[∥sg[rl−1]−el,cl∥22⏟codebook+β∥rl−1−sg[el,cl]∥22⏟commitment].\mathcal L=\underbrace{\|x-g_\phi(\hat z)\|_2^2}_{\mathcal L_{\rm recon}} + \sum_{l=1}^L\left[\underbrace{\|\mathrm{sg}[r_{l-1}]-e_{l,c_l}\|_2^2}_{\rm codebook} + \beta\underbrace{\|r_{l-1}-\mathrm{sg}[e_{l,c_l}]\|_2^2}_{\rm commitment}\right].

sg[⋅]\mathrm{sg}[\cdot] (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 xx.
  • 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 e0=0,e1=2e_0=0,e_1=2:

Q(z)={0,z<1,2,z≥1.Q(z)=\begin{cases}0,&z<1,\\2,&z\ge1.\end{cases}

The true derivative is zero almost everywhere and undefined at the decision boundary. Merely differentiating through arg⁡min⁡\arg\min 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: zst=zqz_{\rm st}=z_q.

Backward: ∂zst/∂z=1\partial z_{\rm st}/\partial z=1 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 z=Eθ(x)z=E_\theta(x) and let zqz_q be the selected codeword. Define

zst=z+sg[zq−z].z_{\mathrm{st}} = z+\mathrm{sg}[z_q-z].

The implemented loss is then

L=∥x−Dϕ(zst)∥22⏟Lrecon+∥sg[z]−zq∥22⏟Lcodebook+β∥z−sg[zq]∥22⏟Lcommit.\begin{aligned} \mathcal{L} ={}&\underbrace{\|x-D_\phi(z_{\mathrm{st}})\|_2^2}_{\mathcal{L}_{\mathrm{recon}}}\\ &+\underbrace{\|\mathrm{sg}[z]-z_q\|_2^2}_{\mathcal{L}_{\mathrm{codebook}}}\\ &+\underbrace{\beta\|z-\mathrm{sg}[z_q]\|_2^2}_{\mathcal{L}_{\mathrm{commit}}}. \end{aligned}

Forward: since zst=zqz_{\mathrm{st}}=z_q numerically, the reconstruction loss is exactly the same value as ∥x−Dϕ(zq)∥2\|x-D_\phi(z_q)\|^2.

Backward: autograd sees ∂zst/∂z=I\partial z_{\mathrm{st}}/\partial z=I and ∂zst/∂zq=0\partial z_{\mathrm{st}}/\partial z_q=0. 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 ∂zst/∂z=I\partial z_{\mathrm{st}}/\partial z=I and ∂zst/∂zq=0\partial z_{\mathrm{st}}/\partial z_q=0.

LossEncoderSelected codewordDecoder
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 zst=zqz_{\mathrm{st}}=z_q. 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 zz, consider the nearest-codeword squared error:

L(E)=min⁡k∥z−ek∥22,E={e1,…,eK}.\mathcal{L}(E)=\min_k\|z-e_k\|_2^2,\qquad E=\{e_1,\ldots,e_K\}.

Suppose one codeword ece_c 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

L(E)=∥z−ec∥22.\mathcal{L}(E)=\|z-e_c\|_2^2.

Its derivatives with respect to the codewords are

∂L∂ec=2(ec−z),∂L∂ej=0(j≠c).\frac{\partial\mathcal{L}}{\partial e_c}=2(e_c-z), \qquad \frac{\partial\mathcal{L}}{\partial e_j}=0\quad(j\neq c).

Thus, the selected codeword can be updated by ordinary gradient descent even though the index c=arg⁡min⁡k∥z−ek∥2c=\arg\min_k\|z-e_k\|^2 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:

  1. A genuinely discrete forward representation: each item should select a codeword (and eventually obtain a discrete SID).
  2. 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 rr and codebook vectors eke_k:

c=arg⁡min⁡k∥r−ek∥2,zq=ec.c=\arg\min_k\|r-e_k\|^2,\qquad z_q=e_c.

Example: let r=0.9r=0.9, with codewords e0=0e_0=0 and e1=2e_1=2. The selected codeword is zq=0z_q=0; changing rr slightly does not change the selection.

With these fixed codewords:

Q(r)={0,r<1,2,r≥1.Q(r)=\begin{cases}0,&r<1,\\2,&r\ge1.\end{cases}

The true derivative ∂Q/∂r\partial Q/\partial r is zero almost everywhere and undefined at the boundary. Thus, directly using D(Q(r))D(Q(r)) in reconstruction loss does not provide a useful gradient through the hard quantizer to the encoder.

Nuance: after the index is selected, the value ece_c 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:

dk=∥r−ek∥2,pk=exp⁡(−dk/τ)∑jexp⁡(−dj/τ).d_k=\|r-e_k\|^2,\qquad p_k=\frac{\exp(-d_k/\tau)}{\sum_j\exp(-d_j/\tau)}.

Here τ>0\tau>0 is the temperature. Construct a soft quantized vector:

zsoft=∑kpkek.z_{\mathrm{soft}}=\sum_k p_ke_k.

For r=0.9r=0.9, e0=0e_0=0, e1=2e_1=2, and τ=1\tau=1:

(p0,p1)≈(0.599,0.401),zsoft≈0.802.(p_0,p_1)\approx(0.599,0.401),\qquad z_{\mathrm{soft}}\approx0.802.

Unlike the hard output 00, the soft output is a weighted average. The path

r⟶d⟶p⟶zsoft⟶D(zsoft)r\longrightarrow d\longrightarrow p\longrightarrow z_{\mathrm{soft}}\longrightarrow D(z_{\mathrm{soft}})

is differentiable: gradients reach the encoder through the distance computation and softmax.

Trade-off: if training feeds zsoftz_{\mathrm{soft}} to the decoder but inference uses one hard codeword, the model may experience a training-inference mismatch. Lowering τ\tau 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 arg⁡max⁡\arg\max 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 arg⁡min⁡\arg\min mathematically differentiable; it defines a useful approximate gradient.

Variant A: Identity STE (the classic VQ-VAE choice)

Forward computation path

z→distance + argminc→codebook lookupzq→Identity STEzstz\xrightarrow{\text{distance + argmin}}c \xrightarrow{\text{codebook lookup}}z_q \xrightarrow{\text{Identity STE}}z_{\mathrm{st}}

Where STE acts: at the quantized embedding level, combining the hard vector zqz_q with the encoder output zz via zst=z+sg[zq−z]z_{\mathrm{st}}=z+\mathrm{sg}[z_q-z]. The backward surrogate goes directly to zz, not through index cc.

# 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: zst=zqz_{\mathrm{st}}=z_q, so the decoder sees an actual hard codeword.

Backward: ∂zst/∂z=I\partial z_{\mathrm{st}}/\partial z=I, 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

z→distanced→softmaxp→Softmax STEw→codebookzstz\xrightarrow{\text{distance}}d \xrightarrow{\text{softmax}}p \xrightarrow{\text{Softmax STE}}w \xrightarrow{\text{codebook}}z_{\mathrm{st}}

Where STE acts: at the assignment-weight level: h=onehot(arg⁡max⁡p)h=\mathrm{onehot}(\arg\max p) and w=h−sg[p]+pw=h-\mathrm{sg}[p]+p. The STE constructs ww from the hard one-hot assignment and soft probabilities; it does not differentiate through the integer index.

Start from soft probabilities pp but replace their forward value by a hard one-hot vector hh:

h=onehot(arg⁡max⁡kpk),w=h−sg[p]+p.h=\mathrm{onehot}(\arg\max_k p_k),\qquad w=h-\mathrm{sg}[p]+p.

Quantize with ww:

zst=∑kwkek.z_{\mathrm{st}}=\sum_k w_ke_k.
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: w=hw=h, 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 pp, 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?

MethodForward to decoderBackward to encoder
Hard assignmentSingle codewordNo useful gradient through arg⁡min⁡\arg\min
Soft assignmentWeighted average of codewordsTrue softmax-path gradient
Identity STESingle codewordIdentity surrogate gradient
Softmax STESingle codewordSoftmax-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:

  1. Collapse / dead codes: many codewords are never used.
  2. Imbalance: all or most codewords are used, but a small subset dominates assignments.

Let nl,kn_{l,k} be number of items mapped to code kk at level ll and pl,k=nl,k/Np_{l,k}=n_{l,k}/N.

Utilizationl=∣{k:nl,k>0}∣Kl,Hl=−∑kpl,klog⁡pl,k,Hlnorm=Hl/log⁡Kl.\mathrm{Utilization}_l=\frac{|\{k:n_{l,k}>0\}|}{K_l},\qquad H_l=-\sum_k p_{l,k}\log p_{l,k},\qquad H_l^{\rm norm}=H_l/\log K_l.

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 NN:

min⁡a,μ∑i∥ri−μai∥2s.t.∑i1[ai=k]=N/K ∀k.\min_{a,\mu}\sum_i\|r_i-\mu_{a_i}\|^2\quad\text{s.t.}\quad\sum_i\mathbf 1[a_i=k]=N/K\ \forall k.

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:

InterventionWhere it actsWhat it changesCaution
K-Means initialization (TIGER)InitializationStart codewords near observed vectorsNot a balance guarantee
Dead-code resetCodebook maintenanceRevive persistently inactive entriesChanges codeword semantics
EMA codebook updatesCentroid updateMoving-average alternative to gradient updatingStill does not enforce equal usage
Diversity / contrastive regularization (LETTER)Loss and codeword geometrySeparate codewords, counteract redundant geometryGeometric spread != uniform usage
Entropy regularizationAuxiliary differentiable lossEncourage higher average assignment entropyDepends on soft assignment and batch quality
Frequency-aware routing (S²GR / CoBa RQ-VAE)Hard selection distancesPenalize overused codes; favor underused onesSoft balancing, not strict capacity
Optimal transport / Sinkhorn (OptVQ)Assignment solverCouple batch assignments and balance massesExtra computation; batch-size constraints
Invertible distribution transform (CARD / NU-RQ-VAE)Representation spaceMake skewed latents more quantization-friendlyMay alter semantic geometry

A differentiable balance objective (generic design, not TIGER’s loss)

For soft assignments qi,k=softmax⁡k(−di,k/τ)q_{i,k}=\operatorname{softmax}_k(-d_{i,k}/\tau), define qˉk=1B∑iqi,k\bar q_k=\frac1B\sum_i q_{i,k}. Encourage aggregate usage to approach uniform:

Lbalance=DKL(qˉ∥UK)=log⁡K−H(qˉ).\mathcal L_{\rm balance}=D_{\rm KL}(\bar q\|U_K)=\log K-H(\bar q).

Optionally penalize per-example entropy 1B∑iH(qi)\frac1B\sum_i H(q_i) 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 qq 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:

LDiv=−1B∑i=1Bexp⁡(⟨eci,e+,i⟩)∑j≠ciexp⁡(⟨eci,ej⟩).\mathcal L_{\rm Div}=-\frac1B\sum_{i=1}^B\frac{\exp(\langle e_{c_i},e_{+,i}\rangle)}{\sum_{j\ne c_i}\exp(\langle e_{c_i},e_j\rangle)}.

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 uku_k and mean usage uˉ\bar u, define a bounded adjustment fkf_k (positive for underused codes, negative for overused codes), and change the routing distance:

d~k=dk(1−fk),c=arg⁡min⁡kd~k.\tilde d_k=d_k(1-f_k),\qquad c=\arg\min_k\tilde d_k.

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 PikP_{ik} with row masses summing to 1 and approximately equal column masses B/KB/K:

min⁡P≥0∑i,kPikdik+ε∑i,kPik(log⁡Pik−1),\min_{P\ge0}\sum_{i,k}P_{ik}d_{ik}+\varepsilon\sum_{i,k}P_{ik}(\log P_{ik}-1), ∑kPik=1,∑iPik=B/K.\sum_kP_{ik}=1,\qquad\sum_iP_{ik}=B/K.

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 TT so that y=T(fθ(x))y=T(f_\theta(x)) has a distribution more amenable to RQ; use T−1T^{-1} 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 v=[v(1);…;v(M)]v=[v^{(1)};\ldots;v^{(M)}]:

PQ(v)=(k1,…,kM),v^=[e1,k1;…;eM,kM].\mathrm{PQ}(v)=(k_1,\dots,k_M),\qquad\hat v=[e_{1,k_1};\ldots;e_{M,k_M}].

RQ reconstructs via sum of full-dimensional codewords; PQ reconstructs via concatenation of subspace codewords.

OPQ = optimized rotation + PQ

Let RTR=IR^TR=I. Rotate y=Rvy=Rv, then quantize its subspaces. The idealized objective is:

min⁡R,PQ codebooks,assignments∑i∥Rvi−y^iPQ∥2,RTR=I.\min_{R,\mathrm{PQ\ codebooks},\mathrm{assignments}}\sum_i\left\|Rv_i-\hat y_i^{\rm PQ}\right\|^2,\quad R^TR=I.

The inverse reconstruction is v^=RTy^PQ\hat v=R^T\hat y^{\rm PQ}. 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

x^=∑l=13el,cl+RT[e4,c4;e5,c5].\hat x=\sum_{l=1}^3e_{l,c_l}+R^T[e_{4,c_4};e_{5,c_5}].

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):

TokenizerICRRecall@10MRR@10
RQ-VAE38.83%0.21710.0689
RQ-KMeans68.08%0.28440.1038
RQ-OPQ91.91%0.33690.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.

AxisUseful metrics / testsDiagnostic question
QuantizationOriginal-space reconstruction MSE, residual norms by levelHow much information was lost?
UtilizationPer-level active codes, normalized entropy, top-k code massIs capacity actually being used?
Full SIDDistinct SID count, collision rate, SID bucket-size distributionHow many items share an ID?
SemanticsNearest-neighbor preservation, prefix purity, attribute agreementDo shared prefixes mean anything useful?
PredictabilityPer-level SID cross-entropy / accuracy conditioned on query and userCan the generator infer these codes?
RetrievalRecall@K, HR@K, MRR@K, NDCG@K, head/tail & cold-startDoes the final system improve?
OperationsEncoding stability across retraining, new-item drift, serving costCan the IDs be maintained?

For NN items, define a convenient independent-code ratio ∣{SID(i)}∣/N|\{\mathrm{SID}(i)\}|/N 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.

#generative-retrieval#semantic-ids#vector-quantization