Skip to content
Python

combinatorics

DeepBeepMeep73b22f8a04d1
diff --git a/README.md b/README.md
index ee432d7..6abdaf5 100644
--- a/README.md
+++ b/README.md
@@ -20,6 +20,15 @@ WanGP supports the Wan (and derived models), Hunyuan Video and LTV Video models
**Follow DeepBeepMeep on Twitter/X to get the Latest News**: https://x.com/deepbeepmeep
## 🔥 Latest Updates :
+### September 30 2025: WanGP v8.9 - Combinatorics
+
+This new version of WanGP introduces **Wan 2.1 Lynx** the best Control Net so far to transfer *Facial Identity*. You will be amazed to recognize your friends even with a completely different hair style. Congrats to the *Byte Dance team* for this achievement. Lynx works quite with well *Fusionix t2v* 10 steps.
+
+*WanGP 8.9* also illustrate how existing WanGP features can be easily combined with new models. For instance with *Lynx* you will get out of the box *Video to Video* and *Image/Text to Image*.
+
+Another fun combination is *Vace* + *Lynx*, which works much better than *Vace StandIn*. I have added sliders to change the weight of Vace & Lynx to allow you to tune the effects.
+
+
### September 28 2025: WanGP v8.76 - ~~Here Are Two Three New Contenders in the Vace Arena !~~ The Never Ending Release
So in ~~today's~~ this release you will find two Wannabe Vace that covers each only a subset of Vace features but offers some interesting advantages:
diff --git a/configs/lynx.json b/configs/lynx.json
new file mode 100644
index 0000000..a973d5e
--- /dev/null
+++ b/configs/lynx.json
@@ -0,0 +1,15 @@
+{
+ "_class_name": "WanModel",
+ "_diffusers_version": "0.30.0",
+ "dim": 5120,
+ "eps": 1e-06,
+ "ffn_dim": 13824,
+ "freq_dim": 256,
+ "in_dim": 16,
+ "model_type": "t2v",
+ "num_heads": 40,
+ "num_layers": 40,
+ "out_dim": 16,
+ "text_len": 512,
+ "lynx": "full"
+}
diff --git a/configs/vace_lynx_14B.json b/configs/vace_lynx_14B.json
new file mode 100644
index 0000000..770cbee
--- /dev/null
+++ b/configs/vace_lynx_14B.json
@@ -0,0 +1,17 @@
+{
+ "_class_name": "WanModel",
+ "_diffusers_version": "0.30.0",
+ "dim": 5120,
+ "eps": 1e-06,
+ "ffn_dim": 13824,
+ "freq_dim": 256,
+ "in_dim": 16,
+ "model_type": "t2v",
+ "num_heads": 40,
+ "num_layers": 40,
+ "out_dim": 16,
+ "text_len": 512,
+ "vace_layers": [0, 5, 10, 15, 20, 25, 30, 35],
+ "vace_in_dim": 96,
+ "lynx": "full"
+}
diff --git a/defaults/lynx.json b/defaults/lynx.json
new file mode 100644
index 0000000..4c0a17f
--- /dev/null
+++ b/defaults/lynx.json
@@ -0,0 +1,18 @@
+{
+ "model": {
+ "name": "Wan2.1 Lynx 14B",
+ "modules": [
+ [
+ "https://huggingface.co/DeepBeepMeep/Wan2.1/resolve/main/wan2.1_lynx_full_module_14B_bf16.safetensors",
+ "https://huggingface.co/DeepBeepMeep/Wan2.1/resolve/main/wan2.1_lynx_full_module_14B_quanto_bf16_int8.safetensors",
+ "https://huggingface.co/DeepBeepMeep/Wan2.1/resolve/main/wan2.1_lynx_full_module_14B_quanto_fp16_int8.safetensors"
+ ]
+ ],
+ "architecture": "lynx",
+ "description": "The Lynx ControlNet offers State of the Art Identity Preservation. You need to provide a Reference Image which is a close up of a person face to transfer this person in the Video.",
+ "URLs": "t2v",
+ "preload_URLs": [
+ "wan2.1_lynx_full_arc_resampler.safetensors"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/defaults/vace_lynx_14B.json b/defaults/vace_lynx_14B.json
new file mode 100644
index 0000000..ba8bfbd
--- /dev/null
+++ b/defaults/vace_lynx_14B.json
@@ -0,0 +1,9 @@
+{
+ "model": {
+ "name": "Vace Lynx 14B",
+ "architecture": "vace_lynx_14B",
+ "modules": [ "vace_14B", "lynx"],
+ "description": "The Vace ControlNet model is a powerful model that allows you to control the content of the generated video based of additional custom data : pose or depth video, images or objects you want to see in the video. The Lynx version is specialized in transferring a Person Identity.",
+ "URLs": "t2v"
+ }
+}
\ No newline at end of file
diff --git a/models/wan/any2video.py b/models/wan/any2video.py
index c9b1a29..5beea8e 100644
--- a/models/wan/any2video.py
+++ b/models/wan/any2video.py
@@ -286,7 +286,32 @@ class WanAny2V:
msk = msk.view(1, msk.shape[1] // 4, 4, lat_h, lat_w)
msk = msk.transpose(1,2)[0]
return msk
-
+
+ def encode_reference_images(self, ref_images, ref_prompt="image of a face", any_guidance= False, tile_size = None):
+ ref_images = [convert_image_to_tensor(img).unsqueeze(1).to(device=self.device, dtype=self.dtype) for img in ref_images]
+ shape = ref_images[0].shape
+ freqs = get_rotary_pos_embed( (len(ref_images) , shape[-2] // 8, shape[-1] // 8 ))
+ # batch_ref_image: [B, C, F, H, W]
+ vae_feat = self.vae.encode(ref_images, tile_size = tile_size)
+ vae_feat = torch.cat( vae_feat, dim=1).unsqueeze(0)
+ if any_guidance:
+ vae_feat_uncond = self.vae.encode([ref_images[0] * 0], tile_size = tile_size) * len(ref_images)
+ vae_feat_uncond = torch.cat( vae_feat_uncond, dim=1).unsqueeze(0)
+ context = self.text_encoder([ref_prompt], self.device)[0].to(self.dtype)
+ context = torch.cat([context, context.new_zeros(self.model.text_len -context.size(0), context.size(1)) ]).unsqueeze(0)
+ clear_caches()
+ get_cache("lynx_ref_buffer").update({ 0: {}, 1: {} })
+ ref_buffer = self.model(
+ pipeline =self,
+ x = [vae_feat, vae_feat_uncond] if any_guidance else [vae_feat],
+ context = [context, context] if any_guidance else [context],
+ freqs= freqs,
+ t=torch.stack([torch.tensor(0, dtype=torch.float)]).to(self.device),
+ lynx_feature_extractor = True,
+ )
+ clear_caches()
+ return ref_buffer[0], (ref_buffer[1] if any_guidance else None)
+
def generate(self,
input_prompt,
input_frames= None,
@@ -355,6 +380,7 @@ class WanAny2V:
video_prompt_type= "",
original_input_ref_images = [],
face_arc_embeds = None,
+ control_scale_alt = 1.,
**bbargs
):
@@ -401,13 +427,15 @@ class WanAny2V:
# Text Encoder
if n_prompt == "":
n_prompt = self.sample_neg_prompt
- context = self.text_encoder([input_prompt], self.device)[0]
- context_null = self.text_encoder([n_prompt], self.device)[0]
- context = context.to(self.dtype)
- context_null = context_null.to(self.dtype)
text_len = self.model.text_len
- context = torch.cat([context, context.new_zeros(text_len -context.size(0), context.size(1)) ]).unsqueeze(0)
- context_null = torch.cat([context_null, context_null.new_zeros(text_len -context_null.size(0), context_null.size(1)) ]).unsqueeze(0)
+ any_guidance_at_all = guide_scale > 1 or guide2_scale > 1 and guide_phases >=2 or guide3_scale > 1 and guide_phases >=3
+ context = self.text_encoder([input_prompt], self.device)[0].to(self.dtype)
+ context = torch.cat([context, context.new_zeros(text_len -context.size(0), context.size(1)) ]).unsqueeze(0)
+ if NAG_scale > 1 or any_guidance_at_all:
+ context_null = self.text_encoder([n_prompt], self.device)[0].to(self.dtype)
+ context_null = torch.cat([context_null, context_null.new_zeros(text_len -context_null.size(0), context_null.size(1)) ]).unsqueeze(0)
+ else:
+ context_null = None
if input_video is not None: height, width = input_video.shape[-2:]
# NAG_prompt = "static, low resolution, blurry"
@@ -423,13 +451,13 @@ class WanAny2V:
# if NAG_scale > 1: context = torch.cat([context, context_NAG], dim=0)
if self._interrupt: return None
- vace = model_type in ["vace_1.3B","vace_14B", "vace_multitalk_14B", "vace_standin_14B"]
+ vace = model_type in ["vace_1.3B","vace_14B", "vace_multitalk_14B", "vace_standin_14B", "vace_lynx_14B"]
phantom = model_type in ["phantom_1.3B", "phantom_14B"]
fantasy = model_type in ["fantasy"]
multitalk = model_type in ["multitalk", "infinitetalk", "vace_multitalk_14B", "i2v_2_2_multitalk"]
infinitetalk = model_type in ["infinitetalk"]
standin = model_type in ["standin", "vace_standin_14B"]
- lynx = model_type in ["lynx_lite", "lynx_full", "vace_lynx_lite_14B", "vace_lynx_full_14B"]
+ lynx = model_type in ["lynx_lite", "lynx", "vace_lynx_lite_14B", "vace_lynx_14B"]
recam = model_type in ["recam_1.3B"]
ti2v = model_type in ["ti2v_2_2", "lucy_edit"]
lucy_edit= model_type in ["lucy_edit"]
@@ -651,7 +679,9 @@ class WanAny2V:
if vace :
# vace context encode
input_frames = [input_frames.to(self.device)] +([] if input_frames2 is None else [input_frames2.to(self.device)])
- input_masks = [input_masks.to(self.device)] + ([] if input_masks2 is None else [input_masks2.to(self.device)])
+ input_masks = [input_masks.to(self.device)] + ([] if input_masks2 is None else [input_masks2.to(self.device)])
+ if model_type in ["vace_lynx_14B"]:
+ input_ref_images = input_ref_masks = None
input_ref_images = None if input_ref_images is None else [ u.to(self.device) for u in input_ref_images]
input_ref_masks = None if input_ref_masks is None else [ None if u is None else u.to(self.device) for u in input_ref_masks]
ref_images_before = True
@@ -704,21 +734,36 @@ class WanAny2V:
kwargs["freqs"] = freqs
# Lynx
- if lynx:
- from .lynx.resampler import Resampler
- from accelerate import init_empty_weights
- lynx_lite = model_type in ["lynx_lite", "vace_lynx_lite_14B"]
- with init_empty_weights():
- arc_resampler = Resampler( depth=4, dim=1280, dim_head=64, embedding_dim=512, ff_mult=4, heads=20, num_queries=16, output_dim=2048 if lynx_lite else 5120 )
- offload.load_model_data(arc_resampler, os.path.join("ckpts", "wan2.1_lynx_lite_arc_resampler.safetensors" if lynx_lite else "wan2.1_lynx_full_arc_resampler.safetensors"))
- arc_resampler.to(self.device)
- arcface_embed = face_arc_embeds[None,None,:].to(device=self.device, dtype=torch.float)
- ip_hidden_states = arc_resampler(arcface_embed).to(self.dtype)
- ip_hidden_states_uncond = arc_resampler(torch.zeros_like(arcface_embed)).to(self.dtype)
- arc_resampler = None
- gc.collect()
- torch.cuda.empty_cache()
- kwargs["lynx_ip_scale"] = 1.
+ if lynx :
+ if original_input_ref_images is None or len(original_input_ref_images) == 0:
+ lynx = False
+ else:
+ from .lynx.resampler import Resampler
+ from accelerate import init_empty_weights
+ lynx_lite = model_type in ["lynx_lite", "vace_lynx_lite_14B"]
+ ip_hidden_states = ip_hidden_states_uncond = None
+ if True:
+ with init_empty_weights():
+ arc_resampler = Resampler( depth=4, dim=1280, dim_head=64, embedding_dim=512, ff_mult=4, heads=20, num_queries=16, output_dim=2048 if lynx_lite else 5120 )
+ offload.load_model_data(arc_resampler, os.path.join("ckpts", "wan2.1_lynx_lite_arc_resampler.safetensors" if lynx_lite else "wan2.1_lynx_full_arc_resampler.safetensors"))
+ arc_resampler.to(self.device)
+ arcface_embed = face_arc_embeds[None,None,:].to(device=self.device, dtype=torch.float)
+ ip_hidden_states = arc_resampler(arcface_embed).to(self.dtype)
+ ip_hidden_states_uncond = arc_resampler(torch.zeros_like(arcface_embed)).to(self.dtype)
+ arc_resampler = None
+ if not lynx_lite:
+ standin_ref_pos = -1
+ image_ref = original_input_ref_images[standin_ref_pos]
+ from preprocessing.face_preprocessor import FaceProcessor
+ face_processor = FaceProcessor()
+ lynx_ref = face_processor.process(image_ref, resize_to = 256 )
+ lynx_ref_buffer, lynx_ref_buffer_uncond = self.encode_reference_images([lynx_ref], tile_size=VAE_tile_size, any_guidance= any_guidance_at_all)
+ lynx_ref = None
+ gc.collect()
+ torch.cuda.empty_cache()
+ vace_lynx = model_type in ["vace_lynx_14B"]
+ kwargs["lynx_ip_scale"] = control_scale_alt
+ kwargs["lynx_ref_scale"] = control_scale_alt
#Standin
if standin:
@@ -881,6 +926,9 @@ class WanAny2V:
"context" : [context, context_null],
"lynx_ip_embeds": [ip_hidden_states, ip_hidden_states_uncond]
}
+ if model_type in ["lynx", "vace_lynx_14B"]:
+ gen_args["lynx_ref_buffer"] = [lynx_ref_buffer, lynx_ref_buffer_uncond]
+
elif multitalk and audio_proj != None:
if guide_scale == 1:
gen_args = {
diff --git a/models/wan/lynx/attention_processor.py b/models/wan/lynx/attention_processor.py
new file mode 100644
index 0000000..c64291d
--- /dev/null
+++ b/models/wan/lynx/attention_processor.py
@@ -0,0 +1,41 @@
+# Copyright (c) 2025 The Wan Team and The HuggingFace Team.
+# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
+#
+# This file has been modified by Bytedance Ltd. and/or its affiliates on September 15, 2025.
+#
+# Original file was released under Apache License 2.0, with the full license text
+# available at https://github.com/huggingface/diffusers/blob/v0.30.3/LICENSE and https://github.com/Wan-Video/Wan2.1/blob/main/LICENSE.txt.
+#
+# This modified file is released under the same license.
+
+
+from typing import Optional, List
+import torch
+import torch.nn as nn
+from diffusers.models.normalization import RMSNorm
+
+def setup_lynx_attention_layers(blocks, lynx_full, dim):
+ if lynx_full:
+ lynx_cross_dim = 5120
+ lynx_layers = len(blocks)
+ else:
+ lynx_cross_dim = 2048
+ lynx_layers = 20
+ for i, block in enumerate(blocks):
+ if i < lynx_layers:
+ block.cross_attn.to_k_ip = nn.Linear(lynx_cross_dim, dim , bias=lynx_full)
+ block.cross_attn.to_v_ip = nn.Linear(lynx_cross_dim, dim , bias=lynx_full)
+ else:
+ block.cross_attn.to_k_ip = None
+ block.cross_attn.to_v_ip = None
+ if lynx_full:
+ block.cross_attn.registers = nn.Parameter(torch.randn(1, 16, lynx_cross_dim) / dim**0.5)
+ block.cross_attn.norm_rms_k = None
+ block.self_attn.to_k_ref = nn.Linear(dim, dim, bias=True)
+ block.self_attn.to_v_ref = nn.Linear(dim, dim, bias=True)
+ else:
+ block.cross_attn.registers = None
+ block.cross_attn.norm_rms_k = RMSNorm(dim, eps=1e-5, elementwise_affine=False)
+
+
+
diff --git a/models/wan/lynx/flash_attention.py b/models/wan/lynx/flash_attention.py
deleted file mode 100644
index 3bb807d..0000000
--- a/models/wan/lynx/flash_attention.py
+++ /dev/null
@@ -1,60 +0,0 @@
-# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
-# SPDX-License-Identifier: Apache-2.0
-
-import torch
-try:
- from flash_attn_interface import flash_attn_varlen_func # flash attn 3
-except:
- from flash_attn.flash_attn_interface import flash_attn_varlen_func # flash attn 2
-
-def flash_attention(query, key, value, q_lens, kv_lens, causal=False):
- """
- Args:
- query, key, value: [B, H, T, D_h]
- q_lens: list[int] per sequence query length
- kv_lens: list[int] per sequence key/value length
- causal: whether to use causal mask
-
- Returns:
- output: [B, H, T_q, D_h]
- """
- B, H, T_q, D_h = query.shape
- T_k = key.shape[2]
- device = query.device
-
- # Flatten: [B, H, T, D] -> [total_tokens, H, D]
- q = query.permute(0, 2, 1, 3).reshape(B * T_q, H, D_h)
- k = key.permute(0, 2, 1, 3).reshape(B * T_k, H, D_h)
- v = value.permute(0, 2, 1, 3).reshape(B * T_k, H, D_h)
-
- # Prepare cu_seqlens: prefix sum
- q_lens_tensor = torch.tensor(q_lens, device=device, dtype=torch.int32)
- kv_lens_tensor = torch.tensor(kv_lens, device=device, dtype=torch.int32)
-
- cu_seqlens_q = torch.zeros(len(q_lens_tensor) + 1, device=device, dtype=torch.int32)
- cu_seqlens_k = torch.zeros(len(kv_lens_tensor) + 1, device=device, dtype=torch.int32)
-
- cu_seqlens_q[1:] = torch.cumsum(q_lens_tensor, dim=0)
- cu_seqlens_k[1:] = torch.cumsum(kv_lens_tensor, dim=0)
-
- max_seqlen_q = int(q_lens_tensor.max().item())
- max_seqlen_k = int(kv_lens_tensor.max().item())
-
- # Call FlashAttention varlen kernel
- out = flash_attn_varlen_func(
- q,
- k,
- v,
- cu_seqlens_q,
- cu_seqlens_k,
- max_seqlen_q,
- max_seqlen_k,
- causal=causal
- )
- if not torch.is_tensor(out): # flash attn 3
- out = out[0]
-
- # Restore shape: [total_q, H, D_h] -> [B, H, T_q, D_h]
- out = out.view(B, T_q, H, D_h).permute(0, 2, 1, 3).contiguous()
-
- return out
\ No newline at end of file
diff --git a/models/wan/lynx/full_attention_processor.py b/models/wan/lynx/full_attention_processor.py
deleted file mode 100644
index fd0edb7..0000000
--- a/models/wan/lynx/full_attention_processor.py
+++ /dev/null
@@ -1,305 +0,0 @@
-# Copyright (c) 2025 The Wan Team and The HuggingFace Team.
-# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
-#
-# This file has been modified by Bytedance Ltd. and/or its affiliates on September 15, 2025.
-#
-# Original file was released under Apache License 2.0, with the full license text
-# available at https://github.com/huggingface/diffusers/blob/v0.30.3/LICENSE and https://github.com/Wan-Video/Wan2.1/blob/main/LICENSE.txt.
-#
-# This modified file is released under the same license.
-
-
-from typing import Optional, List
-import torch
-import torch.nn as nn
-from diffusers.models.attention_processor import Attention
-from modules.common.flash_attention import flash_attention
-from modules.common.navit_utils import vector_to_list, list_to_vector, merge_token_lists
-
-def new_forward(
- self,
- hidden_states: torch.Tensor,
- encoder_hidden_states: Optional[torch.Tensor] = None,
- attention_mask: Optional[torch.Tensor] = None,
- **cross_attention_kwargs,
-) -> torch.Tensor:
- return self.processor(
- self,
- hidden_states,
- encoder_hidden_states=encoder_hidden_states,
- attention_mask=attention_mask,
- **cross_attention_kwargs,
- )
-Attention.forward = new_forward
-
-class WanIPAttnProcessor(nn.Module):
- def __init__(
- self,
- cross_attention_dim: int,
- dim: int,
- n_registers: int,
- bias: bool,
- ):
- super().__init__()
- self.to_k_ip = nn.Linear(cross_attention_dim, dim, bias=bias)
- self.to_v_ip = nn.Linear(cross_attention_dim, dim, bias=bias)
- if n_registers > 0:
- self.registers = nn.Parameter(torch.randn(1, n_registers, cross_attention_dim) / dim**0.5)
- else:
- self.registers = None
-
- def forward(
- self,
- attn: Attention,
- hidden_states: torch.Tensor,
- encoder_hidden_states: Optional[torch.Tensor] = None,
- ip_hidden_states: Optional[torch.Tensor] = None,
- attention_mask: Optional[torch.Tensor] = None,
- rotary_emb: Optional[torch.Tensor] = None,
- q_lens: List[int] = None,
- kv_lens: List[int] = None,
- ip_lens: List[int] = None,
- ip_scale: float = 1.0,
- ):
- encoder_hidden_states_img = None
- if attn.add_k_proj is not None:
- encoder_hidden_states_img = encoder_hidden_states[:, :257]
- encoder_hidden_states = encoder_hidden_states[:, 257:]
- if encoder_hidden_states is None:
- encoder_hidden_states = hidden_states
-
- query = attn.to_q(hidden_states)
- key = attn.to_k(encoder_hidden_states)
- value = attn.to_v(encoder_hidden_states)
-
- if ip_hidden_states is not None:
-
- if self.registers is not None:
- ip_hidden_states_list = vector_to_list(ip_hidden_states, ip_lens, 1)
- ip_hidden_states_list = merge_token_lists(ip_hidden_states_list, [self.registers] * len(ip_hidden_states_list), 1)
- ip_hidden_states, ip_lens = list_to_vector(ip_hidden_states_list, 1)
-
- ip_query = query
- ip_key = self.to_k_ip(ip_hidden_states)
- ip_value = self.to_v_ip(ip_hidden_states)
- if attn.norm_q is not None:
- ip_query = attn.norm_q(ip_query)
- if attn.norm_k is not None:
- ip_key = attn.norm_k(ip_key)
- ip_query = ip_query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
- ip_key = ip_key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
- ip_value = ip_value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
- ip_hidden_states = flash_attention(
- ip_query, ip_key, ip_value,
- q_lens=q_lens,
- kv_lens=ip_lens
- )
- ip_hidden_states = ip_hidden_states.transpose(1, 2).flatten(2, 3)
- ip_hidden_states = ip_hidden_states.type_as(ip_query)
-
-
- if attn.norm_q is not None:
- query = attn.norm_q(query)
- if attn.norm_k is not None:
- key = attn.norm_k(key)
-
- query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
- key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
- value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
-
- if rotary_emb is not None:
-
- def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor):
- x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
- x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
- return x_out.type_as(hidden_states)
-
- query = apply_rotary_emb(query, rotary_emb)
- key = apply_rotary_emb(key, rotary_emb)
-
- hidden_states = flash_attention(
- query, key, value,
- q_lens=q_lens,
- kv_lens=kv_lens,
- )
-
- hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
- hidden_states = hidden_states.type_as(query)
-
- if ip_hidden_states is not None:
- hidden_states = hidden_states + ip_scale * ip_hidden_states
-
- hidden_states = attn.to_out[0](hidden_states)
- hidden_states = attn.to_out[1](hidden_states)
- return hidden_states
-
-def register_ip_adapter(
- model,
- cross_attention_dim=None,
- n_registers=0,
- init_method="zero",
- dtype=torch.float32,
-):
- attn_procs = {}
- transformer_sd = model.state_dict()
- for layer_idx, block in enumerate(model.blocks):
- name = f"blocks.{layer_idx}.attn2.processor"
- layer_name = name.split(".processor")[0]
- dim = transformer_sd[layer_name + ".to_k.weight"].shape[1]
- attn_procs[name] = WanIPAttnProcessor(
- cross_attention_dim=dim if cross_attention_dim is None else cross_attention_dim,
- dim=dim,
- n_registers=n_registers,
- bias=True,
- )
- if init_method == "zero":
- torch.nn.init.zeros_(attn_procs[name].to_k_ip.weight)
- torch.nn.init.zeros_(attn_procs[name].to_k_ip.bias)
- torch.nn.init.zeros_(attn_procs[name].to_v_ip.weight)
- torch.nn.init.zeros_(attn_procs[name].to_v_ip.bias)
- elif init_method == "clone":
- layer_name = name.split(".processor")[0]
- weights = {
- "to_k_ip.weight": transformer_sd[layer_name + ".to_k.weight"],
- "to_k_ip.bias": transformer_sd[layer_name + ".to_k.bias"],
- "to_v_ip.weight": transformer_sd[layer_name + ".to_v.weight"],
- "to_v_ip.bias": transformer_sd[layer_name + ".to_v.bias"],
- }
- attn_procs[name].load_state_dict(weights)
- elif init_method == "random":
- pass
- else:
- raise ValueError(f"{init_method} is not supported.")
- block.attn2.processor = attn_procs[name]
- ip_layers = torch.nn.ModuleList(attn_procs.values())
- ip_layers.to(device=model.device, dtype=dtype)
- return model, ip_layers
-
-
-class WanRefAttnProcessor(nn.Module):
- def __init__(
- self,
- dim: int,
- bias: bool,
- ):
- super().__init__()
- self.to_k_ref = nn.Linear(dim, dim, bias=bias)
- self.to_v_ref = nn.Linear(dim, dim, bias=bias)
-
- def forward(
- self,
- attn: Attention,
- hidden_states: torch.Tensor,
- encoder_hidden_states: Optional[torch.Tensor] = None,
- attention_mask: Optional[torch.Tensor] = None,
- rotary_emb: Optional[torch.Tensor] = None,
- q_lens: List[int] = None,
- kv_lens: List[int] = None,
- ref_feature: Optional[tuple] = None,
- ref_scale: float = 1.0,
- ):
- encoder_hidden_states_img = None
- if attn.add_k_proj is not None:
- encoder_hidden_states_img = encoder_hidden_states[:, :257]
- encoder_hidden_states = encoder_hidden_states[:, 257:]
- if encoder_hidden_states is None:
- encoder_hidden_states = hidden_states
-
- query = attn.to_q(hidden_states)
- key = attn.to_k(encoder_hidden_states)
- value = attn.to_v(encoder_hidden_states)
-
- if ref_feature is None:
- ref_hidden_states = None
- else:
- ref_hidden_states, ref_lens = ref_feature
- ref_query = query
- ref_key = self.to_k_ref(ref_hidden_states)
- ref_value = self.to_v_ref(ref_hidden_states)
- if attn.norm_q is not None:
- ref_query = attn.norm_q(ref_query)
- if attn.norm_k is not None:
- ref_key = attn.norm_k(ref_key)
- ref_query = ref_query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
- ref_key = ref_key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
- ref_value = ref_value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
- ref_hidden_states = flash_attention(
- ref_query, ref_key, ref_value,
- q_lens=q_lens,
- kv_lens=ref_lens
- )
- ref_hidden_states = ref_hidden_states.transpose(1, 2).flatten(2, 3)
- ref_hidden_states = ref_hidden_states.type_as(ref_query)
-
- if attn.norm_q is not None:
- query = attn.norm_q(query)
- if attn.norm_k is not None:
- key = attn.norm_k(key)
-
- query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
- key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
- value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
-
- if rotary_emb is not None:
-
- def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor):
- x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
- x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
- return x_out.type_as(hidden_states)
-
- query = apply_rotary_emb(query, rotary_emb)
- key = apply_rotary_emb(key, rotary_emb)
-
- hidden_states = flash_attention(
- query, key, value,
- q_lens=q_lens,
- kv_lens=kv_lens,
- )
-
- hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
- hidden_states = hidden_states.type_as(query)
-
- if ref_hidden_states is not None:
- hidden_states = hidden_states + ref_scale * ref_hidden_states
-
- hidden_states = attn.to_out[0](hidden_states)
- hidden_states = attn.to_out[1](hidden_states)
- return hidden_states
-
-
-def register_ref_adapter(
- model,
- init_method="zero",
- dtype=torch.float32,
-):
- attn_procs = {}
- transformer_sd = model.state_dict()
- for layer_idx, block in enumerate(model.blocks):
- name = f"blocks.{layer_idx}.attn1.processor"
- layer_name = name.split(".processor")[0]
- dim = transformer_sd[layer_name + ".to_k.weight"].shape[0]
- attn_procs[name] = WanRefAttnProcessor(
- dim=dim,
- bias=True,
- )
- if init_method == "zero":
- torch.nn.init.zeros_(attn_procs[name].to_k_ref.weight)
- torch.nn.init.zeros_(attn_procs[name].to_k_ref.bias)
- torch.nn.init.zeros_(attn_procs[name].to_v_ref.weight)
- torch.nn.init.zeros_(attn_procs[name].to_v_ref.bias)
- elif init_method == "clone":
- weights = {
- "to_k_ref.weight": transformer_sd[layer_name + ".to_k.weight"],
- "to_k_ref.bias": transformer_sd[layer_name + ".to_k.bias"],
- "to_v_ref.weight": transformer_sd[layer_name + ".to_v.weight"],
- "to_v_ref.bias": transformer_sd[layer_name + ".to_v.bias"],
- }
- attn_procs[name].load_state_dict(weights)
- elif init_method == "random":
- pass
- else:
- raise ValueError(f"{init_method} is not supported.")
- block.attn1.processor = attn_procs[name]
- ref_layers = torch.nn.ModuleList(attn_procs.values())
- ref_layers.to(device=model.device, dtype=dtype)
- return model, ref_layers
diff --git a/models/wan/lynx/inference_utils.py b/models/wan/lynx/inference_utils.py
deleted file mode 100644
index c1129f3..0000000
--- a/models/wan/lynx/inference_utils.py
+++ /dev/null
@@ -1,39 +0,0 @@
-# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
-# SPDX-License-Identifier: Apache-2.0
-
-from typing import Optional, Union
-
-import torch
-import numpy as np
-
-from PIL import Image
-from dataclasses import dataclass, field
-
-
-dtype_mapping = {
- "bf16": torch.bfloat16,
- "fp16": torch.float16,
- "fp32": torch.float32
-}
-
-
-@dataclass
-class SubjectInfo:
- name: str = ""
- image_pil: Optional[Image.Image] = None
- landmarks: Optional[Union[np.ndarray, torch.Tensor]] = None
- face_embeds: Optional[Union[np.ndarray, torch.Tensor]] = None
-
-
-@dataclass
-class VideoStyleInfo: # key names should match those used in style.yaml file
- style_name: str = 'none'
- num_frames: int = 81
- seed: int = -1
- guidance_scale: float = 5.0
- guidance_scale_i: float = 2.0
- num_inference_steps: int = 50
- width: int = 832
- height: int = 480
- prompt: str = ''
- negative_prompt: str = ''
\ No newline at end of file
diff --git a/models/wan/lynx/light_attention_processor.py b/models/wan/lynx/light_attention_processor.py
deleted file mode 100644
index a3c7516..0000000
--- a/models/wan/lynx/light_attention_processor.py
+++ /dev/null
@@ -1,194 +0,0 @@
-# Copyright (c) 2025 The Wan Team and The HuggingFace Team.
-# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
-#
-# This file has been modified by Bytedance Ltd. and/or its affiliates on September 15, 2025.
-#
-# Original file was released under Apache License 2.0, with the full license text
-# available at https://github.com/huggingface/diffusers/blob/v0.30.3/LICENSE and https://github.com/Wan-Video/Wan2.1/blob/main/LICENSE.txt.
-#
-# This modified file is released under the same license.
-
-from typing import Tuple, Union, Optional
-
-import torch
-import torch.nn as nn
-import torch.nn.functional as F
-
-from diffusers.models.normalization import RMSNorm
-
-
-def register_ip_adapter_wan(
- model,
- hidden_size=5120,
- cross_attention_dim=2048,
- dtype=torch.float32,
- init_method="zero",
- layers=None
-):
- attn_procs = {}
- transformer_sd = model.state_dict()
-
- if layers is None:
- layers = list(range(0, len(model.blocks)))
- elif isinstance(layers, int): # Only interval provided
- layers = list(range(0, len(model.blocks), layers))
-
- for i, block in enumerate(model.blocks):
- if i not in layers:
- continue
-
- name = f"blocks.{i}.attn2.processor"
- attn_procs[name] = IPAWanAttnProcessor2_0(
- hidden_size=hidden_size,
- cross_attention_dim=cross_attention_dim
- )
-
- if init_method == "zero":
- torch.nn.init.zeros_(attn_procs[name].to_k_ip.weight)
- torch.nn.init.zeros_(attn_procs[name].to_v_ip.weight)
- elif init_method == "clone":
- layer_name = name.split(".processor")[0]
- weights = {
- "to_k_ip.weight": transformer_sd[layer_name + ".to_k.weight"],
- "to_v_ip.weight": transformer_sd[layer_name + ".to_v.weight"],
- }
- attn_procs[name].load_state_dict(weights)
- else:
- raise ValueError(f"{init_method} is not supported.")
-
- block.attn2.processor = attn_procs[name]
-
- ip_layers = torch.nn.ModuleList(attn_procs.values())
- ip_layers.to(model.device, dtype=dtype)
-
- return model, ip_layers
-
-
-class IPAWanAttnProcessor2_0(torch.nn.Module):
- def __init__(
- self,
- hidden_size,
- cross_attention_dim=None,
- scale=1.0,
- bias=False,
- ):
- super().__init__()
-
- if not hasattr(F, "scaled_dot_product_attention"):
- raise ImportError("IPAWanAttnProcessor requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
-
- self.hidden_size = hidden_size
- self.cross_attention_dim = cross_attention_dim
- self.scale = scale
-
- self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=bias)
- self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=bias)
-
- torch.nn.init.zeros_(self.to_k_ip.weight)
- torch.nn.init.zeros_(self.to_v_ip.weight)
- if bias:
- torch.nn.init.zeros_(self.to_k_ip.bias)
- torch.nn.init.zeros_(self.to_v_ip.bias)
-
- self.norm_rms_k = RMSNorm(hidden_size, eps=1e-5, elementwise_affine=False)
-
-
- def __call__(
- self,
- attn,
- hidden_states: torch.Tensor,
- image_embed: torch.Tensor = None,
- ip_scale: float = None,
- encoder_hidden_states: Optional[torch.Tensor] = None,
- attention_mask: Optional[torch.Tensor] = None,
- rotary_emb: Optional[torch.Tensor] = None,
- ) -> torch.Tensor:
- encoder_hidden_states_img = None
- if attn.add_k_proj is not None:
- encoder_hidden_states_img = encoder_hidden_states[:, :257]
- encoder_hidden_states = encoder_hidden_states[:, 257:]
- if encoder_hidden_states is None:
- encoder_hidden_states = hidden_states
-
- query = attn.to_q(hidden_states)
- key = attn.to_k(encoder_hidden_states)
- value = attn.to_v(encoder_hidden_states)
-
- # =============================================================
- batch_size = image_embed.size(0)
-
- ip_hidden_states = image_embed
- ip_query = query # attn.to_q(hidden_states.clone())
- ip_key = self.to_k_ip(ip_hidden_states)
- ip_value = self.to_v_ip(ip_hidden_states)
-
- if attn.norm_q is not None:
- ip_query = attn.norm_q(ip_query)
- ip_key = self.norm_rms_k(ip_key)
-
- ip_inner_dim = ip_key.shape[-1]
- ip_head_dim = ip_inner_dim // attn.heads
-
- ip_query = ip_query.view(batch_size, -1, attn.heads, ip_head_dim).transpose(1, 2)
- ip_key = ip_key.view(batch_size, -1, attn.heads, ip_head_dim).transpose(1, 2)
- ip_value = ip_value.view(batch_size, -1, attn.heads, ip_head_dim).transpose(1, 2)
-
- ip_hidden_states = F.scaled_dot_product_attention(
- ip_query, ip_key, ip_value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
- )
-
- ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * ip_head_dim)
- ip_hidden_states = ip_hidden_states.to(ip_query.dtype)
- # ===========================================================================
-
- if attn.norm_q is not None:
- query = attn.norm_q(query)
- if attn.norm_k is not None:
- key = attn.norm_k(key)
-
- query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
- key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
- value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
-
- if rotary_emb is not None:
-
- def apply_rotary_emb_inner(hidden_states: torch.Tensor, freqs: torch.Tensor):
- x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
- x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
- return x_out.type_as(hidden_states)
-
- query = apply_rotary_emb_inner(query, rotary_emb)
- key = apply_rotary_emb_inner(key, rotary_emb)
-
- # I2V task
- hidden_states_img = None
- if encoder_hidden_states_img is not None:
- key_img = attn.add_k_proj(encoder_hidden_states_img)
- key_img = attn.norm_added_k(key_img)
- value_img = attn.add_v_proj(encoder_hidden_states_img)
-
- key_img = key_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
- value_img = value_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
-
- hidden_states_img = F.scaled_dot_product_attention(
- query, key_img, value_img, attn_mask=None, dropout_p=0.0, is_causal=False
- )
- hidden_states_img = hidden_states_img.transpose(1, 2).flatten(2, 3)
- hidden_states_img = hidden_states_img.type_as(query)
- hidden_states = F.scaled_dot_product_attention(
- query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
- )
- hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
- hidden_states = hidden_states.type_as(query)
-
- if hidden_states_img is not None:
- hidden_states = hidden_states + hidden_states_img
-
- # Add IPA residual
- ip_scale = ip_scale or self.scale
- hidden_states = hidden_states + ip_scale * ip_hidden_states
-
- hidden_states = attn.to_out[0](hidden_states)
- hidden_states = attn.to_out[1](hidden_states)
-
- return hidden_states
\ No newline at end of file
diff --git a/models/wan/lynx/model_utils_wan.py b/models/wan/lynx/model_utils_wan.py
deleted file mode 100644
index 2fd1170..0000000
--- a/models/wan/lynx/model_utils_wan.py
+++ /dev/null
@@ -1,264 +0,0 @@
-# Copyright (c) 2025 The Wan Team and The HuggingFace Team.
-# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
-# SPDX-License-Identifier: Apache-2.0
-#
-# This file has been modified by Bytedance Ltd. and/or its affiliates on September 15, 2025.
-#
-# Original file was released under Apache License 2.0, with the full license text
-# available at https://github.com/huggingface/diffusers/blob/v0.30.3/LICENSE and https://github.com/Wan-Video/Wan2.1/blob/main/LICENSE.txt.
-#
-# This modified file is released under the same license.
-
-import os
-import math
-import torch
-
-from typing import List, Optional, Tuple, Union
-
-from diffusers.models.embeddings import get_3d_rotary_pos_embed
-from diffusers.pipelines.cogvideo.pipeline_cogvideox import get_resize_crop_region_for_grid
-
-from diffusers import FlowMatchEulerDiscreteScheduler
-
-""" Utility functions for Wan2.1-T2I model """
-
-
-def cal_mean_and_std(vae, device, dtype):
- # https://github.com/Wan-Video/Wan2.1/blob/main/wan/modules/vae.py#L483
-
- # latents_mean
- latents_mean = torch.tensor(vae.config.latents_mean).view(
- 1, vae.config.z_dim, 1, 1, 1).to(device, dtype)
-
- # latents_std
- latents_std = 1.0 / torch.tensor(vae.config.latents_std).view(
- 1, vae.config.z_dim, 1, 1, 1).to(device, dtype)
-
- return latents_mean, latents_std
-
-
-def encode_video(vae, video):
- # Input video is formatted as [B, F, C, H, W]
- video = video.to(vae.device, dtype=vae.dtype)
- video = video.unsqueeze(0) if len(video.shape) == 4 else video
-
- # VAE takes [B, C, F, H, W]
- video = video.permute(0, 2, 1, 3, 4)
- latent_dist = vae.encode(video).latent_dist
-
- mean, std = cal_mean_and_std(vae, vae.device, vae.dtype)
-
- # NOTE: this implementation is weird but I still borrow it from the official
- # codes. A standard normailization should be (x - mean) / std, but the std
- # here is computed by `1 / vae.config.latents_std` from cal_mean_and_std().
-
- # Sample latent with scaling
- video_latent = (latent_dist.sample() - mean) * std
-
- # Return as [B, C, F, H, W] as required by Wan
- return video_latent
-
-
-def decode_latent(vae, latent):
- # Input latent is formatted as [B, C, F, H, W]
- latent = latent.to(vae.device, dtype=vae.dtype)
- latent = latent.unsqueeze(0) if len(latent.shape) == 4 else latent
-
- mean, std = cal_mean_and_std(vae, latent.device, latent.dtype)
- latent = latent / std + mean
-
- # VAE takes [B, C, F, H, W]
- frames = vae.decode(latent).sample
-
- # Return as [B, F, C, H, W]
- frames = frames.permute(0, 2, 1, 3, 4).float()
-
- return frames
-
-
-def encode_prompt(
- tokenizer,
- text_encoder,
- prompt: Union[str, List[str]],
- num_videos_per_prompt: int = 1,
- max_sequence_length: int = 226,
- device: Optional[torch.device] = None,
- dtype: Optional[torch.dtype] = None,
- text_input_ids=None,
- prompt_attention_mask=None,
-):
- prompt = [prompt] if isinstance(prompt, str) else prompt
- batch_size = len(prompt)
-
- if tokenizer is not None:
- text_inputs = tokenizer(
- prompt,
- padding="max_length",
- max_length=max_sequence_length,
- truncation=True,
- add_special_tokens=True,
- return_tensors="pt",
- )
- text_input_ids = text_inputs.input_ids
- prompt_attention_mask = text_inputs.attention_mask
- else:
- if text_input_ids is None:
- raise ValueError("`text_input_ids` must be provided when the tokenizer is not specified.")
-
- seq_lens = prompt_attention_mask.gt(0).sum(dim=1).long()
- prompt_embeds = text_encoder(text_input_ids.to(device), prompt_attention_mask.to(device)).last_hidden_state
-
- prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
- prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
- prompt_embeds = torch.stack(
- [torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
- )
-
- # duplicate text embeddings for each generation per prompt, using mps friendly method
- _, seq_len, _ = prompt_embeds.shape
- prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
- prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
-
- return prompt_embeds, prompt_attention_mask
-
-
-def compute_prompt_embeddings(
- tokenizer, text_encoder, prompt, max_sequence_length, device, dtype, requires_grad: bool = False
-):
- if requires_grad:
- prompt_embeds = encode_prompt(
- tokenizer,
- text_encoder,
- prompt,
- num_videos_per_prompt=1,
- max_sequence_length=max_sequence_length,
- device=device,
- dtype=dtype,
- )
- else:
- with torch.no_grad():
- prompt_embeds = encode_prompt(
- tokenizer,
- text_encoder,
- prompt,
- num_videos_per_prompt=1,
- max_sequence_length=max_sequence_length,
- device=device,
- dtype=dtype,
- )
- return prompt_embeds[0]
-
-
-def prepare_rotary_positional_embeddings(
- height: int,
- width: int,
- num_frames: int,
- vae_scale_factor_spatial: int = 8,
- patch_size: int = 2,
- attention_head_dim: int = 64,
- device: Optional[torch.device] = None,
- base_height: int = 480,
- base_width: int = 720,
-) -> Tuple[torch.Tensor, torch.Tensor]:
- grid_height = height // (vae_scale_factor_spatial * patch_size)
- grid_width = width // (vae_scale_factor_spatial * patch_size)
- base_size_width = base_width // (vae_scale_factor_spatial * patch_size)
- base_size_height = base_height // (vae_scale_factor_spatial * patch_size)
-
- grid_crops_coords = get_resize_crop_region_for_grid((grid_height, grid_width), base_size_width, base_size_height)
- freqs_cos, freqs_sin = get_3d_rotary_pos_embed(
- embed_dim=attention_head_dim,
- crops_coords=grid_crops_coords,
- grid_size=(grid_height, grid_width),
- temporal_size=num_frames,
- )
-
- freqs_cos = freqs_cos.to(device=device)
- freqs_sin = freqs_sin.to(device=device)
- return freqs_cos, freqs_sin
-
-
-def prepare_sigmas(
- scheduler: FlowMatchEulerDiscreteScheduler,
- sigmas: torch.Tensor,
- batch_size: int,
- num_train_timesteps: int,
- flow_weighting_scheme: str = "none",
- flow_logit_mean: float = 0.0,
- flow_logit_std: float = 1.0,
- flow_mode_scale: float = 1.29,
- device: torch.device = torch.device("cpu"),
- generator: Optional[torch.Generator] = None,
-) -> torch.Tensor:
- if isinstance(scheduler, FlowMatchEulerDiscreteScheduler):
- weights = compute_density_for_timestep_sampling(
- weighting_scheme=flow_weighting_scheme,
- batch_size=batch_size,
- logit_mean=flow_logit_mean,
- logit_std=flow_logit_std,
- mode_scale=flow_mode_scale,
- device=device,
- generator=generator,
- )
- indices = (weights * num_train_timesteps).long()
- else:
- raise ValueError(f"Unsupported scheduler type {type(scheduler)}")
-
- return sigmas[indices]
-
-
-def compute_density_for_timestep_sampling(
- weighting_scheme: str,
- batch_size: int,
- logit_mean: float = None,
- logit_std: float = None,
- mode_scale: float = None,
- device: torch.device = torch.device("cpu"),
- generator: Optional[torch.Generator] = None,
-) -> torch.Tensor:
- r"""
- Compute the density for sampling the timesteps when doing SD3 training.
-
- Courtesy: This was contributed by Rafie Walker in https://github.com/huggingface/diffusers/pull/8528.
-
- SD3 paper reference: https://arxiv.org/abs/2403.03206v1.
- """
- if weighting_scheme == "logit_normal":
- # See 3.1 in the SD3 paper ($rf/lognorm(0.00,1.00)$).
- u = torch.normal(mean=logit_mean, std=logit_std, size=(batch_size,), device=device, generator=generator)
- u = torch.nn.functional.sigmoid(u)
- elif weighting_scheme == "mode":
- u = torch.rand(size=(batch_size,), device=device, generator=generator)
- u = 1 - u - mode_scale * (torch.cos(math.pi * u / 2) ** 2 - 1 + u)
- else:
- u = torch.rand(size=(batch_size,), device=device, generator=generator)
- return u
-
-
-def expand_tensor_dims(tensor: torch.Tensor, ndim: int) -> torch.Tensor:
- assert len(tensor.shape) <= ndim
- return tensor.reshape(tensor.shape + (1,) * (ndim - len(tensor.shape)))
-
-
-def flow_match_xt(x0: torch.Tensor, n: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
- r"""Forward process of flow matching."""
- return (1.0 - t) * x0 + t * n
-
-
-def flow_match_target(n: torch.Tensor, x0: torch.Tensor) -> torch.Tensor:
- r"""Loss target for flow matching."""
- return n - x0
-
-
-def prepare_loss_weights(
- scheduler: FlowMatchEulerDiscreteScheduler,
- sigmas: Optional[torch.Tensor] = None,
- flow_weighting_scheme: str = "none",
-
-) -> torch.Tensor:
-
- assert isinstance(scheduler, FlowMatchEulerDiscreteScheduler)
-
- from diffusers.training_utils import compute_loss_weighting_for_sd3
-
- return compute_loss_weighting_for_sd3(sigmas=sigmas, weighting_scheme=flow_weighting_scheme)
\ No newline at end of file
diff --git a/models/wan/modules/model.py b/models/wan/modules/model.py
index 07e3e54..30f6172 100644
--- a/models/wan/modules/model.py
+++ b/models/wan/modules/model.py
@@ -131,7 +131,7 @@ class WanRMSNorm(nn.Module):
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
- def forward(self, x):
+ def forward(self, x, in_place= True):
r"""
Args:
x(Tensor): Shape [B, L, C]
@@ -141,7 +141,10 @@ class WanRMSNorm(nn.Module):
y = y.mean(dim=-1, keepdim=True)
y += self.eps
y.rsqrt_()
- x *= y
+ if in_place:
+ x *= y
+ else:
+ x = x * y
x *= self.weight
return x
# return self._norm(x).type_as(x) * self.weight
@@ -274,7 +277,7 @@ class WanSelfAttention(nn.Module):
else:
return x, None
- def forward(self, xlist, grid_sizes, freqs, block_mask = None, ref_target_masks = None, ref_images_count = 0, standin_phase =-1):
+ def forward(self, xlist, grid_sizes, freqs, block_mask = None, ref_target_masks = None, ref_images_count = 0, standin_phase =-1, lynx_ref_buffer = None, lynx_ref_scale = 0, sub_x_no=0):
r"""
Args:
x(Tensor): Shape [B, L, num_heads, C / num_heads]
@@ -287,7 +290,21 @@ class WanSelfAttention(nn.Module):
b, s, n, d = *x.shape[:2], self.num_heads, self.head_dim
# query, key, value function
- q, k, v = self.q(x), self.k(x), self.v(x)
+ q = self.q(x)
+ ref_hidden_states = None
+ if not lynx_ref_buffer is None:
+ lynx_ref_features = lynx_ref_buffer[self.block_no]
+ if self.norm_q is not None: ref_query = self.norm_q(q, in_place = False)
+ ref_key = self.to_k_ref(lynx_ref_features)
+ ref_value = self.to_v_ref(lynx_ref_features)
+ if self.norm_k is not None: ref_key = self.norm_k(ref_key)
+ ref_query, ref_key, ref_value = ref_query.unflatten(2, (self.num_heads, -1)), ref_key.unflatten(2, (self.num_heads, -1)), ref_value.unflatten(2, (self.num_heads, -1))
+ qkv_list = [ref_query, ref_key, ref_value ]
+ del ref_query, ref_key, ref_value
+ ref_hidden_states = pay_attention(qkv_list)
+
+ k, v = self.k(x), self.v(x)
+
if standin_phase == 1:
q += self.q_loras(x)
k += self.k_loras(x)
@@ -347,6 +364,8 @@ class WanSelfAttention(nn.Module):
)
del q,k,v
+ if ref_hidden_states is not None:
+ x.add_(ref_hidden_states, alpha= lynx_ref_scale)
x = x.flatten(2)
x = self.o(x)
@@ -537,6 +556,10 @@ class WanAttentionBlock(nn.Module):
motion_vec = None,
lynx_ip_embeds = None,
lynx_ip_scale = 0,
+ lynx_ref_scale = 0,
+ lynx_feature_extractor = False,
+ lynx_ref_buffer = None,
+ sub_x_no =0,
):
r"""
Args:
@@ -571,6 +594,7 @@ class WanAttentionBlock(nn.Module):
x_mod *= 1 + e[1]
x_mod += e[0]
x_mod = restore_latent_shape(x_mod)
+
if cam_emb != None:
cam_emb = self.cam_encoder(cam_emb)
cam_emb = cam_emb.repeat(1, 2, 1)
@@ -579,8 +603,9 @@ class WanAttentionBlock(nn.Module):
x_mod += cam_emb
xlist = [x_mod.to(attention_dtype)]
+ if lynx_feature_extractor: get_cache("lynx_ref_buffer")[sub_x_no][self.block_no] = xlist[0]
del x_mod
- y, x_ref_attn_map = self.self_attn( xlist, grid_sizes, freqs, block_mask = block_mask, ref_target_masks = multitalk_masks, ref_images_count = ref_images_count, standin_phase= standin_phase, )
+ y, x_ref_attn_map = self.self_attn( xlist, grid_sizes, freqs, block_mask = block_mask, ref_target_masks = multitalk_masks, ref_images_count = ref_images_count, standin_phase= standin_phase, lynx_ref_buffer = lynx_ref_buffer, lynx_ref_scale = lynx_ref_scale, sub_x_no = sub_x_no)
y = y.to(dtype)
if cam_emb != None: y = self.projector(y)
@@ -1073,30 +1098,9 @@ class WanModel(ModelMixin, ConfigMixin):
block.self_attn.v_loras = LoRALinearLayer(dim, dim, rank=128)
if lynx is not None:
- from ..lynx.light_attention_processor import IPAWanAttnProcessor2_0
+ from ..lynx.attention_processor import setup_lynx_attention_layers
lynx_full = lynx=="full"
- if lynx_full:
- lynx_cross_dim = 5120
- lynx_layers = len(self.blocks)
- else:
- lynx_cross_dim = 2048
- lynx_layers = 20
- for i, block in enumerate(self.blocks):
- if i < lynx_layers:
- attn = IPAWanAttnProcessor2_0(hidden_size=dim, cross_attention_dim = lynx_cross_dim,)
- block.cross_attn.to_k_ip = attn.to_k_ip
- block.cross_attn.to_v_ip = attn.to_v_ip
- else:
- block.cross_attn.to_k_ip = None
- block.cross_attn.to_v_ip = None
- if lynx_full:
- block.cross_attn.registers = nn.Parameter(torch.randn(1, 16, lynx_cross_dim) / dim**0.5)
- block.cross_attn.norm_rms_k = None
- else:
- block.cross_attn.registers = None
- block.cross_attn.norm_rms_k = attn.norm_rms_k
-
-
+ setup_lynx_attention_layers(self.blocks, lynx_full, dim)
if animate:
self.pose_patch_embedding = nn.Conv3d(
@@ -1302,7 +1306,10 @@ class WanModel(ModelMixin, ConfigMixin):
pose_latents=None,
face_pixel_values=None,
lynx_ip_embeds = None,
- lynx_ip_scale = 0,
+ lynx_ip_scale = 0,
+ lynx_ref_scale = 0,
+ lynx_feature_extractor = False,
+ lynx_ref_buffer = None,
):
# patch_dtype = self.patch_embedding.weight.dtype
@@ -1389,6 +1396,8 @@ class WanModel(ModelMixin, ConfigMixin):
audio_context_lens=audio_context_lens,
ref_images_count=ref_images_count,
lynx_ip_scale= lynx_ip_scale,
+ lynx_ref_scale = lynx_ref_scale,
+ lynx_feature_extractor = lynx_feature_extractor,
)
_flag_df = t.dim() == 2
@@ -1413,6 +1422,12 @@ class WanModel(ModelMixin, ConfigMixin):
else:
lynx_ip_embeds_list = lynx_ip_embeds
+ if lynx_ref_buffer is None:
+ lynx_ref_buffer_list = [None] * len(x_list)
+ else:
+ lynx_ref_buffer_list = lynx_ref_buffer
+
+
if self.inject_sample_info and fps!=None:
fps = torch.tensor(fps, dtype=torch.long, device=device)
@@ -1562,11 +1577,11 @@ class WanModel(ModelMixin, ConfigMixin):
continue
x_list[0] = block(x_list[0], context = context_list[0], audio_scale= audio_scale_list[0], e= e0, **kwargs)
else:
- for i, (x, context, hints, audio_scale, multitalk_audio, multitalk_masks, should_calc, motion_vec, lynx_ip_embeds) in enumerate(zip(x_list, context_list, hints_list, audio_scale_list, multitalk_audio_list, multitalk_masks_list, x_should_calc,motion_vec_list, lynx_ip_embeds_list)):
+ for i, (x, context, hints, audio_scale, multitalk_audio, multitalk_masks, should_calc, motion_vec, lynx_ip_embeds,lynx_ref_buffer) in enumerate(zip(x_list, context_list, hints_list, audio_scale_list, multitalk_audio_list, multitalk_masks_list, x_should_calc,motion_vec_list, lynx_ip_embeds_list,lynx_ref_buffer_list)):
if should_calc:
- x_list[i] = block(x, context = context, hints= hints, audio_scale= audio_scale, multitalk_audio = multitalk_audio, multitalk_masks =multitalk_masks, e= e0, motion_vec = motion_vec, lynx_ip_embeds= lynx_ip_embeds, **kwargs)
+ x_list[i] = block(x, context = context, hints= hints, audio_scale= audio_scale, multitalk_audio = multitalk_audio, multitalk_masks =multitalk_masks, e= e0, motion_vec = motion_vec, lynx_ip_embeds= lynx_ip_embeds, lynx_ref_buffer = lynx_ref_buffer, sub_x_no =i, **kwargs)
del x
- context = hints = audio_embedding = None
+ context = hints = None
if skips_steps_cache != None:
if joint_pass:
@@ -1590,7 +1605,9 @@ class WanModel(ModelMixin, ConfigMixin):
torch.sub(x_list[0], ori_hidden_states[0], out=residual)
skips_steps_cache.previous_residual[x_id] = residual
residual, ori_hidden_states = None, None
-
+ if lynx_feature_extractor:
+ return get_cache("lynx_ref_buffer")
+
for i, x in enumerate(x_list):
if chipmunk:
x = reverse_voxel_chunk_no_padding(x.transpose(1, 2).unsqueeze(-1), x_og_shape, voxel_shape).squeeze(-1)
diff --git a/models/wan/wan_handler.py b/models/wan/wan_handler.py
index b1f5942..95a43ee 100644
--- a/models/wan/wan_handler.py
+++ b/models/wan/wan_handler.py
@@ -18,7 +18,7 @@ def test_standin(base_model_type):
return base_model_type in ["standin", "vace_standin_14B"]
def test_lynx(base_model_type):
- return base_model_type in ["lynx_lite", "vace_lynx_lite_14B", "lynx_full", "vace_lynx_full_14B"]
+ return base_model_type in ["lynx_lite", "vace_lynx_lite_14B", "lynx", "vace_lynx_14B"]
def test_wan_5B(base_model_type):
return base_model_type in ["ti2v_2_2", "lucy_edit"]
@@ -86,7 +86,7 @@ class family_handler():
extra_model_def["multitalk_class"] = test_multitalk(base_model_type)
extra_model_def["standin_class"] = test_standin(base_model_type)
extra_model_def["lynx_class"] = test_lynx(base_model_type)
- vace_class = base_model_type in ["vace_14B", "vace_1.3B", "vace_multitalk_14B", "vace_standin_14B"]
+ vace_class = base_model_type in ["vace_14B", "vace_1.3B", "vace_multitalk_14B", "vace_standin_14B", "vace_lynx_14B"]
extra_model_def["vace_class"] = vace_class
if base_model_type in ["animate"]:
@@ -140,6 +140,7 @@ class family_handler():
"selection":[ "", "A"],
"visible": False
}
+ extra_model_def["v2i_switch_supported"] = True
if base_model_type in ["infinitetalk"]:
@@ -213,15 +214,6 @@ class family_handler():
"visible": False
}
- # extra_model_def["image_ref_choices"] = {
- # "choices": [("None", ""),
- # ("People / Objects", "I"),
- # ("Landscape followed by People / Objects (if any)", "KI"),
- # ],
- # "visible": False,
- # "letters_filter": "KFI",
- # }
-
extra_model_def["video_guide_outpainting"] = [0,1]
extra_model_def["keep_frames_video_guide_not_supported"] = True
extra_model_def["extract_guide_from_window_start"] = True
@@ -257,17 +249,51 @@ class family_handler():
extra_model_def["guide_inpaint_color"] = 127.5
extra_model_def["forced_guide_mask_inputs"] = True
extra_model_def["return_image_refs_tensor"] = True
+ extra_model_def["v2i_switch_supported"] = True
+ if base_model_type in ["vace_lynx_14B"]:
+ extra_model_def["set_video_prompt_type"]="Q"
+ extra_model_def["control_net_weight_alt_name"] = "Lynx"
+ extra_model_def["image_ref_choices"] = { "choices": [("None", ""),("Person Face", "I")], "letters_filter": "I"}
+ extra_model_def["no_background_removal"] = True
+ extra_model_def["fit_into_canvas_image_refs"] = 0
+
- if base_model_type in ["standin", "lynx_lite", "lynx_full"]:
+
+ if base_model_type in ["standin"]:
+ extra_model_def["v2i_switch_supported"] = True
+
+ if base_model_type in ["lynx_lite", "lynx"]:
extra_model_def["fit_into_canvas_image_refs"] = 0
+ extra_model_def["guide_custom_choices"] = {
+ "choices":[("Use Reference Image which is a Person Face", ""),
+ ("Video to Video guided by Text Prompt & Reference Image", "GUV"),
+ ("Video to Video on the Area of the Video Mask", "GVA")],
+ "default": "",
+ "letters_filter": "GUVA",
+ "label": "Video to Video",
+ "show_label" : False,
+ }
+
+ extra_model_def["mask_preprocessing"] = {
+ "selection":[ "", "A"],
+ "visible": False
+ }
+
extra_model_def["image_ref_choices"] = {
"choices": [
("No Reference Image", ""),
("Reference Image is a Person Face", "I"),
],
+ "visible": False,
"letters_filter":"I",
}
+ extra_model_def["set_video_prompt_type"]= "Q"
+ extra_model_def["no_background_removal"] = True
+ extra_model_def["v2i_switch_supported"] = True
+ extra_model_def["control_net_weight_alt_name"] = "Lynx"
+
+
if base_model_type in ["phantom_1.3B", "phantom_14B"]:
extra_model_def["image_ref_choices"] = {
"choices": [("Reference Image", "I")],
@@ -326,8 +352,8 @@ class family_handler():
@staticmethod
def query_supported_types():
- return ["multitalk", "infinitetalk", "fantasy", "vace_14B", "vace_multitalk_14B", "vace_standin_14B",
- "t2v_1.3B", "standin", "lynx_lite", "lynx_full", "t2v", "vace_1.3B", "phantom_1.3B", "phantom_14B",
+ return ["multitalk", "infinitetalk", "fantasy", "vace_14B", "vace_multitalk_14B", "vace_standin_14B", "vace_lynx_14B",
+ "t2v_1.3B", "standin", "lynx_lite", "lynx", "t2v", "vace_1.3B", "phantom_1.3B", "phantom_14B",
"recam_1.3B", "animate",
"i2v", "i2v_2_2", "i2v_2_2_multitalk", "ti2v_2_2", "lucy_edit", "flf2v_720p", "fun_inp_1.3B", "fun_inp"]
@@ -338,11 +364,13 @@ class family_handler():
models_eqv_map = {
"flf2v_720p" : "i2v",
"t2v_1.3B" : "t2v",
+ "vace_standin_14B" : "vace_14B",
+ "vace_lynx_14B" : "vace_14B",
}
models_comp_map = {
- "vace_14B" : [ "vace_multitalk_14B", "vace_standin_14B", "vace_lynx_lite_14B", "vace_lynx_full_14B"],
- "t2v" : [ "vace_14B", "vace_1.3B" "vace_multitalk_14B", "t2v_1.3B", "phantom_1.3B","phantom_14B", "standin", "lynx_lite", "lynx_full"],
+ "vace_14B" : [ "vace_multitalk_14B", "vace_standin_14B", "vace_lynx_lite_14B", "vace_lynx_14B"],
+ "t2v" : [ "vace_14B", "vace_1.3B" "vace_multitalk_14B", "vace_standin_14B", "vace_lynx_lite_14B", "vace_lynx_14B", "t2v_1.3B", "phantom_1.3B","phantom_14B", "standin", "lynx_lite", "lynx"],
"i2v" : [ "fantasy", "multitalk", "flf2v_720p" ],
"i2v_2_2" : ["i2v_2_2_multitalk"],
"fantasy": ["multitalk"],
@@ -523,15 +551,17 @@ class family_handler():
"flow_shift": 7, # 11 for 720p
"sliding_window_overlap" : 9,
"video_prompt_type": "I",
- "remove_background_images_ref" : 1,
+ "remove_background_images_ref" : 1 ,
})
- elif base_model_type in ["lynx_lite", "lynx_full"]:
+
+ elif base_model_type in ["lynx_lite", "lynx"]:
ui_defaults.update({
"guidance_scale": 5.0,
"flow_shift": 7, # 11 for 720p
"sliding_window_overlap" : 9,
- "video_prompt_type": "QI",
- "remove_background_images_ref" : 1,
+ "video_prompt_type": "I",
+ "denoising_strength": 0.8,
+ "remove_background_images_ref" : 0,
})
elif base_model_type in ["phantom_1.3B", "phantom_14B"]:
diff --git a/requirements.txt b/requirements.txt
index 354d465..9b2c6ee 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -35,8 +35,9 @@ rembg[gpu]==2.0.65
onnxruntime-gpu==1.22
decord
timm
-# insightface==0.7.3
-# facexlib==0.3.0
+insightface @ https://github.com/deepbeepmeep/insightface/raw/refs/heads/master/wheels/insightface-0.7.3-cp310-cp310-win_amd64.whl ; sys_platform == "win32" and python_version == "3.10"
+insightface==0.7.3 ; sys_platform == "linux"
+facexlib==0.3.0
# Config & orchestration
omegaconf
diff --git a/shared/utils/utils.py b/shared/utils/utils.py
index 00178aa..a03927e 100644
--- a/shared/utils/utils.py
+++ b/shared/utils/utils.py
@@ -205,7 +205,7 @@ def get_outpainting_full_area_dimensions(frame_height,frame_width, outpainting_d
frame_width = int(frame_width * (100 + outpainting_left + outpainting_right) / 100)
return frame_height, frame_width
-def rgb_bw_to_rgba_mask(img, thresh=127):
+def rgb_bw_to_rgba_mask(img, thresh=127):
a = img.convert('L').point(lambda p: 255 if p > thresh else 0) # alpha
out = Image.new('RGBA', img.size, (255, 255, 255, 0)) # white, transparent
out.putalpha(a) # white where alpha=255
diff --git a/wgp.py b/wgp.py
index e48070c..74223a6 100644
--- a/wgp.py
+++ b/wgp.py
@@ -63,7 +63,7 @@ AUTOSAVE_FILENAME = "queue.zip"
PROMPT_VARS_MAX = 10
target_mmgp_version = "3.6.0"
-WanGP_version = "8.761"
+WanGP_version = "8.9"
settings_version = 2.38
max_source_video_frames = 3000
prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer = None, None, None, None
@@ -3492,7 +3492,23 @@ def select_video(state, input_file_list, event_data: gr.EventData):
if video_apg_switch is not None and video_apg_switch != 0:
values += ["on"]
labels += ["APG"]
-
+
+ control_net_weight = ""
+ if test_vace_module(video_model_type):
+ video_control_net_weight = configs.get("control_net_weight", 1)
+ if len(filter_letters(video_video_prompt_type, video_guide_processes))> 1:
+ video_control_net_weight2 = configs.get("control_net_weight2", 1)
+ control_net_weight = f"Vace #1={video_control_net_weight}, Vace #2={video_control_net_weight2}"
+ else:
+ control_net_weight = f"Vace={video_control_net_weight}"
+ control_net_weight_alt_name = model_def.get("control_net_weight_alt_name", "")
+ if len(control_net_weight_alt_name) >0:
+ if len(control_net_weight): control_net_weight += ", "
+ control_net_weight += control_net_weight_alt_name + "=" + str(configs.get("control_net_alt", 1))
+ if len(control_net_weight) > 0:
+ values += [control_net_weight]
+ labels += ["Control Net Weights"]
+
video_skip_steps_cache_type = configs.get("skip_steps_cache_type", "")
video_skip_steps_multiplier = configs.get("skip_steps_multiplier", 0)
video_skip_steps_cache_start_step_perc = configs.get("skip_steps_start_step_perc", 0)
@@ -3736,7 +3752,7 @@ def extract_faces_from_video_with_mask(input_video_path, input_mask_path, max_fr
alpha_mask[mask > 127] = 1
frame = frame * alpha_mask
frame = Image.fromarray(frame)
- face = face_processor.process(frame, resize_to=size, face_crop_scale = 1.2,)
+ face = face_processor.process(frame, resize_to=size)
face_list.append(face)
face_processor = None
@@ -4513,6 +4529,7 @@ def generate_video(
image_mask,
control_net_weight,
control_net_weight2,
+ control_net_weight_alt,
mask_expand,
audio_guide,
audio_guide2,
@@ -4577,6 +4594,9 @@ def generate_video(
model_def = get_model_def(model_type)
is_image = image_mode > 0
+ set_video_prompt_type = model_def.get("set_video_prompt_type", None)
+ if set_video_prompt_type is not None:
+ video_prompt_type = add_to_sequence(video_prompt_type, set_video_prompt_type)
if is_image:
if min_frames_if_references >= 1000:
video_length = min_frames_if_references - 1000
@@ -4728,7 +4748,7 @@ def generate_video(
_, _, latent_size = get_model_min_frames_and_step(model_type)
original_image_refs = image_refs
- image_refs = None if image_refs is None else [] + image_refs # work on a copy as it is going to be modified
+ image_refs = None if image_refs is None else ([] + image_refs) # work on a copy as it is going to be modified
# image_refs = None
# nb_frames_positions= 0
# Output Video Ratio Priorities:
@@ -5025,7 +5045,7 @@ def generate_video(
# Generic Video Preprocessing
process_outside_mask = process_map_outside_mask.get(filter_letters(video_prompt_type, "YWX"), None)
preprocess_type, preprocess_type2 = "raw", None
- for process_num, process_letter in enumerate( filter_letters(video_prompt_type, "PEDSLCMU")):
+ for process_num, process_letter in enumerate( filter_letters(video_prompt_type, video_guide_processes)):
if process_num == 0:
preprocess_type = process_map_video_guide.get(process_letter, "raw")
else:
@@ -5224,6 +5244,7 @@ def generate_video(
audio_scale= audio_scale,
audio_context_lens= audio_context_lens,
context_scale = context_scale,
+ control_scale_alt = control_net_weight_alt,
model_mode = model_mode,
causal_block_size = 5,
causal_attention = True,
@@ -6231,7 +6252,10 @@ def prepare_inputs_dict(target, inputs, model_type = None, model_filename = None
if not vace:
pop += ["frames_positions", "control_net_weight", "control_net_weight2"]
-
+
+ if not len(model_def.get("control_net_weight_alt_name", "")) >0:
+ pop += ["control_net_alt"]
+
if model_def.get("video_guide_outpainting", None) is None:
pop += ["video_guide_outpainting"]
@@ -6679,6 +6703,7 @@ def save_inputs(
image_mask,
control_net_weight,
control_net_weight2,
+ control_net_weight_alt,
mask_expand,
audio_guide,
audio_guide2,
@@ -6992,6 +7017,7 @@ def refresh_video_prompt_type_alignment(state, video_prompt_type, video_prompt_t
return video_prompt_type
all_guide_processes ="PDESLCMUVBH"
+video_guide_processes = "PEDSLCMU"
def refresh_video_prompt_type_video_guide(state, filter_type, video_prompt_type, video_prompt_type_video_guide, image_mode, old_image_mask_guide_value, old_image_guide_value, old_image_mask_value ):
model_type = state["model_type"]
@@ -7440,13 +7466,9 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
phantom = base_model_type in ["phantom_1.3B", "phantom_14B"]
fantasy = base_model_type in ["fantasy"]
multitalk = model_def.get("multitalk_class", False)
- standin = model_def.get("standin_class", False)
infinitetalk = base_model_type in ["infinitetalk"]
hunyuan_t2v = "hunyuan_video_720" in model_filename
hunyuan_i2v = "hunyuan_video_i2v" in model_filename
- hunyuan_video_custom = "hunyuan_video_custom" in model_filename
- hunyuan_video_custom = base_model_type in ["hunyuan_custom", "hunyuan_custom_audio", "hunyuan_custom_edit"]
- hunyuan_video_custom_audio = base_model_type in ["hunyuan_custom_audio"]
hunyuan_video_custom_edit = base_model_type in ["hunyuan_custom_edit"]
hunyuan_video_avatar = "hunyuan_video_avatar" in model_filename
flux = base_model_family in ["flux"]
@@ -7460,7 +7482,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
image_prompt_type_value = ""
video_prompt_type_value = ""
any_start_image = any_end_image = any_reference_image = any_image_mask = False
- v2i_switch_supported = (vace or t2v or standin) and not image_outputs
+ v2i_switch_supported = model_def.get("v2i_switch_supported", False) and not image_outputs
ti2v_2_2 = base_model_type in ["ti2v_2_2"]
gallery_height = 350
def get_image_gallery(label ="", value = None, single_image_mode = False, visible = False ):
@@ -7539,7 +7561,6 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
guide_custom_choices = model_def.get("guide_custom_choices", None)
image_ref_choices = model_def.get("image_ref_choices", None)
- # with gr.Column(visible= vace or phantom or hunyuan_video_custom or hunyuan_video_avatar or hunyuan_video_custom_edit or t2v or standin or ltxv or infinitetalk or recammaster or (flux or qwen ) and model_reference_image and image_mode_value >=1) as video_prompt_column:
with gr.Column(visible= guide_preprocessing is not None or mask_preprocessing is not None or guide_custom_choices is not None or image_ref_choices is not None) as video_prompt_column:
video_prompt_type_value= ui_defaults.get("video_prompt_type","")
video_prompt_type = gr.Text(value= video_prompt_type_value, visible= False)
@@ -7923,10 +7944,11 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
choices= sample_solver_choices, visible= True, label= "Sampler Solver / Scheduler"
)
flow_shift = gr.Slider(1.0, 25.0, value=ui_defaults.get("flow_shift",3), step=0.1, label="Shift Scale", visible = not image_outputs)
-
- with gr.Row(visible = vace) as control_net_weights_row:
- control_net_weight = gr.Slider(0.0, 2.0, value=ui_defaults.get("control_net_weight",1), step=0.1, label="Control Net Weight #1", visible=vace)
- control_net_weight2 = gr.Slider(0.0, 2.0, value=ui_defaults.get("control_net_weight2",1), step=0.1, label="Control Net Weight #2", visible=vace)
+ control_net_weight_alt_name = model_def.get("control_net_weight_alt_name", "")
+ with gr.Row(visible = vace or len(control_net_weight_alt_name) >0 ) as control_net_weights_row:
+ control_net_weight = gr.Slider(0.0, 2.0, value=ui_defaults.get("control_net_weight",1), step=0.1, label="Vace Weight #1", visible=vace)
+ control_net_weight2 = gr.Slider(0.0, 2.0, value=ui_defaults.get("control_net_weight2",1), step=0.1, label="Vace Weight #2", visible=vace)
+ control_net_weight_alt = gr.Slider(0.0, 2.0, value=ui_defaults.get("control_net_weight2",1), step=0.1, label=control_net_weight_alt_name + " Weight", visible=len(control_net_weight_alt_name) >0)
negative_prompt = gr.Textbox(label="Negative Prompt (ignored if no Guidance that is if CFG = 1)", value=ui_defaults.get("negative_prompt", ""), visible = not (hunyuan_t2v or hunyuan_i2v or no_negative_prompt) )
with gr.Column(visible = vace or t2v or test_class_i2v(model_type)) as NAG_col:
gr.Markdown("<B>NAG enforces Negative Prompt even if no Guidance is set (CFG = 1), set NAG Scale to > 1 to enable it</B>")
@@ -8113,7 +8135,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
with gr.Row():
cfg_zero_step = gr.Slider(-1, 39, value=ui_defaults.get("cfg_zero_step",-1), step=1, label="CFG Zero below this Layer (Extra Process)", visible = any_cfg_zero)
- with gr.Column(visible = (vace or t2v or standin) and image_outputs) as min_frames_if_references_col:
+ with gr.Column(visible = v2i_switch_supported and image_outputs) as min_frames_if_references_col:
gr.Markdown("<B>Generating a single Frame alone may not be sufficient to preserve Reference Image Identity / Control Image Information or simply to get a good Image Quality. A workaround is to generate a short Video and keep the First Frame.")
min_frames_if_references = gr.Dropdown(
choices=[