| """Spec for `conv3d-tiled-decode-blend` — per-tile causal Conv3d with tile-local padding + feathered blend.""" |
| import pathlib |
| import sys |
|
|
| sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) |
| from spec import TaskSpec |
|
|
| SPEC = TaskSpec( |
| name="conv3d-tiled-decode-blend", |
| title="Write a fast tiled causal Conv3d with feathered blending (tiled video VAE decode)", |
| blurb=("Tiled VAE decoding does not just slice the activation — each tile is convolved as if it were a " |
| "standalone image, against its OWN zero padding at the tile borders. That is what makes tiling " |
| "cheap and what makes the seams: the tile-local padding gives different answers near the " |
| "borders than a whole-image convolution would. Production decoders hide it by overlapping the " |
| "tiles and blending them with a feathered ramp. This kernel is the whole stage: the per-tile " |
| "convolution, the tile-local padding, and the weighted accumulation, all at once."), |
| keywords=["mle", "kernel-generation", "conv3d", "causal", "tiling", "blending", "feather", "video", |
| "vae", "decode", "wan", "hunyuanvideo"], |
| module="tiledconv3d.py", |
| func="conv3d_tiled_decode_blend", |
| signature="conv3d_tiled_decode_blend(x, weight, bias, origins, tile, overlap)", |
| returns_doc="""Per-tile causal Conv3d with tile-local zero padding, feathered onto the full canvas. |
| |
| Args: |
| x: (Cin, T, H, W) bfloat16 — the full input feature volume (one clip, no batch axis). |
| weight: (Cout, Cin, 3, 3, 3) bfloat16 — convolution weights. |
| bias: (Cout,) bfloat16 — per-output-channel bias. |
| origins: (Nt, 2) int32 — (y0, x0) top-left of each tile. |
| tile: python int — tile height and width. |
| overlap: python int — feather width in pixels at each tile edge. |
| |
| Returns: |
| out: (Cout, T, H, W) bfloat16 — the blended canvas.""", |
|
|
| reference_imports="import torch\nimport torch.nn.functional as F", |
| reference_src=''' |
| def _ramp(n, ov, device): |
| """1 in the interior, rising linearly from 1/(ov+1) over the first and last `ov` pixels.""" |
| r = torch.ones(n, device=device, dtype=torch.float32) |
| if ov > 0: |
| w = (torch.arange(ov, device=device, dtype=torch.float32) + 1.0) / (ov + 1.0) |
| r[:ov] = torch.minimum(r[:ov], w) |
| r[n - ov:] = torch.minimum(r[n - ov:], w.flip(0)) |
| return r |
| |
| |
| def conv3d_tiled_decode_blend(x, weight, bias, origins, tile, overlap): |
| """For each tile: crop, zero-pad the tile's OWN borders, causal conv, feather, accumulate; then divide. |
| |
| Correct and simple -- the numerical SPECIFICATION, not a performance target. |
| """ |
| Cin, T, H, W = x.shape |
| Cout = weight.shape[0] |
| dev = x.device |
| wt = _ramp(tile, overlap, dev)[:, None] * _ramp(tile, overlap, dev)[None, :] # (tile, tile) |
| |
| acc = torch.zeros(Cout, T, H, W, device=dev, dtype=torch.float32) |
| wacc = torch.zeros(H, W, device=dev, dtype=torch.float32) |
| wf, bf = weight.float(), bias.float() |
| for (y0, x0) in origins.tolist(): |
| sub = x[:, :, y0:y0 + tile, x0:x0 + tile].float().unsqueeze(0) # (1, Cin, T, t, t) |
| sp = F.pad(sub, (1, 1, 1, 1, 2, 0)) # tile-local spatial pad + causal temporal pad |
| with torch.backends.cudnn.flags(enabled=True, allow_tf32=False): |
| o = F.conv3d(sp, wf, bf)[0] # (Cout, T, t, t) |
| acc[:, :, y0:y0 + tile, x0:x0 + tile] += o * wt |
| wacc[y0:y0 + tile, x0:x0 + tile] += wt |
| return (acc / wacc).to(torch.bfloat16) |
| ''', |
| make_inputs_src=''' |
| def _mk(Cin, Cout, T, H, W, tile, stride, seed): |
| gen = torch.Generator(device="cuda").manual_seed(seed) |
| x = torch.randn(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) |
| org = [(y, xx) for y in _tile_origins(H, tile, stride) for xx in _tile_origins(W, tile, stride)] |
| origins = torch.tensor(org, device="cuda", dtype=torch.int32) |
| return x, w, b, origins, tile, tile - stride |
| ''', |
| flops_src=''' |
| def _tile_origins(n, tile, stride): |
| """Tile starts along one axis: strided, plus a final tile flush with the far edge.""" |
| if tile >= n: |
| return [0] |
| xs = list(range(0, n - tile + 1, stride)) |
| if xs[-1] != n - tile: |
| xs.append(n - tile) |
| return xs |
| |
| |
| def canonical_work(Cin, Cout, T, H, W, tile, stride): |
| """FLOPs of the tiled convolution, from the SHAPE ALONE. |
| |
| Every tile is convolved in full: Ntiles * Cout * T * tile * tile outputs, each a dot product over |
| Cin*27 taps (one multiply, one add). The overlapped work is counted -- it is genuinely performed, and |
| counting it keeps the attribution independent of how a kernel chooses to share it. The blend itself is |
| a multiply-add per element and is not counted. |
| """ |
| nt = len(_tile_origins(H, tile, stride)) * len(_tile_origins(W, tile, stride)) |
| return 2 * nt * Cout * Cin * 27 * T * tile * tile |
| ''', |
| flops_formula="2 * Ntiles * Cout * Cin * 27 * T * tile * tile", |
|
|
| metric="TFLOP/s", |
| compare="tensor", |
| tol=1.2e-2, |
| shape_names=("Cin", "Cout", "T", "H", "W", "tile", "stride"), |
| grader_shapes=[(64, 64, 9, 320, 320, 112, 80), (96, 96, 5, 384, 384, 128, 96), |
| (128, 64, 7, 256, 256, 96, 64), (64, 128, 9, 240, 320, 96, 72), |
| (96, 96, 9, 288, 288, 96, 72)], |
| measure_shapes=[(64, 64, 7, 320, 320, 112, 80), (96, 96, 5, 320, 320, 128, 96), |
| (128, 64, 5, 256, 256, 96, 64), (64, 128, 7, 240, 320, 96, 72), |
| (96, 96, 7, 288, 288, 96, 72)], |
| measure_quick_shapes=[(32, 32, 3, 128, 128, 64, 48), (64, 32, 3, 160, 160, 64, 48), |
| (32, 64, 5, 96, 128, 48, 32)], |
| correct_shapes=[(16, 24, 3, 48, 80, 32, 24), (32, 16, 5, 37, 53, 24, 16), |
| (24, 24, 2, 64, 64, 40, 24), (16, 32, 4, 45, 61, 32, 20)], |
|
|
| spec_md="""For each tile: crop the input, convolve it **as a standalone volume**, weight it with a |
| separable feather, and accumulate onto the canvas. Then divide by the accumulated weight. |
| |
| ### Per tile |
| |
| With `(y0, x0) = origins[i]` and side length `tile`: |
| |
| ``` |
| sub = x[:, :, y0 : y0+tile, x0 : x0+tile] # (Cin, T, tile, tile) |
| sp = zero_pad(sub, W: 1 left / 1 right, H: 1 top / 1 bottom, T: 2 BEFORE / 0 after) |
| |
| o[co, t, y, xx] = bias[co] |
| + sum_{ci, kt, kh, kw} sp[ci, t+kt, y+kh, xx+kw] * weight[co, ci, kt, kh, kw] |
| ``` |
| |
| **The spatial padding is tile-local.** The one-pixel halo around a tile is **zero**, not the neighbouring |
| pixels of `x`, even when those pixels exist. This is not an approximation you are allowed to improve on: it |
| is what tiled decoding actually computes, it is why seams appear, and it is what the blend exists to hide. |
| A kernel that reads the true neighbours instead (a "halo exchange") produces a different tensor and fails |
| the gate. |
| |
| The temporal padding is the usual causal one: two zero frames before, none after, so output frame `t` sees |
| input frames `t-2, t-1, t` and nothing later. `weight[..., 2, :, :]` is the tap on the current frame. |
| |
| ### The feather |
| |
| ``` |
| ramp[i] = min( 1, (i + 1) / (ov + 1), (tile - i) / (ov + 1) ) # ov = overlap |
| wt[y, x] = ramp[y] * ramp[x] # (tile, tile), > 0 everywhere |
| ``` |
| |
| ### Accumulate and normalise |
| |
| ``` |
| acc [:, :, y0:y0+tile, x0:x0+tile] += o * wt |
| wacc[ y0:y0+tile, x0:x0+tile] += wt |
| |
| out[co, t, y, x] = bfloat16( acc[co, t, y, x] / wacc[y, x] ) |
| ``` |
| |
| `wacc` is shared across all channels and frames. Every canvas pixel is covered by at least one tile (the |
| tiling includes a final tile flush with each far edge), so `wacc > 0` everywhere. |
| |
| `/app/reference.py` loops over tiles, pads, calls `F.conv3d` in fp32, and does sliced `+=`. That is the |
| exact specification; it is deliberately simple rather than fast.""", |
|
|
| contract_md="""| arg | shape | dtype | meaning | |
| |-----|-------|-------|---------| |
| | `x` | `(Cin, T, H, W)` | `bfloat16` | full input volume, contiguous; **no batch axis** | |
| | `weight` | `(Cout, Cin, 3, 3, 3)` | `bfloat16` | conv weights, taps ordered `(kt, kh, kw)` | |
| | `bias` | `(Cout,)` | `bfloat16` | per-output-channel bias | |
| | `origins` | `(Nt, 2)` | `int32` | `(y0, x0)` top-left of each tile | |
| | `tile` | scalar | python `int` | tile height **and** width | |
| | `overlap` | scalar | python `int` | feather width `ov` at each tile edge | |
| |
| **Return** a single tensor: |
| |
| | out | shape | dtype | notes | |
| |-----|-------|-------|-------| |
| | `out` | `(Cout, T, H, W)` | `bfloat16` | the blended canvas, contiguous | |
| |
| The convolution kernel is always `3x3x3` with unit stride. Tiles lie fully inside the canvas and together |
| cover every pixel, but are **not** on a regular grid: the last tile in each row and column is flush with |
| the far edge, so its offset from the previous one is smaller than the stride and three tiles can meet in |
| one column. `Cin` and `Cout` are independent and need not be multiples of any tile size (the correctness |
| shapes include `Cin = 16`, `Cout = 24`). All inputs are read-only.""", |
|
|
| regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `Cin` and |
| `Cout` in 64–128, `T` in 5–9 frames, canvases of `240x320` to `384x384`, tiles of 96–128 pixels with |
| overlaps of 24–32, giving 15–16 tiles per clip. That is one decoder layer of a 4x8x8 tokenizer running in |
| tiled mode, where the overlapped tiles carry roughly 1.8–2.2x the canvas's pixels. `T` is kept small and the |
| canvas modest so the fp32 reference — which materialises a full-canvas fp32 accumulator **and** a per-tile |
| fp32 convolution output — fits in memory; a real 720p tiled decode runs the same structure with far more |
| tiles. Write a **general** kernel: tile counts, overlaps and the ragged final-tile offsets all vary.""", |
|
|
| correctness_md="""`out` must match the reference (per-tile convolution and accumulation in fp32) within |
| **relative Frobenius error `1.2e-2`** at every graded shape, including the timed ones.""", |
|
|
| perf_md="""Two problems in one kernel: a convolution that dominates the FLOPs, and a scatter-accumulate |
| that dominates the memory traffic. |
| |
| **Fuse the blend into the convolution's epilogue.** The reference writes a `(Cout, T, tile, tile)` fp32 |
| tensor per tile and reads it back to accumulate — that is two extra passes over roughly twice the canvas. |
| A fused kernel keeps the convolution's accumulators in registers, multiplies by the feather weight, and |
| adds straight into the canvas. `wacc` depends only on the geometry, so compute it analytically from |
| `origins`, `tile` and `overlap` and fold the division into the final write; the canvas is then written |
| exactly once. |
| |
| **Choose canvas-parallel over tile-parallel if you can.** Tile-parallel accumulation needs fp32 atomics on |
| the canvas wherever tiles overlap. Canvas-parallel — each CTA owns a canvas region, determines which tiles |
| cover it (at most four), and computes the convolution for each of them — avoids atomics entirely and turns |
| the blend into a register-level combine, at the cost of recomputing the convolution for shared pixels. The |
| work attribution already counts that overlapped work, so recomputation is not penalised. |
| |
| **The tile-local padding is a boundary condition per tile, not per canvas.** Every tile has a zero halo on |
| all four sides, so a CTA that owns an interior canvas region still has to know where its tile's borders |
| are. Precompute, per tile, the predicate masks for the first and last row/column; do not branch per element. |
| |
| **The convolution itself.** NCDHW-style layout puts `Cin` slowest; internally the problem is |
| `(Nt*T*tile*tile) x (Cin*27) x Cout`. Never materialise im2col. Stream a `(T+2, BH+2, BW+2)` halo through |
| shared memory so each input element serves all 27 taps, and walk `t` in the pipeline dimension — consecutive |
| output frames share two thirds of their input. |
| |
| **The feather is separable and closed-form.** `wt[y, x] = ramp[y] * ramp[x]`; compute the row ramp once per |
| CTA into registers and reuse it across all `Cout*T` planes. Do not build a `(tile, tile)` weight tensor and |
| re-read it per channel per frame. |
| |
| Keep the weight tensor (at most `Cout*Cin*27` bf16, ~0.7 MB) resident in SMEM.""", |
|
|
| precision_md="""Everything in and out is **bfloat16**; the convolution accumulation, the feather weights, |
| the canvas accumulation and the division are all **fp32**. |
| |
| The tolerance was **measured** on the components: an independent fp32 convolution (27 shifted matmuls) |
| differs from this style of reference by `4.7e-5` and a bf16 convolution with fp32 accumulation by `2.9e-3`; |
| the blend adds the final bf16 rounding of the canvas, about `1.7e-3`. Composed, that is roughly `4e-3`, so |
| the gate is `1.2e-2` — about 3x the observed noise, and far below the error of getting the causal temporal |
| padding wrong (replicating frame 0 instead of zero-padding costs `2.5e-1` on a single convolution). |
| |
| Three things that are *not* noise and will fail: reading the true neighbouring pixels instead of the |
| **tile-local zero padding**; using uniform blend weights or skipping the normalisation by `wacc`; and |
| accumulating the canvas in bf16, which loses several bits per pixel exactly in the overlap regions the |
| feather exists to smooth. |
| |
| **fp8 is not appropriate here** — the graded dtype is bf16 in and bf16 out.""", |
| ).validate() |
|
|