vector_quantize
vector_quantize
¶
Single-layer vector quantization with straight-through gradient estimator.
Wraps an EuclideanCodebook with optional input/output projections. Gradients flow through the quantization step via the straight-through estimator: forward uses the discrete codebook lookup, backward pretends it was an identity. Loss computation is handled externally by the metrics module (VQCommitmentLoss).
VectorQuantize
¶
VectorQuantize(input_dimension, code_dim, num_codes, ema_decay=0.99, dead_code_threshold=1.0, kmeans_init=True)
Bases: Module
Single-layer vector quantizer with straight-through gradients.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_dimension
|
int
|
Dimension of the input vectors from the encoder. |
required |
code_dim
|
int
|
Dimension of each codebook vector. If different from input_dimension, linear projections are added. |
required |
num_codes
|
int
|
Number of codebook entries (K). |
required |
ema_decay
|
float
|
EMA decay for codebook updates. |
0.99
|
dead_code_threshold
|
float
|
Cluster size below which a code is replaced. |
1.0
|
kmeans_init
|
bool
|
Initialize codebook from the first batch. |
True
|
Source code in src/versatil/models/decoding/latent/vq/vector_quantize.py
forward
¶
Quantize input via nearest codebook lookup with straight-through gradient.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z_e
|
Tensor
|
Encoder output, shape (B, input_dimension). |
required |
Returns:
| Type | Description |
|---|---|
tuple[Tensor, Tensor, Tensor, Tensor]
|
Tuple of: z_q: Quantized output with straight-through gradient, shape (B, input_dimension). indices: Codebook indices, shape (B,). z_e_projected: Pre-quantization encoder output in code space, shape (B, code_dim). Carries gradient; used as the commitment-loss target for the encoder. z_q_code: Hard-quantized codebook vector in code space, shape (B, code_dim), detached from the computation graph. Paired with z_e_projected for per-layer commitment loss. |