"""Spec for `conv3d-layout-transform` — NCDHW <-> NDHWC repacking with channel padding, both directions.""" import pathlib import sys sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from spec import TaskSpec SPEC = TaskSpec( name="conv3d-layout-transform", title="Write a fast NCDHW <-> NDHWC layout transform kernel (video VAE conv plumbing)", blurb=("Every fast 3D convolution wants NDHWC — the reduction axis contiguous, channels padded up to " "the tensor-core alignment — while PyTorch hands you NCDHW. In a video VAE that repack runs " "twice per layer on activations of hundreds of megabytes, and the two directions are not " "symmetric: going in you pad the channel axis with zeros, coming out you drop the padding. It " "is the least glamorous kernel in the decoder and often several percent of the wall clock, " "because a naive permute-and-copy strides through memory in exactly the wrong order."), keywords=["mle", "kernel-generation", "layout", "transpose", "ndhwc", "conv3d", "video", "vae", "memory-bound", "channels-last"], module="layout3d.py", func="conv3d_layout_transform", signature="conv3d_layout_transform(x, g)", returns_doc="""NCDHW -> NDHWC (with channel zero-padding) and NDHWC -> NCDHW (dropping the padding). Args: x: (B, C, T, H, W) bfloat16 — an activation in PyTorch's NCDHW layout. g: (B, T, H, W, Cp) bfloat16 — an activation in NDHWC layout, Cp = round_up(C, 8). Returns a 2-tuple, in this order: x_ndhwc: (B, T, H, W, Cp) bfloat16 — x repacked to NDHWC, channels [C, Cp) set to ZERO g_ncdhw: (B, C, T, H, W) bfloat16 — g repacked to NCDHW, padding channels dropped""", reference_imports="import torch", reference_src=''' def conv3d_layout_transform(x, g): """Repack NCDHW -> NDHWC with zero channel padding, and NDHWC -> NCDHW dropping the padding. Correct and simple -- the numerical SPECIFICATION, not a performance target. """ B, C, T, H, W = x.shape Cp = g.shape[-1] x_ndhwc = torch.zeros(B, T, H, W, Cp, device=x.device, dtype=x.dtype) x_ndhwc[..., :C] = x.permute(0, 2, 3, 4, 1) g_ncdhw = g[..., :C].permute(0, 4, 1, 2, 3).contiguous() return x_ndhwc, g_ncdhw ''', make_inputs_src=''' def _mk(B, C, T, H, W, seed): gen = torch.Generator(device="cuda").manual_seed(seed) Cp = (C + 7) // 8 * 8 x = torch.randn(B, C, T, H, W, device="cuda", dtype=torch.bfloat16, generator=gen) g = torch.randn(B, T, H, W, Cp, device="cuda", dtype=torch.bfloat16, generator=gen) return x, g ''', flops_src=''' def canonical_work(B, C, T, H, W): """BYTES moved by the two repacks, from the SHAPE ALONE. Forward : read B*C*T*H*W bf16, write B*Cp*T*H*W bf16 (Cp = C rounded up to 8). Backward: read B*Cp*T*H*W bf16, write B*C*T*H*W bf16. This is a pure data-movement kernel, so the score is achieved bandwidth against this fixed byte count. """ Cp = (C + 7) // 8 * 8 return 2 * 2 * (B * C * T * H * W) + 2 * 2 * (B * Cp * T * H * W) ''', flops_formula="4 * B * C * T * H * W + 4 * B * Cp * T * H * W # Cp = round_up(C, 8), bf16", metric="GB/s", compare="tuple", tuple_names=("x_ndhwc", "g_ncdhw"), tol=1e-6, shape_names=("B", "C", "T", "H", "W"), grader_shapes=[(1, 128, 33, 224, 224), (1, 256, 17, 208, 240), (1, 100, 33, 240, 240), (2, 96, 25, 208, 224), (1, 192, 21, 224, 256)], measure_shapes=[(1, 128, 25, 224, 224), (1, 256, 13, 208, 240), (1, 100, 25, 240, 240), (2, 96, 21, 208, 224), (1, 192, 17, 224, 256)], measure_quick_shapes=[(1, 64, 9, 96, 96), (1, 128, 5, 64, 96), (1, 36, 17, 96, 128)], correct_shapes=[(1, 32, 5, 12, 16), (1, 17, 7, 15, 23), (2, 12, 4, 10, 14), (1, 64, 3, 16, 16)], spec_md="""Two repacks of the same 5D activation, in opposite directions, in one call. Let `Cp = round_up(C, 8)` — the channel count rounded up to the next multiple of 8, which is what an NDHWC tensor-core convolution needs for a 128-bit-aligned `k` axis. ### Forward: NCDHW -> NDHWC, with zero channel padding ``` x_ndhwc[b, t, h, w, c] = x[b, c, t, h, w] for c in [0, C) x_ndhwc[b, t, h, w, c] = 0 for c in [C, Cp) ``` The padding channels must be **exactly zero**, not left uninitialised: they participate in the convolution's `k` reduction, and garbage there corrupts every output. ### Backward: NDHWC -> NCDHW, dropping the padding ``` g_ncdhw[b, c, t, h, w] = g[b, t, h, w, c] for c in [0, C) ``` The channels `[C, Cp)` of `g` are discarded. Both outputs must be **contiguous** in the shapes given. `C == Cp` whenever `C` is already a multiple of 8, which is the common case; the correctness shapes include `C = 17` (`Cp = 24`) and `C = 12` (`Cp = 16`), and one graded shape uses `C = 100` (`Cp = 104`). `/app/reference.py` does `permute(...)` into a preallocated zeroed tensor and a `permute(...).contiguous()`. That is the exact specification; it is deliberately simple rather than fast.""", contract_md="""| arg | shape | dtype | meaning | |-----|-------|-------|---------| | `x` | `(B, C, T, H, W)` | `bfloat16` | contiguous NCDHW activation | | `g` | `(B, T, H, W, Cp)` | `bfloat16` | contiguous NDHWC activation, `Cp = round_up(C, 8)` | **Return** a 2-tuple `(x_ndhwc, g_ncdhw)` **in that order**: | out | shape | dtype | notes | |-----|-------|-------|-------| | `x_ndhwc` | `(B, T, H, W, Cp)` | `bfloat16` | contiguous; channels `[C, Cp)` are **exactly zero** | | `g_ncdhw` | `(B, C, T, H, W)` | `bfloat16` | contiguous; `g`'s padding channels dropped | `Cp` is not passed separately — derive it from `g.shape[-1]` (or from `C`; they agree). Returning a non-contiguous view (e.g. a bare `permute`) does not satisfy the contract: the point of the operator is that the bytes are physically rearranged. `C` need not be a multiple of anything and `H`/`W` are ragged. Both inputs are read-only.""", regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `B` in 1–2, `C` in 96–256 (including `C = 100`, which pads to 104), `T` in 17–33, `H` in 208–240, `W` in 224–256 — one decoder or encoder layer of a 4x8x8 video tokenizer at 720p/1080p latent resolution, about 0.4 GB of bf16 per tensor and four such tensors touched per call. Resolution is capped there because all four live at once; a pixel-resolution 720p x 129-frame layer would be tens of gigabytes, which is why real decoders tile. Write a **general** kernel: `C` is not a multiple of 8 at every shape, and `H`/`W` are not multiples of any tile size.""", correctness_md="""**Both** returned tensors must match the reference within **relative error `1e-6`** at every graded shape, including the timed ones. That is a *de-facto exact* gate, and deliberately so: this operator only moves bytes, so any correct implementation is bit-exact (measured — see Precision). The zero padding in `x_ndhwc[..., C:]` is graded like every other element.""", perf_md="""**Memory-bound and nothing else**: the score is achieved bandwidth against one read and one write per direction. There is no arithmetic to hide behind, so this is a pure access-pattern problem and a good implementation should approach the machine's copy bandwidth. **The transpose is `(C) x (T*H*W)`, and both extents are large.** In NCDHW a channel plane is `T*H*W` contiguous elements; in NDHWC a voxel's channels are `Cp` contiguous elements. So one side of each copy is always contiguous and the other always strides by `T*H*W` — the classic tiled-transpose situation. Stage a `(BC x BN)` tile through **shared memory**: read `BN` contiguous elements from each of `BC` channels, write `BC` contiguous elements for each of `BN` voxels. Both halves are then fully coalesced. **Pad the SMEM tile.** A `32 x 32` bf16 tile hits a 2-way bank conflict on the strided half; padding the row stride by one 32-bit word (or using a swizzled layout / `ldmatrix`-style access) removes it. **Vectorise to 128 bits on the contiguous side.** 8 bf16 per access. On the NDHWC side that means the channel axis, so `Cp` being a multiple of 8 is exactly what makes the store a single `st.global.v4`; on the NCDHW side it means the `W` axis. When `C != Cp` the last partial vector needs the zero fill — generate the zeros in registers rather than pre-zeroing the whole output tensor, which would cost an extra full write (the reference does exactly that, and it is a third of its traffic). **Both directions in one launch or two?** They touch disjoint tensors, so a single kernel can interleave them and keep more memory transactions in flight, but they want opposite SMEM tilings. Measure; a persistent kernel handling both with a grid split is often the best of both. **Ragged tails.** `C = 100` means the last channel tile is 4 wide and its NDHWC store crosses the padding boundary; `H`/`W` are not multiples of the tile either. Predicate, do not branch into a scalar path — at these sizes the tail is a visible fraction of the tiles.""", precision_md="""Everything is **bfloat16** and nothing is computed: this operator copies bytes and writes zeros. This is a **bit-exact** task, not an arithmetic one, and the tolerance is set accordingly. **Measured.** An independent implementation — one that builds `x_ndhwc` by concatenating a `movedim` view with an explicit zero block (rather than scattering into a pre-zeroed tensor) and produces `g_ncdhw` by `reshape / transpose / reshape` on a narrowed view (rather than `permute().contiguous()`) — was compared against the reference on all four correctness shapes and all five graded shapes. The measured relative error `E` is **exactly 0.0** at every one of them. There is no reduction, no accumulation and no rounding anywhere in this operator, so there is nothing for a tolerance to absorb. `tol = 1e-6` therefore makes the gate effectively exact: `E = 0` << `1e-6`, and the smallest realistic mistake is far above it — a *single* mis-copied bf16 element at the largest graded shape (211M elements) already registers ~`1e-4`, a hundred times the gate. **Drop-the-feature margins**, measured on the same nine shapes: - **Not writing the zero padding** (leaving `[C, Cp)` as allocation garbage): relative error **0.20–0.64** on the three shapes that actually have padding (`C = 17, 12, 100`) — >= 2·10^5 x the gate. This feature only exists where `C` is not a multiple of 8; at the other six shapes `Cp == C` and there is no padding to get wrong, which is exactly why those three ragged shapes are in the lists. - **Not transposing** (reinterpreting the buffer in the requested shape instead of physically repacking): relative error **1.41** at every one of the nine shapes. What the tolerance still does **not** cover, because the gate compares values: - returning a non-contiguous permuted view instead of a physically repacked tensor; - widening to fp32 anywhere — both outputs must be genuine `bfloat16`.""", ).validate()