Skip to content

perf(wan): batch-sharded cross-attn KV cache and batch-aware VAE mesh - #519

Merged
copybara-service[bot] merged 1 commit into
mainfrom
perf/wan-batch-sharded-kv-cache-vae-mesh
Nov 23, 2026
Merged

copybara-service[bot] merged 1 commit into
mainfrom
perf/wan-batch-sharded-kv-cache-vae-mesh

Conversation

@Perseus14

@Perseus14 Perseus14 commented Oct 25, 2026 •

Copy link
Copy Markdown
Collaborator

Two memory fixes for Wan 2.2 T2V at per-device batch >= 1, from a B=1..16 batch-scaling sweep at 720p / 81 frames / 40 steps on v6e-8 and tpu7x-8.

1. Cross-attention KV cache is batch-sharded and scanned (transformer_wan.py)

compute_kv_cache ran an eager nnx.vmap over all 40 layers on replicated prompt embeds, so every device materialised the full CFG-doubled cache plus the FP32 RMSNorm temporaries for every layer at once (~6.8 GiB per video per device at 720p). It is now a single jitted executable that pins the batch axis to ('data', 'fsdp') on input and output and nnx.scans the layers one at a time. The cross-attention consumer already re-constrains K/V to (BATCH, CROSS_ATTN_HEAD, None, D_KV), so nothing is resharded at use time — each device simply holds its own B_local slice.

If the batch is not divisible by data * fsdp (e.g. data_parallelism > 1 with per_device_batch_size = 1 and CFG off — the same case the pipelines already tolerate for the CFG cache), the batch constraint is skipped and the cache stays replicated, as before. Skipping keeps that case explicit instead of depending on how with_sharding_constraint treats a non-divisible axis (JAX 0.11: it raises eagerly and drops the axis under jit).

The batch mesh axes are resolved from the ambient axis_rules in compute_kv_cache, outside the jit, and passed to it as a static argument. axis_rules is thread-local state and not part of the jit cache key, so reading it at trace time would let one call under different rules (or none) decide the sharding of every later call with the same inputs.

WanModel.compute_kv_cache is shared, so the i2v pipelines get the same cache layout. VACE has its own compute_kv_cache and is unchanged.

2. vae_spatial=-1 picks a batch-aware VAE mesh for T2V inference (wan_pipeline.py)

The VAE mesh is ('redundant', 'vae_spatial'); batch is sharded on redundant, and the longer spatial axis (height for portrait videos, width otherwise) / conv channels on vae_spatial. With the old auto value (vae_spatial = N) the batch axis is fully replicated, so at B = N every chip holds all N videos' activations and the causal conv stack pays ~10x (and OOMs on 32 GiB parts). Auto now resolves to (N, 1) — one video per device, no cross-chip collectives — when the global batch is a multiple of the device count, and to the unchanged (1, N) otherwise. Mixed meshes were measured and are not a win (at B=2 on v6e-8, (2, 4) needed a 21.2 GiB decode program vs 15.5 GiB for (1, 8)). An explicit vae_spatial still overrides.

This is opt-in at load time, and generate_wan.py opts in for T2V. batch_parallel_vae is an argument on from_pretrained / from_checkpoint and on the WanCheckpointer loaders, forwarded only when set. With the base configs (vae_spatial: -1, integer per_device_batch_size) T2V inference through generate_wan.py therefore gets (N, 1). Everything else that loads a T2V pipeline keeps the (1, N) mesh: dataset preprocessing (which VAE-encodes its own batch sizes), the trainers, and tests.

Scope: only the T2V pipelines (wan_pipeline_2_1, wan_pipeline_2_2) support the argument. The VAE constrains every activation to P('redundant', …, 'vae_spatial', …); on a (N, 1) mesh the batch axis is the only sharded one, so every tensor that goes through the VAE needs a batch divisible by N. That holds for T2V inference (the only VAE call is the final full-batch decode) but not for VACE (reference images are encoded one at a time, [1, 1, H, W, C]) or the i2v / animate conditioning encodes. Those pipelines reject the argument (_supports_batch_parallel_vae; VACE subclasses the T2V pipeline and opts out explicitly) and keep the previous (1, N) mesh, so nothing changes for them.

