| """Spec for `conformer-conv-module` — the Conformer/Zipformer convolution module, fused end to end.""" |
| import pathlib |
| import sys |
|
|
| sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) |
| from spec import TaskSpec |
|
|
| SPEC = TaskSpec( |
| name="conformer-conv-module", |
| title="Write a fast fused Conformer convolution-module kernel", |
| blurb=("Every speech encoder in production — Conformer, Zipformer, the Whisper-sized ASR models that " |
| "replaced the plain transformer block — carries a convolution module next to its attention: " |
| "layer-norm, a pointwise projection to 2C with a GLU gate, a wide depthwise convolution along " |
| "time, a frozen batch-norm affine, SiLU, a second pointwise projection, and a residual add. It " |
| "is two GEMMs with a stencil wedged between them, and eager PyTorch runs it as eight kernels " |
| "with a transpose on either side of the depthwise conv."), |
| keywords=["mle", "kernel-generation", "audio", "asr", "conformer", "speech", "depthwise-conv", "glu", |
| "fused-block", "compute-bound"], |
| module="conv_module.py", |
| func="conformer_conv_module", |
| signature="conformer_conv_module(x, ln_w, ln_b, w1, b1, dw, bn_w, bn_b, w2, b2, eps=1e-5)", |
| returns_doc="""The Conformer convolution module, including its residual connection. |
| |
| Args: |
| x: (B, T, C) bfloat16 — encoder hidden states, time-major inside a batch entry. |
| ln_w, ln_b: (C,) float32 — LayerNorm affine. |
| w1: (2C, C) bfloat16 — pointwise projection to the GLU pair. |
| b1: (2C,) bfloat16 — its bias. |
| dw: (C, K) bfloat16 — depthwise convolution taps, K odd. |
| bn_w, bn_b: (C,) float32 — folded batch-norm scale and shift. |
| w2: (C, C) bfloat16 — output pointwise projection. |
| b2: (C,) bfloat16 — its bias. |
| eps: float — LayerNorm epsilon, default 1e-5. |
| |
| Returns: |
| y: (B, T, C) bfloat16.""", |
|
|
| reference_imports="import torch\nimport torch.nn.functional as F", |
| reference_src=''' |
| def conformer_conv_module(x, ln_w, ln_b, w1, b1, dw, bn_w, bn_b, w2, b2, eps=1e-5): |
| """The module written out as eight separate fp32 ops. |
| |
| Correct and simple — it is the numerical SPECIFICATION, not a performance target. |
| """ |
| B, T, C = x.shape |
| K = dw.shape[-1] |
| xf = x.float() |
| |
| h = F.layer_norm(xf, (C,), ln_w.float(), ln_b.float(), eps) |
| h = h @ w1.float().t() + b1.float() # (B, T, 2C) |
| a, g = h.chunk(2, dim=-1) |
| h = a * torch.sigmoid(g) # GLU |
| |
| h = h.transpose(1, 2) # (B, C, T) |
| h = F.conv1d(h, dw.float().unsqueeze(1), None, padding=(K - 1) // 2, groups=C) |
| h = h * bn_w.float().view(1, C, 1) + bn_b.float().view(1, C, 1) |
| h = h * torch.sigmoid(h) # SiLU |
| h = h.transpose(1, 2) # (B, T, C) |
| |
| h = h @ w2.float().t() + b2.float() |
| return (xf + h).to(x.dtype) |
| ''', |
| make_inputs_src=''' |
| def _mk(B, T, C, K, seed): |
| gen = torch.Generator(device="cuda").manual_seed(seed) |
| x = torch.randn(B, T, C, device="cuda", dtype=torch.bfloat16, generator=gen) |
| ln_w = (1 + 0.05 * torch.randn(C, device="cuda", generator=gen)).float() |
| ln_b = (0.02 * torch.randn(C, device="cuda", generator=gen)).float() |
| w1 = (torch.randn(2 * C, C, device="cuda", generator=gen) * C ** -0.5).to(torch.bfloat16) |
| b1 = (0.02 * torch.randn(2 * C, device="cuda", generator=gen)).to(torch.bfloat16) |
| dw = (torch.randn(C, K, device="cuda", generator=gen) * K ** -0.5).to(torch.bfloat16) |
| bn_w = (1 + 0.05 * torch.randn(C, device="cuda", generator=gen)).float() |
| bn_b = (0.02 * torch.randn(C, device="cuda", generator=gen)).float() |
| w2 = (torch.randn(C, C, device="cuda", generator=gen) * C ** -0.5).to(torch.bfloat16) |
| b2 = (0.02 * torch.randn(C, device="cuda", generator=gen)).to(torch.bfloat16) |
| return x, ln_w, ln_b, w1, b1, dw, bn_w, bn_b, w2, b2, 1e-5 |
| ''', |
| flops_src=''' |
| def canonical_work(B, T, C, K): |
| """FLOPs of the three contractions, from the SHAPE ALONE. |
| |
| Pointwise 1: (B*T, C) x (C, 2C) = 2*B*T*C*2C. Depthwise: K taps per (time, channel) = 2*B*T*C*K. |
| Pointwise 2: (B*T, C) x (C, C) = 2*B*T*C*C. The LayerNorm, the GLU, the batch-norm affine, the SiLU and |
| the residual add are all O(B*T*C) elementwise and are not counted -- they are the fusion opportunity, |
| not the work. Compute-bound: the score is achieved TFLOP/s against this fixed count. |
| """ |
| return 2 * B * T * C * (3 * C + K) |
| ''', |
| flops_formula="2 * B * T * C * (3*C + K)", |
|
|
| metric="TFLOP/s", |
| compare="tensor", |
| tol=2e-2, |
| shape_names=("B", "T", "C", "K"), |
| grader_shapes=[(48, 1500, 1024, 31), (32, 3000, 1024, 31), (64, 1500, 768, 31), |
| (40, 2000, 1024, 31), (96, 1500, 640, 31)], |
| measure_shapes=[(40, 1500, 1024, 31), (28, 3000, 1024, 31), (56, 1500, 768, 31), |
| (32, 2000, 1024, 31), (80, 1500, 640, 31)], |
| measure_quick_shapes=[(8, 1500, 1024, 31), (4, 1000, 768, 31), (16, 500, 640, 31)], |
| correct_shapes=[(2, 137, 256, 15), (3, 64, 128, 7), (1, 1500, 1024, 31), (5, 33, 192, 31)], |
|
|
| spec_md="""One block, seven stages, one residual: |
| |
| ``` |
| h = layer_norm(x, eps) * ln_w + ln_b # over the C axis, per (b, t) |
| h = h @ w1^T + b1 # (B, T, 2C) |
| a, g = h[..., :C], h[..., C:] |
| h = a * sigmoid(g) # GLU: first half gated by the second |
| |
| h[b, c, t] = sum_k dw[c, k] * h[b, c, t + k - (K-1)//2] # depthwise, zero-padded, non-causal |
| h = h * bn_w + bn_b # per channel |
| h = h * sigmoid(h) # SiLU |
| |
| h = h @ w2^T + b2 # (B, T, C) |
| y = x + h |
| ``` |
| |
| Note the details that a re-implementation gets wrong: |
| |
| * The **GLU split is contiguous, not interleaved**: rows `0..C-1` of `w1` produce the value half and rows |
| `C..2C-1` produce the gate half. That is `torch.chunk(h, 2, dim=-1)`, not a stride-2 view. Reading it as |
| interleaved pairs is a **0.39** relative error and swapping the two halves is **0.37**. |
| * The depthwise convolution is **non-causal and symmetric**: `padding = (K-1)//2` with `K` odd, so the |
| output length equals `T` and tap `k` reaches `k - (K-1)//2` samples away. It is zero-padded at both ends, |
| and it runs over the **time** axis with one independent filter per channel. Padding it causally instead |
| (`K-1` on the left, none on the right) is a **0.39** relative error. |
| * The batch-norm is already **folded into an affine** — `bn_w` and `bn_b` are the inference-time scale and |
| shift, there are no running statistics to compute and nothing is reduced over the batch. |
| * The LayerNorm is over the **`C` axis only**, with the biased (`1/C`) variance, and the residual is added to |
| the **original** `x`, not to the normalised one. |
| |
| `/app/reference.py` runs all of it in fp32 as eight separate ops, with two transposes around the depthwise |
| convolution. That is the numerical specification, not a performance target.""", |
|
|
| contract_md="""| arg | shape | dtype | meaning | |
| |-----|-------|-------|---------| |
| | `x` | `(B, T, C)` | `bfloat16` | hidden states, contiguous | |
| | `ln_w`, `ln_b` | `(C,)` | `float32` | LayerNorm affine | |
| | `w1` | `(2C, C)` | `bfloat16` | pointwise projection, **row-major, out-features first** | |
| | `b1` | `(2C,)` | `bfloat16` | bias for `w1` | |
| | `dw` | `(C, K)` | `bfloat16` | depthwise taps, one filter per channel | |
| | `bn_w`, `bn_b` | `(C,)` | `float32` | folded batch-norm affine | |
| | `w2` | `(C, C)` | `bfloat16` | output projection, same layout as `w1` | |
| | `b2` | `(C,)` | `bfloat16` | bias for `w2` | |
| | `eps` | — | `float` | LayerNorm epsilon, `1e-5` in every graded call | |
| |
| Both projections are applied as `h @ W^T`, i.e. `W` is stored the way `nn.Linear` stores it. |
| |
| **Return** a single tensor `y` of shape `(B, T, C)` and dtype **bfloat16**. |
| |
| All inputs are **read-only**; nothing is updated in place. `K` is **odd** (31 in every graded shape; 7 and 15 |
| appear in the correctness shapes) and may exceed `T` — `(5, 33, 192, 31)` is a correctness shape, where the |
| zero padding covers most of the receptive field. `T` is ragged (`33`, `64`, `137`) and is never a multiple of |
| a tile size.""", |
|
|
| regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `C` 640–1024 |
| (Conformer-large is 512–1024 wide), `K = 31` — the standard Conformer depthwise kernel — `T` 1500–3000 |
| frames, which at a 40 ms subsampled frame rate is one to two minutes of audio, and `B` 32–96 utterances per |
| batch. Every graded shape is **295–610 GFLOP**. A 17-layer encoder runs this block once per layer, so it is |
| a few percent of every ASR forward and it is entirely fusable.""", |
|
|
| correctness_md="""`y` must match the reference (evaluated in fp32) within **relative Frobenius error |
| `2e-2`** at every graded shape, including the timed ones.""", |
|
|
| perf_md="""Two GEMMs — `(B*T, C) x (C, 2C)` and `(B*T, C) x (C, C)` — with a depthwise stencil, a GLU, an |
| affine and a SiLU between them. At the graded sizes `B*T` is 48k–96k rows, so both GEMMs are large and |
| tensor-core bound; everything else is elementwise and should cost nothing. |
| |
| In the reference it costs a great deal. There are **six** full-size `(B, T, C)` or `(B, T, 2C)` fp32 |
| temporaries — the normalised input, the projection output at 2C, the GLU result, the conv output, the affine |
| output, the SiLU output — plus **two transposes** to get `(B, T, C)` into the `(B, C, T)` layout `F.conv1d` |
| demands and back. At `B=32, T=3000, C=1024` the 2C temporary alone is 786 MB. And all of it runs in fp32, at |
| a quarter of the bf16 tensor-core rate. |
| |
| The kernel to write keeps a tile of `(rows of B*T) x C` resident and pushes it through the whole chain: |
| |
| * **Fuse the LayerNorm into the first GEMM's prologue.** It is a row-wise reduction over `C`, and the GEMM |
| wants that row in shared memory anyway. |
| * **Fuse the GLU into the first GEMM's epilogue.** Compute both halves of the `2C` output in the same tile — |
| they share the same A operand — and emit `a * sigmoid(g)` directly, so the `2C`-wide tensor never exists. |
| * **Do not transpose for the depthwise conv.** The stencil is along `T` with an independent filter per |
| channel, so a tile that owns `T_tile` consecutive frames of `C_tile` channels needs a halo of `(K-1)/2 = 15` |
| frames on each side and nothing else. Loading a haloed tile is far cheaper than materialising a transposed |
| copy of the whole tensor, and the halo can be re-read from the GLU output in shared memory if the tile is |
| large enough along `T`. |
| * **Fuse the affine, the SiLU and the second GEMM's prologue**, and fold the residual `+ x` into that GEMM's |
| epilogue — `x` is already the tile you started from. |
| |
| `K = 31` is wide enough that the depthwise conv is not free: it is `2*B*T*C*K` FLOPs (about 1% of the total |
| here) but its access pattern, if you get it wrong, costs far more than its arithmetic. The two natural |
| schedules are a haloed shared-memory tile along `T`, or holding `K` running registers per channel and |
| sliding — the second wins when `C_tile` is small. |
| |
| The weights are small — `w1` is at most `2*1024*1024` bf16 = 4 MB and `w2` half that — so they stay in L2 |
| across the whole grid.""", |
|
|
| precision_md="""`x`, both projection weights, their biases and the depthwise taps are **bfloat16**; the |
| LayerNorm and batch-norm affines are **float32**; the output is **bfloat16**. |
| |
| Do the LayerNorm reduction, the GLU sigmoid, the depthwise accumulation, the affine, the SiLU and both GEMM |
| accumulations in **fp32**. The GEMM `k` dimension is only `C` (640–1024), which is comfortably inside the |
| gate with fp32 accumulation of bf16 products. |
| |
| The tolerance was measured against an independent implementation that runs both projections as bf16 matmuls |
| with fp32 accumulation, computes the LayerNorm statistics explicitly instead of calling `F.layer_norm`, and |
| evaluates the depthwise convolution as an `unfold` + `einsum` rather than `F.conv1d` — a different reduction |
| order at every stage. The observed relative Frobenius error against the fp32 reference was **1.9e-3**, |
| stable across `C` 256–1024, `T` 137–3000 and `K` 15–31. The `2e-2` gate is ~10x that. |
| |
| For scale, the drop-the-feature checks all land 17–20x above the gate: dropping the GLU gate entirely |
| (passing the first half through unchanged) is **0.34**, swapping the value and gate halves is **0.37**, |
| reading the `2C` projection as interleaved pairs is **0.39**, and padding the depthwise convolution causally |
| is **0.39**. Every structural detail above is genuinely graded. |
| |
| **fp8 is not acceptable here**: the contract fixes the output at bf16, and the SiLU sits directly on the |
| depthwise output whose per-channel scale varies by more than an e4m3 mantissa can absorb.""", |
| ).validate() |
|
|