diff --git a/src/maxdiffusion/checkpointing/wan_checkpointer.py b/src/maxdiffusion/checkpointing/wan_checkpointer.py index 6ebb5bab7..f19cf17a6 100644 --- a/src/maxdiffusion/checkpointing/wan_checkpointer.py +++ b/src/maxdiffusion/checkpointing/wan_checkpointer.py @@ -60,15 +60,18 @@ def _create_optimizer(self, model, config, learning_rate): @classmethod def load_pretrained_pipeline_or_diffusers( - cls, config, pipeline_cls, pretrained_state_sources, pretrained_config_transformer_attr + cls, config, pipeline_cls, pretrained_state_sources, pretrained_config_transformer_attr, batch_parallel_vae=False ): """Load a WAN pipeline from the pretrained Orbax cache, or seed it from diffusers. This helper is used only for inference when no training checkpoint exists. `pretrained_config_transformer_attr` is explicit because WAN 2.2 has separate transformer states but still saves one `wan_config`, matching the existing - training checkpoint format. + training checkpoint format. `batch_parallel_vae` opts T2V inference into + the batch-parallel VAE mesh (see `WanPipeline._auto_vae_spatial`); it is + only forwarded when set. """ + vae_kwargs = {"batch_parallel_vae": True} if batch_parallel_vae else {} pretrained_dir = getattr(config, "pretrained_orbax_dir", "") if pretrained_dir: restored_checkpoint = cls._restore_pretrained_checkpoint( @@ -76,10 +79,10 @@ def load_pretrained_pipeline_or_diffusers( ) if restored_checkpoint is not None: max_logging.log(f"Loading WAN pipeline from pretrained orbax checkpoint at {pretrained_dir}") - return pipeline_cls.from_checkpoint(config, restored_checkpoint) + return pipeline_cls.from_checkpoint(config, restored_checkpoint, **vae_kwargs) max_logging.log("No checkpoint found, loading default pipeline.") - pipeline = pipeline_cls.from_pretrained(config) + pipeline = pipeline_cls.from_pretrained(config, **vae_kwargs) if pretrained_dir: cls._save_pretrained_checkpoint(pretrained_dir, pipeline, pretrained_state_sources, pretrained_config_transformer_attr) return pipeline @@ -184,6 +187,7 @@ def load_diffusers_checkpoint( load_text_encoder=None, load_transformer=None, load_scheduler=None, + batch_parallel_vae=False, ) -> T: pipeline = self.pipeline_class.from_pretrained( self.config, @@ -192,6 +196,7 @@ def load_diffusers_checkpoint( load_text_encoder=load_text_encoder, load_transformer=load_transformer, load_scheduler=load_scheduler, + **({"batch_parallel_vae": True} if batch_parallel_vae else {}), ) return pipeline @@ -203,7 +208,14 @@ def load_checkpoint( load_text_encoder=None, load_transformer=None, load_scheduler=None, + batch_parallel_vae=False, ) -> Tuple[T, Optional[dict], Optional[int]]: + """Loads the pipeline from a training checkpoint, or from diffusers if there is none. + + `batch_parallel_vae` opts T2V inference into the batch-parallel VAE mesh + (see `WanPipeline._auto_vae_spatial`); it is only forwarded when set. + """ + vae_kwargs = {"batch_parallel_vae": True} if batch_parallel_vae else {} restored_checkpoint, step = self.load_wan_configs_from_orbax(step) opt_state = None if restored_checkpoint: @@ -216,6 +228,7 @@ def load_checkpoint( load_text_encoder=load_text_encoder, load_transformer=load_transformer, load_scheduler=load_scheduler, + **vae_kwargs, ) opt_state = self._extract_opt_state(restored_checkpoint) else: @@ -226,6 +239,7 @@ def load_checkpoint( load_text_encoder=load_text_encoder, load_transformer=load_transformer, load_scheduler=load_scheduler, + **vae_kwargs, ) return pipeline, opt_state, step diff --git a/src/maxdiffusion/generate_wan.py b/src/maxdiffusion/generate_wan.py index f5f08a32a..5d2ef7f13 100644 --- a/src/maxdiffusion/generate_wan.py +++ b/src/maxdiffusion/generate_wan.py @@ -526,15 +526,19 @@ def run(config, pipeline=None, filename_prefix="", commit_hash=None): checkpoint_loader = WanCheckpointer2_2(config=config) else: raise ValueError(f"Unsupported model_name for checkpointer: {model_key}") + # T2V inference always decodes the full (padded) batch, so it can use the + # batch-parallel VAE mesh; see WanPipeline._auto_vae_spatial. + batch_parallel_vae = pipeline_cls._supports_batch_parallel_vae # pylint: disable=protected-access checkpoint_step = checkpoint_loader.checkpoint_manager.latest_step() if checkpoint_step is not None: - pipeline, _, _ = checkpoint_loader.load_checkpoint(checkpoint_step) + pipeline, _, _ = checkpoint_loader.load_checkpoint(checkpoint_step, batch_parallel_vae=batch_parallel_vae) else: pipeline = checkpoint_loader.load_pretrained_pipeline_or_diffusers( config, pipeline_cls, pretrained_state_sources, pretrained_config_transformer_attr, + batch_parallel_vae=batch_parallel_vae, ) load_time = time.perf_counter() - load_start max_logging.log(f"load_time: {load_time:.1f}s") diff --git a/src/maxdiffusion/models/wan/autoencoder_kl_wan.py b/src/maxdiffusion/models/wan/autoencoder_kl_wan.py index 00e80857a..73ed6348c 100644 --- a/src/maxdiffusion/models/wan/autoencoder_kl_wan.py +++ b/src/maxdiffusion/models/wan/autoencoder_kl_wan.py @@ -48,6 +48,27 @@ def _update_cache(cache, idx, value): return cache[:idx] + (value,) + cache[idx + 1 :] +def check_vae_batch_is_shardable(mesh: Optional[jax.sharding.Mesh], batch_size: int, what: str) -> None: + """Raises if a VAE batch would run fully replicated on a batch-parallel mesh. + + On a ('redundant', 'vae_spatial') == (N, 1) mesh the batch axis is the only + sharded one. A batch that is not a multiple of N cannot be sharded on it, + so under jit the constraint is dropped and every device runs the whole + batch (outside jit it raises an IndivisibleError deep in the conv stack). + Meshes with vae_spatial > 1 are fine: there an indivisible batch only loses + its batch sharding and stays spatially sharded. + """ + if mesh is None: + return + redundant = mesh.shape.get("redundant", 1) + if redundant > 1 and mesh.shape.get("vae_spatial", 1) == 1 and batch_size % redundant != 0: + raise ValueError( + f"VAE {what} batch size ({batch_size}) must be divisible by the 'redundant' mesh axis ({redundant}) on the " + f"batch-parallel vae_mesh={dict(mesh.shape)}, which has no spatial sharding. Pass a full batch matching " + "global_batch_size_to_train_on, set vae_spatial explicitly, or load the pipeline without batch_parallel_vae." + ) + + def _spatial_sharding( mesh: Optional[jax.sharding.Mesh], shape: Sequence[int], batch_axis: Optional[str] = "redundant" ) -> Optional[NamedSharding]: @@ -1281,6 +1302,7 @@ def encode( self, x: jax.Array, feat_cache: AutoencoderKLWanCache, return_dict: bool = True ) -> Union[FlaxAutoencoderKLOutput, Tuple[FlaxDiagonalGaussianDistribution]]: """Encode video into latent distribution.""" + check_vae_batch_is_shardable(self.mesh, x.shape[0], "encode") h = self._encode(x, feat_cache) posterior = WanDiagonalGaussianDistribution(h) if not return_dict: diff --git a/src/maxdiffusion/models/wan/autoencoder_kl_wan_2p2.py b/src/maxdiffusion/models/wan/autoencoder_kl_wan_2p2.py index c1b300497..bb925cee0 100644 --- a/src/maxdiffusion/models/wan/autoencoder_kl_wan_2p2.py +++ b/src/maxdiffusion/models/wan/autoencoder_kl_wan_2p2.py @@ -20,7 +20,12 @@ import jax from jax import tree_util import jax.numpy as jnp -from maxdiffusion.models.wan.autoencoder_kl_wan import AutoencoderKLWanCache, WanCausalConv3d, _spatial_sharding # pylint: disable=g-importing-member,protected-access +from maxdiffusion.models.wan.autoencoder_kl_wan import ( # pylint: disable=g-importing-member,protected-access + AutoencoderKLWanCache, + WanCausalConv3d, + _spatial_sharding, + check_vae_batch_is_shardable, +) from ... import common_types from ...configuration_utils import ConfigMixin @@ -1375,6 +1380,7 @@ def encode( return_dict: bool = True, ) -> Union[FlaxAutoencoderKLOutput, Tuple[FlaxDiagonalGaussianDistribution]]: """Encode video into latent distribution.""" + check_vae_batch_is_shardable(self.mesh, x.shape[0], "encode") h = self._encode(x, feat_cache) posterior = WanDiagonalGaussianDistribution(h) if not return_dict: diff --git a/src/maxdiffusion/models/wan/transformers/transformer_wan.py b/src/maxdiffusion/models/wan/transformers/transformer_wan.py index 53e14a2ca..c15663393 100644 --- a/src/maxdiffusion/models/wan/transformers/transformer_wan.py +++ b/src/maxdiffusion/models/wan/transformers/transformer_wan.py @@ -16,6 +16,7 @@ from typing import Tuple, Optional, Dict, Union, Any import contextlib +import functools import math import jax import jax.numpy as jnp @@ -39,6 +40,112 @@ from ...gradient_checkpoint import GradientCheckpointType BlockSizes = common_types.BlockSizes +BATCH = common_types.BATCH + + +def _batch_mesh_axes() -> Optional[Tuple[str, ...]]: + """Mesh axes the ambient ``axis_rules`` context maps BATCH to, or None. + + ``axis_rules`` is thread-local Python state and not part of the ``jax.jit`` + cache key, so it must be read *outside* any jitted function and passed in as + a static argument; reading it at trace time would bake the first caller's + rules into the cached executable. The result is canonicalised to a tuple so + it is hashable and equal rules give one cache entry. + """ + axes = nn.logical_to_mesh_axes((BATCH,))[0] + if axes is None: + return None + axes = (axes,) if isinstance(axes, str) else tuple(axes) + return axes or None + + +def _batch_sharding( + mesh, batch_mesh_axes: Optional[Tuple[str, ...]], ndim: int, batch_axis: int, batch_size: Optional[int] = None +): + """NamedSharding with ``batch_mesh_axes`` on ``batch_axis``, rest replicated. + + ``batch_mesh_axes`` comes from ``_batch_mesh_axes()``. Returns None (caller + skips the constraint, array stays replicated) when there is no mesh, when + BATCH is not mapped to any mesh axis, or when ``batch_size`` is not divisible + by the product of the batch mesh axes -- e.g. ``data_parallelism > 1`` with + ``per_device_batch_size = 1`` and CFG off, which the pipelines already + tolerate for the CFG cache. Skipping keeps that case explicitly replicated + instead of depending on how ``with_sharding_constraint`` treats a + non-divisible axis (it raises eagerly and drops the axis under jit). + """ + if mesh is None or not batch_mesh_axes: + return None + if batch_size is not None: + num_shards = math.prod(mesh.shape[a] for a in batch_mesh_axes) + if batch_size % num_shards != 0: + return None + spec = [None] * ndim + spec[batch_axis] = tuple(batch_mesh_axes) + return jax.sharding.NamedSharding(mesh, jax.sharding.PartitionSpec(*spec)) + + +def _shard_kv_cache_on_batch(kv_cache, mesh, batch_mesh_axes: Optional[Tuple[str, ...]]): + """Pins every K/V cache array to the activation batch sharding. + + Cache arrays are either [B, S, H*D] (one layer) or [L, B, S, H*D] (stacked), + so the batch axis is the first non-layer axis. The cross-attention consumer + re-constrains K/V to (BATCH, CROSS_ATTN_HEAD, None, D_KV), i.e. batch on + ('data', 'fsdp') and everything else replicated, so this is exactly the + layout it needs — no resharding at use time, and each device only holds its + own B_local slice instead of the full CFG-doubled batch. + """ + if mesh is None or not batch_mesh_axes: + return kv_cache + + def _constrain(x): + batch_axis = 1 if x.ndim == 4 else 0 + sharding = _batch_sharding(mesh, batch_mesh_axes, x.ndim, batch_axis, batch_size=x.shape[batch_axis]) + return x if sharding is None else jax.lax.with_sharding_constraint(x, sharding) + + return jax.tree.map(_constrain, kv_cache) + + +@functools.partial(jax.jit, static_argnames=("num_layers", "mesh", "batch_mesh_axes")) +def _scanned_compute_kv( + blocks_graphdef, blocks_state, encoder_hidden_states, encoder_attention_mask, num_layers, mesh, batch_mesh_axes +): + """Cross-attention K/V cache for all layers as ONE sharded executable. + + Replaces the eager ``nnx.vmap`` over the stacked blocks. Eager vmap + materialises the K/V projections, the FP32 RMSNorm upcast and the bf16 + downcast for all ``num_layers`` at once *and* on every device (the inputs + are replicated), which is what blew the 32 GiB parts at B=8. + + Here the batch axis is sharded on ('data', 'fsdp') before the projections, + and ``nnx.scan`` processes one layer per iteration so the FP32 temporaries + are bounded to a single layer and freed before the next. The stacked + [L, B, S, H*D] outputs stay batch-sharded. + + ``batch_mesh_axes`` is static so the sharding is part of the jit cache key; + see ``_batch_mesh_axes``. + """ + blocks = nnx.merge(blocks_graphdef, blocks_state) + batch_size = encoder_hidden_states.shape[0] + in_sharding = _batch_sharding(mesh, batch_mesh_axes, encoder_hidden_states.ndim, 0, batch_size=batch_size) + if in_sharding is not None: + encoder_hidden_states = jax.lax.with_sharding_constraint(encoder_hidden_states, in_sharding) + if encoder_attention_mask is not None: + encoder_attention_mask = jax.lax.with_sharding_constraint( + encoder_attention_mask, + _batch_sharding(mesh, batch_mesh_axes, encoder_attention_mask.ndim, 0, batch_size=batch_size), + ) + + def scan_fn(carry, block): + kv = block.compute_kv(encoder_hidden_states, encoder_attention_mask) + return carry, _shard_kv_cache_on_batch(kv, mesh, batch_mesh_axes) + + _, kv_cache = nnx.scan( + scan_fn, + length=num_layers, + in_axes=(nnx.Carry, 0), + out_axes=(nnx.Carry, 0), + )(None, blocks) + return _shard_kv_cache_on_batch(kv_cache, mesh, batch_mesh_axes) def get_frequencies(max_seq_len: int, theta: int, attention_head_dim: int): @@ -650,6 +757,7 @@ def __init__( out_channels = out_channels or in_channels self.num_layers = num_layers self.scan_layers = scan_layers + self.mesh = mesh self.enable_jax_named_scopes = enable_jax_named_scopes self.wan_cfg_before_unpatchify = ( wan_runtime_options.default("wan_cfg_before_unpatchify") @@ -817,17 +925,21 @@ def compute_kv_cache( ) encoder_attention_mask = jnp.concatenate([encoder_attention_mask, text_mask], axis=1) + # Resolved here, outside the jit, so the sharding is part of its cache key. + batch_mesh_axes = _batch_mesh_axes() if self.scan_layers: - - @nnx.vmap( - in_axes=(0, None, None), - out_axes=0, - transform_metadata={nnx.PARTITION_NAME: "layers_per_stage"}, + # Jitted + scanned + batch-sharded; see _scanned_compute_kv for why the + # previous eager nnx.vmap was a 6.8 GiB-per-video HBM hit on every device. + blocks_graphdef, blocks_state = nnx.split(self.blocks) + kv_cache = _scanned_compute_kv( + blocks_graphdef, + blocks_state, + encoder_hidden_states, + encoder_attention_mask, + num_layers=self.num_layers, + mesh=self.mesh, + batch_mesh_axes=batch_mesh_axes, ) - def _compute_kv(block, enc_states, enc_mask): - return block.compute_kv(enc_states, enc_mask) - - kv_cache = _compute_kv(self.blocks, encoder_hidden_states, encoder_attention_mask) else: kv_cache_list = [] for block in self.blocks: @@ -838,6 +950,7 @@ def _compute_kv(block, enc_states, enc_mask): k_list = [d[k][0] for d in kv_cache_list] v_list = [d[k][1] for d in kv_cache_list] kv_cache[k] = (jnp.stack(k_list, axis=0), jnp.stack(v_list, axis=0)) + kv_cache = _shard_kv_cache_on_batch(kv_cache, self.mesh, batch_mesh_axes) return kv_cache, encoder_attention_mask diff --git a/src/maxdiffusion/pipelines/wan/wan_pipeline.py b/src/maxdiffusion/pipelines/wan/wan_pipeline.py index 77dc0abdd..a062ba544 100644 --- a/src/maxdiffusion/pipelines/wan/wan_pipeline.py +++ b/src/maxdiffusion/pipelines/wan/wan_pipeline.py @@ -36,7 +36,7 @@ from ...max_utils import get_flash_block_sizes, get_precision, device_put_replicated from ...models.wan.wan_utils import load_wan_transformer, load_wan_vae from ...models.wan.transformers.transformer_wan import WanModel -from ...models.wan.autoencoder_kl_wan import AutoencoderKLWan, AutoencoderKLWanCache +from ...models.wan.autoencoder_kl_wan import AutoencoderKLWan, AutoencoderKLWanCache, check_vae_batch_is_shardable from maxdiffusion.video_processor import VideoProcessor from ...schedulers.scheduling_unipc_multistep_flax import FlaxUniPCMultistepScheduler, UniPCMultistepSchedulerState from transformers import AutoTokenizer, UMT5EncoderModel @@ -488,6 +488,8 @@ class WanPipeline: """ _transformer_keys = ["transformer"] + # Whether the pipeline can run on the batch-parallel (N, 1) VAE mesh; see _auto_vae_spatial. + _supports_batch_parallel_vae = False def __init__( self, @@ -989,6 +991,7 @@ def _denormalize_latents(self, latents: jax.Array) -> jax.Array: def _decode_latents_to_video(self, latents: jax.Array, trace: Optional[dict] = None) -> np.ndarray: """Decodes latents to video frames and postprocesses.""" + check_vae_batch_is_shardable(self.vae_mesh, latents.shape[0], "decode") t_vae_tpu_start = time.perf_counter() with self.vae_mesh, nn_partitioning.axis_rules(self.vae_logical_axis_rules): graphdef, state, rest_of_state = nnx.split(self.vae, nnx.Param, ...) @@ -1006,6 +1009,55 @@ def _decode_latents_to_video(self, latents: jax.Array, trace: Optional[dict] = N video = np.asarray(video) return video + @staticmethod + def _auto_vae_spatial(config, total_devices: int, batch_parallel_vae: bool = False) -> int: + """Picks the `vae_spatial` mesh extent when the config leaves it at -1 (auto). + + The VAE mesh is ('redundant', 'vae_spatial') with redundant * vae_spatial == + total_devices. Batch is sharded on 'redundant', and the longer spatial axis + (height for portrait videos, width otherwise) / conv channels on + 'vae_spatial'. Spatial sharding is what lets a single video fit, but with + vae_spatial == total_devices the batch axis is fully replicated, so at + B == total_devices every chip holds all B videos' activations and the + causal conv stack pays a ~10x slowdown (41.6s -> 6.3s at B=8 on tpu7x-8) + and OOMs on 32 GiB parts. + + Measured on v6e-8 / tpu7x-8 (720p, 81 frames): + * B % total_devices == 0: pure data parallelism (vae_spatial == 1) is + strictly better -- 1 video per device, zero cross-chip collectives. + * 1 < B < total_devices: mixed meshes are NOT a win. At B=2 on v6e-8 + the (2, 4) mesh needed a 21.2 GiB decode program vs 15.5 GiB for + (1, 8), even though per-device activation volume is identical. + So this only switches to vae_spatial == 1 when the batch is a multiple of + the device count and keeps full spatial sharding otherwise. Setting + `vae_spatial` explicitly in the config still overrides this. + + `batch_parallel_vae` gates the batch-aware choice and is opt-in: it is a + load-time argument (`from_pretrained` / `from_checkpoint` / + `WanCheckpointer.load_checkpoint`) that only T2V inference + (`generate_wan.py`) sets. The VAE constrains every activation to + P('redundant', ..., 'vae_spatial', ...). On a vae_spatial == 1 mesh the + batch axis is the only sharded axis, so *every* tensor that goes through + the VAE needs a batch divisible by total_devices + (`check_vae_batch_is_shardable` raises otherwise, on encode, on decode and + before denoising, rather than silently running replicated on every chip). + That holds for T2V inference (the only VAE call is the final decode of the + full batch), but not for: + * pipelines that also encode conditioning through the VAE at a different + batch -- VACE encodes reference images one at a time + ([1, 1, H, W, C]), animate / i2v encode conditioning clips. They do + not support the gate (`_supports_batch_parallel_vae`). + * other users of a T2V pipeline's VAE, e.g. dataset preprocessing, which + encodes its own batch sizes. They load without the gate. + All of those keep the full-spatial (1, N) mesh. + """ + if not batch_parallel_vae: + return total_devices + batch_size = int(config.global_batch_size_to_train_on) + if batch_size >= total_devices and batch_size % total_devices == 0: + return 1 + return total_devices + @classmethod def _create_common_components( cls, @@ -1014,6 +1066,7 @@ def _create_common_components( load_text_encoder=True, load_scheduler=True, i2v=False, + batch_parallel_vae=False, ): devices_array = max_utils.create_device_mesh(config) mesh = Mesh(devices_array, config.mesh_axes) @@ -1022,7 +1075,7 @@ def _create_common_components( total_devices = math.prod(devices_array.shape) if vae_spatial == -1: - vae_spatial = total_devices + vae_spatial = cls._auto_vae_spatial(config, total_devices, batch_parallel_vae=batch_parallel_vae) assert ( total_devices % vae_spatial == 0 @@ -1033,7 +1086,8 @@ def _create_common_components( vae_mesh = Mesh(vae_devices_array, ("redundant", "vae_spatial")) max_logging.log( - f"Created VAE specific mesh with axes ('redundant', 'vae_spatial') to support spatial sharding of {vae_spatial}." + f"Created VAE specific mesh with axes ('redundant', 'vae_spatial') = " + f"({total_devices // vae_spatial}, {vae_spatial}) to support spatial sharding of {vae_spatial}." ) # logical axis rules for VAE encoding/decoding @@ -1156,6 +1210,22 @@ def _resolve_and_validate_load_flags( True if load_scheduler is None else load_scheduler, ) + @classmethod + def _batch_parallel_vae_kwargs(cls, batch_parallel_vae: bool) -> dict: + """`_load_and_init` kwargs for the opt-in batch-parallel VAE mesh; see `_auto_vae_spatial`. + + Empty unless requested, so pipelines that do not support the gate keep + their `_load_and_init` signature. + """ + if not batch_parallel_vae: + return {} + if not cls._supports_batch_parallel_vae: + raise ValueError( + f"{cls.__name__} does not support batch_parallel_vae: it runs the VAE at batch sizes other than the " + "global batch (conditioning encodes), which a batch-parallel VAE mesh cannot shard." + ) + return {"batch_parallel_vae": True} + @classmethod def from_pretrained( cls, @@ -1165,6 +1235,7 @@ def from_pretrained( load_text_encoder=None, load_transformer=None, load_scheduler=None, + batch_parallel_vae=False, ): ( load_vae, @@ -1185,6 +1256,7 @@ def from_pretrained( load_text_encoder=load_text_encoder, load_transformer=load_transformer, load_scheduler=load_scheduler, + **cls._batch_parallel_vae_kwargs(batch_parallel_vae), ) pipeline = outputs[0] loaded_transformers = outputs[1:] @@ -1205,6 +1277,7 @@ def from_checkpoint( load_text_encoder=None, load_transformer=None, load_scheduler=None, + batch_parallel_vae=False, ): ( load_vae, @@ -1225,6 +1298,7 @@ def from_checkpoint( load_text_encoder=load_text_encoder, load_transformer=load_transformer, load_scheduler=load_scheduler, + **cls._batch_parallel_vae_kwargs(batch_parallel_vae), ) pipeline = outputs[0] loaded_transformers = outputs[1:] diff --git a/src/maxdiffusion/pipelines/wan/wan_pipeline_2_1.py b/src/maxdiffusion/pipelines/wan/wan_pipeline_2_1.py index d6ceb5df0..b40cddc96 100644 --- a/src/maxdiffusion/pipelines/wan/wan_pipeline_2_1.py +++ b/src/maxdiffusion/pipelines/wan/wan_pipeline_2_1.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +from ...models.wan.autoencoder_kl_wan import check_vae_batch_is_shardable from .wan_pipeline import ( WanPipeline, transformer_forward_pass, @@ -41,6 +42,9 @@ class WanPipeline2_1(WanPipeline): """Pipeline for WAN 2.1 with a single transformer.""" + # T2V only runs the VAE on the final full-batch decode; see _auto_vae_spatial. + _supports_batch_parallel_vae = True + def __init__(self, config: HyperParameters, transformer: Optional[WanModel], **kwargs): super().__init__(config=config, **kwargs) self.transformer = transformer @@ -54,6 +58,7 @@ def _load_and_init( load_text_encoder=True, load_transformer=True, load_scheduler=True, + batch_parallel_vae=False, ): # Load VAE/tokenizer/text-encoder/scheduler in a background thread while # the main thread converts the 14B transformer: the small components and @@ -68,6 +73,8 @@ def _load_and_init( load_vae=load_vae, load_text_encoder=load_text_encoder, load_scheduler=load_scheduler, + # Opt-in batch-aware (N, 1) VAE mesh; see _auto_vae_spatial. + batch_parallel_vae=batch_parallel_vae, ) transformer = None try: @@ -164,6 +171,9 @@ def __call__( prompt_embeds, negative_prompt_embeds, ) + if output_type != "latent": + # Fail before denoising rather than at the final decode. + check_vae_batch_is_shardable(self.vae_mesh, latents.shape[0], "decode") latents.block_until_ready() prompt_embeds.block_until_ready() trace["conditioning"] = time.perf_counter() - t_cond_start diff --git a/src/maxdiffusion/pipelines/wan/wan_pipeline_2_2.py b/src/maxdiffusion/pipelines/wan/wan_pipeline_2_2.py index 80fb76e9d..d2534d822 100644 --- a/src/maxdiffusion/pipelines/wan/wan_pipeline_2_2.py +++ b/src/maxdiffusion/pipelines/wan/wan_pipeline_2_2.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +from ...models.wan.autoencoder_kl_wan import check_vae_batch_is_shardable from .wan_pipeline import ( WanPipeline, transformer_forward_pass, @@ -45,6 +46,9 @@ class WanPipeline2_2(WanPipeline): _transformer_keys = ["low_noise_transformer", "high_noise_transformer"] + # T2V only runs the VAE on the final full-batch decode; see _auto_vae_spatial. + _supports_batch_parallel_vae = True + def __init__( self, config: HyperParameters, @@ -66,6 +70,7 @@ def _load_and_init( load_text_encoder=True, load_transformer=True, load_scheduler=True, + batch_parallel_vae=False, ): # Load VAE/tokenizer/text-encoder/scheduler in a background thread while # the main thread converts the two 14B transformers: the small components @@ -79,6 +84,8 @@ def _load_and_init( load_vae=load_vae, load_text_encoder=load_text_encoder, load_scheduler=load_scheduler, + # Opt-in batch-aware (N, 1) VAE mesh; see _auto_vae_spatial. + batch_parallel_vae=batch_parallel_vae, ) low_noise_transformer, high_noise_transformer = None, None transformer_executor = concurrent.futures.ThreadPoolExecutor(max_workers=2) @@ -218,6 +225,9 @@ def __call__( prompt_embeds, negative_prompt_embeds, ) + if output_type != "latent": + # Fail before denoising rather than at the final decode. + check_vae_batch_is_shardable(self.vae_mesh, latents.shape[0], "decode") latents.block_until_ready() prompt_embeds.block_until_ready() trace["conditioning"] = time.perf_counter() - t_cond_start diff --git a/src/maxdiffusion/pipelines/wan/wan_vace_pipeline_2_1.py b/src/maxdiffusion/pipelines/wan/wan_vace_pipeline_2_1.py index 879844355..96f27d36b 100644 --- a/src/maxdiffusion/pipelines/wan/wan_vace_pipeline_2_1.py +++ b/src/maxdiffusion/pipelines/wan/wan_vace_pipeline_2_1.py @@ -174,6 +174,10 @@ class VaceWanPipeline2_1(WanPipeline2_1): Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations. """ + # VACE encodes reference images one at a time through the VAE, so unlike its + # T2V base class it cannot use the batch-parallel VAE mesh. + _supports_batch_parallel_vae = False + def preprocess_conditions( self, video: Optional[PipelineImageInput] = None, diff --git a/src/maxdiffusion/tests/generate_wan_smoke_test.py b/src/maxdiffusion/tests/generate_wan_smoke_test.py index ee332e52a..23363bf3c 100644 --- a/src/maxdiffusion/tests/generate_wan_smoke_test.py +++ b/src/maxdiffusion/tests/generate_wan_smoke_test.py @@ -55,10 +55,12 @@ def setUpClass(cls): ) cls.config = pyconfig.config checkpoint_loader = WanCheckpointer2_1(config=cls.config) - cls.pipeline, _, _ = checkpoint_loader.load_checkpoint() + # Same as generate_wan.py: T2V inference opts into the batch-parallel VAE mesh + # and always runs a full batch. + cls.pipeline, _, _ = checkpoint_loader.load_checkpoint(batch_parallel_vae=True) - cls.prompt = [cls.config.prompt] - cls.negative_prompt = [cls.config.negative_prompt] + cls.prompt = [cls.config.prompt] * cls.config.global_batch_size_to_train_on + cls.negative_prompt = [cls.config.negative_prompt] * cls.config.global_batch_size_to_train_on def test_wan_inference(self): """Test that Wan pipeline can run inference and produce output.""" diff --git a/src/maxdiffusion/tests/wan/wan_checkpointer_test.py b/src/maxdiffusion/tests/wan/wan_checkpointer_test.py index 213c599e3..40050464b 100644 --- a/src/maxdiffusion/tests/wan/wan_checkpointer_test.py +++ b/src/maxdiffusion/tests/wan/wan_checkpointer_test.py @@ -84,6 +84,23 @@ def test_empty_pretrained_dir_uses_diffusers_without_cache(self, mock_restore, m self.pipeline_cls.from_pretrained.assert_called_once_with(self.config) self.assertEqual(result, pipeline) + @patch.object(WanCheckpointer, "_save_pretrained_checkpoint") + @patch.object(WanCheckpointer, "_restore_pretrained_checkpoint") + def test_batch_parallel_vae_is_forwarded_only_when_set(self, mock_restore, mock_save): + """Cache hit and miss both forward batch_parallel_vae=True; the default call signature is unchanged (above).""" + restored_checkpoint = MagicMock() + mock_restore.return_value = restored_checkpoint + WanCheckpointer.load_pretrained_pipeline_or_diffusers( + self.config, self.pipeline_cls, self.state_sources, self.config_transformer_attr, batch_parallel_vae=True + ) + self.pipeline_cls.from_checkpoint.assert_called_once_with(self.config, restored_checkpoint, batch_parallel_vae=True) + + mock_restore.return_value = None + WanCheckpointer.load_pretrained_pipeline_or_diffusers( + self.config, self.pipeline_cls, self.state_sources, self.config_transformer_attr, batch_parallel_vae=True + ) + self.pipeline_cls.from_pretrained.assert_called_once_with(self.config, batch_parallel_vae=True) + @patch("maxdiffusion.checkpointing.wan_checkpointer.nnx.split") def test_pretrained_save_items_uses_explicit_transformer_config(self, mock_split): pipeline = MagicMock() @@ -194,6 +211,26 @@ def test_load_from_diffusers(self, mock_from_pretrained, mock_create_manager): self.assertIsNone(opt_state) self.assertIsNone(step) + @patch("maxdiffusion.checkpointing.wan_checkpointer.create_orbax_checkpoint_manager") + @patch.object(WanPipeline2_1, "from_pretrained", autospec=True) + def test_load_checkpoint_forwards_batch_parallel_vae(self, mock_from_pretrained, mock_create_manager): + mock_manager = MagicMock() + mock_manager.latest_step.return_value = None + mock_create_manager.return_value = mock_manager + + checkpointer = WanCheckpointer2_1(config=self.config) + checkpointer.load_checkpoint(step=None, batch_parallel_vae=True) + + mock_from_pretrained.assert_called_once_with( + self.config, + vae_only=False, + load_vae=None, + load_text_encoder=None, + load_transformer=None, + load_scheduler=None, + batch_parallel_vae=True, + ) + @patch("maxdiffusion.checkpointing.wan_checkpointer.create_orbax_checkpoint_manager") @patch.object(WanPipeline2_1, "from_checkpoint", autospec=True) def test_load_checkpoint_no_optimizer(self, mock_from_checkpoint, mock_create_manager): diff --git a/src/maxdiffusion/tests/wan/wan_vae_mesh_test.py b/src/maxdiffusion/tests/wan/wan_vae_mesh_test.py new file mode 100644 index 000000000..aea78882f --- /dev/null +++ b/src/maxdiffusion/tests/wan/wan_vae_mesh_test.py @@ -0,0 +1,357 @@ +""" +Copyright 2026 Google LLC + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +CPU checks for the batch-aware VAE mesh selection and the batch-sharded +cross-attention KV cache (helpers, and compute_kv_cache against the eager vmap +it replaced). +""" + +import os +import types +from unittest import mock + +os.environ.setdefault("XLA_FLAGS", "--xla_force_host_platform_device_count=4") + +import jax +import jax.numpy as jnp +import numpy as np +import pytest +from flax import nnx +from flax.linen import partitioning as nn_partitioning +from jax.sharding import Mesh, NamedSharding, PartitionSpec as P + +from maxdiffusion.models.wan.autoencoder_kl_wan import check_vae_batch_is_shardable +from maxdiffusion.pipelines.wan.wan_pipeline import WanPipeline +from maxdiffusion.pipelines.wan.wan_pipeline_2_1 import WanPipeline2_1 +from maxdiffusion.pipelines.wan.wan_pipeline_2_2 import WanPipeline2_2 +from maxdiffusion.pipelines.wan.wan_pipeline_animate import WanAnimatePipeline +from maxdiffusion.pipelines.wan.wan_pipeline_i2v_2p1 import WanPipelineI2V_2_1 +from maxdiffusion.pipelines.wan.wan_pipeline_i2v_2p2 import WanPipelineI2V_2_2 +from maxdiffusion.pipelines.wan.wan_vace_pipeline_2_1 import VaceWanPipeline2_1 +from maxdiffusion.models.wan.transformers import transformer_wan +from maxdiffusion.models.wan.transformers.transformer_wan import WanModel + + +def _cfg(batch_size): + return types.SimpleNamespace(global_batch_size_to_train_on=batch_size) + + +@pytest.mark.parametrize( + "batch_size, total_devices, expected", + [ + (0, 8, 8), + (1, 8, 8), + (2, 8, 8), + (3, 8, 8), + (4, 8, 8), + (8, 8, 1), + (12, 8, 8), + (16, 8, 1), + (4, 4, 1), + (1, 1, 1), + ], +) +def test_auto_vae_spatial_batch_parallel(batch_size, total_devices, expected): + """With the gate on, B % N == 0 picks pure data parallelism, otherwise full spatial.""" + assert WanPipeline._auto_vae_spatial(_cfg(batch_size), total_devices, batch_parallel_vae=True) == expected + + +@pytest.mark.parametrize("batch_size", [0, 1, 2, 8, 16]) +def test_auto_vae_spatial_default_is_full_spatial(batch_size): + """Without the gate (i2v / vace / animate) auto always resolves to the old value.""" + assert WanPipeline._auto_vae_spatial(_cfg(batch_size), 8) == 8 + assert WanPipeline._auto_vae_spatial(_cfg(batch_size), 8, batch_parallel_vae=False) == 8 + + +def test_only_t2v_pipelines_support_batch_parallel_vae(): + """Guard against the gate leaking into pipelines that VAE-encode at batch != global batch. + + VACE subclasses the T2V pipeline, so it has to opt out explicitly. + """ + assert WanPipeline2_1._supports_batch_parallel_vae + assert WanPipeline2_2._supports_batch_parallel_vae + for pipeline_cls in (WanPipeline, WanPipelineI2V_2_1, WanPipelineI2V_2_2, WanAnimatePipeline, VaceWanPipeline2_1): + assert not pipeline_cls._supports_batch_parallel_vae, pipeline_cls.__name__ + with pytest.raises(ValueError, match="does not support batch_parallel_vae"): + pipeline_cls._batch_parallel_vae_kwargs(True) + assert pipeline_cls._batch_parallel_vae_kwargs(False) == {} + + +@pytest.mark.parametrize("pipeline_cls", [WanPipeline2_1, WanPipeline2_2]) +@pytest.mark.parametrize("loader", ["from_pretrained", "from_checkpoint"]) +def test_batch_parallel_vae_is_opt_in_at_load_time(pipeline_cls, loader): + """The loaders only ask for the batch-parallel mesh when told to. + + Everything that loads a T2V pipeline without saying so (dataset + preprocessing, trainers, tests) keeps the full-spatial (1, N) VAE mesh. + """ + outputs = (mock.MagicMock(),) + (None,) * len(pipeline_cls._transformer_keys) + with ( + mock.patch.object(pipeline_cls, "_load_and_init", return_value=outputs) as load_and_init, + mock.patch.object(pipeline_cls, "quantize_transformer", return_value=None), + ): + getattr(pipeline_cls, loader)(mock.MagicMock()) + assert "batch_parallel_vae" not in load_and_init.call_args.kwargs + getattr(pipeline_cls, loader)(mock.MagicMock(), batch_parallel_vae=True) + assert load_and_init.call_args.kwargs["batch_parallel_vae"] is True + + +def _vae_mesh(redundant, vae_spatial): + devices = jax.devices() + if len(devices) < redundant * vae_spatial: + pytest.skip(f"Requires {redundant * vae_spatial} JAX devices") + return Mesh(np.array(devices[: redundant * vae_spatial]).reshape(redundant, vae_spatial), ("redundant", "vae_spatial")) + + +def test_check_vae_batch_is_shardable(): + """Only a batch-parallel (N, 1) mesh with an indivisible batch is rejected.""" + batch_parallel = _vae_mesh(4, 1) + for what in ("encode", "decode"): + with pytest.raises(ValueError, match=f"VAE {what} batch size .* divisible by the 'redundant' mesh axis"): + check_vae_batch_is_shardable(batch_parallel, 1, what) + with pytest.raises(ValueError, match="divisible by the 'redundant' mesh axis"): + check_vae_batch_is_shardable(batch_parallel, 10, "encode") + check_vae_batch_is_shardable(batch_parallel, 4, "decode") + check_vae_batch_is_shardable(batch_parallel, 8, "decode") + # Spatially sharded meshes take any batch: an indivisible one only loses its batch sharding. + for mesh in (_vae_mesh(1, 4), _vae_mesh(2, 2), _vae_mesh(1, 1), None): + for batch in (1, 3, 4): + check_vae_batch_is_shardable(mesh, batch, "encode") + + +def test_decode_latents_rejects_indivisible_batch_on_batch_parallel_mesh(): + """_decode_latents_to_video must fail fast instead of silently decoding replicated.""" + dummy_pipeline = types.SimpleNamespace(vae_mesh=_vae_mesh(4, 1)) + latents = jnp.zeros((1, 16, 1, 8, 8)) + with pytest.raises(ValueError, match="VAE decode batch size .* divisible by the 'redundant' mesh axis"): + WanPipeline._decode_latents_to_video(dummy_pipeline, latents) + + +@pytest.mark.parametrize("pipeline_cls", [WanPipeline2_1, WanPipeline2_2]) +def test_t2v_call_rejects_indivisible_batch_before_denoising(pipeline_cls): + """A short batch on the batch-parallel mesh fails right after input prep, not after every denoising step.""" + pipeline = pipeline_cls.__new__(pipeline_cls) + pipeline.vae_mesh = _vae_mesh(4, 1) + pipeline.config = types.SimpleNamespace(max_sequence_length=512) + prepared = (jnp.zeros((1, 16, 1, 8, 8)), jnp.zeros((1, 4, 8)), jnp.zeros((1, 4, 8)), None, 1) + with ( + mock.patch.object(pipeline_cls, "_validate_svg_cache_compatibility"), + mock.patch.object(pipeline_cls, "_prepare_model_inputs", return_value=prepared) as prepare, + ): + # No transformer is attached: reaching the denoise loop would raise AttributeError instead. + with pytest.raises(ValueError, match="VAE decode batch size .* divisible by the 'redundant' mesh axis"): + pipeline(prompt=["test"]) + assert prepare.call_count == 1 + + +@pytest.fixture +def mesh_and_rules(): + all_devices = jax.devices() + if len(all_devices) < 2: + pytest.skip("Requires at least 2 JAX devices to test multi-shard batch sharding") + usable = (len(all_devices) // 2) * 2 + devices = np.array(all_devices[:usable]).reshape(2, 1, -1, 1) + mesh = Mesh(devices, ("data", "fsdp", "context", "tensor")) + rules = (("activation_batch", ("data", "fsdp")),) + return mesh, rules + + +def test_batch_sharding_divisible(mesh_and_rules): + mesh, rules = mesh_and_rules + with mesh, nn_partitioning.axis_rules(rules): + batch_mesh_axes = transformer_wan._batch_mesh_axes() + assert batch_mesh_axes == ("data", "fsdp") + # Explicit axes: no axis_rules context is needed (or read) from here on. + sharding = transformer_wan._batch_sharding(mesh, batch_mesh_axes, ndim=3, batch_axis=0, batch_size=4) + assert sharding is not None + assert sharding.spec == P(("data", "fsdp"), None, None) + + +def test_batch_sharding_not_divisible_returns_none(mesh_and_rules): + """B=3 on data*fsdp=2 must skip the constraint instead of raising inside the jit.""" + mesh, _ = mesh_and_rules + assert transformer_wan._batch_sharding(mesh, ("data", "fsdp"), ndim=3, batch_axis=0, batch_size=3) is None + + +def test_batch_sharding_without_rules_or_mesh(mesh_and_rules): + mesh, _ = mesh_and_rules + assert transformer_wan._batch_sharding(None, ("data", "fsdp"), ndim=3, batch_axis=0) is None + assert transformer_wan._batch_sharding(mesh, None, ndim=3, batch_axis=0) is None + with mesh, nn_partitioning.axis_rules(()): + assert transformer_wan._batch_mesh_axes() is None + assert transformer_wan._batch_mesh_axes() is None + # A single-axis rule is canonicalised to a tuple, so it is a valid static jit argument. + with mesh, nn_partitioning.axis_rules((("activation_batch", "data"),)): + assert transformer_wan._batch_mesh_axes() == ("data",) + + +def test_shard_kv_cache_on_batch_layouts(mesh_and_rules): + """[B,S,D] shards on axis 0, stacked [L,B,S,D] on axis 1; odd batches stay replicated.""" + mesh, rules = mesh_and_rules + cache = { + "text": (jnp.zeros((4, 16, 8)), jnp.zeros((2, 4, 16, 8))), + "odd": (jnp.zeros((3, 16, 8)), jnp.zeros((2, 3, 16, 8))), + } + with mesh, nn_partitioning.axis_rules(rules): + batch_mesh_axes = transformer_wan._batch_mesh_axes() + out = jax.jit(lambda c: transformer_wan._shard_kv_cache_on_batch(c, mesh, batch_mesh_axes))(cache) + k, v = out["text"] + # JAX canonicalises the spec of the returned array (size-1 'fsdp' is dropped), + # so compare semantically rather than by literal PartitionSpec. + assert k.sharding.is_equivalent_to(NamedSharding(mesh, P(("data", "fsdp"), None, None)), k.ndim) + assert v.sharding.is_equivalent_to(NamedSharding(mesh, P(None, ("data", "fsdp"), None, None)), v.ndim) + assert k.addressable_shards[0].data.shape[0] == 2 + assert v.addressable_shards[0].data.shape[1] == 2 + k_odd, v_odd = out["odd"] + assert k_odd.shape == (3, 16, 8) and v_odd.shape == (2, 3, 16, 8) + assert k_odd.sharding.is_equivalent_to(NamedSharding(mesh, P()), k_odd.ndim) + + +# Production logical axis rules (configs/base_wan_27b.yml), so the tiny model +# below is constrained the same way the real one is. +_WAN_LOGICAL_AXIS_RULES = ( + ("batch", ("data", "fsdp")), + ("activation_batch", ("data", "fsdp")), + ("activation_self_attn_heads", ("context", "tensor")), + ("activation_cross_attn_q_length", ("context", "tensor")), + ("activation_length", "context"), + ("activation_heads", "tensor"), + ("mlp", "tensor"), + ("embed", ("context", "fsdp")), + ("heads", "tensor"), + ("norm", "tensor"), + ("conv_batch", ("data", "context", "fsdp")), + ("out_channels", "tensor"), + ("conv_out", "context"), +) + + +def _eager_vmap_kv_cache(model, encoder_hidden_states): + """The eager nnx.vmap implementation that _scanned_compute_kv replaced.""" + timestep = jnp.zeros((encoder_hidden_states.shape[0],), dtype=jnp.int32) + _, _, encoder_hidden_states, _, encoder_attention_mask = model.condition_embedder(timestep, encoder_hidden_states, None) + + @nnx.vmap(in_axes=(0, None, None), out_axes=0, transform_metadata={nnx.PARTITION_NAME: "layers_per_stage"}) + def _compute_kv(block, enc_states, enc_mask): + return block.compute_kv(enc_states, enc_mask) + + return _compute_kv(model.blocks, encoder_hidden_states, encoder_attention_mask) + + +def _assert_close(actual, expected, dtype): + actual = np.asarray(actual, np.float32) + expected = np.asarray(expected, np.float32) + if dtype == jnp.float32: + np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=1e-6) + else: + # Scan and vmap may be fused differently on TPU, so allow one bf16 ULP of the output scale. + np.testing.assert_allclose(actual, expected, rtol=2**-7, atol=2**-7 * float(np.max(np.abs(expected)))) + + +@pytest.mark.parametrize( + "dtype, batch_size", + [(jnp.float32, 4), (jnp.bfloat16, 4), (jnp.float32, 3)], + ids=["f32_divisible", "bf16_divisible", "f32_not_divisible"], +) +def test_scanned_kv_cache_matches_eager_vmap(mesh_and_rules, dtype, batch_size): + """compute_kv_cache (jitted, scanned, batch-sharded) equals the old eager vmap, and the forward pass accepts it.""" + mesh, _ = mesh_and_rules + num_layers = 2 + with mesh, nn_partitioning.axis_rules(_WAN_LOGICAL_AXIS_RULES): + model = WanModel( + rngs=nnx.Rngs(0), + patch_size=(1, 2, 2), + num_attention_heads=2, + attention_head_dim=16, + in_channels=4, + out_channels=4, + text_dim=32, + freq_dim=32, + ffn_dim=64, + num_layers=num_layers, + mesh=mesh, + dtype=dtype, + weights_dtype=dtype, + scan_layers=True, + ) + encoder_hidden_states = jax.random.normal(jax.random.PRNGKey(2), (batch_size, 8, 32), dtype) + expected = _eager_vmap_kv_cache(model, encoder_hidden_states) + kv_cache, encoder_attention_mask = model.compute_kv_cache(encoder_hidden_states) + + assert set(kv_cache) == set(expected) + data_shards = mesh.shape["data"] * mesh.shape["fsdp"] + for name, expected_kv in expected.items(): + for actual, want in zip(kv_cache[name], expected_kv): + assert actual.shape == want.shape and actual.shape[:2] == (num_layers, batch_size) + assert actual.dtype == want.dtype + _assert_close(actual, want, dtype) + if batch_size % data_shards == 0: + # Stacked [L, B, S, H*D]: each device holds only its own slice of the batch. + assert actual.addressable_shards[0].data.shape[1] == batch_size // data_shards + else: + assert actual.addressable_shards[0].data.shape[1] == batch_size + + hidden_states = jax.random.normal(jax.random.PRNGKey(1), (batch_size, 4, 4, 8, 8), dtype) + timestep = jnp.full((batch_size,), 500.0) + uncached = model(hidden_states, timestep, encoder_hidden_states, return_dict=False) + cached = model( + hidden_states, + timestep, + encoder_hidden_states, + return_dict=False, + kv_cache=kv_cache, + encoder_attention_mask=encoder_attention_mask, + ) + _assert_close(cached[0], uncached[0], dtype) + + +@pytest.mark.parametrize("scan_layers", [True, False], ids=["scan", "loop"]) +def test_kv_cache_sharding_follows_axis_rules_not_the_jit_cache(mesh_and_rules, scan_layers): + """axis_rules is not part of the jit cache key, so the batch axes must be passed to the jit explicitly. + + Same model, same inputs, same mesh; only the ambient axis_rules differ + between calls. Each call has to get the sharding of its own rules rather + than whatever executable an earlier call cached. + """ + mesh, _ = mesh_and_rules + with mesh, nn_partitioning.axis_rules(_WAN_LOGICAL_AXIS_RULES): + model = WanModel( + rngs=nnx.Rngs(0), + patch_size=(1, 2, 2), + num_attention_heads=2, + attention_head_dim=16, + in_channels=4, + out_channels=4, + text_dim=32, + freq_dim=32, + ffn_dim=64, + num_layers=2, + mesh=mesh, + scan_layers=scan_layers, + ) + batch_size = 4 + data_shards = mesh.shape["data"] * mesh.shape["fsdp"] + encoder_hidden_states = jax.random.normal(jax.random.PRNGKey(2), (batch_size, 8, 32)) + + def local_batch(rules): + with mesh, nn_partitioning.axis_rules(rules): + kv_cache, _ = model.compute_kv_cache(encoder_hidden_states) + # Stacked [L, B, S, H*D]: the batch a single device holds. + return {k.addressable_shards[0].data.shape[1] for kv in kv_cache.values() for k in kv} + + no_batch_rule = () + assert local_batch(no_batch_rule) == {batch_size} + assert local_batch(_WAN_LOGICAL_AXIS_RULES) == {batch_size // data_shards} + assert local_batch(no_batch_rule) == {batch_size}