FastVideo icon indicating copy to clipboard operation
FastVideo copied to clipboard

[perf] Cache RoPE position-embedding tables across denoising steps

Open Godmook opened this issue 5 months ago • 4 comments

Summary

get_rotary_pos_embed is called inside every DiT forward(), i.e. once per denoising step. Its inputs (latent grid size, head dim, theta, dtype, SP shard,start_frame) are constant across the entire denoising loop, yet it rebuilds the full float64 cos/sin tables (meshgrid + 3× outer + cos/sin) from scratch every step and then copies them host→device. For a 50-step run this is the same table computed 50× (100× with CFG).

This PR memoizes the result, matching the existing _ROPE_DICT / get_rope caching pattern already in the same file. All 11 DiT models that call get_rotary_pos_embed benefit with no model-side changes.

It is a pure-function memoization, so outputs are bitwise-identical and SSIM is unchanged.

What changed

  • fastvideo/layers/rotary_embedding.py: add a module-level _ROTARY_POS_EMBED_CACHE and return the cached (cos, sin) on hit.
  • The cache key includes every output-affecting argument: rope_sizes, rope_dim_list (post-None-normalization), rope_theta, theta_rescale_factor, interpolation_factor, shard_dim, sp_rank, sp_world_size, dtype, start_frame, use_real.
    • sp_rank / sp_world_size are in the key so sequence-parallel ranks never share a table (e.g. MatrixGame do_sp_sharding=True).
    • start_frame is in the key so causal/autoregressive models (causal-Wan, MatrixGame) stay correct frame-to-frame.

Before / After

Micro-benchmark of get_rotary_pos_embed (CPU, float64 — same dtype the DiT call sites use). "Before" = recompute every step (current behavior); "After" = cache hit.

Config seq len Before (per step) After (per step) 50-step saved
Wan1.3B 480p 32,760 13.7 ms 25.9 µs ~0.69 s
Wan14B 480p 32,760 13.3 ms 21.8 µs ~0.67 s
Wan14B 720p 75,600 28.7 ms 49.8 µs ~1.43 s

~99.8% of the per-step RoPE cost removed (double the wall-clock saving when CFG runs cond+uncond). This is a host-side cost that sits on the critical path at the start of each forward; the relative win is largest on small / few-step distilled models (FastWan 1.3B, Turbo*), smaller on large many-step models where the DiT blocks dominate.

Correctness & safety

  • Pure memoization → cached tensors are bitwise-equal to a fresh recompute (covered by tests), so generated output / SSIM is unchanged.
  • Cached tensors are CPU (pre-transfer) and treated as read-only; all call sites copy via .to(device).float(), and no call site mutates the returned tensors in place (verified by grep). Cache holds only CPU memory, bounded by the number of distinct resolutions used in a run.

Testing

New CPU-only test suite: fastvideo/tests/ops/test_rotary_pos_embed_cache.py (20 cases), covering:

  • cache hit returns the same objects; repeated calls keep a single entry
  • cached values == fresh recompute (parametrized over resolutions / dtype / use_real)
  • distinct keys for each of: resolution, dtype, use_real, start_frame, theta, shard_dim
  • None rope_dim_list shares a key with its normalized explicit list
  • use_real controls last-dim size; degenerate grids (1,1,1), (1,H,W), (T,1,1)
  • list-vs-scalar rescale factors are hashable and keyed apart
  • caller .to()/.float() copy does not corrupt the cache
  • start_frame shifts temporal positions (causal path)

Run:

pytest fastvideo/tests/ops/test_rotary_pos_embed_cache.py -v

Result: 20 passed. pre-commit (yapf / ruff / mypy / codespell) passes on the modified source file.

Godmook avatar Jun 08 '26 10:06 Godmook

Merge Protections

🟢 Merge protection satisfied — ready to merge.

Show 1 satisfied protection

