File size: 11,529 Bytes
0f775e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
"""Spec for `causal-conv3d-cache-step` — the streaming (feat_cache) form of the video-VAE causal Conv3d."""
import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from spec import TaskSpec

SPEC = TaskSpec(
    name="causal-conv3d-cache-step",
    title="Write a fast streaming causal Conv3d cache-step kernel (video VAE decode)",
    blurb=("A 720p x 129-frame decode does not fit in memory as one tensor, so Wan and HunyuanVideo decode "
           "the clip in short chunks of frames and carry a per-layer feat_cache holding the last two input "
           "frames. Each step conditions on that cache instead of on zero padding, emits the chunk's "
           "outputs, and hands the last two frames forward. Chunks are only one to a few frames deep but "
           "full pixel resolution, so the kernel is short-and-wide: a two-frame halo dominates the traffic "
           "and the arithmetic has almost no temporal reuse to hide behind."),
    keywords=["mle", "kernel-generation", "conv3d", "causal", "streaming", "cache", "video", "vae", "wan",
              "hunyuanvideo", "decode"],
    module="conv3d_cache.py",
    func="causal_conv3d_cache_step",
    signature="causal_conv3d_cache_step(x, cache, weight, bias)",
    returns_doc="""One streaming step of the causal 3x3x3 convolution.

Args:
    x:      (B, Cin, Tc, H, W)     bfloat16 — this chunk's input frames.
    cache:  (B, Cin, 2, H, W)      bfloat16 — the two INPUT frames immediately before this chunk,
                                              oldest at index 0.
    weight: (Cout, Cin, 3, 3, 3)   bfloat16 — dense convolution weights.
    bias:   (Cout,)                bfloat16 — per-output-channel bias.

Returns:
    (y, cache_out) where
      y:         (B, Cout, Tc, H, W) bfloat16 — this chunk's outputs
      cache_out: (B, Cin, 2, H, W)   bfloat16 — the last two frames of [cache | x], for the next step""",

    reference_imports="import torch\nimport torch.nn.functional as F",
    reference_src='''
def causal_conv3d_cache_step(x, cache, weight, bias):
    """Streaming causal Conv3d: the cache REPLACES the two frames of temporal zero padding.

    Correct and simple -- the numerical SPECIFICATION, not a performance target.
    """
    xf = torch.cat([cache.float(), x.float()], dim=2)         # (B, Cin, 2 + Tc, H, W)
    xp = F.pad(xf, (1, 1, 1, 1, 0, 0))                        # spatial pad only; time is supplied by cache
    with torch.backends.cudnn.flags(enabled=True, allow_tf32=False):
        y = F.conv3d(xp, weight.float(), bias.float())        # -> (B, Cout, Tc, H, W)
    cache_out = torch.cat([cache, x], dim=2)[:, :, -2:].contiguous()
    return y.to(torch.bfloat16), cache_out
''',
    make_inputs_src='''
def _mk(B, Cin, Cout, Tc, H, W, seed):
    gen = torch.Generator(device="cuda").manual_seed(seed)
    x = torch.randn(B, Cin, Tc, H, W, device="cuda", dtype=torch.bfloat16, generator=gen)
    cache = torch.randn(B, Cin, 2, 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, cache, w, b
''',
    flops_src='''
def canonical_work(B, Cin, Cout, Tc, H, W):
    """FLOPs of one streaming chunk, from the SHAPE ALONE.

    B*Cout*Tc*H*W outputs, each a dot product over Cin*27 taps (one multiply, one add). The cache frames
    contribute to the outputs but are not themselves outputs, so they add no work of their own; copying the
    cache forward is bookkeeping and is not counted.
    """
    return 2 * B * Cout * Cin * 27 * Tc * H * W
''',

    metric="TFLOP/s",
    compare="tuple",
    tuple_names=("y", "cache_out"),
    tol=1e-2,
    shape_names=("B", "Cin", "Cout", "Tc", "H", "W"),
    grader_shapes=[(1, 128, 128, 4, 256, 256), (1, 128, 128, 2, 384, 384), (1, 192, 128, 3, 256, 320),
                   (1, 128, 256, 1, 352, 480), (2, 96, 96, 4, 224, 224)],
    measure_shapes=[(1, 128, 128, 3, 256, 288), (1, 128, 128, 2, 320, 384), (1, 160, 128, 3, 256, 320),
                    (1, 128, 224, 1, 352, 480), (2, 96, 96, 3, 224, 256)],
    measure_quick_shapes=[(1, 64, 64, 2, 96, 96), (1, 96, 64, 1, 128, 128), (1, 32, 96, 4, 64, 96)],
    correct_shapes=[(1, 32, 32, 3, 16, 16), (1, 48, 32, 1, 24, 20), (2, 16, 24, 2, 17, 23),
                    (1, 64, 64, 5, 32, 32)],

    spec_md="""One streaming step of the causal 3x3x3 convolution. The chunk is `Tc` frames deep; the two
frames that precede it arrive separately, in `cache`.

```
xfull = concat([cache, x], dim=T)                      # (B, Cin, 2 + Tc, H, W)
xp    = zero_pad(xfull, W: 1 left / 1 right, H: 1 top / 1 bottom)     # NO temporal padding

y[b, co, t, h, w] = bias[co]
                  + sum_{ci, kt, kh, kw} xp[b, ci, t + kt, h + kh, w + kw] * weight[co, ci, kt, kh, kw]
                                                        for t in [0, Tc)

cache_out = xfull[:, :, -2:]                            # the last two frames of [cache | x]
```

So output frame `t` of the chunk reads input frames `t-2, t-1, t` of the *concatenated* stream: for `t = 0`
that is `cache[0]`, `cache[1]`, `x[0]`.

### Why this is the causal conv, not a different one

The full-clip kernel prepends **two zero frames** to the whole video. In streaming decode the clip is cut
into chunks and the zeros are only correct for the *first* chunk; every later chunk must condition on the
real previous frames, which is what `cache` carries. That is precisely the trick that lets a 4x8x8 tokenizer
decode 129 frames of 720p without ever materialising the whole volume — and it means a kernel that
zero-pads instead of reading the cache is wrong on the first two output frames of every chunk. At `Tc = 1`
that is *every* output.

`cache_out` is the input-side carry for the next chunk: the last two frames of `[cache | x]`. When
`Tc >= 2` that is just `x[:, :, -2:]`; when `Tc == 1` it is `[cache[:, :, 1], x[:, :, 0]]`, and `Tc = 1`
does appear in the correctness shapes. The contract is **functional** — return a new tensor, do not mutate
`cache` in place; the grader calls your function and the reference on the same buffers, so an in-place
update corrupts the comparison and fails.

Spatial padding is the ordinary symmetric zero padding of a `3x3` conv, so `H` and `W` are preserved.

`/app/reference.py` concatenates, spatially pads, 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, Tc, H, W)` | `bfloat16` | this chunk's input frames, contiguous NCDHW |
| `cache` | `(B, Cin, 2, H, W)` | `bfloat16` | the two input frames before the chunk, **oldest at index 0** |
| `weight` | `(Cout, Cin, 3, 3, 3)` | `bfloat16` | taps ordered `(kt, kh, kw)`; `weight[..., 2, :, :]` hits the current frame |
| `bias` | `(Cout,)` | `bfloat16` | per-output-channel bias |

**Return** a 2-tuple `(y, cache_out)` **in that order**:

| out | shape | dtype | notes |
|-----|-------|-------|-------|
| `y` | `(B, Cout, Tc, H, W)` | `bfloat16` | contiguous NCDHW, one output per input frame of the chunk |
| `cache_out` | `(B, Cin, 2, H, W)` | `bfloat16` | last two frames of `[cache \\| x]`; **must be bf16** |

`Tc` can be as small as **1** and is never larger than a handful — this is a streaming decode, not a full
clip. `Cin` and `Cout` are independent and need not be multiples of any tile size (correctness shapes
include `Cin = 16`, `Cout = 24`, `H = 17`, `W = 23`). All inputs are **read-only** and the cache update is
**functional**.""",

    regime_md="""**Shape regime you are graded in** (the exact grader sizes are *not* disclosed): `B` in 1–2,
`Cin`/`Cout` in 64–256, `Tc` (chunk depth) in **1–4**, and `H`/`W` in 224–480 — a decoder layer running at
or near pixel resolution while streaming a 720p clip a few frames at a time. This is the short-and-wide
regime: two frames of halo per chunk is a large fraction of the input, so the kernel has far less temporal
reuse than the full-clip convolution and the cache traffic is a first-order cost. Resolution is capped so
the fp32 reference fits in memory. Write a **general** kernel — `Tc = 1` and ragged channels both appear.""",

    correctness_md="""**Both** returned tensors must match the reference (evaluated in fp32) within
**relative Frobenius error `1e-2`** at every graded shape, including the timed ones. A wrong `cache_out`
corrupts every subsequent chunk, so it is graded exactly as hard as `y`.""",

    perf_md="""The chunk is only a few frames deep but full pixel resolution, which changes the balance
completely relative to the full-clip convolution.

**The halo is expensive.** With `Tc = 2`, the two cache frames are as much data as the chunk itself: half of
the input traffic produces no output. There is nothing to do about the bytes, but there is a lot to do about
*not reading them twice* — load a `(2 + BT, BH + 2, BW + 2)` halo once into shared memory and let every
output frame in the tile consume it.

**Fuse the cache copy into the main kernel.** `cache_out` is a slice of data the convolution already has in
registers or SMEM. Emitting it from a second kernel costs an extra full read of two frames of the volume,
which at `H = W = 384` and `Cin = 128` is another 75 MB round trip per layer per step.

**Layout still decides everything.** NCDHW puts the reduction axis `Cin` slowest. Transpose to NDHWC
internally so the `Cin*27` reduction is contiguous and the convolution is an implicit GEMM of shape
`(B*Tc*H*W) x (Cin*27) x Cout`. Never materialise the `27x` im2col matrix.

**Watch the occupancy at `Tc = 1`.** The output volume is `B*Cout*H*W`, so the parallelism is entirely
spatial; a tiling that assumes a deep `T` axis will leave the machine half idle. Conversely, at `Tc = 1`
every one of the 27 taps still has to be applied — three temporal taps against `cache[0]`, `cache[1]` and
`x[0]` respectively — so there is no shortcut, only better scheduling.

Other things that matter: keep the weight tensor (at most 4.5 MB) resident across the tile; vectorise loads
and stores along the contiguous channel axis of your internal layout; and predicate the spatial halo rather
than writing a padded copy of a multi-hundred-megabyte volume.""",

    precision_md="""Inputs and outputs are **bfloat16**; accumulate in **fp32**. The reference convolves in
fp32 with TF32 disabled, so it is a true fp32 result and a faithful bf16 kernel's only error is the final
rounding of `y` plus accumulation order.

The tolerance was **measured** on the same convolution: an independent fp32 implementation (27 shifted
`Cin x Cout` matmuls) differs from this reference by `4.7e-5`, and a bf16 convolution with fp32
accumulation by `2.9e-3`. The gate is `1e-2`, about 3.4x the observed bf16 noise. Zero-padding instead of
reading the cache is *not* noise: it is wrong on the first two output frames of every chunk, which at
`Tc <= 4` is at least half the output and lands orders of magnitude outside the gate.

`cache_out` **must be bfloat16** — it is the carry the next chunk consumes, and widening it would both break
the contract and hide the quantisation the real streaming decoder lives with.

**fp8 is not appropriate here**; the graded dtype is bf16 in and bf16 out.""",
).validate()