KBench / tools /factory /specs /causal_conv3d_forward.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
10.5 kB
"""Spec for `causal-conv3d-forward` — the 3x3x3 causal convolution at the heart of the Wan / HunyuanVideo VAE."""
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from spec import TaskSpec
SPEC = TaskSpec(
name="causal-conv3d-forward",
title="Write a fast causal 3D convolution kernel (video VAE)",
blurb=("Every layer of the Wan and HunyuanVideo 3D video tokenizers is a CAUSAL Conv3d: a 3x3x3 "
"convolution whose temporal padding is entirely one-sided, so a frame can only ever see itself "
"and the frames before it. That one-sided pad is what lets the tokenizer stream, and it is the "
"single most expensive operator in the whole decoder — at 720p the activations are hundreds of "
"megabytes per layer and cuDNN's NCDHW 3D kernels leave a lot of the machine on the table."),
keywords=["mle", "kernel-generation", "conv3d", "causal", "video", "vae", "wan", "hunyuanvideo",
"tokenizer", "diffusion"],
module="conv3d.py",
func="causal_conv3d",
signature="causal_conv3d(x, weight, bias)",
returns_doc="""Causal 3x3x3 convolution over a video feature volume.
Args:
x: (B, Cin, T, H, W) bfloat16 — the input feature volume (frames along T).
weight: (Cout, Cin, 3, 3, 3) bfloat16 — dense convolution weights.
bias: (Cout,) bfloat16 — per-output-channel bias.
Returns:
y: (B, Cout, T, H, W) bfloat16 — same T, H, W as the input.""",
reference_imports="import torch\nimport torch.nn.functional as F",
reference_src='''
def causal_conv3d(x, weight, bias):
"""Causal Conv3d: temporal pad is (2, 0) — two zero frames BEFORE, none after. Spatial pad is (1, 1).
Correct and simple — it is the numerical SPECIFICATION, not a performance target. The convolution is
evaluated in fp32 with TF32 explicitly disabled so the spec is a true fp32 result.
"""
xp = F.pad(x.float(), (1, 1, 1, 1, 2, 0)) # W_left, W_right, H_top, H_bot, T_before, T_after
with torch.backends.cudnn.flags(enabled=True, allow_tf32=False):
y = F.conv3d(xp, weight.float(), bias.float())
return y.to(torch.bfloat16)
''',
make_inputs_src='''
def _mk(B, Cin, Cout, T, H, W, seed):
gen = torch.Generator(device="cuda").manual_seed(seed)
x = torch.randn(B, Cin, T, H, W, device="cuda", dtype=torch.bfloat16, generator=gen)
w = (torch.randn(Cout, Cin, 3, 3, 3, device="cuda", dtype=torch.bfloat16, generator=gen)
* (1.0 / (Cin * 27) ** 0.5))
b = (torch.randn(Cout, device="cuda", dtype=torch.bfloat16, generator=gen) * 0.1)
return x, w, b
''',
flops_src='''
def canonical_work(B, Cin, Cout, T, H, W):
"""FLOPs of the causal 3x3x3 convolution, from the SHAPE ALONE.
Output volume is B*Cout*T*H*W; each output element is a dot product over Cin*27 inputs, counted as one
multiply and one add. The zero-padded taps are counted like every other tap: the work attribution must
not depend on how a kernel chooses to skip them.
"""
return 2 * B * Cout * Cin * 27 * T * H * W
''',
metric="TFLOP/s",
compare="tensor",
tol=1e-2,
shape_names=("B", "Cin", "Cout", "T", "H", "W"),
grader_shapes=[(1, 128, 128, 17, 128, 128), (1, 256, 128, 9, 128, 128), (1, 96, 96, 33, 96, 160),
(1, 128, 256, 5, 176, 240), (2, 64, 128, 17, 128, 128)],
measure_shapes=[(1, 128, 128, 13, 128, 160), (1, 192, 128, 9, 128, 128), (1, 96, 96, 25, 112, 160),
(1, 128, 192, 5, 176, 240), (2, 64, 128, 13, 128, 144)],
measure_quick_shapes=[(1, 64, 64, 5, 64, 64), (1, 128, 64, 3, 64, 64), (1, 32, 96, 9, 48, 64)],
correct_shapes=[(1, 32, 32, 5, 16, 16), (1, 48, 32, 7, 24, 20), (2, 16, 24, 4, 17, 23),
(1, 64, 64, 3, 32, 32)],
spec_md="""A dense 3D convolution with a **3x3x3** kernel, unit stride, and **causal temporal padding**.
```
xp = zero_pad(x, W: 1 left / 1 right, H: 1 top / 1 bottom, T: 2 BEFORE / 0 after)
y[b, co, t, h, w] = bias[co]
+ sum over ci, kt in [0,3), kh in [0,3), kw in [0,3) of
xp[b, ci, t + kt, h + kh, w + kw] * weight[co, ci, kt, kh, kw]
```
Equivalently, in un-padded coordinates:
```
y[b, co, t, h, w] = bias[co] + sum_{ci, kt, kh, kw} x[b, ci, t - 2 + kt, h - 1 + kh, w - 1 + kw]
* weight[co, ci, kt, kh, kw]
```
with every out-of-range index reading **zero**.
### The causal part — this is the whole point
The temporal padding is **entirely one-sided**: two zero frames are prepended and **none** are appended.
Output frame `t` therefore depends on input frames `t-2`, `t-1`, `t` only — never on `t+1`. `weight[..., 2, :, :]`
is the tap that multiplies the **current** frame, `weight[..., 0, :, :]` the frame from two steps ago.
This is what makes the tokenizer streamable, and it means the first two output frames are computed against
zeros rather than real data. Padding symmetrically `(1, 1)`, or replicating frame 0 into the pad instead of
using zeros, both produce a *different tensor* and both fail the correctness gate — the second by a relative
error of roughly `2.5e-1`, twenty-five times the tolerance.
The spatial padding is the ordinary symmetric zero padding of a `3x3` conv, so `H` and `W` are preserved,
and so is `T`.
`/app/reference.py` materialises the zero-padded volume and calls `F.conv3d` in fp32 with TF32 disabled.
That is the exact specification; it is deliberately simple rather than fast.""",
contract_md="""| arg | shape | dtype | meaning |
|-----|-------|-------|---------|
| `x` | `(B, Cin, T, H, W)` | `bfloat16` | input feature volume, contiguous NCDHW, frames along `T` |
| `weight` | `(Cout, Cin, 3, 3, 3)` | `bfloat16` | dense conv weights, taps ordered `(kt, kh, kw)` |
| `bias` | `(Cout,)` | `bfloat16` | per-output-channel bias |
**Return** a single tensor:
| out | shape | dtype | notes |
|-----|-------|-------|-------|
| `y` | `(B, Cout, T, H, W)` | `bfloat16` | contiguous NCDHW; same `T`, `H`, `W` as `x` |
The kernel size is **always** `3x3x3` and the stride is always 1. `Cin` and `Cout` are independent and are
**not** guaranteed to be equal, nor to be multiples of any tile size — the correctness shapes include
`Cin = 16`, `Cout = 24`, `H = 17`, `W = 23`, so handle ragged channels and ragged spatial extents. All
inputs are read-only; the result is a fresh tensor. You may transpose to NDHWC internally, but the returned
tensor must be contiguous in the NCDHW shape given above.""",
regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `B` in 1–2,
`Cin` and `Cout` in 64–256, `T` (latent or pixel frames) in 5–33, and `H`, `W` in 96–240. These are one
decoder layer of a 4x8x8 video tokenizer working on a 720p-class clip: a few hundred megabytes of bf16
activation per tensor. Resolution is deliberately capped so the fp32 reference fits comfortably in memory —
a full 720p x 129-frame decode at pixel resolution would be tens of gigabytes per layer, which is exactly why
production decoders tile. Write a **general** kernel: ragged channel counts and odd spatial extents appear.""",
correctness_md="""`y` must match the reference (evaluated in fp32) within **relative Frobenius error
`1e-2`** at every graded shape, including the timed ones.""",
perf_md="""This is compute-bound arithmetic wrapped around an awkward memory layout, and that is where
the whole game is.
**The layout.** The input arrives NCDHW, which is the worst possible layout for a 3D convolution: the
reduction axis `Cin` is the *slowest*-varying one, so a naive kernel strides through memory by `T*H*W`
elements per channel. Every fast implementation works in **NDHWC** internally, where the `Cin` reduction is
contiguous and the convolution becomes an implicit GEMM: `(B*T*H*W) x (Cin*27)` times `(Cin*27) x Cout`. The
transpose in and out is pure bandwidth and can often be folded into the load/store of the main loop.
**Implicit GEMM, not im2col.** Materialising the `27x` unfolded matrix would cost `27 * Cin * B*T*H*W`
elements of traffic — at these sizes hundreds of gigabytes. Compute the gather addresses on the fly from
`(t, h, w)` and feed the MMA directly. With `Cin` a multiple of 8, a `k`-tile of 3 taps x 8 channels lands
exactly on a `k=24` MMA step.
**Reuse across taps.** A `3x3` spatial window means each input element is read by 9 output positions
(27 counting the temporal taps). A tile that holds a `(BT, BH+2, BW+2)` halo in shared memory reads each
input once and serves the whole `3x3x3` neighbourhood from SMEM.
**The temporal axis is nearly free reuse.** Consecutive output frames share two of their three input frames.
A kernel that walks `t` in the register/pipeline dimension, keeping the two previous frames' contributions
live, does one third of the loads a naive frame-independent kernel does.
Other things that matter: vectorise the loads (`Cin` contiguous in NDHWC gives you 128-bit accesses), keep
the weights (`Cout*Cin*27` elements — at most 4.5 MB) resident in SMEM/registers across the whole tile,
and handle the `T`-boundary taps by predication rather than by a separate padded copy of the volume.""",
precision_md="""Inputs and output are **bfloat16**; accumulate in **fp32**. The reference evaluates the
convolution in fp32 with TF32 explicitly disabled, so it is a true fp32 result and the only error a faithful
bf16 kernel shows is the final rounding of `y` back to bf16 plus fp32 accumulation order.
The tolerance was **measured**, not guessed. Against this reference: an independent fp32 implementation (27
shifted `Cin x Cout` matmuls, an entirely different reduction order) differs by `4.7e-5`; a bf16 cuDNN
convolution with fp32 accumulation differs by `2.9e-3`. The gate is set at `1e-2`, about 3.4x the observed
bf16 noise, and roughly 25x *below* the error of getting the causal padding wrong (`2.5e-1` for replicating
frame 0 instead of zero-padding, `1.4e0` for symmetric padding). Noise passes; a wrong pad does not.
**fp8 is not appropriate here** — the graded dtype is bf16 in and bf16 out, and quantising the activations to
fp8 to use a wider tensor-core path introduces a *bias* that grows with `Cin` and will not pass.
Do **not** infer from the reference that fp32 storage is wanted; it computes in fp32 purely to be a stable
numerical specification.""",
).validate()