FastVideo icon indicating copy to clipboard operation
FastVideo copied to clipboard

[perf] fused RoPE Triton kernel + FP32LayerNorm fp32 cache

Open Godmook opened this issue 7 months ago • 15 comments

Purpose

_apply_rotary_emb launches 5–9 CUDA kernels per call (reshape + unbind + stack + flatten + two float() casts + mul + add + dtype cast) and shuttles the full Q/K tensor through DRAM on each one. It is called twice per attention layer, so on a 115k-token × bf16 workload the RoPE round-trips dominate an otherwise trivial computation.

FP32LayerNorm.forward additionally calls self.weight.float() / self.bias.float() on every forward, allocating a fresh fp32 copy of weights that never change during inference.

Fixes #

Changes

  • fastvideo-kernel/python/fastvideo_kernel/triton_kernels/rope_triton.py (new)
    • Single CTA-per-(token, head) Triton kernel covering all three RoPE layouts via a tl.constexpr MODE switch: rotate_half (HunyuanVideo / GameCraft), gpt_j (interleaved half), neox (split half).
    • Loads x / cos / sin once and writes the rotated output once. Partner index is a branch-free d ^ 1 (modes 0/1) or d ± D/2 (mode 2).
    • apply_rope(...) wrapper validates dtype / shape / contiguity and returns None on ineligible inputs so the caller can fall back.
  • fastvideo/layers/rotary_embedding.py
    • One try/except import and a 3-line fast-path at the top of _apply_rotary_emb. Existing PyTorch fallback is untouched.
  • fastvideo/layers/layernorm.py::FP32LayerNorm
    • Cache fp32 copies of weight / bias, invalidated on (data_ptr, _version) change. Stored in self.__dict__ so the cache does not pollute state_dict and survives FSDP / from_pretrained semantics.
  • fastvideo-kernel/tests/test_rope_triton.py (new)
    • 14 pytest cases (10 parametrized correctness + 4 ineligibility) covering all 3 modes × all 3 dtypes × edge shapes (T=1, odd T, non-power-of-2 D=96, D=256, DiT-scale T=2048, H=24).

Test Plan

cd fastvideo-kernel
pip install -e . --no-build-isolation

# 14 unit tests (3 modes, 3 dtypes, edge shapes, ineligibility)
pytest tests/test_rope_triton.py -v

# Microbenchmark: fused Triton vs. PyTorch reference
python - <<'PY'
import torch, triton
from fastvideo_kernel.triton_kernels.rope_triton import apply_rope
def ref(x, cos, sin):
    c, s = cos.unsqueeze(-2), sin.unsqueeze(-2)
    xr, xi = x.float().reshape(*x.shape[:-1], -1, 2).unbind(-1)
    rot = torch.stack([-xi, xr], dim=-1).flatten(-2)
    return (x.float()*c + rot*s).type_as(x)
for T,H,D in [(30720,24,128),(115200,24,128),(30720,16,128),(4096,16,64)]:
    x   = torch.randn(T, H, D, device="cuda", dtype=torch.bfloat16)
    cos = torch.randn(T, D,    device="cuda", dtype=torch.bfloat16)
    sin = torch.randn(T, D,    device="cuda", dtype=torch.bfloat16)
    t_ref  = triton.testing.do_bench(lambda: ref(x, cos, sin),                     warmup=25, rep=100)
    t_fast = triton.testing.do_bench(lambda: apply_rope(x, cos, sin, is_neox_style=False), warmup=25, rep=100)
    print(f"T={T} H={H} D={D}: {t_ref:.3f} ms -> {t_fast:.3f} ms  ({t_ref/t_fast:.2f}x)")
PY

Test Results

Microbenchmark (bf16, rotate_half mode unless noted)

Shape (T × H × D) PyTorch Triton fused Speedup Max abs error
Hunyuan-like 30 720 × 24 × 128 5.76 ms 0.56 ms 10.22× 0.00e+00
Hunyuan-like 115 200 × 24 × 128 20.55 ms 2.25 ms 9.12× 0.00e+00
Wan-like GPT-J 30 720 × 16 × 128 3.05 ms 0.37 ms 8.16× 0.00e+00
Small 4 096 × 16 × 64 0.23 ms 0.056 ms 4.19× 0.00e+00

CUDA kernel launches (20 iterations, torch.profiler)

Path Launches CUDA total
PyTorch baseline 160 (8 ops × 20) 116.5 ms
Triton fused 20 (_rope_kernel only) 13.4 ms