🟢 PR merge requirements

  • [X] #approved-reviews-by>=1
  • [X] check-success=fastcheck-passed
  • [X] check-success=full-suite-passed
  • [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 Jun 08 '26 10:06 mergify[bot]

Thanks for the contribution! The implementation looks great — clean memoization matching the existing _ROPE_DICT pattern in the same file, bitwise-identical output, and solid test coverage.

One question before I approve: have you measured the end-to-end wall-clock impact (a full generation before/after)? The micro-benchmark is convincing, but since the saved RoPE cost is host-side it may partly overlap with async GPU work, so I am curious how much it actually moves the needle end to end. Everything else looks great.

alexzms avatar Jun 10 '26 21:06 alexzms

E2E latency test

I'll do E2E test! Thanks!

Godmook avatar Jun 10 '26 23:06 Godmook

E2E latency test

I'll do E2E test! Thanks!

Quick Following. I'm currently doing other works nowadays. I'll do this E2E test until tomorrow night. I requested GPU for E2E test and I think It will allocated to me at tomorrow 3pm. Thanks!

Godmook avatar Jun 12 '26 05:06 Godmook

Maintainer update: we ran the end-to-end comparison alexzms asked for. GB200, Wan2.1-1.3B, 480x832, 45 frames, 50 steps, seed 42, second-run timing:

gen time denoise
main (no cache) 33.20 s 1.56 it/s
this PR + hardening 31.93 s 1.63 it/s

−3.85% end-to-end, and outputs are bitwise identical (same sha256 over raw frames).

I also rebased onto current main and added one hardening commit (d0168465): the LRU hit path now pops with a default (no KeyError on concurrent eviction), and the "callers copy via .to()" comment was wrong — .to(device) is an identity alias when already on-device, so the comment now states the real invariant (cache entries are read-only, copy before in-place ops).

Your 22 unit tests pass at the new head (0.53s). They're in fastvideo/tests/ops/, which #1559 is wiring into CI — so they'll actually run on PRs going forward. @alexzms this answers the E2E question; over to you.

SolitaryThinker avatar Jul 05 '26 23:07 SolitaryThinker

@SolitaryThinker I'm so sorry about that. I have personal issues these days... I'll make PR if I can have responsibility about PRs. Really sorry about that.

Godmook avatar Jul 05 '26 23:07 Godmook

@Godmook no worries at all — hope things settle down soon. Nothing is needed from you: we carried the PR over the line (rebase, two small hardenings, and the E2E measurement — 3.85% faster, bitwise-identical outputs). The commits and credit stay yours. Take care.

SolitaryThinker avatar Jul 06 '26 00:07 SolitaryThinker

Rebased onto current main (d016846 -> 712dead) per the maintainer-carry decision — no content changes (range-diff clean, all 3 commits =; main never touched rotary_embedding.py since the PR base, so the bitwise-parity evidence still applies).

SolitaryThinker avatar Jul 08 '26 00:07 SolitaryThinker

/merge

SolitaryThinker avatar Jul 08 '26 00:07 SolitaryThinker

@alexzms this PR was carried by the maintainer per review: your June comments were addressed in the follow-up commits (E2E −3.85%, outputs bitwise-identical — evidence upthread), and it's now freshly rebased onto main (712dead0, pure rebase, RoPE files untouched on main since the base so the parity evidence stands). Your CHANGES_REQUESTED is the last merge blocker — could you re-review or dismiss when you get a chance? Auto-merge is armed; it merges on your approval + green suite.

SolitaryThinker avatar Jul 08 '26 00:07 SolitaryThinker

B200 (GB200) benchmark, main (19a51a1f) vs this PR (fd53fe9e), Wan2.1-T2V-1.3B + FastWan-QAD 3-step FP4 + TAEHV, 2 warmups + 10 timed runs each, same node/hold:

denoise (s) mean ± std min max
main 2.444 ± 0.118 2.341 2.720
PR 2.322 ± 0.006 2.318 2.340

−5.0% mean; the ranges don't overlap (every PR run beat every main run). The cache also collapses run-to-run jitter (std 118ms → 6ms) — the uncached host-side float64 rebuild is the jitter source.

RoPE-path microbenchmark (Wan 480p call-site shapes: rope_sizes (21,30,52), seq 32760, incl. H2D copy + sync, medians of 50): cold first build 25.2ms, uncached 5.80ms/step, warm hit 0.42ms/step → 13.7×. Cross-check: 3 steps × ~5.4ms saved ≈ the 23ms min-vs-min e2e delta.

Correctness at the rebased head: full suite 4300 green; the PR's 22 rope-cache tests pass on the B200; test_hyworld fails bit-identically on main and PR (pre-existing GB200-vs-reference-hardware drift — that exact equality doubles as the main-vs-PR parity proof).

SolitaryThinker avatar Jul 11 '26 21:07 SolitaryThinker