KBench / tools /factory /specs /audio_codec_rvq_quantize.py
ZMC2019's picture
Reorganise: group 313 tasks into 17 families under tasks/, generators under tools/ (part 10)
0f775e2 verified
Raw
History Blame Contribute Delete
12.5 kB
"""Spec for `audio-codec-rvq-quantize` — residual vector quantisation in a neural audio codec encoder."""
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from spec import TaskSpec
SPEC = TaskSpec(
name="audio-codec-rvq-quantize",
title="Write a fast residual vector quantisation (RVQ) kernel",
blurb=("Neural audio codecs (EnCodec, DAC, Mimi, SNAC) — the tokenisers under every speech LM and TTS "
"system — compress each latent frame with a CHAIN of vector quantisers: find the nearest entry in "
"codebook 0, subtract it, find the nearest in codebook 1, subtract, and so on. Each stage is a "
"(frames x dim) by (dim x codebook) distance GEMM followed by an argmin, and the stages are "
"strictly sequential, so the residual has to stay resident while eight to sixteen of them run."),
keywords=["mle", "kernel-generation", "audio", "codec", "rvq", "vector-quantisation", "encodec",
"speech", "compute-bound"],
module="rvq.py",
func="rvq_quantize",
signature="rvq_quantize(x, codebooks)",
returns_doc="""Greedy residual vector quantisation over Q sequential codebooks.
Args:
x: (B, T, D) float32 — encoder latents, one vector per frame.
codebooks: (Q, K, D) bfloat16 — Q codebooks of K entries each.
Returns:
(codes, quantized) where
codes: (B, T, Q) int32 — the chosen entry of each codebook, in stage order
quantized: (B, T, D) float32 — the sum of the chosen codewords""",
reference_imports="import torch",
reference_src='''
def rvq_quantize(x, codebooks):
"""Greedy RVQ: nearest neighbour, subtract, repeat — in fp32.
Correct and simple — it is the numerical SPECIFICATION, not a performance target.
"""
B, T, D = x.shape
Q, K, _ = codebooks.shape
r = x.reshape(B * T, D).clone()
out = torch.zeros_like(r)
codes = torch.empty(B * T, Q, dtype=torch.int32, device=x.device)
for q in range(Q):
C = codebooks[q].float() # (K, D)
d = (r * r).sum(-1, keepdim=True) - 2.0 * (r @ C.t()) + (C * C).sum(-1).view(1, K)
j = d.argmin(dim=-1) # nearest entry per frame
codes[:, q] = j.to(torch.int32)
sel = C[j] # (B*T, D)
r = r - sel
out = out + sel
return codes.view(B, T, Q), out.view(B, T, D)
''',
make_inputs_src='''
def _mk(B, T, Q, K, D, seed):
gen = torch.Generator(device="cuda").manual_seed(seed)
# Codebook q has entries of norm ~0.5**q: that geometric decay is what makes a GREEDY residual
# quantiser work, and it is what real RVQ codecs learn. It also means the nearest entry at every
# stage wins by a wide margin, so the argmin is not a coin flip on rounding.
scales = (0.5 ** torch.arange(Q, device="cuda", dtype=torch.float32)).view(Q, 1, 1)
# Per-ENTRY norm jitter (0.6x .. 1.4x). Learned codebooks are not norm-equalised, and it is what makes
# the ||C_e||^2 term of the distance actually matter: without it every entry of a codebook has the same
# norm, the term is a constant, and dropping it would change nothing.
jitter = 0.6 + 0.8 * torch.rand(Q, K, 1, device="cuda", generator=gen)
# quantise the codebooks FIRST, then build x out of the quantised codewords, so the residual chain is
# exact: every stage's residual is the exact sum of the codewords the later stages will remove.
codebooks = (torch.randn(Q, K, D, device="cuda", generator=gen) * D ** -0.5 * jitter * scales
).to(torch.bfloat16)
pick = torch.randint(0, K, (Q, B * T), device="cuda", generator=gen)
x = torch.zeros(B * T, D, device="cuda", dtype=torch.float32)
for q in range(Q):
x += codebooks[q][pick[q]].float()
x += (0.5 ** Q) * 0.05 * torch.randn(B * T, D, device="cuda", generator=gen) * D ** -0.5
return x.view(B, T, D).contiguous(), codebooks
''',
flops_src='''
def canonical_work(B, T, Q, K, D):
"""FLOPs of the distance computation, from the SHAPE ALONE.
Each of the Q stages compares B*T residual vectors against K codewords of width D: the -2*r.C term is a
(B*T, D) x (D, K) GEMM, 2 FLOPs per multiply-add. The ||r||^2 and ||C||^2 terms are O((B*T + K)*D) and
the argmin, the subtraction and the accumulation are O(B*T*(K + D)) -- all negligible next to the GEMM,
and none of them counted. Compute-bound: the score is achieved TFLOP/s against this fixed count.
"""
return 2 * Q * (B * T) * K * D
''',
metric="TFLOP/s",
compare="tuple",
tuple_names=("codes", "quantized"),
tol=2e-2,
shape_names=("B", "T", "Q", "K", "D"),
grader_shapes=[(48, 2048, 8, 1024, 128), (32, 2048, 16, 1024, 128), (64, 1024, 8, 2048, 128),
(24, 3000, 8, 1024, 256), (96, 1024, 8, 1024, 128)],
measure_shapes=[(40, 2048, 8, 1024, 128), (24, 2048, 16, 1024, 128), (48, 1024, 8, 2048, 128),
(20, 3000, 8, 1024, 256), (80, 1024, 8, 1024, 128)],
measure_quick_shapes=[(8, 1024, 8, 1024, 128), (4, 2048, 4, 512, 256), (16, 512, 8, 1024, 128)],
correct_shapes=[(2, 301, 8, 1024, 128), (3, 128, 4, 256, 64), (1, 2048, 16, 1024, 128),
(5, 65, 2, 129, 96)],
spec_md="""Greedy residual quantisation, stage by stage. Starting from `r = x` and `quantized = 0`, for
`q = 0, 1, ..., Q-1`:
```
j[q] = argmin over entries e of || r - codebooks[q, e, :] ||^2
codes[q] = j[q]
r -= codebooks[q, j[q], :]
quantized += codebooks[q, j[q], :]
```
per frame, independently for every `(b, t)`. Ties are impossible in the graded inputs (see below), so
`argmin` is unambiguous; if you nonetheless want a rule, take the **lowest index**, as `torch.argmin` does.
Expanding the squared distance gives the form the reference uses:
```
||r - C_e||^2 = ||r||^2 - 2 * dot(r, C_e) + ||C_e||^2
```
The `||r||^2` term is the same for every `e` and cannot change the argmin — you may drop it — but `||C_e||^2`
**does** vary per entry and must be included: the codebook entries are deliberately **not** norm-equalised
(their norms spread over roughly 0.6x–1.4x of the stage mean, as learned codebooks do). Dropping the
`||C_e||^2` term was measured to flip **1–4% of all codes** and to put `quantized` **8–11%** off the
reference — many times the gate. The dominant term is the `(B*T, D) x (D, K)` matrix product.
The stages are **strictly sequential**: stage `q+1`'s residual depends on stage `q`'s decision. Codebook `q`
has entries whose norms shrink geometrically with `q` (that is what makes greedy RVQ converge, and it is what
these codecs learn), so later stages refine progressively smaller corrections.
`/app/reference.py` is the direct transcription, materialising a full `(B*T, K)` fp32 distance matrix at
every stage. That is the numerical specification, not a performance target.""",
contract_md="""| arg | shape | dtype | meaning |
|-----|-------|-------|---------|
| `x` | `(B, T, D)` | `float32` | encoder latents, contiguous |
| `codebooks` | `(Q, K, D)` | `bfloat16` | `Q` codebooks of `K` entries, contiguous |
**Return** a 2-tuple `(codes, quantized)` **in that order**:
| out | shape | dtype | notes |
|-----|-------|-------|-------|
| `codes` | `(B, T, Q)` | `int32` | stage-major in the last axis; **compared exactly** |
| `quantized` | `(B, T, D)` | `float32` | sum of the selected codewords |
Both inputs are **read-only**. `Q` is 2–16, `K` is 129–2048 (not always a power of two) and `D` is 64–256.
`T` is ragged (`65`, `301` in the correctness shapes).""",
regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `Q` (codebook
stages) 8–16, `K` (entries per codebook) 1024–2048, `D` (latent width) 128–256, `T` 1024–3000 frames — at a
75 Hz codec frame rate 2048 frames is 27 seconds — and `B` 24–96 clips. Every graded shape is
**200–300 GFLOP**. This is the regime of a speech-LM data pipeline or a batched TTS encoder.""",
correctness_md="""`codes` must match the reference **exactly** (they are integers, and a single wrong
code changes the decoded audio) and `quantized` must be within **relative Frobenius error `2e-2`**, at every
graded shape including the timed ones.
The exact-match requirement on `codes` is safe because the graded inputs are constructed so the winner at
every stage is well clear of the runner-up: across every graded and correctness shape the *smallest*
observed gap was `(d2 - d1) / (d2 + d1) = 0.13`, i.e. the runner-up's squared distance is at least ~30%
larger. A faithful implementation, in any precision down to bf16 operands with fp32 accumulation, selects
the same entries; this was checked against two independent implementations (see the precision section). If
your codes differ, the distance computation is wrong, not unlucky.""",
perf_md="""Per stage: a `(B*T, D) x (D, K)` GEMM, an argmin over `K`, and a gather-subtract over `D`. The
GEMM is 99% of the FLOPs, but the stage boundary is a hard dependency, so the kernel is really about what you
keep resident across `Q` sequential passes.
Where the reference loses. It materialises the whole `(B*T, K)` fp32 distance matrix per stage — 400 MB at
the graded sizes, written and read back for the argmin — recomputes `||r||^2` every stage (which cannot
affect the argmin), gathers `C[j]` as another full `(B*T, D)` tensor, and runs everything in fp32.
The shape to aim for: tile over frames. A block owns a tile of `B*T` frames, holds their residuals in
registers or shared memory (fp32, rounded to bf16 only as the MMA operand), and for each stage streams the codebook (`K*D` bf16 = 256 KB–1 MB, small
enough to stay in L2 for every block) through the MMA, keeping a running `(min, argmin)` in registers so the
distance row is **never written to memory**. Then it subtracts the selected codeword in place and moves to
the next stage — the frame tile never leaves the SM across all `Q` stages.
Two smaller wins: `||C_e||^2` is `Q*K` values that depend only on the codebooks, so compute them once in a
prologue; and the argmin reduction over `K` can ride the GEMM epilogue instead of being a separate pass.
Note the codebook is the *shared* operand here — every block reads all of it — so its L2 residency matters
more than its size suggests.""",
precision_md="""The latents and `quantized` are **float32**; the codebooks are **bfloat16**. The
residual, the distances and the accumulation must be carried in **fp32**.
That split is not decoration. After `Q` stages the residual is about `2^-Q` of the original magnitude — down
to `3e-5` at `Q = 16` — so a bf16 residual (8 mantissa bits) would be pure noise by stage 9 and the later
codes would be arbitrary. The residual is `D` floats per frame held in registers, not a memory cost. The
codebooks, in contrast, are bf16 because each stage's entries are compared against a residual of the *same*
magnitude, so their relative precision is all that matters.
The distance GEMM itself can run on bf16 tensor cores with fp32 accumulation. The measured margin between
the winning and the runner-up entry is at worst `(d2 - d1) / (d2 + d1) = 0.13`, which is orders of magnitude
above the bf16 product error, so the argmin is unaffected. This was verified two ways against the fp32
reference, at every correctness shape and at reduced-`B` versions of the graded shapes, over two seeds:
* an implementation that rounds the residual to bf16 for the matmul, drops `||r||^2` and folds `||C||^2`
into the epilogue — codes matched **exactly**, `quantized` matched to **0.0** relative error;
* a completely different algebra (`torch.cdist` in fp32, no expansion of the square) — codes matched
**exactly**.
The `2e-2` gate is therefore pure slack on `quantized`; `codes` is the real gate and it is exact.
**fp16 is not acceptable, and this is not a style point.** The same experiment run with an fp16 residual and
fp16 codebook mismatches **19% of the codes at `Q = 16`**: by stage 15 the residual is `~2^-15` of the input
and the products that form the distance fall below fp16's smallest normal, so they flush to zero. bf16 has
fp32's exponent range and does not have this problem. fp8 is worse still — e4m3 quantisation of the
later-stage residuals destroys the distance ordering outright.""",
).validate()