8.7× fewer kernel launches and 8.7× lower CUDA time on the same workload.

Correctness

pytest tests/test_rope_triton.py -v
============================= 14 passed =============================
Profiler output (20 iterations, T=30 720, H=24, D=128, bf16)
PyTorch baseline
-------------------------------------------------------  -------------  -----------  --------
Name                                                     Self CUDA %    Self CUDA    # Calls
elementwise_kernel<128, 4, ...>                          26.03%         30.339 ms    40
CatArrayBatchedCopy<...>                                 25.64%         29.884 ms    20
unrolled_elementwise_kernel<...>                         19.90%         23.197 ms    40
vectorized_elementwise_kernel<4, ...>                    13.98%         16.287 ms    20
elementwise_kernel<128, 2, ...>                           7.30%          8.503 ms    20
vectorized_elementwise_kernel<4, ...>                     7.15%          8.335 ms    20
Self CUDA time total: 116.544 ms

Triton fused
---------------------------  -------------  -----------  --------
Name                         Self CUDA %    Self CUDA    # Calls
_rope_kernel                 100.00%        13.374 ms    20
Self CUDA time total: 13.374 ms

Notes

  • Numbers above are from A100. The absolute ms will be lower on H100; the speedup ratio is a function of kernel-launch overhead and memory bandwidth and tends to stay in the same range (see PR discussion).
  • max_err = 0.00e+00 at bf16 is exact — the fused kernel computes in fp32 internally and rounds once on store, identical to the reference's (x.float()*cos + ...).type_as(x).
  • The fast path is only taken for CUDA / fp16-bf16-fp32 / contiguous / matching token counts / even head_size. Any other input falls back to the original PyTorch code unchanged.
  • FP32LayerNorm cache is validated by (data_ptr, _version), so in-place optimizer steps, from_pretrained, and .to(device) all invalidate the cache correctly. The cache lives in self.__dict__ and is excluded from state_dict.

Checklist

  • [x] I ran pre-commit run --all-files and fixed all issues
  • [x] I added or updated tests for my changes — tests/test_rope_triton.py covers all 3 modes × 3 dtypes × edge shapes + ineligibility fallback
  • [ ] I updated documentation if needed
  • [x] I considered GPU memory impact of my changes — the fused kernel allocates one output tensor shaped like x and reads cos/sin in place; the PyTorch path materialized x_real, x_imag, x_rotated, and two fp32 copies of x. FP32LayerNorm cache adds one fp32 copy of weight/bias per module (constant, already implicitly allocated every forward in the old code).

For model/pipeline changes, also check:

  • [ ] I verified SSIM regression tests pass
  • [ ] I updated the support matrix if adding a new model

Godmook avatar Apr 21 '26 20:04 Godmook

Merge Protections

🟠 1 of 1 protections blocking · waiting on 🤖 CI

Protection Waiting on
🟠 PR merge requirements 🤖 CI

🟠 PR merge requirements

Waiting for

  • [ ] check-success=fastcheck-passed
  • [ ] check-success=full-suite-passed
Waiting checks: fastcheck-passed, full-suite-passed.
  • [ ] check-success=fastcheck-passed
  • [ ] check-success=full-suite-passed
  • [X] #approved-reviews-by>=1
  • [X] check-success~=pre-commit
  • [X] title~=(?i)^\[(feat|feature|bugfix|fix|refactor|perf|ci|doc|docs|misc|chore|kernel|new.?model|skill|skills|infra)\]

mergify[bot] avatar Apr 21 '26 20:04 mergify[bot]

/test ssim

SolitaryThinker avatar Apr 22 '26 18:04 SolitaryThinker

/test training

SolitaryThinker avatar Apr 22 '26 18:04 SolitaryThinker

I checked the CI and the kernel looks good to me. @SolitaryThinker @alexzms, when you get a chance, could you review this PR? No rush at All!

This is my first contribution to FastVideo, and I'd love to get a sense of your preferred coding style and conventions before submitting more PRs. Any feedback is appreciated! Happy to align with your direction!

Thanks!

Godmook avatar Apr 22 '26 22:04 Godmook

/test ssim

Eigensystem avatar Apr 23 '26 21:04 Eigensystem

Heads up — I tested locally with the new RoPE kernel and FP32LayerNorm changes both disabled, and the LTX-2 SSIM score comes out similiar. So I don't think this PR is the cause.

My read is that the LTX-2 test itself may be a little flaky right now. Before finishing this PR, would it be okay if I took a closer look at the LTX-2 test and tried some improvements? Just want to check no one else is already on it.

