Skip to content

Commit d2536ff

Browse files
Merge pull request #526 from AI-Hypercomputer:ninatu/wan_vace_cache
PiperOrigin-RevId: 1028213157
2 parents 6629957 + b32e8ab commit d2536ff

7 files changed

Lines changed: 239 additions & 37 deletions

File tree

‎src/maxdiffusion/configs/base_wan_14b.yml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -467,6 +467,10 @@ use_cfg_cache: False
467467
use_batched_text_encoder: False
468468

469469
use_kv_cache: False
470+
# WAN-VACE training: compute the VACE hints from zero latents at timestep 999, the first inference timestep,
471+
# instead of from the noisy latents. This fine-tunes the model for use_vace_cache=True in the VACE pipeline, which
472+
# computes the hints once and reuses them at every denoising step.
473+
use_vace_cache: False
470474
use_magcache: False
471475
magcache_thresh: 0.12
472476
magcache_K: 2

‎src/maxdiffusion/configs/base_wan_1_3b.yml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,10 @@ flow_shift: 3.0
414414
# Diffusion CFG cache (FasterCache-style, WAN 2.1 T2V only)
415415
use_cfg_cache: False
416416
use_kv_cache: False
417+
# WAN-VACE training: compute the VACE hints from zero latents at timestep 999, the first inference timestep,
418+
# instead of from the noisy latents. This fine-tunes the model for use_vace_cache=True in the VACE pipeline, which
419+
# computes the hints once and reuses them at every denoising step.
420+
use_vace_cache: False
417421

418422
# Batch positive and negative prompts in text encoder to save compute.
419423
use_batched_text_encoder: False

‎src/maxdiffusion/models/wan/transformers/transformer_wan_vace.py‎

Lines changed: 43 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515

1616
import contextlib
1717
import math
18-
from typing import Any, Dict, Optional, Tuple
18+
from typing import Any, Dict, Optional, Sequence, Tuple, Union
1919

2020
from flax import nnx
2121
import flax.linen as nn
@@ -557,7 +557,12 @@ def __call__(
557557
encoder_attention_mask: Optional[jax.Array] = None,
558558
deterministic: bool = True,
559559
rngs: nnx.Rngs = None,
560-
) -> jax.Array:
560+
# VACE caching: `return_vace_hints=True` returns the unscaled VACE hints (one per VACE layer) instead of the
561+
# prediction. Passing them back as `vace_hints` skips the VACE blocks; `control_hidden_states_scale` still applies.
562+
# The hints depend on `hidden_states` and `timestep`, so reusing them at other steps approximates the full model.
563+
vace_hints: Optional[Sequence[jax.Array]] = None,
564+
return_vace_hints: bool = False,
565+
) -> Union[jax.Array, Tuple[jax.Array, ...]]:
561566
hidden_states = nn.with_logical_constraint(hidden_states, ("batch", None, None, None, None))
562567
batch_size, _, num_frames, height, width = hidden_states.shape
563568
p_t, p_h, p_w = self.config.patch_size
@@ -573,6 +578,8 @@ def __call__(
573578
f" {len(control_hidden_states_scale)} should be equal to"
574579
f" {len(self.config.vace_layers)}."
575580
)
581+
if vace_hints is not None and len(vace_hints) != len(self.config.vace_layers):
582+
raise ValueError(f"Length of `vace_hints` {len(vace_hints)} should be equal to {len(self.config.vace_layers)}.")
576583

