|
| 1 | +# Copyright (c) 2026, Alibaba Group; |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# Unless required by applicable law or agreed to in writing, software |
| 7 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 8 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 9 | +# See the License for the specific language governing permissions and |
| 10 | +# limitations under the License. |
| 11 | + |
| 12 | +"""ResidualQuantizer: abstract base for multi-layer residual quantizers.""" |
| 13 | + |
| 14 | +from typing import List, Tuple, Union |
| 15 | + |
| 16 | +import torch |
| 17 | +from torch import nn |
| 18 | +from torch.nn import functional as F |
| 19 | + |
| 20 | + |
| 21 | +def normalize_n_embed(n_embed: Union[int, List[int]], n_layers: int) -> List[int]: |
| 22 | + """Broadcast a scalar codebook size to a per-layer list (or validate one). |
| 23 | +
|
| 24 | + Args: |
| 25 | + n_embed (int|List[int]): codebook size, shared or per-layer. |
| 26 | + n_layers (int): number of residual quantization layers. |
| 27 | +
|
| 28 | + Returns: |
| 29 | + List[int]: per-layer codebook sizes, length ``n_layers``. |
| 30 | + """ |
| 31 | + if isinstance(n_embed, int): |
| 32 | + return [n_embed] * n_layers |
| 33 | + assert len(n_embed) == n_layers, ( |
| 34 | + "length of n_embed and n_layers must be same, " |
| 35 | + f"but got {len(n_embed)} vs {n_layers}" |
| 36 | + ) |
| 37 | + return list(n_embed) |
| 38 | + |
| 39 | + |
| 40 | +class ResidualQuantizer(nn.Module): |
| 41 | + """Abstract base for multi-layer residual quantization. |
| 42 | +
|
| 43 | + Shared contract for the two SID quantizer backends — the VQ-based, |
| 44 | + gradient-trained :class:`ResidualVectorQuantizer` and the K-Means-based, |
| 45 | + offline-FAISS-trained :class:`ResidualKMeansQuantizer`. Both quantize the |
| 46 | + residual of the previous layer: |
| 47 | +
|
| 48 | + residual_0 = input |
| 49 | + for each layer i: |
| 50 | + (optionally) residual_i = L2_normalize(residual_i) |
| 51 | + code_i, quantized_i = layer_i(residual_i) |
| 52 | + residual_{i+1} = residual_i - quantized_i |
| 53 | + output = sum of all quantized_i |
| 54 | +
|
| 55 | + Semantic ID = (code_0, code_1, ..., code_{n_layers-1}). |
| 56 | +
|
| 57 | + This base owns the structural invariants (``embed_dim``, ``n_layers``, |
| 58 | + per-layer codebook sizes, residual normalization toggle) and the shared |
| 59 | + residual walk (:meth:`_residual_pass`, :meth:`get_codes`, |
| 60 | + :meth:`decode_codes`, :meth:`output_dim`). Subclasses build ``self.layers`` |
| 61 | + and implement the per-layer primitives :meth:`_quantize_layer` (encode) and |
| 62 | + :meth:`_lookup_code` (decode), plus :meth:`forward` and |
| 63 | + :meth:`get_codebook_embeddings`. |
| 64 | +
|
| 65 | + Args: |
| 66 | + embed_dim (int): feature / codebook dimension. |
| 67 | + n_layers (int): number of residual quantization layers. |
| 68 | + n_embed (int|List[int]): codebook size per layer. Default: 256. |
| 69 | + normalize_residuals (bool): L2-normalize residuals before each |
| 70 | + layer. Default: False. |
| 71 | + """ |
| 72 | + |
| 73 | + def __init__( |
| 74 | + self, |
| 75 | + embed_dim: int, |
| 76 | + n_layers: int, |
| 77 | + n_embed: Union[int, List[int]] = 256, |
| 78 | + normalize_residuals: bool = False, |
| 79 | + ) -> None: |
| 80 | + super().__init__() |
| 81 | + self.embed_dim = embed_dim |
| 82 | + self.n_layers = n_layers |
| 83 | + self.normalize_residuals = normalize_residuals |
| 84 | + self.n_embed_list = normalize_n_embed(n_embed, n_layers) |
| 85 | + # Subclasses MUST populate this with one quantization layer each. |
| 86 | + self.layers: nn.ModuleList = nn.ModuleList() |
| 87 | + |
| 88 | + def output_dim(self) -> int: |
| 89 | + """Output dimension of the module.""" |
| 90 | + return self.embed_dim |
| 91 | + |
| 92 | + def forward(self, input: torch.Tensor): # noqa: ANN201 |
| 93 | + """Assign codes per layer and accumulate the quantized output.""" |
| 94 | + raise NotImplementedError |
| 95 | + |
| 96 | + def _quantize_layer( |
| 97 | + self, |
| 98 | + layer_idx: int, |
| 99 | + residual: torch.Tensor, |
| 100 | + temperature: float = 1.0, |
| 101 | + ) -> Tuple[torch.Tensor, torch.Tensor]: |
| 102 | + """Assign one layer's codes and look up its quantized vector. |
| 103 | +
|
| 104 | + Backend primitive behind the residual walk (encode-direction mirror of |
| 105 | + :meth:`_lookup_code`). ``temperature`` is used only by the VQ backend. |
| 106 | +
|
| 107 | + Args: |
| 108 | + layer_idx (int): quantization layer index. |
| 109 | + residual (Tensor): current residual, shape (B, D). |
| 110 | + temperature (float): Gumbel-Softmax temperature (VQ only). |
| 111 | +
|
| 112 | + Returns: |
| 113 | + codes (Tensor): per-layer cluster ids, shape (B,). |
| 114 | + quantized (Tensor): the layer's quantized vector, shape (B, D). |
| 115 | + """ |
| 116 | + raise NotImplementedError |
| 117 | + |
| 118 | + def _residual_pass( |
| 119 | + self, |
| 120 | + input: torch.Tensor, |
| 121 | + temperature: float = 1.0, |
| 122 | + ) -> Tuple[torch.Tensor, torch.Tensor, List[torch.Tensor]]: |
| 123 | + """Shared residual walk: per-layer assign, subtract, accumulate. |
| 124 | +
|
| 125 | + The quantized vector is subtracted detached (keeps the residual chain |
| 126 | + gradient-free) and accumulated (keeps gradient when the backend |
| 127 | + supplies it, e.g. VQ). |
| 128 | +
|
| 129 | + Args: |
| 130 | + input (Tensor): input embeddings, shape (B, D). |
| 131 | + temperature (float): forwarded to :meth:`_quantize_layer`. |
| 132 | +
|
| 133 | + Returns: |
| 134 | + cluster_ids (Tensor): stacked codes, shape (B, n_layers). |
| 135 | + aggregated (Tensor): sum of quantized vectors, shape (B, D). |
| 136 | + cumulative (List[Tensor]): running sum after each layer |
| 137 | + (``cumulative[-1] is aggregated``). |
| 138 | + """ |
| 139 | + residual = input |
| 140 | + all_codes: List[torch.Tensor] = [] |
| 141 | + cumulative: List[torch.Tensor] = [] |
| 142 | + aggregated = torch.zeros_like(input) |
| 143 | + for i in range(self.n_layers): |
| 144 | + if self.normalize_residuals: |
| 145 | + residual = F.normalize(residual, dim=-1) |
| 146 | + codes, quantized = self._quantize_layer(i, residual, temperature) |
| 147 | + all_codes.append(codes) |
| 148 | + aggregated = aggregated + quantized |
| 149 | + cumulative.append(aggregated) |
| 150 | + residual = residual - quantized.detach() |
| 151 | + cluster_ids = torch.stack(all_codes, dim=-1) # (B, n_layers) |
| 152 | + return cluster_ids, aggregated, cumulative |
| 153 | + |
| 154 | + @torch.no_grad() |
| 155 | + def get_codes(self, input: torch.Tensor) -> torch.Tensor: |
| 156 | + """Assign semantic IDs without updating the codebook. |
| 157 | +
|
| 158 | + Shared encode-direction mirror of :meth:`decode_codes`. |
| 159 | +
|
| 160 | + Args: |
| 161 | + input (Tensor): input embeddings, shape (B, D). |
| 162 | +
|
| 163 | + Returns: |
| 164 | + Tensor: cluster ids, shape (B, n_layers). |
| 165 | + """ |
| 166 | + cluster_ids, _, _ = self._residual_pass(input) |
| 167 | + return cluster_ids |
| 168 | + |
| 169 | + @torch.no_grad() |
| 170 | + def get_codebook_embeddings(self, layer_idx: int) -> torch.Tensor: |
| 171 | + """Get the codebook (centroid) weights for a specific layer. |
| 172 | +
|
| 173 | + Args: |
| 174 | + layer_idx (int): index of the quantization layer. |
| 175 | +
|
| 176 | + Returns: |
| 177 | + Tensor: codebook weights, shape (n_embed, embed_dim). |
| 178 | + """ |
| 179 | + raise NotImplementedError |
| 180 | + |
| 181 | + def _lookup_code(self, layer_idx: int, code_idx: torch.Tensor) -> torch.Tensor: |
| 182 | + """Look up the codebook vectors for ``code_idx`` at ``layer_idx``. |
| 183 | +
|
| 184 | + The single backend-specific primitive :meth:`decode_codes` builds on |
| 185 | + (VQ reads ``embedding(idx)``, K-Means reads ``centroids[idx]``). |
| 186 | +
|
| 187 | + Args: |
| 188 | + layer_idx (int): index of the quantization layer. |
| 189 | + code_idx (Tensor): codebook indices, shape (B,). |
| 190 | +
|
| 191 | + Returns: |
| 192 | + Tensor: looked-up codebook vectors, shape (B, embed_dim). |
| 193 | + """ |
| 194 | + raise NotImplementedError |
| 195 | + |
| 196 | + @torch.no_grad() |
| 197 | + def decode_codes(self, codes: torch.Tensor) -> torch.Tensor: |
| 198 | + """Reconstruct embeddings from semantic ID codes (centroid sum). |
| 199 | +
|
| 200 | + Args: |
| 201 | + codes (Tensor): cluster ids, shape (B, n_layers). |
| 202 | +
|
| 203 | + Returns: |
| 204 | + Tensor: reconstructed embeddings, shape (B, embed_dim). |
| 205 | + """ |
| 206 | + # Seed from the first lookup so device and dtype follow the codebook |
| 207 | + # (avoids pinning the sum to fp32 under mixed precision). n_layers >= 1 |
| 208 | + # is guaranteed by the codebook config. |
| 209 | + quantized_sum = self._lookup_code(0, codes[:, 0]) |
| 210 | + for i in range(1, self.n_layers): |
| 211 | + quantized_sum = quantized_sum + self._lookup_code(i, codes[:, i]) |
| 212 | + return quantized_sum |
0 commit comments