Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions src/maxdiffusion/checkpointing/wan_checkpointer.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,26 +60,29 @@ 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(
pretrained_dir, tuple(state_item_name for state_item_name, _ in pretrained_state_sources)
)
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
Expand Down Expand Up @@ -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,
Expand All @@ -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

Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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
Expand Down
6 changes: 5 additions & 1 deletion src/maxdiffusion/generate_wan.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
22 changes: 22 additions & 0 deletions src/maxdiffusion/models/wan/autoencoder_kl_wan.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down Expand Up @@ -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:
Expand Down
8 changes: 7 additions & 1 deletion src/maxdiffusion/models/wan/autoencoder_kl_wan_2p2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
131 changes: 122 additions & 9 deletions src/maxdiffusion/models/wan/transformers/transformer_wan.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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:
Expand All @@ -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

Expand Down
Loading
Loading