Skip to content

feat(attention): FlyWheel self-attention backend for Wan inference on TPU - #523

Open
Deepolar wants to merge 1 commit into
AI-Hypercomputer:mainfrom
Deepolar:feat/flywheel-attention
Open

Deepolar wants to merge 1 commit into
AI-Hypercomputer:mainfrom
Deepolar:feat/flywheel-attention

Conversation

@Deepolar

@Deepolar Deepolar commented Nov 15, 2026 •

Copy link
Copy Markdown

Summary

Adds attention=flywheel and attention=ulysses_flywheel. Both run Wan self-attention on the
FlyWheel Pallas kernel (flash_attn_varlen_func,
flywheel-tpu>=0.4.1 on 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 flywheel and 1.28x with ulysses_flywheel.

What's in it

  • attention_flax.py: _flywheel_attention plus two registry entries.
    • flywheel uses the flash sharding: q is sequence-sharded on context and every device holds the
      full K/V. If K/V is sequence-sharded, the call raises and points the user to ulysses_flywheel.
    • ulysses_flywheel uses the ulysses sharding: an all-to-all around the kernel, the implicit
      Ulysses-degree check (ulysses_shards), and ulysses_attention_chunks.
    • Each device makes one varlen call, with the batch folded into the head axis and 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.
    • Unsupported inputs: an attention mask, causal attention, GQA, or non-bf16 q/k/v raise an error
      instead of falling back to another kernel. jax.grad raises NotImplementedError from the kernel.
    • Both kernel names respect flash_min_seq_length the way flash does.
    • FlaxWanAttention maps both names to flash for cross-attention. The I2V image mask therefore stays on Splash.
  • Packaging: pyproject.toml gets an optional extra, flywheel. flywheel_tpu is imported only when one
    of the two kernels is selected.
  • Configs, docs, test runner: attention comments in the Wan yml files, a README section, and the new
    test 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.

  • Inference only, no backward pass.
  • Wired and tested for Wan only. Other models' attention modules do not map cross-attention back to Splash.
  • Cross-attention stays on Splash. At 480p / 81 frames it is about 1.6% of the self-attention FLOPs.
  • Unsupported inputs raise:
    • bf16 only, as the kernel requires;
    • no attention masks: the kernel takes lengths (cu_seqlens), not mask arrays, so masks need a
      conversion that is planned together with cross-attention;
    • no causal attention or GQA: the kernel supports both, but they are not wired because no DiT in the
      repo uses them.
  • Supported on TPU v6e and tpu7x only, which are the targets FlyWheel supports.

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%):

Attention Splash tiling (bq/bkv/bkv_compute) Denoise Generate vs Splash
flash 512/512/512 (yml default) 88.3 s 92.8 s
flash 3024/2048/1024 60.6 s 65.1 s
flash 2048/4096/1024 58.8 s 63.3 s baseline
flywheel n/a 49.5 s 54.0 s 1.17x

Notes on the baseline:

  • enable_tile_search=true failed on every candidate for this shape, so the Splash tilings above were set by hand.
  • Video quality, flywheel vs Splash (2048/4096/1024): PSNR 25.0 dB, SSIM 0.880.
  • For comparison, Splash 512 vs Splash 2048/4096/1024 (the same kernel with only the tiling changed)
    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%):

Attention Splash tiling (bq/bkv/bkv_compute) Denoise Generate vs Splash
flash 512/512/512 (yml default) 44.1 s 47.6 s
flash 3024/2048/1024 27.4 s 30.3 s
flash 2048/4096/1024 25.1 s 28.0 s baseline
flywheel n/a 21.0 s 23.8 s 1.18x

The Splash tilings are the v6e ones, not retuned for tpu7x. These runs add the MagCache keys that
base_wan_1_3b.yml lacks 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:

Resolution Sharding Splash FlyWheel Speedup
480x832 flash vs flywheel 124.0 s 108.8 s 1.14x
480x832 ulysses vs ulysses_flywheel 116.6 s 98.2 s 1.19x
1280x720 flash vs flywheel 501.4 s 401.8 s 1.25x
1280x720 ulysses vs ulysses_flywheel 457.3 s 357.8 s 1.28x

Tests

flywheel_attention_test.py has 19 tests:

  • Without flywheel-tpu (these run in CI): 8 guard tests and 2 Wan wiring tests.
  • Need flywheel-tpu on v6e or tpu7x: 9 numerical tests, 2 of which also need 4 devices. They compare
    against an fp32 reference (observed error about 3e-3 against a 1e-2 tolerance). They cover:
    • a single device and a single device under Ulysses;
    • a length that is not a multiple of 128, and batch 1;
    • prescaled K;
    • the error raised by jax.grad;
    • a FlaxWanAttention flash-vs-flywheel parity check;
    • 4-way context and Ulysses sharding with context padding and ulysses_attention_chunks=2.

Results:

  • flywheel_attention_test.py on TPU v6e-4: 19 passed.
  • flywheel_attention_test.py on TPU v6e-1: 17 passed, 2 skipped (the two 4-device tests).
  • flywheel_attention_test.py on tpu7x (4 chips): 19 passed.
  • Regression set plus cross_attention_pallas_test, ulysses_out_a2a_test, wan_patch_embed_test and
    wan_seq_pad_test, on tpu7x: 159 passed, 1 skipped on both this branch and main.
  • Regression set (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 same
    results on this branch and on main: 78 passed, 8 skipped, 5 failed. The 5 failures are
    attention_test Ulysses tests whose _ulysses_mesh() needs 2 devices and has no skip guard.
  • pyink, ruff and pylint pass on the changed files.

Joint work with Yucheng Lu (EugeneLYC).

@Deepolar
Deepolar requested a review from entrpn as a code owner November 15, 2026 03:09
@google-cla

google-cla Bot commented Nov 15, 2026

Copy link
Copy Markdown

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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@Deepolar
Deepolar force-pushed the feat/flywheel-attention branch 2 times, most recently from fd3866d to 98d651e Compare November 16, 2026 06:18
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).
@Deepolar
Deepolar force-pushed the feat/flywheel-attention branch from 98d651e to 75e3e1d Compare November 23, 2026 23:48

@entrpn entrpn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants