euclidean_codebook
euclidean_codebook
¶
Euclidean codebook with EMA updates for vector quantization.
Manages a set of learnable embedding vectors updated via exponential moving averages of encoder outputs, following van den Oord et al. (2017) and Tolstikhin et al. (2018). Supports automatic initialization on the first batch and dead code replacement.
EuclideanCodebook
¶
Bases: Module
Codebook of embedding vectors with nearest-neighbor lookup and EMA updates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_codes
|
int
|
Number of codebook entries (K). |
required |
code_dim
|
int
|
Dimension of each codebook vector. |
required |
ema_decay
|
float
|
Exponential moving average decay for codebook updates. Higher values (e.g. 0.99) produce slower, more stable updates. |
0.99
|
dead_code_threshold
|
float
|
Minimum average cluster size below which a code is considered dead and replaced with a random encoder output. |
1.0
|
kmeans_init
|
bool
|
Initialize codebook vectors from the first batch (True) or from N(0, 1) (False). |
True
|
Source code in src/versatil/models/decoding/latent/vq/euclidean_codebook.py
forward
¶
Quantize encoder outputs to nearest codebook entries.
During training, updates codebook via EMA and replaces dead codes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z_e
|
Tensor
|
Encoder outputs, shape (B, D). |
required |
Returns:
| Type | Description |
|---|---|
tuple[Tensor, Tensor]
|
Tuple of: quantized: Nearest codebook vectors, shape (B, D). indices: Codebook indices for each input, shape (B,). |