| """Spec for `audio-mel-spectrogram-fused` — Whisper's log-mel front end from the complex STFT.""" |
| import pathlib |
| import sys |
|
|
| sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) |
| from spec import TaskSpec |
|
|
| SPEC = TaskSpec( |
| name="audio-mel-spectrogram-fused", |
| title="Write a fast fused log-mel spectrogram kernel", |
| blurb=("Between the FFT and the encoder, every ASR request runs the same chain: power spectrum, mel " |
| "filterbank projection, log10, and a per-clip dynamic-range clamp that depends on the maximum of " |
| "the whole clip. The complex STFT of a batch of 30-second clips is well over a gigabyte, the " |
| "filterbank collapses it 1.6x, and the clamp forces a second pass — so the naive version writes " |
| "and re-reads four full-size temporaries for what should be one streaming kernel with a " |
| "reduction in the middle."), |
| keywords=["mle", "kernel-generation", "audio", "whisper", "asr", "mel-spectrogram", "reduction", |
| "memory-bound"], |
| module="log_mel.py", |
| func="log_mel_spectrogram", |
| signature="log_mel_spectrogram(stft, mel_filters)", |
| returns_doc="""Whisper's log-mel spectrogram from a complex STFT. |
| |
| Args: |
| stft: (B, F, NF) complex64 — STFT, F frames of NF frequency bins per clip. |
| mel_filters: (NM, NF) float32 — mel filterbank, NM mel bands. |
| |
| Returns: |
| out: (B, F, NM) float32 — the normalised log-mel spectrogram.""", |
|
|
| reference_imports="import torch", |
| reference_src=''' |
| def log_mel_spectrogram(stft, mel_filters): |
| """Power -> mel -> log10 -> per-clip clamp -> rescale, in fp32. |
| |
| Correct and simple — it is the numerical SPECIFICATION, not a performance target. |
| """ |
| mag = stft.real.float() ** 2 + stft.imag.float() ** 2 # power spectrum (B, F, NF) |
| mel = mag @ mel_filters.float().t() # (B, F, NM) |
| log_spec = torch.log10(mel.clamp(min=1e-10)) |
| hi = log_spec.amax(dim=(1, 2), keepdim=True) # per-clip maximum |
| log_spec = torch.maximum(log_spec, hi - 8.0) # 80 dB dynamic range |
| return (log_spec + 4.0) / 4.0 |
| ''', |
| make_inputs_src=''' |
| def _mk(B, F_, NF, NM, seed): |
| gen = torch.Generator(device="cuda").manual_seed(seed) |
| # STFT of speech: strong low-frequency content, ~60 dB of dynamic range across frames |
| tilt = torch.exp(-torch.arange(NF, device="cuda", dtype=torch.float32) / (NF / 3.0)).view(1, 1, NF) |
| env = (0.05 + torch.rand(B, F_, 1, device="cuda", generator=gen) ** 2) |
| re = torch.randn(B, F_, NF, device="cuda", generator=gen) * tilt * env |
| im = torch.randn(B, F_, NF, device="cuda", generator=gen) * tilt * env |
| stft = torch.complex(re, im) |
| # triangular mel filterbank: NM overlapping triangles spread over the NF bins |
| centres = torch.linspace(0, NF - 1, NM + 2, device="cuda") |
| bins = torch.arange(NF, device="cuda", dtype=torch.float32).view(1, NF) |
| lo, mid, hi = centres[:-2].view(NM, 1), centres[1:-1].view(NM, 1), centres[2:].view(NM, 1) |
| left = (bins - lo) / (mid - lo).clamp(min=1e-6) |
| right = (hi - bins) / (hi - mid).clamp(min=1e-6) |
| mel_filters = torch.minimum(left, right).clamp(min=0.0).contiguous() |
| return stft, mel_filters |
| ''', |
| flops_src=''' |
| def canonical_work(B, F_, NF, NM): |
| """BYTES moved, from the SHAPE ALONE. |
| |
| The complex64 STFT is read once (8 bytes per bin) and the fp32 log-mel written once (4 bytes per band). |
| The per-clip maximum forces a second pass over SOMETHING, but the cheapest thing to revisit is the mel |
| output, which is already counted -- so the unavoidable HBM traffic is one read of the source and one |
| write of the result. The (NM, NF) filterbank is at most 400 KB and stays resident. |
| """ |
| return B * F_ * NF * 8 + B * F_ * NM * 4 |
| ''', |
| flops_formula="B * F * NF * 8 + B * F * NM * 4", |
|
|
| metric="GB/s", |
| compare="tensor", |
| tol=1e-4, |
| shape_names=("B", "F", "NF", "NM"), |
| grader_shapes=[(256, 3000, 201, 128), (224, 3000, 201, 128), (512, 1500, 201, 128), |
| (128, 3000, 401, 80), (256, 3000, 201, 80)], |
| measure_shapes=[(208, 3000, 201, 128), (176, 3000, 201, 128), (416, 1500, 201, 128), |
| (104, 3000, 401, 80), (208, 3000, 201, 80)], |
| measure_quick_shapes=[(16, 3000, 201, 128), (32, 1500, 201, 80), (8, 3000, 401, 128)], |
| correct_shapes=[(3, 301, 201, 128), (5, 128, 65, 40), (2, 3000, 201, 128), (7, 97, 129, 80)], |
|
|
| spec_md="""Per clip `b`: |
| |
| ``` |
| mag[b, f, k] = real(stft[b, f, k])^2 + imag(stft[b, f, k])^2 # power, not magnitude |
| mel[b, f, n] = sum over k of mag[b, f, k] * mel_filters[n, k] |
| log_spec[b, f, n] = log10( max(mel[b, f, n], 1e-10) ) |
| hi[b] = max over (f, n) of log_spec[b, f, n] # the WHOLE clip |
| out[b, f, n] = (max(log_spec[b, f, n], hi[b] - 8.0) + 4.0) / 4.0 |
| ``` |
| |
| This is exactly `whisper.audio.log_mel_spectrogram`. The two subtleties are both in the last two lines: the |
| floor is **per clip**, not per frame and not per batch — it implements an 80 dB dynamic-range window relative |
| to that clip's loudest mel bin — and the `1e-10` clamp comes *before* the log, so silent bins do not produce |
| `-inf`. |
| |
| The mel projection is a small dense matmul: `NF` (129–401) bins in, `NM` (40–128) bands out, applied at every |
| frame. The filterbank is triangular and therefore sparse-ish, but it is given to you as a dense matrix and the |
| counted work does not depend on how you exploit that. |
| |
| `/app/reference.py` materialises `mag`, `mel` and two more full-size fp32 tensors before returning. That is |
| the numerical specification, not a performance target.""", |
|
|
| contract_md="""| arg | shape | dtype | meaning | |
| |-----|-------|-------|---------| |
| | `stft` | `(B, F, NF)` | `complex64` | STFT, contiguous; real and imaginary interleaved | |
| | `mel_filters` | `(NM, NF)` | `float32` | mel filterbank, contiguous, row-major over bands | |
| |
| **Return** a single tensor `out` of shape `(B, F, NM)` and dtype **float32** (fp32 is required — this feeds |
| the encoder's first convolution and the contract fixes it). |
| |
| Both inputs are **read-only**. `F` is ragged (`97`, `301` in the correctness shapes), `NF` is 65–401 and `NM` |
| is 40–128; none is a multiple of a convenient tile size, and `NF` is always odd (it is `n_fft/2 + 1`).""", |
|
|
| regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `F` in |
| {1500, 3000} frames (3000 = 30 s at a 10 ms hop), `NF` in {201, 401} bins, `NM` in {80, 128} mel bands, and |
| `B` — clips in the batch — from 128 to 512. Every graded shape moves **1.3–1.6 GiB**, dominated by the |
| complex64 source. Batches this size are what an offline transcription queue looks like.""", |
|
|
| correctness_md="""`out` must match the reference within **relative Frobenius error `1e-4`** at every |
| graded shape, including the timed ones. This gate is tight because the whole pipeline is fp32 — there is no |
| low-precision storage to hide behind, and an independent fp32 implementation agrees to ~2e-8. It is tight |
| enough to catch a per-frame or per-batch clamp instead of the specified per-clip one.""", |
|
|
| perf_md="""The counted traffic is one read of the complex64 STFT and one write of the fp32 result — about |
| 1.5 GiB per graded shape. The mel projection is only ~40 GFLOP, an order of magnitude short of being the |
| bottleneck, so this is a bandwidth kernel with a matmul in it, not the other way round. |
| |
| The reference costs about 4x the roofline: `mag` is a full-size fp32 temporary (as big as the source), `mel` |
| another, `log10` another, and the `amax` and `maximum` each make their own pass. |
| |
| The dependency to design around is the per-clip maximum: nothing can be written in final form until the whole |
| clip has been reduced. Two workable shapes, and it is worth measuring both. (1) Compute `mel` and its |
| per-clip max in one pass, store `mel` (or `log_spec`), then a second cheap pass applies the floor and the |
| rescale — the second pass touches only the small output, which `canonical_work` already counts once, so the |
| extra traffic is the output size, not the source size. (2) Keep a clip's frames resident across a persistent |
| block and never write the intermediate at all — possible when `F * NM` is small enough, and a clear win when |
| it is. |
| |
| Inside the main pass, the mel projection is `NF -> NM` per frame with the filterbank (at most 400 KB) fully |
| resident in shared memory or L2. Loading the complex64 source as `float2` gives 8-byte vector loads; the |
| power spectrum is then two FMAs per bin, and the reduction over `NF` is short enough that a warp per frame, |
| or a tile of frames per block, both work.""", |
|
|
| precision_md="""Everything here is **float32**: the power spectrum, the filterbank projection, the |
| logarithm, the reduction and the output. The complex input is complex64 (two fp32 values). |
| |
| Do **not** be tempted to run the mel projection through bf16 tensor cores. The power spectrum spans ~10 |
| orders of magnitude within a clip (that is exactly why the pipeline takes a logarithm), and bf16 has three |
| decimal digits: the small mel bands, which are the ones the dynamic-range floor is about to act on, would be |
| destroyed. The `1e-4` gate is set to catch this — a bf16 projection lands around 5e-3. |
| |
| fp32 accumulation over `NF` (up to 401) terms is exact enough that reduction order is irrelevant; an |
| independent implementation that reduces in a different order agrees to ~2e-8. |
| |
| The `1e-10` clamp before the log and the `hi - 8.0` floor after it are part of the specification, in that |
| order. |
| |
| **fp8 and bf16 are not acceptable** anywhere on this data path.""", |
| ).validate() |
|
|