@SolitaryThinker @Eigensystem

Godmook avatar Apr 23 '26 23:04 Godmook

Heads up — I tested locally with the new RoPE kernel and FP32LayerNorm changes both disabled, and the LTX-2 SSIM score comes out similiar. So I don't think this PR is the cause.

My read is that the LTX-2 test itself may be a little flaky right now. Before finishing this PR, would it be okay if I took a closer look at the LTX-2 test and tried some improvements? Just want to check no one else is already on it.

@SolitaryThinker @Eigensystem

Yeah sure. Go ahead. Thank you!

Eigensystem avatar Apr 23 '26 23:04 Eigensystem

/test ssim

Eigensystem avatar Apr 24 '26 09:04 Eigensystem

just a ping! After finish ssim test at #1253 , could you re-run test ssim? Thanks!

Godmook avatar Apr 29 '26 00:04 Godmook

/merge

alexzms avatar May 03 '26 22:05 alexzms

@alexzms @Eigensystem Sorry for late response. Could you kindly run CI again? I think there is no errors in my code after I double checked.

Godmook avatar May 23 '26 11:05 Godmook

@Eigensystem @SolitaryThinker @alexzms ping!

Godmook avatar Jun 05 '26 05:06 Godmook

@SolitaryThinker @Eigensystem @alexzms All CI Passed. Could you merge it? Thanks!

Godmook avatar Jun 08 '26 14:06 Godmook

🤖 This review was generated by Claude (Claude Code). I've read it over before posting, but the analysis and wording are Claude's — flagging in case you want to verify the call-site claims independently.

Thanks for this @Godmook, and thanks @alexzms for the review. The Triton kernel itself is genuinely well done — I checked the math and all three modes (rotate_half, gpt_j, neox) are bit-exact against the PyTorch reference, the mode auto-detection mirrors _apply_rotary_emb exactly, and the eligibility/fallback is appropriately conservative. Two things to sort out before this lands, building on Alex's note:

