diff --git a/src/maxdiffusion/configs/base_wan_14b.yml b/src/maxdiffusion/configs/base_wan_14b.yml index 5404f1a22..679e20401 100644 --- a/src/maxdiffusion/configs/base_wan_14b.yml +++ b/src/maxdiffusion/configs/base_wan_14b.yml @@ -452,6 +452,10 @@ use_cfg_cache: False use_batched_text_encoder: False use_kv_cache: False +# WAN-VACE training: compute the VACE hints from zero latents at timestep 999, the first inference timestep, +# instead of from the noisy latents. This fine-tunes the model for use_vace_cache=True in the VACE pipeline, which +# computes the hints once and reuses them at every denoising step. +use_vace_cache: False use_magcache: False magcache_thresh: 0.12 magcache_K: 2 diff --git a/src/maxdiffusion/configs/base_wan_1_3b.yml b/src/maxdiffusion/configs/base_wan_1_3b.yml index cfb8c9a4d..1547b5915 100644 --- a/src/maxdiffusion/configs/base_wan_1_3b.yml +++ b/src/maxdiffusion/configs/base_wan_1_3b.yml @@ -399,6 +399,10 @@ flow_shift: 3.0 # Diffusion CFG cache (FasterCache-style, WAN 2.1 T2V only) use_cfg_cache: False use_kv_cache: False +# WAN-VACE training: compute the VACE hints from zero latents at timestep 999, the first inference timestep, +# instead of from the noisy latents. This fine-tunes the model for use_vace_cache=True in the VACE pipeline, which +# computes the hints once and reuses them at every denoising step. +use_vace_cache: False # Batch positive and negative prompts in text encoder to save compute. use_batched_text_encoder: False diff --git a/src/maxdiffusion/models/wan/transformers/transformer_wan_vace.py b/src/maxdiffusion/models/wan/transformers/transformer_wan_vace.py index ca052282f..064d9d236 100644 --- a/src/maxdiffusion/models/wan/transformers/transformer_wan_vace.py +++ b/src/maxdiffusion/models/wan/transformers/transformer_wan_vace.py @@ -15,7 +15,7 @@ import contextlib import math -from typing import Any, Dict, Optional, Tuple +from typing import Any, Dict, Optional, Sequence, Tuple, Union from flax import nnx import flax.linen as nn @@ -557,7 +557,12 @@ def __call__( encoder_attention_mask: Optional[jax.Array] = None, deterministic: bool = True, rngs: nnx.Rngs = None, - ) -> jax.Array: + # VACE caching: `return_vace_hints=True` returns the unscaled VACE hints (one per VACE layer) instead of the + # prediction. Passing them back as `vace_hints` skips the VACE blocks; `control_hidden_states_scale` still applies. + # The hints depend on `hidden_states` and `timestep`, so reusing them at other steps approximates the full model. + vace_hints: Optional[Sequence[jax.Array]] = None, + return_vace_hints: bool = False, + ) -> Union[jax.Array, Tuple[jax.Array, ...]]: hidden_states = nn.with_logical_constraint(hidden_states, ("batch", None, None, None, None)) batch_size, _, num_frames, height, width = hidden_states.shape p_t, p_h, p_w = self.config.patch_size @@ -573,6 +578,8 @@ def __call__( f" {len(control_hidden_states_scale)} should be equal to" f" {len(self.config.vace_layers)}." ) + if vace_hints is not None and len(vace_hints) != len(self.config.vace_layers): + raise ValueError(f"Length of `vace_hints` {len(vace_hints)} should be equal to {len(self.config.vace_layers)}.") hidden_states = jnp.transpose(hidden_states, (0, 2, 3, 4, 1)) control_hidden_states = jnp.transpose(control_hidden_states, (0, 2, 3, 4, 1)) @@ -613,36 +620,41 @@ def __call__( else: vace_kv_cache, main_kv_cache = kv_cache if kv_cache is not None else (None, None) - # Prepare VACE hints - control_hidden_states_list = [] - for i, vace_block in enumerate(self.vace_blocks): - layer_kv_cache = None - if vace_kv_cache is not None: - layer_kv_cache = jax.tree.map(lambda x: x[i], vace_kv_cache) - - def layer_forward(hidden_states, control_hidden_states, rngs): - return vace_block( - hidden_states=hidden_states, - encoder_hidden_states=encoder_hidden_states, - control_hidden_states=control_hidden_states, - temb=timestep_proj, - rotary_emb=rotary_emb, - kv_cache=layer_kv_cache, - encoder_attention_mask=encoder_attention_mask, - deterministic=deterministic, - rngs=rngs, + # Prepare VACE hints, unless precomputed ones are passed (VACE caching). + if vace_hints is None: + vace_hints = [] + for i, vace_block in enumerate(self.vace_blocks): + layer_kv_cache = None + if vace_kv_cache is not None: + layer_kv_cache = jax.tree.map(lambda x: x[i], vace_kv_cache) + + def layer_forward(hidden_states, control_hidden_states, rngs): + return vace_block( + hidden_states=hidden_states, + encoder_hidden_states=encoder_hidden_states, + control_hidden_states=control_hidden_states, + temb=timestep_proj, + rotary_emb=rotary_emb, + kv_cache=layer_kv_cache, + encoder_attention_mask=encoder_attention_mask, + deterministic=deterministic, + rngs=rngs, + ) + + rematted_layer_forward = self.gradient_checkpoint.apply( + layer_forward, + self.names_which_can_be_saved, + self.names_which_can_be_offloaded, + prevent_cse=not self.scan_layers, ) - - rematted_layer_forward = self.gradient_checkpoint.apply( - layer_forward, - self.names_which_can_be_saved, - self.names_which_can_be_offloaded, - prevent_cse=not self.scan_layers, - ) - conditioning_states, control_hidden_states = rematted_layer_forward(hidden_states, control_hidden_states, rngs) - control_hidden_states_list.append((conditioning_states, control_hidden_states_scale[i])) - - control_hidden_states_list = control_hidden_states_list[::-1] + conditioning_states, control_hidden_states = rematted_layer_forward(hidden_states, control_hidden_states, rngs) + vace_hints.append(conditioning_states) + elif any(hint.shape != hidden_states.shape for hint in vace_hints): + raise ValueError(f"Each VACE hint should have shape {hidden_states.shape}.") + if return_vace_hints: + return tuple(vace_hints) + + control_hidden_states_list = [(hint, control_hidden_states_scale[i]) for i, hint in enumerate(vace_hints)][::-1] for i, block in enumerate(self.blocks): layer_kv_cache = None 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..69f2b881c 100644 --- a/src/maxdiffusion/pipelines/wan/wan_vace_pipeline_2_1.py +++ b/src/maxdiffusion/pipelines/wan/wan_vace_pipeline_2_1.py @@ -496,6 +496,7 @@ def __call__( negative_prompt_embeds: jax.Array | None = None, vae_only: bool = False, use_kv_cache: bool = False, + use_vace_cache: bool = False, ): """Runs the VACE model for the given inputs. @@ -517,6 +518,9 @@ def __call__( prompt_embeds: Optional precomputed prompt embeddings for the text encoder. negative_prompt_embeds: Optional precomputed negative prompt embeddings for the text encoder. vae_only: Whether to only run the decoder for a given latent. + use_vace_cache: Whether to compute the VACE hints once and reuse them at every denoising step. This only + approximates the full model, so the model needs to be fine-tuned with hints computed the same way, see + `run_inference`. """ config = getattr(self, "config", None) if max_sequence_length is None: @@ -641,6 +645,7 @@ def __call__( scheduler=self.scheduler, scheduler_state=scheduler_state, use_kv_cache=use_kv_cache, + use_vace_cache=use_vace_cache, ) with self.mesh, nn_partitioning.axis_rules(self.config.logical_axis_rules): @@ -729,7 +734,7 @@ def prepare_video_latents( return jnp.stack(latent_list) -@partial(aot_cache.cached_jit, static_argnames=("do_classifier_free_guidance",)) +@partial(aot_cache.cached_jit, static_argnames=("do_classifier_free_guidance", "return_vace_hints")) def transformer_forward_pass( graphdef: nnx.graph.GraphDef, sharded_state: nnx.State, @@ -743,12 +748,18 @@ def transformer_forward_pass( guidance_scale: float, kv_cache=None, encoder_attention_mask=None, + vace_hints=None, + return_vace_hints=False, ): - """Performs a forward pass on the transformer.""" + """Performs a forward pass on the transformer. + + With `return_vace_hints=True`, returns the VACE hints instead of the noise prediction, to be passed back as + `vace_hints`. + """ if do_classifier_free_guidance and latents.shape[0] != prompt_embeds.shape[0]: latents = jnp.concatenate([latents, latents], axis=0) wan_transformer = nnx.merge(graphdef, sharded_state, rest_of_state) - noise_pred = wan_transformer( + output = wan_transformer( hidden_states=latents, timestep=timestep, encoder_hidden_states=prompt_embeds, @@ -756,7 +767,12 @@ def transformer_forward_pass( control_hidden_states_scale=control_hidden_states_scale, kv_cache=kv_cache, encoder_attention_mask=encoder_attention_mask, + vace_hints=vace_hints, + return_vace_hints=return_vace_hints, ) + if return_vace_hints: + return output + noise_pred = output if do_classifier_free_guidance: bsz = latents.shape[0] // 2 noise_uncond = noise_pred[bsz:] @@ -780,6 +796,7 @@ def run_inference( control_hidden_states, control_hidden_states_scale, use_kv_cache: bool = False, + use_vace_cache: bool = False, ): do_classifier_free_guidance = guidance_scale > 1.0 if do_classifier_free_guidance: @@ -794,6 +811,26 @@ def run_inference( bsz = latents.shape[0] * 2 if do_classifier_free_guidance else latents.shape[0] timesteps = jnp.array(scheduler_state.timesteps, dtype=jnp.int32) + + vace_hints = None + if use_vace_cache: + # The hints are computed once, from zero latents at the first timestep, and reused at every step. + vace_hints = transformer_forward_pass( + graphdef, + sharded_state, + rest_of_state, + jnp.zeros_like(latents), + jnp.broadcast_to(timesteps[0], (bsz,)), + prompt_embeds, + control_hidden_states=control_hidden_states, + control_hidden_states_scale=control_hidden_states_scale, + do_classifier_free_guidance=do_classifier_free_guidance, + guidance_scale=guidance_scale, + kv_cache=kv_cache, + encoder_attention_mask=encoder_attention_mask, + return_vace_hints=True, + ) + for step in range(num_inference_steps): t = timesteps[step] timestep = jnp.broadcast_to(t, (bsz,)) @@ -811,6 +848,7 @@ def run_inference( guidance_scale=guidance_scale, kv_cache=kv_cache, encoder_attention_mask=encoder_attention_mask, + vace_hints=vace_hints, ) latents, scheduler_state = scheduler.step(scheduler_state, noise_pred, t, latents).to_tuple() diff --git a/src/maxdiffusion/tests/wan/wan_vace_pipeline_test.py b/src/maxdiffusion/tests/wan/wan_vace_pipeline_test.py index 38acaddb3..da2a82c72 100644 --- a/src/maxdiffusion/tests/wan/wan_vace_pipeline_test.py +++ b/src/maxdiffusion/tests/wan/wan_vace_pipeline_test.py @@ -32,9 +32,13 @@ jax_config.pallas_tpu_interpret_mode_context_manager.set_global(True) import jax.numpy as jnp -from maxdiffusion import pyconfig +from flax import nnx +from jax.sharding import Mesh -from maxdiffusion.pipelines.wan.wan_vace_pipeline_2_1 import VaceWanPipeline2_1 +from maxdiffusion import pyconfig +from maxdiffusion.max_utils import create_device_mesh +from maxdiffusion.models.wan.transformers.transformer_wan_vace import WanVACEModel +from maxdiffusion.pipelines.wan.wan_vace_pipeline_2_1 import VaceWanPipeline2_1, run_inference, transformer_forward_pass from maxdiffusion.schedulers.scheduling_unipc_multistep_flax import FlaxUniPCMultistepScheduler THIS_DIR = os.path.dirname(os.path.abspath(__file__)) @@ -495,6 +499,75 @@ def run_scenario(load_vae, load_text_encoder, load_transformer, load_scheduler): # Scenario 5: All components run_scenario(load_vae=True, load_text_encoder=True, load_transformer=True, load_scheduler=True) + def test_run_inference_reuses_vace_hints_of_zero_latents(self): + mesh = Mesh(create_device_mesh(self.config), self.config.mesh_axes) + model = WanVACEModel( + rngs=nnx.Rngs(0), + vace_layers=[0, 2], + vace_in_channels=8, + num_attention_heads=2, + attention_head_dim=16, + in_channels=16, + out_channels=16, + text_dim=32, + freq_dim=32, + ffn_dim=64, + num_layers=4, + mesh=mesh, + attention="dot_product", + scan_layers=False, + ) + graphdef, state, rest_of_state = nnx.split(model, nnx.Param, ...) + latents_key, control_key, prompt_key = jax.random.split(jax.random.key(0), 3) + latents = jax.random.normal(latents_key, (1, 16, 2, 4, 4)) + control_hidden_states = jax.random.normal(control_key, (1, 8, 2, 4, 4)) + prompt_embeds = jax.random.normal(prompt_key, (1, 8, 32)) + control_hidden_states_scale = jnp.array([0.5, -1.25]) + guidance_scale = 5.0 + scheduler = FlaxUniPCMultistepScheduler( + num_train_timesteps=1000, prediction_type="flow_prediction", use_flow_sigmas=True, flow_shift=3.0 + ) + scheduler_state = scheduler.set_timesteps(scheduler.create_state(), num_inference_steps=1, shape=latents.shape) + t = scheduler_state.timesteps[0] + + def forward_pass(latents, **kwargs): + return transformer_forward_pass( + graphdef, + state, + rest_of_state, + latents, + jnp.broadcast_to(t, (2,)), + jnp.concatenate([prompt_embeds, -prompt_embeds]), + control_hidden_states=jnp.concatenate([control_hidden_states] * 2), + control_hidden_states_scale=control_hidden_states_scale, + do_classifier_free_guidance=True, + guidance_scale=guidance_scale, + **kwargs, + ) + + with mesh: + # The hints are computed from zero latents at the first timestep. + vace_hints = forward_pass(jnp.zeros_like(latents), return_vace_hints=True) + noise_pred = forward_pass(latents, vace_hints=vace_hints) + expected, _ = scheduler.step(scheduler_state, noise_pred, t, latents).to_tuple() + actual = run_inference( + graphdef, + state, + rest_of_state, + latents, + prompt_embeds, + -prompt_embeds, + guidance_scale, + num_inference_steps=1, + scheduler=scheduler, + scheduler_state=scheduler_state, + control_hidden_states=control_hidden_states, + control_hidden_states_scale=control_hidden_states_scale, + use_vace_cache=True, + ) + + self.assertTrue(jnp.allclose(actual, expected, atol=1e-5)) + if __name__ == "__main__": unittest.main() diff --git a/src/maxdiffusion/tests/wan/wan_vace_transformer_test.py b/src/maxdiffusion/tests/wan/wan_vace_transformer_test.py index ce5fdf2db..5aeb63371 100644 --- a/src/maxdiffusion/tests/wan/wan_vace_transformer_test.py +++ b/src/maxdiffusion/tests/wan/wan_vace_transformer_test.py @@ -28,6 +28,7 @@ WanRotaryPosEmbed, ) from maxdiffusion.models.wan.transformers.transformer_wan_vace import ( + WanVACEModel, WanVACETransformerBlock, ) import qwix @@ -131,6 +132,43 @@ def test_wan_vace_block_returns_the_correct_shape(self): assert conditioning_states.shape == dummy_hidden_states.shape assert control_hidden_states.shape == dummy_hidden_states.shape + def test_wan_vace_model_reuses_returned_vace_hints(self): + pyconfig.initialize([None, os.path.join(THIS_DIR, "..", "..", "configs", "base_wan_14b.yml")], unittest=True) + config = pyconfig.config + mesh = Mesh(create_device_mesh(config), config.mesh_axes) + model = WanVACEModel( + rngs=nnx.Rngs(0), + vace_layers=[0, 2], + vace_in_channels=8, + num_attention_heads=2, + attention_head_dim=16, + in_channels=16, + out_channels=16, + text_dim=32, + freq_dim=32, + ffn_dim=64, + num_layers=4, + mesh=mesh, + attention="dot_product", + scan_layers=False, + ) + latents_key, control_key, prompt_key = jax.random.split(jax.random.key(0), 3) + inputs = { + "hidden_states": jax.random.normal(latents_key, (1, 16, 2, 4, 4)), + "timestep": jnp.array([700]), + "encoder_hidden_states": jax.random.normal(prompt_key, (1, 8, 32)), + "control_hidden_states": jax.random.normal(control_key, (1, 8, 2, 4, 4)), + "control_hidden_states_scale": jnp.array([0.5, -1.25]), + } + + with mesh: + expected = model(**inputs) + vace_hints = model(**inputs, return_vace_hints=True) + actual = model(**inputs, vace_hints=vace_hints) + + self.assertEqual(len(vace_hints), 2) + self.assertTrue(jnp.array_equal(actual, expected)) + if __name__ == "__main__": absltest.main() diff --git a/src/maxdiffusion/trainers/wan_vace_trainer.py b/src/maxdiffusion/trainers/wan_vace_trainer.py index 329a73171..38d307607 100644 --- a/src/maxdiffusion/trainers/wan_vace_trainer.py +++ b/src/maxdiffusion/trainers/wan_vace_trainer.py @@ -137,6 +137,28 @@ def train_step(state, data, rng, scheduler_state, scheduler, config): return step_optimizer(state, data, rng, scheduler_state, scheduler, config) +# VACE caching (config.use_vace_cache): the hints are computed from zero latents, not from the training noise. With +# x_t, the noise would give away the flow-matching target `noise - x0`, so the model could read it off the hints. +# 999 is `scheduler_state.timesteps[0]` of the UniPC flow-sigma inference scheduler, where cached-VACE inference +# computes the hints (also from zero latents) once and reuses them at every step. +_VACE_CACHE_TIMESTEP = 999 + + +def _cached_vace_hints(model, timesteps, encoder_hidden_states, control_hidden_states, deterministic, rngs=None): + """Returns the VACE hints computed from zero latents at `_VACE_CACHE_TIMESTEP`, for config.use_vace_cache.""" + batch_size, _, *video_shape = control_hidden_states.shape + zero_latents = jnp.zeros((batch_size, model.config.in_channels, *video_shape), control_hidden_states.dtype) + return model( + hidden_states=zero_latents, + timestep=jnp.full_like(timesteps, _VACE_CACHE_TIMESTEP), + encoder_hidden_states=encoder_hidden_states, + control_hidden_states=control_hidden_states, + deterministic=deterministic, + rngs=rngs, + return_vace_hints=True, + ) + + def step_optimizer(state, data, rng, scheduler_state, scheduler, config): _, new_rng, timestep_rng, dropout_rng = jax.random.split(rng, num=4) @@ -154,13 +176,20 @@ def loss_fn(params): noise = jax.random.normal(key=new_rng, shape=latents.shape, dtype=latents.dtype) noisy_latents, training_target, training_weight = scheduler.apply_flow_match(noise, latents, timesteps) with jax.named_scope("forward_pass"): + rngs = nnx.Rngs(dropout=dropout_rng) + vace_hints = None + if getattr(config, "use_vace_cache", False): + vace_hints = _cached_vace_hints( + model, timesteps, encoder_hidden_states, control_hidden_states, deterministic=False, rngs=rngs + ) model_pred = model( hidden_states=noisy_latents, timestep=timesteps, encoder_hidden_states=encoder_hidden_states, control_hidden_states=control_hidden_states, deterministic=False, - rngs=nnx.Rngs(dropout=dropout_rng), + rngs=rngs, + vace_hints=vace_hints, ) with jax.named_scope("loss"): @@ -217,6 +246,9 @@ def loss_fn( noise = jax.random.normal(key=rng, shape=latents.shape, dtype=latents.dtype) noisy_latents, training_target, training_weight = scheduler.apply_flow_match(noise, latents, timesteps) + vace_hints = None + if getattr(config, "use_vace_cache", False): + vace_hints = _cached_vace_hints(model, timesteps, encoder_hidden_states, conditioning_latents, deterministic=True) # Get the model's prediction model_pred = model( hidden_states=noisy_latents, @@ -224,6 +256,7 @@ def loss_fn( encoder_hidden_states=encoder_hidden_states, control_hidden_states=conditioning_latents, deterministic=True, + vace_hints=vace_hints, ) # Calculate the loss against the target