Fail fast: check_vae_batch_is_shardable raises a ValueError for a batch that does not divide N on a (N, 1) mesh, instead of running it replicated on every chip. It is checked in VAE encode, in _decode_latents_to_video, and in the T2V __call__ right after input preparation, so a short batch fails before denoising. Meshes with vae_spatial > 1 are not affected: there an indivisible batch only loses its batch sharding and stays spatially sharded. generate_wan.py always pads to the full batch.

Measurements (before rebasing onto current main; DP=2, CP=4, use_kv_cache=true unless noted)

Platform B Compile Denoise VAE decode (TPU) Peak HBM / device
tpu7x-8 2 main 229.9s 270.5s 2.2s 27.49 GiB
tpu7x-8 2 this PR 193.0s 269.8s 2.2s 16.65 GiB
tpu7x-8 8 main 265.8s 897.8s 41.6s 68.12 GiB
tpu7x-8 8 this PR 233.7s 893.4s 6.3s 24.32 GiB
v6e-8 (DP=1, FSDP=2, CP=4, vae_decode_chunk=1) 8 main — — — OOM in compute_kv_cache (6.25 GiB alloc, 4.99 GiB free)
v6e-8 (same) 8 this PR 192.2s 1302.6s 4.8s 17.41 GiB — completes

Denoise time is unchanged within noise; the wins are −64% peak HBM and 6.6x faster VAE decode at B=8 on tpu7x-8, and B=8 with the KV cache becoming possible at all on v6e-8.

Validation

New tests/wan/wan_vae_mesh_test.py (4 host devices on CPU):

  • _auto_vae_spatial table for B in {0,1,2,3,4,8,12,16} with the gate on and off.
  • Only the T2V pipelines support batch_parallel_vae, and from_pretrained / from_checkpoint only pass it when asked to.
  • _batch_sharding / _shard_kv_cache_on_batch layout checks, including the non-divisible-batch fallback.
  • compute_kv_cache on a tiny scan_layers WanModel under the production logical axis rules, against the eager nnx.vmap it replaced: f32 and bf16, batch divisible and not divisible by data * fsdp. It also checks that the batch axis stays sharded and that the cached forward pass matches the uncached one.
  • The KV cache sharding following the axis_rules of each call rather than a previously cached executable.
  • check_vae_batch_is_shardable, _decode_latents_to_video and the T2V __call__ rejecting a batch that does not divide a (N, 1) mesh.

Other notes:

  • wan_checkpointer_test.py covers the loaders forwarding batch_parallel_vae.
  • generate_wan_smoke_test.py now loads the way generate_wan.py does (gate on, full batch), so CI exercises the batch-parallel decode on TPU.
  • wan_kv_cache_test.py is TPU-only (attention=flash); not runnable on CPU before or after this change.
  • pyink clean. The branch is rebased onto current main, which fixed the two unrelated files the Linter workflow was failing on.

@Perseus14
Perseus14 requested a review from entrpn as a code owner October 25, 2026 11:22
@github-actions

Copy link
Copy Markdown

@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 optimizes memory usage and performance for the Wan model by replacing eager nnx.vmap with a jitted, scanned, and batch-sharded implementation (_scanned_compute_kv) for cross-attention KV cache computation. It also introduces dynamic vae_spatial mesh extent selection in the VAE pipeline to prevent OOMs and improve decoding speed. A critical issue was identified in the JIT compilation of _scanned_compute_kv, where blocks_graphdef must be marked as a static argument to avoid a JAX TypeError since it is not a valid JAX PyTree.

@Perseus14
Perseus14 force-pushed the perf/wan-batch-sharded-kv-cache-vae-mesh branch from 2a78845 to 182357d Compare October 25, 2026 20:23
@Perseus14 Perseus14 self-assigned this Oct 25, 2026
@Perseus14
Perseus14 force-pushed the perf/wan-batch-sharded-kv-cache-vae-mesh branch from 182357d to 98ea89f Compare October 25, 2026 23:18
@Perseus14
Perseus14 force-pushed the perf/wan-batch-sharded-kv-cache-vae-mesh branch from 98ea89f to 2b7e2bb Compare November 20, 2026 09:32
@Perseus14
Perseus14 requested a review from mbohlool November 20, 2026 11:44
@Perseus14
Perseus14 force-pushed the perf/wan-batch-sharded-kv-cache-vae-mesh branch from 6a91b43 to 4ac4bbf Compare November 20, 2026 12:29

