Repository navigation
Conversation
|
Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA). View this failed invocation of the CLA check for more information. For the most up to date status, view the checks section at the bottom of the pull request. |
There was a problem hiding this comment.
Code Review
This pull request adds support for FlyWheel Attention (flywheel and ulysses_flywheel backends) for Wan self-attention on TPU v6e and tpu7x, including documentation, configuration updates, and comprehensive unit tests. The feedback suggests an optimization in _flywheel_attention to avoid unnecessary padding and copying of Key and Value tensors when Ulysses is not used.
fd3866d to
98d651e
Compare
Add `attention=flywheel` and `attention=ulysses_flywheel`, which run Wan self-attention on the FlyWheel Pallas varlen kernel (flywheel-tpu on PyPI) instead of Splash. `flywheel` follows the `flash` sharding and `ulysses_flywheel` follows the `ulysses` sharding. Cross-attention stays on Splash. The backend is inference only. Attention masks, causal attention, GQA and non-bf16 inputs raise instead of falling back to another kernel. flywheel-tpu is an optional extra, imported only when one of the two kernels is selected. Developed together with Yucheng Lu (@EugeneLYC).
98d651e to
75e3e1d
Compare
entrpn
left a comment
There was a problem hiding this comment.
Thanks @Deepolar for the clean PR, lazy optional import, and thorough guard/numerical tests!
Before deciding on adding a new external optional dependency (flywheel-tpu) to pyproject.toml, could you rebase onto current main and share an apples-to-apples benchmark comparison against the in-tree custom Ulysses stack that landed recently (attention="ulysses_custom_fixed_m_per_q_block", wan_ulysses_out_a2a="chunked", wan_seq_pad="lane", use_fused_rope_kernel=True; see end_to_end/tpu/run_wan_fast_inference.sh)?
On the earlier base commit this branch was measured against, stock attention="ulysses" on v6e-4 (DP=1, CP=4, CFG B=2) did not yet have the [B, H, S, D] -> [1, B*H, S, D] batch-fold around all_to_all or the custom fixed_m Pallas kernel (current main runs Wan 2.2 A14B 720p/81f/40 steps in ~125s on v6e-8 DP=2, CP=4, or ~250s at 4-chip DP=1, CP=4 parity, vs 457.3s on old ulysses). Seeing how flywheel / ulysses_flywheel compares against ulysses_custom_fixed_m_per_q_block on v6e-1 and v6e-4 / tpu7x after rebasing will help us evaluate whether an external package extra is still needed.
Also left three concrete comments inline on token_padding handling, attention_sharding_uniform=False sharding validation, and folding the CFG batch before all_to_all.
| f"sharded over '{CONTEXT}'. Use ulysses_flywheel for sequence-sharded K/V." | ||
| ) | ||
|
|
||
| query, orig_q_seq_len = _reshape_data_for_flash(query, heads, num_shards) |
There was a problem hiding this comment.
When use_ulysses=False and attention_sharding_uniform=False (base_wan_*.yml maps activation_self_attn_heads to ('context', 'tensor') and leaves SELF_ATTN_Q_LENGTH unsharded unless pyconfig.py adds SEQUENCE_PARALLEL_AXIS_RULES), q_axis_names[2] is None while q_axis_names[1] shards heads across context. Passing num_shards unconditionally here pads an unsharded sequence axis on query, and jax.shard_map below fails with an opaque axis-divisibility ValueError whenever heads % context != 0 (e.g., Wan 2.1 1.3B heads=12 on context=8).
Please check _mesh_axis_in_spec(q_axis_names[1], CONTEXT) up front on the use_ulysses=False path (raising a clear ValueError pointing to attention_sharding_uniform=True or ulysses_flywheel), or gate query sequence padding on _mesh_axis_in_spec(q_axis_names[2], CONTEXT).
| def local_attention(q, k, v): | ||
| if use_ulysses: | ||
| # [b, h, S/N, d] -> [b, h/N, S, d]: give up heads, gather the sequence. | ||
| q = jax.lax.all_to_all(q, axis_name=CONTEXT, split_axis=1, concat_axis=2, tiled=True) |
There was a problem hiding this comment.
Perf note for v6e-4 (DP=1, CP=4) with CFG (B=2): running the 4D all_to_all on [b, h, S/N, d] with b=2 before folding b * h on line 1337 causes XLA on TPU to place the size-2 batch dimension in tile sublanes (T(2, 128) instead of T(8, 128)), adding expensive relayouts around the collectives inside the scanned layers.
See _ulysses_attention on current main (fold_batch when batch > 1, devices_in_batch_sharding == 1, and (batch * heads) % num_shards == 0), which reshapes [B, H, S, D] -> [1, B*H, S, D] outside shard_map before the Ulysses all_to_all.
|
|
||
|
|
||
| @register_kernel("flywheel") | ||
| def flywheel_kernel(q, k, v, context): |
There was a problem hiding this comment.
NNXAttentionOp.apply_attention passes token_padding in context (from wan_seq_pad='lane' on main), and every registered kernel outside TOKEN_PADDING_KERNELS forwards token_padding=context.get('token_padding') and calls _reject_token_padding(...) (matching flash_kernel, tokamax_flash_kernel, and wan_seq_pad_test.py).
Right now both flywheel_kernel and ulysses_flywheel_kernel drop context.get('token_padding'), so a direct kernel call with active TokenPadding passes the padded orig_kv_seq_len into cu_seqlens_k and silently attends to tail pad tokens. Please thread token_padding=context.get('token_padding') into both wrappers and either reject it via _reject_token_padding or validate _resolve_token_padding(token_padding, orig_kv_seq_len, num_segments=1, q_seq_len=orig_q_seq_len) and use token_padding.real_len for cu_seqlens_k.
Summary
Adds
attention=flywheelandattention=ulysses_flywheel. Both run Wan self-attention on theFlyWheel Pallas kernel (
flash_attn_varlen_func,flywheel-tpu>=0.4.1on PyPI) instead of Splash. Cross-attention, RoPE and QK-norm are unchanged.The backend is for inference only, because the kernel has no backward pass. It targets TPU v6e and tpu7x.
On one v6e chip, Wan 2.1 T2V 1.3B at 480p / 81 frames generates in 54.0 s instead of 63.3 s (1.17x).
On one tpu7x chip, it generates in 23.8 s instead of 28.0 s (1.18x).
On v6e-4, Wan 2.2 A14B at 720p is 1.25x faster with
flywheeland 1.28x withulysses_flywheel.What's in it
attention_flax.py:_flywheel_attentionplus two registry entries.flywheeluses theflashsharding: q is sequence-sharded oncontextand every device holds thefull K/V. If K/V is sequence-sharded, the call raises and points the user to
ulysses_flywheel.ulysses_flywheeluses theulyssessharding: an all-to-all around the kernel, the implicitUlysses-degree check (
ulysses_shards), andulysses_attention_chunks.cu_seqlens = [0, len].Rows of K/V beyond the real length are never attended, and this includes the context-axis padding.
Lengths that are not a multiple of 128 therefore need no mask.
instead of falling back to another kernel.
jax.gradraisesNotImplementedErrorfrom the kernel.flash_min_seq_lengththe wayflashdoes.FlaxWanAttentionmaps both names toflashfor cross-attention. The I2V image mask therefore stays on Splash.pyproject.tomlgets an optional extra,flywheel.flywheel_tpuis imported only when oneof the two kernels is selected.
attentioncomments in the Wan yml files, a README section, and the newtest file added to
end_to_end/tpu/run_wan_stack_tests.sh.Known limitations
Scope: this PR replaces Splash in Wan self-attention, the dominant attention cost at inference.
Wider coverage is left to follow-ups.
cu_seqlens), not mask arrays, so masks need aconversion that is planned together with cross-attention;
repo uses them.
Performance
Wan 2.1 T2V 1.3B, 480x832, 81 frames, 30 steps, CFG, seed 0, TPU v6e-1, average of 2 runs (spread < 0.2%):
flashflashflashflywheelNotes on the baseline:
enable_tile_search=truefailed on every candidate for this shape, so the Splash tilings above were set by hand.gives PSNR 25.1 dB, SSIM 0.879.
Same setup on one tpu7x chip (two TensorCores, context-sharded,
per_device_batch_size=0.5),average of 2 runs (spread < 3%):
flashflashflashflywheelThe Splash tilings are the v6e ones, not retuned for tpu7x. These runs add the MagCache keys that
base_wan_1_3b.ymllacks on main (#527), with MagCache off.Wan 2.2 T2V A14B, 81 frames, 40 steps, TPU v6e-4 with
ici_context_parallelism=4, batch 1,Splash tiling tuned per resolution:
flashvsflywheelulyssesvsulysses_flywheelflashvsflywheelulyssesvsulysses_flywheelTests
flywheel_attention_test.pyhas 19 tests:against an fp32 reference (observed error about 3e-3 against a 1e-2 tolerance). They cover:
jax.grad;FlaxWanAttentionflash-vs-flywheel parity check;ulysses_attention_chunks=2.Results:
flywheel_attention_test.pyon TPU v6e-4: 19 passed.flywheel_attention_test.pyon TPU v6e-1: 17 passed, 2 skipped (the two 4-device tests).flywheel_attention_test.pyon tpu7x (4 chips): 19 passed.cross_attention_pallas_test,ulysses_out_a2a_test,wan_patch_embed_testandwan_seq_pad_test, on tpu7x: 159 passed, 1 skipped on both this branch andmain.attention_test,attention_config_guards_test,attention_block_sizes_test,dot_fallback_layout_test,wan_runtime_options_test,wan/wan_transformer_test) on TPU v6e-1, with the sameresults on this branch and on
main: 78 passed, 8 skipped, 5 failed. The 5 failures areattention_testUlysses tests whose_ulysses_mesh()needs 2 devices and has no skip guard.Joint work with Yucheng Lu (EugeneLYC).