577584
hidden_states = jnp.transpose(hidden_states, (0, 2, 3, 4, 1))
578585
control_hidden_states = jnp.transpose(control_hidden_states, (0, 2, 3, 4, 1))
@@ -613,36 +620,41 @@ def __call__(
613620
else:
614621
vace_kv_cache, main_kv_cache = kv_cache if kv_cache is not None else (None, None)
615622

616-
# Prepare VACE hints
617-
control_hidden_states_list = []
618-
for i, vace_block in enumerate(self.vace_blocks):
619-
layer_kv_cache = None
620-
if vace_kv_cache is not None:
621-
layer_kv_cache = jax.tree.map(lambda x: x[i], vace_kv_cache)
622-
623-
def layer_forward(hidden_states, control_hidden_states, rngs):
624-
return vace_block(
625-
hidden_states=hidden_states,
626-
encoder_hidden_states=encoder_hidden_states,
627-
control_hidden_states=control_hidden_states,
628-
temb=timestep_proj,
629-
rotary_emb=rotary_emb,
630-
kv_cache=layer_kv_cache,
631-
encoder_attention_mask=encoder_attention_mask,
632-
deterministic=deterministic,
633-
rngs=rngs,
623+
# Prepare VACE hints, unless precomputed ones are passed (VACE caching).
624+
if vace_hints is None:
625+
vace_hints = []
626+
for i, vace_block in enumerate(self.vace_blocks):
627+
layer_kv_cache = None
628+
if vace_kv_cache is not None:
629+
layer_kv_cache = jax.tree.map(lambda x: x[i], vace_kv_cache)
630+
631+
def layer_forward(hidden_states, control_hidden_states, rngs):
632+
return vace_block(
633+
hidden_states=hidden_states,
634+
encoder_hidden_states=encoder_hidden_states,
635+
control_hidden_states=control_hidden_states,
636+
temb=timestep_proj,
637+
rotary_emb=rotary_emb,
638+
kv_cache=layer_kv_cache,
639+
encoder_attention_mask=encoder_attention_mask,
640+
deterministic=deterministic,
641+
rngs=rngs,
642+
)
643+
644+
rematted_layer_forward = self.gradient_checkpoint.apply(
645+
layer_forward,
646+
self.names_which_can_be_saved,
647+
self.names_which_can_be_offloaded,
648+
prevent_cse=not self.scan_layers,
634649
)
635-
636-
rematted_layer_forward = self.gradient_checkpoint.apply(
637-
layer_forward,
638-
self.names_which_can_be_saved,
639-
self.names_which_can_be_offloaded,
640-
prevent_cse=not self.scan_layers,
641-
)
642-
conditioning_states, control_hidden_states = rematted_layer_forward(hidden_states, control_hidden_states, rngs)
643-
control_hidden_states_list.append((conditioning_states, control_hidden_states_scale[i]))
644-
645-
control_hidden_states_list = control_hidden_states_list[::-1]
650+
conditioning_states, control_hidden_states = rematted_layer_forward(hidden_states, control_hidden_states, rngs)
651+
vace_hints.append(conditioning_states)
652+
elif any(hint.shape != hidden_states.shape for hint in vace_hints):
653+
raise ValueError(f"Each VACE hint should have shape {hidden_states.shape}.")
654+
if return_vace_hints:
655+
return tuple(vace_hints)
656+
657+
control_hidden_states_list = [(hint, control_hidden_states_scale[i]) for i, hint in enumerate(vace_hints)][::-1]
646658

647659
for i, block in enumerate(self.blocks):
648660
layer_kv_cache = None

‎src/maxdiffusion/pipelines/wan/wan_vace_pipeline_2_1.py‎

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -500,6 +500,7 @@ def __call__(
500500
negative_prompt_embeds: jax.Array | None = None,
501501
vae_only: bool = False,
502502
use_kv_cache: bool = False,
503+
use_vace_cache: bool = False,
503504
):
504505
"""Runs the VACE model for the given inputs.
505506
@@ -521,6 +522,9 @@ def __call__(
521522
prompt_embeds: Optional precomputed prompt embeddings for the text encoder.
522523
negative_prompt_embeds: Optional precomputed negative prompt embeddings for the text encoder.
523524
vae_only: Whether to only run the decoder for a given latent.
525+
use_vace_cache: Whether to compute the VACE hints once and reuse them at every denoising step. This only
526+
approximates the full model, so the model needs to be fine-tuned with hints computed the same way, see
527+
`run_inference`.
524528
"""
525529
config = getattr(self, "config", None)
526530
if max_sequence_length is None:
@@ -645,6 +649,7 @@ def __call__(
645649
scheduler=self.scheduler,
646650
scheduler_state=scheduler_state,
647651
use_kv_cache=use_kv_cache,
652+
use_vace_cache=use_vace_cache,
648653
)
649654

650655
with self.mesh, nn_partitioning.axis_rules(self.config.logical_axis_rules):
@@ -733,7 +738,7 @@ def prepare_video_latents(
733738
return jnp.stack(latent_list)
734739

735740

736-
@partial(aot_cache.cached_jit, static_argnames=("do_classifier_free_guidance",))
741+
@partial(aot_cache.cached_jit, static_argnames=("do_classifier_free_guidance", "return_vace_hints"))
737742
def transformer_forward_pass(
738743
graphdef: nnx.graph.GraphDef,
739744
sharded_state: nnx.State,
@@ -747,20 +752,31 @@ def transformer_forward_pass(
747752
guidance_scale: float,
748753
kv_cache=None,
749754
encoder_attention_mask=None,
755+
vace_hints=None,
756+
return_vace_hints=False,
750757
):
751-
"""Performs a forward pass on the transformer."""
758+
"""Performs a forward pass on the transformer.
759+
760+
With `return_vace_hints=True`, returns the VACE hints instead of the noise prediction, to be passed back as
761+
`vace_hints`.
762+
"""
752763
if do_classifier_free_guidance and latents.shape[0] != prompt_embeds.shape[0]:
753764
latents = jnp.concatenate([latents, latents], axis=0)
754765
wan_transformer = nnx.merge(graphdef, sharded_state, rest_of_state)
755-
noise_pred = wan_transformer(
766+
output = wan_transformer(
756767
hidden_states=latents,
757768
timestep=timestep,
758769
encoder_hidden_states=prompt_embeds,
759770
control_hidden_states=control_hidden_states,
760771
control_hidden_states_scale=control_hidden_states_scale,
761772
kv_cache=kv_cache,
762773
encoder_attention_mask=encoder_attention_mask,
774+
vace_hints=vace_hints,
775+
return_vace_hints=return_vace_hints,
763776
)
777+
if return_vace_hints:
778+
return output
779+
noise_pred = output
764780
if do_classifier_free_guidance:
765781
bsz = latents.shape[0] // 2
766782
noise_uncond = noise_pred[bsz:]
@@ -784,6 +800,7 @@ def run_inference(
784800
control_hidden_states,
785801
control_hidden_states_scale,
786802
use_kv_cache: bool = False,
803+
use_vace_cache: bool = False,
787804
):
788805
do_classifier_free_guidance = guidance_scale > 1.0
789806
if do_classifier_free_guidance:
@@ -798,6 +815,26 @@ def run_inference(
798815

799816
bsz = latents.shape[0] * 2 if do_classifier_free_guidance else latents.shape[0]
800817
timesteps = jnp.array(scheduler_state.timesteps, dtype=jnp.int32)
818+
819+
vace_hints = None
820+
if use_vace_cache:
821+
# The hints are computed once, from zero latents at the first timestep, and reused at every step.
822+
vace_hints = transformer_forward_pass(
823+
graphdef,
824+
sharded_state,
825+
rest_of_state,
826+
jnp.zeros_like(latents),
827+
jnp.broadcast_to(timesteps[0], (bsz,)),
828+
prompt_embeds,
829+
control_hidden_states=control_hidden_states,
830+
control_hidden_states_scale=control_hidden_states_scale,
831+
do_classifier_free_guidance=do_classifier_free_guidance,
832+
guidance_scale=guidance_scale,
833+
kv_cache=kv_cache,
834+
encoder_attention_mask=encoder_attention_mask,
835+
return_vace_hints=True,
836+
)
837+
801838
for step in range(num_inference_steps):
802839
t = timesteps[step]
803840
timestep = jnp.broadcast_to(t, (bsz,))
@@ -815,6 +852,7 @@ def run_inference(
815852
guidance_scale=guidance_scale,
816853
kv_cache=kv_cache,
817854
encoder_attention_mask=encoder_attention_mask,
855+
vace_hints=vace_hints,
818856
)
819857

820858
latents, scheduler_state = scheduler.step(scheduler_state, noise_pred, t, latents).to_tuple()

‎src/maxdiffusion/tests/wan/wan_vace_pipeline_test.py‎

Lines changed: 75 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,13 @@
3232
jax_config.pallas_tpu_interpret_mode_context_manager.set_global(True)
3333
import jax.numpy as jnp
3434

35-
from maxdiffusion import pyconfig
35+
from flax import nnx
36+
from jax.sharding import Mesh
3637

37-
from maxdiffusion.pipelines.wan.wan_vace_pipeline_2_1 import VaceWanPipeline2_1
38+
from maxdiffusion import pyconfig
39+
from maxdiffusion.max_utils import create_device_mesh
40+
from maxdiffusion.models.wan.transformers.transformer_wan_vace import WanVACEModel
41+
from maxdiffusion.pipelines.wan.wan_vace_pipeline_2_1 import VaceWanPipeline2_1, run_inference, transformer_forward_pass
3842
from maxdiffusion.schedulers.scheduling_unipc_multistep_flax import FlaxUniPCMultistepScheduler
3943

4044
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):
495499
# Scenario 5: All components
496500
run_scenario(load_vae=True, load_text_encoder=True, load_transformer=True, load_scheduler=True)
497501

502+
def test_run_inference_reuses_vace_hints_of_zero_latents(self):
503+
mesh = Mesh(create_device_mesh(self.config), self.config.mesh_axes)
504+
model = WanVACEModel(
505+
rngs=nnx.Rngs(0),
506+
vace_layers=[0, 2],
507+
vace_in_channels=8,
508+
num_attention_heads=2,
509+
attention_head_dim=16,
510+
in_channels=16,
511+
out_channels=16,
512+
text_dim=32,
513+
freq_dim=32,
514+
ffn_dim=64,
515+
num_layers=4,
516+
mesh=mesh,
517+
attention="dot_product",
518+
scan_layers=False,
519+
)
520+
graphdef, state, rest_of_state = nnx.split(model, nnx.Param, ...)
521+
latents_key, control_key, prompt_key = jax.random.split(jax.random.key(0), 3)
522+
latents = jax.random.normal(latents_key, (1, 16, 2, 4, 4))
523+
control_hidden_states = jax.random.normal(control_key, (1, 8, 2, 4, 4))
524+
prompt_embeds = jax.random.normal(prompt_key, (1, 8, 32))
525+
control_hidden_states_scale = jnp.array([0.5, -1.25])
526+
guidance_scale = 5.0
527+
scheduler = FlaxUniPCMultistepScheduler(
528+
num_train_timesteps=1000, prediction_type="flow_prediction", use_flow_sigmas=True, flow_shift=3.0
529+
)
530+
scheduler_state = scheduler.set_timesteps(scheduler.create_state(), num_inference_steps=1, shape=latents.shape)
531+
t = scheduler_state.timesteps[0]
532+
533+
def forward_pass(latents, **kwargs):
534+
return transformer_forward_pass(
535+
graphdef,
536+
state,
537+
rest_of_state,
538+
latents,
539+
jnp.broadcast_to(t, (2,)),
540+
jnp.concatenate([prompt_embeds, -prompt_embeds]),
541+
control_hidden_states=jnp.concatenate([control_hidden_states] * 2),
542+
control_hidden_states_scale=control_hidden_states_scale,
543+
do_classifier_free_guidance=True,
544+
guidance_scale=guidance_scale,
545+
**kwargs,
546+
)
547+
548+
with mesh:
549+
# The hints are computed from zero latents at the first timestep.
550+
vace_hints = forward_pass(jnp.zeros_like(latents), return_vace_hints=True)
551+
noise_pred = forward_pass(latents, vace_hints=vace_hints)
552+
expected, _ = scheduler.step(scheduler_state, noise_pred, t, latents).to_tuple()
553+
actual = run_inference(
554+
graphdef,
555+
state,
556+
rest_of_state,
557+
latents,
558+
prompt_embeds,
559+
-prompt_embeds,
560+
guidance_scale,
561+
num_inference_steps=1,
562+
scheduler=scheduler,
563+
scheduler_state=scheduler_state,
564+
control_hidden_states=control_hidden_states,
565+
control_hidden_states_scale=control_hidden_states_scale,
566+
use_vace_cache=True,
567+
)
568+
569+
self.assertTrue(jnp.allclose(actual, expected, atol=1e-5))
570+
498571

499572
if __name__ == "__main__":
500573
unittest.main()

‎src/maxdiffusion/tests/wan/wan_vace_transformer_test.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
WanRotaryPosEmbed,
2929
)
3030
from maxdiffusion.models.wan.transformers.transformer_wan_vace import (
31+
WanVACEModel,
3132
WanVACETransformerBlock,
3233
)
3334
import qwix
@@ -131,6 +132,43 @@ def test_wan_vace_block_returns_the_correct_shape(self):
131132
assert conditioning_states.shape == dummy_hidden_states.shape
132133
assert control_hidden_states.shape == dummy_hidden_states.shape
133134

135+
def test_wan_vace_model_reuses_returned_vace_hints(self):
136+
pyconfig.initialize([None, os.path.join(THIS_DIR, "..", "..", "configs", "base_wan_14b.yml")], unittest=True)
137+
config = pyconfig.config
138+
mesh = Mesh(create_device_mesh(config), config.mesh_axes)
139+
model = WanVACEModel(
140+
rngs=nnx.Rngs(0),
141+
vace_layers=[0, 2],
142+
vace_in_channels=8,
143+
num_attention_heads=2,
144+
attention_head_dim=16,
145+
in_channels=16,
146+
out_channels=16,
147+
text_dim=32,
148+
freq_dim=32,
149+
ffn_dim=64,
150+
num_layers=4,
151+
mesh=mesh,
152+
attention="dot_product",
153+
scan_layers=False,
154+
)
155+
latents_key, control_key, prompt_key = jax.random.split(jax.random.key(0), 3)
156+
inputs = {
157+
"hidden_states": jax.random.normal(latents_key, (1, 16, 2, 4, 4)),
158+
"timestep": jnp.array([700]),
159+
"encoder_hidden_states": jax.random.normal(prompt_key, (1, 8, 32)),
160+
"control_hidden_states": jax.random.normal(control_key, (1, 8, 2, 4, 4)),
161+
"control_hidden_states_scale": jnp.array([0.5, -1.25]),
162+
}
163+
164+
with mesh:
165+
expected = model(**inputs)
166+
vace_hints = model(**inputs, return_vace_hints=True)
167+
actual = model(**inputs, vace_hints=vace_hints)
168+
169+
self.assertEqual(len(vace_hints), 2)
170+
self.assertTrue(jnp.array_equal(actual, expected))
171+
134172

135173
if __name__ == "__main__":
136174
absltest.main()

0 commit comments

Comments
 (0)