@mbohlool mbohlool 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.

Nice memory win. Main ask: fail fast when the decode batch doesn't divide the batch-parallel VAE mesh.

@Perseus14
Perseus14 force-pushed the perf/wan-batch-sharded-kv-cache-vae-mesh branch 2 times, most recently from 06cd3dc to 947eb99 Compare November 20, 2026 22:00
mbohlool
mbohlool previously approved these changes Nov 21, 2026

@mbohlool mbohlool 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.

just one nit. LGTM otherwise.


def _decode_latents_to_video(self, latents: jax.Array, trace: Optional[dict] = None) -> np.ndarray:
"""Decodes latents to video frames and postprocesses."""
if self.vae_mesh is not None and hasattr(self.vae_mesh, "shape"):

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.

nit: self.vae_mesh is always a Mesh (L520) and L1001 enters it right after, so the is not None and hasattr(self.vae_mesh, "shape") guard can go.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in fe4aa3d4 — dropped the guard; self.vae_mesh is always a Mesh there.

csgoogle
csgoogle previously approved these changes Nov 21, 2026
@Perseus14
Perseus14 dismissed stale reviews from csgoogle and mbohlool via 04f3eb7 November 21, 2026 19:16
@Perseus14
Perseus14 force-pushed the perf/wan-batch-sharded-kv-cache-vae-mesh branch 2 times, most recently from 04f3eb7 to fe4aa3d Compare November 21, 2026 19:21
csgoogle
csgoogle previously approved these changes Nov 21, 2026

@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.

Nice HBM and VAE decode speedup! Found two issues that need a quick fix before merging (plus one fail-fast suggestion):

  1. _scanned_compute_kv reads nn.logical_to_mesh_axes((BATCH,)) inside @jax.jit, where Flax's thread-local axis_rules context is not part of JAX's jit cache key.
  2. WanPipeline2_1 sets batch_parallel_vae=True, which also affects WanCheckpointer2_1 callers that run vae.encode (wan_txt2vid_data_preprocessing.py and data_processing_test.py).

@Perseus14
Perseus14 force-pushed the perf/wan-batch-sharded-kv-cache-vae-mesh branch from fe4aa3d to 6347d1a Compare November 21, 2026 21:33
Two memory fixes for Wan 2.2 T2V at per-device batch >= 1, motivated by a
batch-scaling sweep (B=1..16) at 720p/81f/40 steps on v6e-8 and tpu7x-8.

1. Cross-attention KV cache (transformer_wan.py)

   compute_kv_cache ran an eager nnx.vmap over all 40 layers on replicated
   prompt embeds, so every device materialised the full CFG-doubled cache
   plus the FP32 RMSNorm temporaries for every layer at once. It is now one
   jitted executable that pins the batch axis to ('data', 'fsdp') on input
   and output and scans the layers one at a time. The cross-attn consumer
   already re-constrains K/V to that layout, so nothing is resharded at use
   time; each device just holds its own B_local slice.

   If the batch is not divisible by data * fsdp (e.g. data_parallelism > 1
   with per_device_batch_size = 1 and CFG off, the case the pipelines
   already tolerate for the CFG cache) the batch constraint is skipped and
   the cache stays replicated as before. Skipping keeps that case explicit
   instead of depending on how with_sharding_constraint treats a
   non-divisible axis (JAX 0.11: it raises eagerly and drops the axis under
   jit).

   The batch mesh axes are resolved from the ambient axis_rules in
   compute_kv_cache, outside the jit, and passed to it as a static argument.
   axis_rules is thread-local state and not part of the jit cache key, so
   reading it at trace time would let one call under different rules (or
   none) decide the sharding of every later call with the same inputs.

   WanModel.compute_kv_cache is shared, so the i2v pipelines get the same
   cache layout. VACE has its own compute_kv_cache and is unchanged.

   Sharding the 512-token text axis on 'context' as well was tried and
   rejected: XLA hoists the per-layer all-gather out of the layer scan, so
   the forward program's reservation grew by 5.8 GiB (net loss on v6e-8).