1. The fused kernel never fires at any current call site (so the speedup isn't realized)

Alex is right that "all call sites fall back today," and the reason is a layout mismatch: _is_eligible requires 3D contiguous [num_tokens, num_heads, head_size], but all 16 _apply_rotary_emb call sites pass 4D [B, S, H, D] or a non-contiguous tensor:

Call site Why it falls back
attention/layer.py:283-284 assert q.dim() == 4 → rejected by x.dim() != 3
attention/layer.py:110/202 qkv/qkvg are [3*batch, seq, heads, dim] (4D)
causal_wanvideo.py:97-98 q is [B, L, num_heads, C/H] (4D)
matrixgame2/action_module.py:69-70, matrixgame2/model.py:290-291, matrixgame3/action_module.py:60-61 4D [B, S, H, D], and cos/sin are strided (cos[:, ::2]) → non-contiguous
rotary_embedding.py:228/235 (forward_native) cos from chunk(2, -1) is non-contiguous
magi_human.py:477-478 partial-RoPE q[..., :rot_dim] slice + tensor_split cos are non-contiguous

The 9–10× numbers were measured on hand-built torch.randn(T, H, D) 3D contiguous tensors, which match the kernel's API but no actual call site — so as wired, the fast path is dead code and realized speedup ≈ 0 (just a cheap _is_eligible check on the always-taken fallback). To actually deliver the win, the kernel needs to accept the 4D [B, S, H, D] layout the callers use (flatten B·S, or add a grid dim) and tolerate the strided cos/sin the models pass — then please re-benchmark through a real model forward (e.g. Wan inference) to confirm the speedup survives.

2. Add inference-only guards before this can be safe in training

Alex's catch is correct: apply_rope returns a bare torch.empty_like with no autograd.Function, so it drops gradients. It's dormant only because the kernel never fires (§1) — but the moment it becomes eligible (4D support, a stray .contiguous(), a 3D varlen path), it turns into a silent gradient barrier on the q/k projections in training. So the guard should go in regardless; I'd use not torch.is_grad_enabled() over if x.requires_grad so it covers all training paths.

The same gap exists in the FP32LayerNorm cache, independent of the kernel (it's pure Python, always active). It's a no-op for the common elementwise_affine=False norms (most Wan transformer blocks — _fp32_cached returns None with no weight), but for the affine instances (matrixgame2/3 action modules, longcat cross-norm, stable_audio, Wan's image embedding) it caches a weight.float() that carries an autograd graph. Under gradient accumulation (matrixgame2_ar_diffusion_pipeline.py:351 runs forward+backward() per micro-batch with the optimizer step after the loop, so weights are unchanged between backwards), the cached grad-bearing tensor from micro-batch 1 gets reused in later micro-batches — which can raise "backward through the graph a second time." There's also a latent staleness path: invalidation keys on (_version, data_ptr), which .data-style in-place updates (some EMA/optimizer code) don't bump. Both are avoided by the same not torch.is_grad_enabled() guard, which matches the stated "weights that never change during inference" intent.

3. Test coverage

The current tests exercise the kernel in isolation with 3D inputs only — no backward pass, no FP32LayerNorm test, and nothing through _apply_rotary_emb with the real 4D layout. So a green CI run doesn't actually validate either path under grad (the fused path falls back at every call site). Worth adding: (a) a 4D integration test through _apply_rotary_emb asserting fused == reference once 4D is supported, (b) a grad-equivalence test, and (c) an FP32LayerNorm test doing two backward()s with no optimizer step between.

(Also +1 to gemini's same-CUDA-device check in _is_eligible — cheap robustness.)

Happy to pair on the 4D kernel layout if useful — the core kernel is solid, it just needs to meet the callers where they are. Thanks again for the contribution!

SolitaryThinker avatar Jun 10 '26 17:06 SolitaryThinker

@SolitaryThinker Okay. I'll do that works! Thanks!

Godmook avatar Jun 10 '26 23:06 Godmook

@alexzms I'm working for 4D jobs. I'll force-push at this repo after my works. Thanks!

Godmook avatar Jun 18 '26 01:06 Godmook

This review was generated by Claude (Claude Code). I've read it over before posting, but the analysis and wording are Claude's

Follow-up: make the fused RoPE actually fire + keep fast paths inference-only

The fused RoPE path was effectively dead code — its eligibility only accepted 3D contiguous [T,H,D], but every real _apply_rotary_emb call site passes 4D [B,S,H,D] with strided/non-contiguous cos/sin, so the speedup never triggered. The kernel/wrapper now accept those (B·S folded into one token axis to dodge the 65535 gridDim limit), and both fast paths stay inference-only (fused kernel must not run under grad; FP32LayerNorm recomputes weight.float() per call under grad instead of caching).

Performance / quality

Op-level — A100-40GB, full Wan seq (n_tokens=131040, H=12, D=128):

median p10 / p90 peak mem
fused 1.396 ms 1.390 / 1.603 832 MB
torch fallback 11.752 ms 11.744 / 11.768 3520 MB

→ op 8.42× faster, 2688 MB (2.7 GB) less scratch.

Op-level — L4 (Wan-scale 4D, B=1, S=32760, H=12, D=128):

torch.bfloat16   fused=0.972ms  torch=15.999ms  speedup=16.46x
torch.float16    fused=0.988ms  torch=16.011ms  speedup=16.20x

torch.profiler (A100, 50 iters each) — fallback splits into 5–6 elementwise kernels, fused collapses to a single _rope_kernel:

fallback elementwise kernels:  1.633ms / 1.393ms / 1.087ms / 1.764ms / 0.901ms / 0.895ms (avg)
fused _rope_kernel          :  1.389ms (avg, single kernel)

End-to-end — A100-40GB, Wan2.1-T2V-1.3B, 480×832×81, 40 steps (median of 3, warmed up):

median e2e peak mem
fused ON 167.3 s 30337 MB
fused OFF 178.7 s 30337 MB

→ e2e 6.8% faster (off/on = 1.068×, 11.4 s saved). Fully accounted for by the RoPE op savings (≈11.75 ms × ~1200 calls ≈ 14 s → ~12 s expected). e2e peak memory is unchanged (overall peak is set by attention, not RoPE).

Quality — fused vs fallback output: mean SSIM = 0.9946. The pointwise diff is FMA-level fp32 rounding amplified by the diffusion sampler (chaotic), not a regression — bit-exactness isn't expected across kernels.

Correctness — A100

============================= test session starts ==============================
platform linux -- Python 3.12.13, pytest-8.4.2, pluggy-1.6.0
rootdir: /content/FastVideo
collected 28 items

fastvideo-kernel/tests/test_rope_triton.py::test_rope_fused[rotate_half-dtype0-1-1-64] PASSED
fastvideo-kernel/tests/test_rope_triton.py::test_rope_fused[rotate_half-dtype1-17-8-96] PASSED
fastvideo-kernel/tests/test_rope_triton.py::test_rope_fused[rotate_half-dtype2-2048-24-128] PASSED
fastvideo-kernel/tests/test_rope_triton.py::test_rope_fused[rotate_half-dtype3-64-4-256] PASSED
fastvideo-kernel/tests/test_rope_triton.py::test_rope_fused[gptj-dtype4-17-4-128] PASSED
fastvideo-kernel/tests/test_rope_triton.py::test_rope_fused[gptj-dtype5-1-2-64] PASSED
fastvideo-kernel/tests/test_rope_triton.py::test_rope_fused[gptj-dtype6-513-8-128] PASSED
fastvideo-kernel/tests/test_rope_triton.py::test_rope_fused[neox-dtype7-17-4-128] PASSED
fastvideo-kernel/tests/test_rope_triton.py::test_rope_fused[neox-dtype8-1-2-64] PASSED
fastvideo-kernel/tests/test_rope_triton.py::test_rope_fused[neox-dtype9-513-8-128] PASSED
fastvideo-kernel/tests/test_rope_triton.py::test_rope_fused_4d[rotate_half-dtype0-2-512-12-128] PASSED
fastvideo-kernel/tests/test_rope_triton.py::test_rope_fused_4d[rotate_half-dtype1-1-17-4-64] PASSED
fastvideo-kernel/tests/test_rope_triton.py::test_rope_fused_4d[gptj-dtype2-3-128-8-128] PASSED
fastvideo-kernel/tests/test_rope_triton.py::test_rope_fused_4d[neox-dtype3-2-256-6-96] PASSED
fastvideo-kernel/tests/test_rope_triton.py::test_rope_strided_cos[3-rotate_half] PASSED
fastvideo-kernel/tests/test_rope_triton.py::test_rope_strided_cos[3-gptj] PASSED
fastvideo-kernel/tests/test_rope_triton.py::test_rope_strided_cos[3-neox] PASSED
fastvideo-kernel/tests/test_rope_triton.py::test_rope_strided_cos[4-rotate_half] PASSED
fastvideo-kernel/tests/test_rope_triton.py::test_rope_strided_cos[4-gptj] PASSED
fastvideo-kernel/tests/test_rope_triton.py::test_rope_strided_cos[4-neox] PASSED
... (test_rope_noncontiguous_x / test_grad_enabled_falls_back PASSED)
========================= 27 passed, 1 skipped =========================
# 1 skipped = test_mixed_device_falls_back (needs 2 GPUs; single-GPU runner)

Visual quality

https://github.com/user-attachments/assets/16b6ff93-5045-47be-9ec6-a0032c91eebb

https://github.com/user-attachments/assets/02a58167-963a-4373-bdbf-5b34286d39d1

Godmook avatar Jun 19 '26 14:06 Godmook

This pull request has been automatically marked as stale because it has not had any activity within 60 days. It will be automatically closed if no further activity occurs within 14 days. Leave a comment if you feel this pull request should remain open. Thank you!

github-actions[bot] avatar Aug 25 '26 02:08 github-actions[bot]

Merge Protections

🟠 1 of 1 protections blocking · waiting on 🤖 CI

Protection Waiting on
🟠 PR merge requirements 🤖 CI

🟠 PR merge requirements

Waiting for

  • [ ] check-success=fastcheck-passed
  • [ ] check-success=full-suite-passed
Waiting checks: fastcheck-passed, full-suite-passed.
  • [ ] check-success=fastcheck-passed
  • [ ] check-success=full-suite-passed
  • [X] #approved-reviews-by>=1
  • [X] check-success~=pre-commit
  • [X] title~=(?i)^\[(feat|feature|bugfix|fix|refactor|perf|ci|doc|docs|misc|chore|kernel|new.?model|skill|skills|infra)\]

mergify[bot] avatar Aug 25 '26 02:08 mergify[bot]

Merge Protections

🟠 1 of 1 protections blocking · waiting on 🤖 CI

Protection Waiting on
🟠 PR merge requirements 🤖 CI

🟠 PR merge requirements

Waiting for

  • [ ] check-success=fastcheck-passed
  • [ ] check-success=full-suite-passed
Waiting checks: fastcheck-passed, full-suite-passed.
  • [ ] check-success=fastcheck-passed
  • [ ] check-success=full-suite-passed
  • [X] #approved-reviews-by>=1
  • [X] check-success~=pre-commit
  • [X] title~=(?i)^\[(feat|feature|bugfix|fix|refactor|perf|ci|doc|docs|misc|chore|kernel|new.?model|skill|skills|infra)\]

mergify[bot] avatar Aug 26 '26 02:08 mergify[bot]