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
4 changes: 4 additions & 0 deletions src/maxdiffusion/configs/base_wan_14b.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions src/maxdiffusion/configs/base_wan_1_3b.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
74 changes: 43 additions & 31 deletions src/maxdiffusion/models/wan/transformers/transformer_wan_vace.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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))

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.

Optional (eager compute / memory): When precomputed vace_hints are passed in, control_hidden_states is unused after the vace_patch_embedding block, so XLA dead-code-eliminates it under jit, but eager WanVACEModel(..., vace_hints=...) calls still run the 3D conv + padding, and callers with cached hints cannot pass control_hidden_states=None (run_inference also has to keep passing [2*B, 96, F, H, W] control_hidden_states on every step). Consider making control_hidden_states: Optional[jax.Array] = None (requiring it only when vace_hints is None) and moving the control_hidden_states transpose / vace_patch_embedding / padding block inside if vace_hints is None:.

Expand Down Expand Up @@ -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
Expand Down
44 changes: 41 additions & 3 deletions src/maxdiffusion/pipelines/wan/wan_vace_pipeline_2_1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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:
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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,
Expand All @@ -743,20 +748,31 @@ def transformer_forward_pass(
guidance_scale: float,
kv_cache=None,
encoder_attention_mask=None,
vace_hints=None,
Comment thread
ninatu marked this conversation as resolved.
Resolved
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,
control_hidden_states=control_hidden_states,
control_hidden_states_scale=control_hidden_states_scale,
kv_cache=kv_cache,
encoder_attention_mask=encoder_attention_mask,
vace_hints=vace_hints,
Comment thread
ninatu marked this conversation as resolved.
Resolved
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:]
Expand All @@ -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:
Expand All @@ -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,))
Expand All @@ -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()
Expand Down
77 changes: 75 additions & 2 deletions src/maxdiffusion/tests/wan/wan_vace_pipeline_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__))
Expand Down Expand Up @@ -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)

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.

Optional (test coverage): With num_inference_steps=1, the denoising loop only executes at timesteps[0], which is the same timestep used to precompute vace_hints. Using num_inference_steps=2 here would also verify that step 1 reuses the timesteps[0] zero-latent hints rather than recomputing hints at timesteps[1]. A small unit test covering train_step / eval_step with use_vace_cache=True in wan_vace_trainer.py would also be great if convenient.

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()
38 changes: 38 additions & 0 deletions src/maxdiffusion/tests/wan/wan_vace_transformer_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
WanRotaryPosEmbed,
)
from maxdiffusion.models.wan.transformers.transformer_wan_vace import (
WanVACEModel,
WanVACETransformerBlock,
)
import qwix
Expand Down Expand Up @@ -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()
Loading
Loading