2. VAE mesh (wan_pipeline.py), T2V inference only

   With vae_spatial=-1 (auto) the VAE mesh is now ('redundant', 'vae_spatial')
   = (N, 1) when the global batch is a multiple of the device count N, i.e.
   one video per device with no cross-chip collectives, and (1, N) otherwise
   (unchanged). Mixed meshes were measured and are not a win: at B=2 on
   v6e-8 a (2, 4) mesh needed a 21.2 GiB decode program vs 15.5 GiB for
   (1, 8). An explicit vae_spatial still overrides.

   The batch-aware choice is opt-in at load time: a batch_parallel_vae
   argument on from_pretrained / from_checkpoint and on the WanCheckpointer
   loaders, forwarded only when set. generate_wan.py sets it for T2V, so
   with the base configs (vae_spatial: -1, integer per_device_batch_size)
   T2V inference gets (N, 1). Everything else that loads a T2V pipeline
   (dataset preprocessing, which VAE-encodes its own batch sizes, the
   trainers, tests) keeps the (1, N) mesh.

   The VAE constrains activations to P('redundant', ..., 'vae_spatial', ...);
   on a (N, 1) mesh the batch axis is the only sharded one, so every tensor
   through the VAE needs a batch divisible by N. That holds for T2V
   inference (only the final full-batch decode) but not for VACE (reference
   images encoded one at a time, [1, 1, H, W, C]) or the i2v / animate
   conditioning encodes; those pipelines reject the argument
   (_supports_batch_parallel_vae; VACE subclasses the T2V pipeline and opts
   out explicitly).

   check_vae_batch_is_shardable raises a ValueError for a batch that does
   not divide N on such a mesh, instead of running it replicated on every
   chip: in VAE encode, in _decode_latents_to_video, and in the T2V
   __call__ right after input preparation so a short batch fails before
   denoising. Meshes with vae_spatial > 1 are not affected; there an
   indivisible batch only loses its batch sharding.

Tests: new tests/wan/wan_vae_mesh_test.py (4 host devices on CPU):
- the _auto_vae_spatial table for B in {0..16}, gated and ungated;
- only the T2V pipelines support the gate, and the loaders only pass it
  when asked to;
- _batch_sharding / _shard_kv_cache_on_batch layouts including the
  non-divisible fallback;
- compute_kv_cache on a tiny scan_layers WanModel under the production
  logical axis rules against the eager nnx.vmap it replaced (f32 and bf16,
  batch divisible and not divisible by data * fsdp), including that the
  batch axis stays sharded and that the cached forward matches the
  uncached one.
- the KV cache sharding following the axis_rules of each call rather than
  a previously cached executable;
- check_vae_batch_is_shardable, _decode_latents_to_video and the T2V
  __call__ rejecting a batch that does not divide a (N, 1) mesh.

wan_checkpointer_test.py covers the loaders forwarding batch_parallel_vae.
generate_wan_smoke_test.py now loads the way generate_wan.py does (gate on,
full batch), so CI exercises the batch-parallel decode on TPU.

Measured before rebasing onto current main (DP=2, CP=4 unless noted,
use_kv_cache=true):

  tpu7x-8  B=2  peak HBM 27.49 -> 16.65 GiB, denoise 270.5 -> 269.8 s
  tpu7x-8  B=8  peak HBM 68.12 -> 24.32 GiB, VAE decode 41.6 -> 6.3 s,
                denoise 897.8 -> 893.4 s
  v6e-8    B=8  (DP=1, FSDP=2, CP=4, vae_decode_chunk=1) main OOMs in
                compute_kv_cache (6.25 GiB alloc, 4.99 GiB free); with this
                change it completes: peak 17.41 GiB, denoise 1302.6 s,
                VAE decode 4.8 s.
@Perseus14
Perseus14 force-pushed the perf/wan-batch-sharded-kv-cache-vae-mesh branch from 6347d1a to d1e5aa6 Compare November 23, 2026 08:34

@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 @Perseus14! Verified all three updates (_batch_mesh_axes resolved outside @jax.jit, opt-in batch_parallel_vae preserving the (1, N) spatial VAE mesh for preprocessing/checkpointer/other pipelines, and the pre-denoise check_vae_batch_is_shardable guard). LGTM!

@copybara-service
copybara-service Bot merged commit 6629957 into main Nov 23, 2026
54 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants