residual_vq
residual_vq
¶
Residual vector quantization with cascading codebook layers.
Each layer quantizes the residual left by previous layers, producing a hierarchical discrete representation. Coarse layers capture the dominant structure, fine layers capture residual detail.
ResidualVQ
¶
ResidualVQ(input_dimension, code_dim, num_codes, num_layers=1, ema_decay=0.99, dead_code_threshold=1.0, kmeans_init=True)
Bases: Module
Multi-layer residual vector quantizer.
Cascades N VectorQuantize layers. Each layer quantizes the residual from the previous layer. The final quantized output is the sum of all layers' contributions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_dimension
|
int
|
Dimension of the input vectors. |
required |
code_dim
|
int
|
Dimension of each codebook vector per layer. |
required |
num_codes
|
int
|
Number of codebook entries per layer (K). |
required |
num_layers
|
int
|
Number of residual VQ layers. |
1
|
ema_decay
|
float
|
EMA decay for codebook updates in each layer. |
0.99
|
dead_code_threshold
|
float
|
Dead code replacement threshold per layer. |
1.0
|
kmeans_init
|
bool
|
Initialize each layer's codebook from data. |
True
|
Source code in src/versatil/models/decoding/latent/vq/residual_vq.py
forward
¶
Quantize input through cascading residual layers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z_e
|
Tensor
|
Encoder output, shape (B, input_dimension). |
required |
Returns:
| Type | Description |
|---|---|
tuple[Tensor, list[Tensor], Tensor, Tensor]
|
Tuple of: z_q: Sum of all layers' quantized outputs, shape (B, input_dimension). all_indices: List of per-layer codebook indices, each shape (B,). z_e_per_layer: Per-layer pre-quantization encoder outputs in code space, stacked along dim 0, shape (L, B, code_dim). Carries gradient; used as commitment-loss target. z_q_per_layer: Per-layer hard-quantized codebook vectors in code space, stacked along dim 0, shape (L, B, code_dim). Detached; paired with z_e_per_layer for per-layer commitment loss. |
Source code in src/versatil/models/decoding/latent/vq/residual_vq.py
decode_from_indices
¶
Reconstruct quantized output from codebook indices.
Used by the prior at inference to convert predicted indices into the quantized embedding that the decoder expects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_indices
|
list[Tensor]
|
List of per-layer codebook indices, each shape (B,). |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Reconstructed quantized output, shape (B, input_dimension). |