Skip to content
Python

added flux 2 & zimage control netsz

DeepBeepMeepde3246167ccf
diff --git a/README.md b/README.md
index 44de59c..ed43515 100644
--- a/README.md
+++ b/README.md
@@ -37,7 +37,7 @@ WanGP supports the Wan (and derived models), Hunyuan Video and LTV Video models
## 🔥 Latest Updates :
-### December 2 2025: WanGP v9.72, The Alpha & the Omega ... and the Dancer
+### December 4 2025: WanGP v9.74, The Alpha & the Omega ... and the Dancer
- **Flux 2**: the best ever open source *Image Generator* has just landed. It does everything very well: generate an *Image* based a *Text Prompt* or combine up to 10 *Images References*
@@ -45,8 +45,12 @@ The only snag is that it is a 60B parameters for the *Transformer* part and 40B
Behold the WanGP Miracle ! Flux 2 wil work with only 8 GB of VRAM if you are happy with 8 bits quantization (no need for lower quality 4bits). With 9GB of VRAM you can run the model at full power. You will need at least 64 GB of RAM. If not maybe Memory Profile 5 will be your friend.
+*With WanGP v9.74*, **Flux 2 Control Net** hidden power has also been unleashed from the vanilla model. You can now enjoy Flux 2 *Inpainting* and *Pose transfer*. This can be combined with *Image Refs* to do *Face Swapping* as it is targetted only to specific areas using *Masking*.
+
- **Z-Image**: a small model, very fast (8 steps), very low VRAM (optimized even more in WanGP for fun, just in case you want to generate 16 images at a time) that produces outstanding Image quality. Not yet the Flux 2 level, and no Image editing yet but a very good trade-off.
+While waiting for Z-Image edit, *WanGP 9.74* offers now support for **Z-Image Fun Control Net**. You can use it for *Pose transfer*, *Canny Edge* tranfer. Don't be surprise if it is a bit slower. Please note it will work best at 1080p and will require a minimum of 9 steps.
+
- **Steady Dancer**: here is *Wan Steady Dancer* a very nice alternative to *Wan Animate*. You can transfer the motion of a Control video in a very smooth way. It will work best with Videos where the action happens center stage (hint: *dancing*). Use the *Lora accelerator* *Fusionix i2v 10 steps* for a fast generation. For higher quality you can set *Condition Guidance* to 2 or if you are very patient keep *Guidance* to a value greater than 1.
I have added a new Memory Profile *Profile 4+* that is sligthly slower than *Profile 4* but can save you up to 1GB of VRAM with Flux 2.
@@ -56,6 +60,7 @@ Also as we have now quite few models and Loras folders. *I have moved all the lo
*update 9.71* : added missing source file, have fun !
*update 9.72* : added Z-Image & Loras reorg
*update 9.73* : added Steady Dancer
+*update 9.74* : added Z-Image Fun Control Net & Flux 2 Control Net + Masking
### November 24 2025: WanGP v9.62, The Return of the King
diff --git a/defaults/flux2_dev.json b/defaults/flux2_dev.json
index e4f034d..b3976f5 100644
--- a/defaults/flux2_dev.json
+++ b/defaults/flux2_dev.json
@@ -1,6 +1,6 @@
{
"model": {
- "name": "Flux 2 Dev",
+ "name": "Flux 2 Dev 32B",
"architecture": "flux2_dev",
"description": "FLUX.2 Dev is the latest rectified flow transformer from Black Forest Labs for image generation and editing.",
"URLs": [
diff --git a/defaults/hunyuan_1_5_i2v.json b/defaults/hunyuan_1_5_i2v.json
index 70be446..740e44f 100644
--- a/defaults/hunyuan_1_5_i2v.json
+++ b/defaults/hunyuan_1_5_i2v.json
@@ -1,6 +1,6 @@
{
"model": {
- "name": "Hunyuan Video 1.5 Image2video 720p 8B",
+ "name": "Hunyuan Video 1.5 Image2video 720p 8B",
"architecture": "hunyuan_1_5_i2v",
"description": "HunyuanVideo-1.5 is a video generation model that delivers top-tier quality with only 8.3B parameters, significantly lowering the barrier to usage. This is the Image2video 720p version.",
"URLs": [
diff --git a/defaults/z_image.json b/defaults/z_image.json
index 62a2350..555c679 100644
--- a/defaults/z_image.json
+++ b/defaults/z_image.json
@@ -1,6 +1,6 @@
{
"model": {
- "name": "Z-Image Turbo",
+ "name": "Z-Image Turbo 6B",
"architecture": "z_image",
"description": "Z-Image Turbo text-to-image model.",
"URLs": [
diff --git a/defaults/z_image_control.json b/defaults/z_image_control.json
new file mode 100644
index 0000000..0dfc192
--- /dev/null
+++ b/defaults/z_image_control.json
@@ -0,0 +1,18 @@
+{
+ "model": {
+ "name": "Z-Image Turbo Fun ControlNet 6B",
+ "architecture": "z_image_control",
+ "modules": [
+ [
+ "https://huggingface.co/DeepBeepMeep/Z-Image/resolve/main/Z-Image-Turbo-Fun-Controlnet-Union_bf16.safetensors",
+ "https://huggingface.co/DeepBeepMeep/Z-Image/resolve/main/Z-Image-Turbo-Fun-Controlnet-Union_quanto_bf16_int8.safetensors"
+ ]
+ ],
+ "description": "Z-Image Turbo with ControlNet Union supporting Pose, Canny, Depth, and Scribble control types.",
+ "URLs": "z_image"
+ },
+ "batch_size": 1,
+ "num_inference_steps": 9,
+ "guidance_scale": 0,
+ "control_net_weight_alt": 0.75
+}
\ No newline at end of file
diff --git a/models/flux/flux_handler.py b/models/flux/flux_handler.py
index 457f835..9e9cd0f 100644
--- a/models/flux/flux_handler.py
+++ b/models/flux/flux_handler.py
@@ -111,6 +111,23 @@ class family_handler():
if flux2:
extra_model_def["group"] ="flux2"
extra_model_def["no_background_removal"] = True
+ # extra_model_def["inpaint_support"] = True
+ extra_model_def["mask_preprocessing"] = {
+ "selection":[ ""],
+ "visible": False
+ }
+
+ extra_model_def["guide_preprocessing"] = {
+ "selection": ["", "PV", "MV"],
+ }
+
+ extra_model_def["mask_preprocessing"] = {
+ "selection": ["", "A", "NA"],
+ "visible": True,
+ }
+
+ # extra_model_def["guide_inpaint_color"] = 0
+ # extra_model_def["video_guide_outpainting"] = [1,2]
extra_model_def["fit_into_canvas_image_refs"] = 0
diff --git a/models/flux/flux_main.py b/models/flux/flux_main.py
index 265b470..7d2f761 100644
--- a/models/flux/flux_main.py
+++ b/models/flux/flux_main.py
@@ -6,7 +6,7 @@ from glob import iglob
from mmgp import offload as offload
import torch
from shared.utils.utils import calculate_new_dimensions
-from .sampling import denoise, get_schedule, get_schedule_flux2, prepare_kontext, prepare_prompt, prepare_multi_ip, unpack, resizeinput, patches_to_image
+from .sampling import denoise, get_schedule, get_schedule_flux2, prepare_kontext, prepare_prompt, prepare_multi_ip, unpack, resizeinput, patches_to_image, build_mask
from .modules.layers import get_linear_split_map
from transformers import SiglipVisionModel, SiglipImageProcessor
import torchvision.transforms.functional as TVF
@@ -230,8 +230,8 @@ class model_factory:
joint_pass = False,
image_refs_relative_size = 100,
denoising_strength = 1.,
- masking_strength = 1.,
- **bbargs
+ masking_strength = 1.,
+ **bbargs
):
if self._interrupt:
return None
@@ -247,6 +247,9 @@ class model_factory:
flux_kontext_dreamomni2 = self.name in ['flux-dev-kontext-dreamomni2']
if flux2:
+ if input_frames is not None:
+ input_ref_images = [convert_tensor_to_image(input_frames) ] + (input_ref_images or [])
+
shape = (batch_size, 128, height // 16, width // 16)
generator = torch.Generator(device="cuda").manual_seed(seed)
randn = torch.randn(shape, generator=generator, dtype=torch.bfloat16, device="cuda")
@@ -262,6 +265,10 @@ class model_factory:
txt_embeds, txt_ids = txt_embeds.expand(batch_size, -1, -1), txt_ids.expand(batch_size, -1, -1)
inp.update({ "neg_txt": txt_embeds.to(device), "neg_txt_ids": txt_ids.to(device), "neg_vec": vec })
+ if input_masks is not None:
+ inp.update( build_mask(width, height, convert_tensor_to_image(input_masks, mask_levels= True), device))
+ inp["original_image_latents"], _ = encode_image_refs(self.vae, [input_ref_images[0].resize((width, height), resample=Image.Resampling.LANCZOS)])
+
if input_ref_images is not None and len(input_ref_images):
cond_latents, cond_ids = encode_image_refs(self.vae, input_ref_images)
cond_latents, cond_ids = cond_latents.expand(batch_size, -1, -1), cond_ids.expand(batch_size, -1, -1)
diff --git a/models/flux/sampling.py b/models/flux/sampling.py
index fa1e7c6..901fce3 100644
--- a/models/flux/sampling.py
+++ b/models/flux/sampling.py
@@ -157,6 +157,20 @@ def resizeinput(img):
return img
+def build_mask(target_width, target_height, img_mask, device):
+ from shared.utils.utils import convert_image_to_tensor, convert_tensor_to_image
+ # image_height, image_width = calculate_new_dimensions(ref_height, ref_width, image_height, image_width, False, block_size=multiple_of)
+ image_mask_latents = convert_image_to_tensor(img_mask.resize((target_width // 16, target_height // 16), resample=Image.Resampling.LANCZOS))
+ image_mask_latents = torch.where(image_mask_latents>-0.5, 1., 0. )[0:1]
+ image_mask_rebuilt = image_mask_latents.repeat_interleave(16, dim=-1).repeat_interleave(16, dim=-2).unsqueeze(0)
+ # convert_tensor_to_image( image_mask_rebuilt.squeeze(0).repeat(3,1,1)).save("mmm.png")
+ image_mask_latents = image_mask_latents.reshape(1, -1, 1).to(device)
+ return {
+ "img_msk_latents": image_mask_latents,
+ "img_msk_rebuilt": image_mask_rebuilt,
+ }
+
+
def prepare_kontext(
ae: AutoEncoder | None,
img_cond_list: list,
@@ -227,17 +241,7 @@ def prepare_kontext(
"img_cond_seq_ids": img_cond_seq_ids,
}
if img_mask is not None:
- from shared.utils.utils import convert_image_to_tensor, convert_tensor_to_image
- # image_height, image_width = calculate_new_dimensions(ref_height, ref_width, image_height, image_width, False, block_size=multiple_of)
- image_mask_latents = convert_image_to_tensor(img_mask.resize((target_width // 16, target_height // 16), resample=Image.Resampling.LANCZOS))
- image_mask_latents = torch.where(image_mask_latents>-0.5, 1., 0. )[0:1]
- image_mask_rebuilt = image_mask_latents.repeat_interleave(16, dim=-1).repeat_interleave(16, dim=-2).unsqueeze(0)
- # convert_tensor_to_image( image_mask_rebuilt.squeeze(0).repeat(3,1,1)).save("mmm.png")
- image_mask_latents = image_mask_latents.reshape(1, -1, 1).to(device)
- return_dict.update({
- "img_msk_latents": image_mask_latents,
- "img_msk_rebuilt": image_mask_rebuilt,
- })
+ return_dict.update(build_mask(target_width, target_height, img_mask), device)
img = get_noise(
bs,
@@ -346,6 +350,7 @@ def denoise(
denoising_strength = 1,
masking_strength = 1,
preview_meta = None,
+ original_image_latents = None,
):
kwargs = {
@@ -359,10 +364,11 @@ def denoise(
if callback != None:
callback(-1, None, True)
- original_image_latents = None if img_cond_seq is None else img_cond_seq.clone()
original_timesteps = timesteps
+
morph, first_step = False, 0
if img_msk_latents is not None:
+ if original_image_latents is None: original_image_latents= img_cond_seq.clone()
randn = torch.randn_like(original_image_latents)
if denoising_strength < 1.:
first_step = int(len(timesteps) * (1. - denoising_strength))
diff --git a/models/qwen/pipeline_qwenimage.py b/models/qwen/pipeline_qwenimage.py
index ebcedee..f181267 100644
--- a/models/qwen/pipeline_qwenimage.py
+++ b/models/qwen/pipeline_qwenimage.py
@@ -767,7 +767,6 @@ class QwenImagePipeline(): #DiffusionPipeline
latents,
tile_size=VAE_tile_size
)
- original_image_latents = None if image_latents is None else image_latents.clone()
if image is not None:
img_shapes = [
@@ -813,8 +812,10 @@ class QwenImagePipeline(): #DiffusionPipeline
negative_prompt_embeds_mask.sum(dim=1).tolist() if negative_prompt_embeds_mask is not None else None
)
morph, first_step = False, 0
- lanpaint_proc = None
+ lanpaint_proc = original_image_latents = None
if image_mask_latents is not None:
+ original_image_latents = image_latents[:, :latents.shape[1]].clone()
+
randn = torch.randn_like(original_image_latents)
if denoising_strength < 1.:
first_step = int(len(timesteps) * (1. - denoising_strength))
diff --git a/models/qwen/qwen_handler.py b/models/qwen/qwen_handler.py
index 049a329..471d23c 100644
--- a/models/qwen/qwen_handler.py
+++ b/models/qwen/qwen_handler.py
@@ -49,7 +49,7 @@ class family_handler():
if base_model_type in ["qwen_image_edit_plus_20B"]:
extra_model_def["guide_preprocessing"] = {
- "selection": ["", "PV", "DV", "SV", "CV"],
+ "selection": ["", "PV", "DV", "SV", "CV"], #, "MV"
}
extra_model_def["mask_preprocessing"] = {
diff --git a/models/wan/wan_handler.py b/models/wan/wan_handler.py
index 7ba1001..10ce711 100644
--- a/models/wan/wan_handler.py
+++ b/models/wan/wan_handler.py
@@ -405,6 +405,8 @@ class family_handler():
if vace_class:
+ extra_model_def["control_net_weight_name"] = "Vace"
+ extra_model_def["control_net_weight_size"] = 2
extra_model_def["guide_preprocessing"] = {
"selection": ["", "UV", "PV", "DV", "SV", "LV", "CV", "MV", "V", "PDV", "PSV", "PLV" , "DSV", "DLV", "SLV"],
"labels" : { "V": "Use Vace raw format"}
diff --git a/models/z_image/config_control.json b/models/z_image/config_control.json
new file mode 100644
index 0000000..00ea8b7
--- /dev/null
+++ b/models/z_image/config_control.json
@@ -0,0 +1,33 @@
+{
+ "_class_name": "ZImageTransformer2DModel",
+ "_diffusers_version": "0.36.0.dev0",
+ "all_f_patch_size": [
+ 1
+ ],
+ "all_patch_size": [
+ 2
+ ],
+ "axes_dims": [
+ 32,
+ 48,
+ 48
+ ],
+ "axes_lens": [
+ 1536,
+ 512,
+ 512
+ ],
+ "cap_feat_dim": 2560,
+ "dim": 3840,
+ "in_channels": 16,
+ "n_heads": 30,
+ "n_kv_heads": 30,
+ "n_layers": 30,
+ "n_refiner_layers": 2,
+ "norm_eps": 1e-05,
+ "qk_norm": true,
+ "rope_theta": 256.0,
+ "t_scale": 1000.0,
+ "enable_control": true,
+ "control_layers_places": [0, 5, 10, 15, 20, 25]
+}
diff --git a/models/z_image/pipeline_z_image.py b/models/z_image/pipeline_z_image.py
index 6924512..b105f98 100644
--- a/models/z_image/pipeline_z_image.py
+++ b/models/z_image/pipeline_z_image.py
@@ -326,6 +326,8 @@ class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):
max_sequence_length: int = 512,
callback=None,
pipeline=None,
+ control_image: Optional[torch.Tensor] = None,
+ control_context_scale: float = 0.75,
):
r"""
Function invoked when calling the pipeline for generation.
@@ -512,6 +514,21 @@ class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
self._num_timesteps = len(timesteps)
+ # Encode control image if provided and transformer supports it
+ control_latent = None
+ if control_image is not None and hasattr(self.transformer, 'has_control') and self.transformer.has_control:
+ # input_frames comes in video format [C, F, H, W] - convert to image format [B, C, H, W]
+ control_image_tensor = control_image
+ if control_image_tensor.dim() == 4 and control_image_tensor.shape[1] == 1:
+ # Shape is [C, F=1, H, W] - squeeze frame dim and add batch dim
+ control_image_tensor = control_image_tensor.squeeze(1).unsqueeze(0) # [C, H, W] -> [1, C, H, W]
+ elif control_image_tensor.dim() == 3:
+ # Shape is [C, H, W] - just add batch dim
+ control_image_tensor = control_image_tensor.unsqueeze(0) # [1, C, H, W]
+ control_image_tensor = control_image_tensor.to(device=device, dtype=self.vae.dtype)
+ control_latent = self.vae.encode(control_image_tensor).latent_dist.sample()
+ control_latent = (control_latent - self.vae.config.shift_factor) * self.vae.config.scaling_factor
+
callback(-1, None, True, len(timesteps))
# 6. Denoising loop
@@ -552,10 +569,21 @@ class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):
latent_model_input = latent_model_input.unsqueeze(2)
latent_model_input_list = list(latent_model_input.unbind(dim=0))
+ # Prepare control latent list if available
+ control_latent_list = None
+ if control_latent is not None:
+ control_latent_input = control_latent.unsqueeze(2)
+ if apply_cfg:
+ # Duplicate control latent for CFG (both positive and negative)
+ control_latent_input = control_latent_input.repeat(2, 1, 1, 1, 1)
+ control_latent_list = list(control_latent_input.unbind(dim=0))
+
model_out_list = self.transformer(
latent_model_input_list,
timestep_model_input,
prompt_embeds_model_input,
+ control_latent=control_latent_list,
+ control_context_scale=control_context_scale,
callback=callback,
pipeline=self,
)[0]
diff --git a/models/z_image/transformer_z_image.py b/models/z_image/transformer_z_image.py
index 7e242a8..682262f 100644
--- a/models/z_image/transformer_z_image.py
+++ b/models/z_image/transformer_z_image.py
@@ -192,10 +192,12 @@ class ZImageTransformerBlock(nn.Module):
norm_eps: float,
qk_norm: bool,
modulation=True,
+ block_id=None, # For control hint injection
):
super().__init__()
self.dim = dim
self.head_dim = dim // n_heads
+ self.block_id = block_id # For control hint injection
# Refactored to use diffusers Attention with custom processor
# Original Z-Image params: dim, n_heads, n_kv_heads, qk_norm
@@ -244,7 +246,19 @@ class ZImageTransformerBlock(nn.Module):
attn_mask: torch.Tensor,
freqs_cis: torch.Tensor,
adaln_input: Optional[torch.Tensor] = None,
+ hints: Optional[List[torch.Tensor]] = None,
+ context_scale: float = 1.0,
):
+ # Process control hint just-in-time if this layer has control attached
+ hint_skip = None
+ if self.block_id is not None and hints is not None and hasattr(self, 'control'):
+ kwargs = {
+ "attn_mask": attn_mask,
+ "freqs_cis": freqs_cis,
+ "adaln_input": adaln_input,
+ }
+ hint_skip = self.control(hints, x if self.block_id == 0 else None, **kwargs)
+
if self.modulation:
assert adaln_input is not None
scale_msa, gate_msa, scale_mlp, gate_mlp = self.adaLN_modulation(adaln_input).unsqueeze(1).chunk(4, dim=2)
@@ -273,9 +287,59 @@ class ZImageTransformerBlock(nn.Module):
x.add_(self._apply_ffn(x))
+ # Apply control hint skip connection
+ if hint_skip is not None:
+ if context_scale == 1.0:
+ x.add_(hint_skip)
+ else:
+ x.add_(hint_skip, alpha=context_scale)
+
return x
+@maybe_allow_in_graph
+class ZImageControlTransformerBlock(ZImageTransformerBlock):
+ """Control block that processes control context and generates skip connection hints."""
+
+ def __init__(
+ self,
+ layer_id: int,
+ dim: int,
+ n_heads: int,
+ n_kv_heads: int,
+ norm_eps: float,
+ qk_norm: bool,
+ modulation=True,
+ block_id=0,
+ ):
+ super().__init__(layer_id, dim, n_heads, n_kv_heads, norm_eps, qk_norm, modulation, block_id=None)
+ self.control_block_id = block_id
+ if block_id == 0:
+ self.before_proj = nn.Linear(self.dim, self.dim)
+ nn.init.zeros_(self.before_proj.weight)
+ nn.init.zeros_(self.before_proj.bias)
+ self.after_proj = nn.Linear(self.dim, self.dim)
+ nn.init.zeros_(self.after_proj.weight)
+ nn.init.zeros_(self.after_proj.bias)
+
+ def forward(self, hints, x, **kwargs):
+ # Get current control state from mutable list
+ c = hints[0]
+ hints[0] = None # Free memory immediately
+
+ # First block: project control and add to main signal
+ if self.control_block_id == 0:
+ c = self.before_proj(c) + x
+
+ # Run through parent transformer block (without hint application)
+ c = super().forward(c, **kwargs)
+
+ # Create skip connection output
+ c_skip = self.after_proj(c)
+ hints[0] = c # Put processed state back for next control layer
+ return c_skip # Return skip connection (used immediately)
+
+
class FinalLayer(nn.Module):
def __init__(self, hidden_size, out_channels):
super().__init__()
@@ -338,7 +402,7 @@ class RopeEmbedder:
class ZImageTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
_supports_gradient_checkpointing = True
- _no_split_modules = ["ZImageTransformerBlock"]
+ _no_split_modules = ["ZImageTransformerBlock", "ZImageControlTransformerBlock"]
@register_to_config
def __init__(
@@ -358,6 +422,8 @@ class ZImageTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOr
t_scale=1000.0,
axes_dims=[32, 48, 48],
axes_lens=[1024, 512, 512],
+ enable_control=False, # Whether to create control layers
+ control_layers_places=None, # Explicit layer positions for control injection, e.g. [0, 5, 10, 15, 20, 25]
) -> None:
super().__init__()
self.in_channels = in_channels
@@ -421,12 +487,65 @@ class ZImageTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOr
self.x_pad_token = nn.Parameter(torch.empty((1, dim)))
self.cap_pad_token = nn.Parameter(torch.empty((1, dim)))
- self.layers = nn.ModuleList(
- [
- ZImageTransformerBlock(layer_id, dim, n_heads, n_kv_heads, norm_eps, qk_norm)
- for layer_id in range(n_layers)
- ]
- )
+ # Control layers - created if enable_control is True
+ self.enable_control = enable_control
+
+ if enable_control:
+ # Use explicit control_layers_places from config (e.g. [0, 5, 10, 15, 20, 25])
+ if control_layers_places is None:
+ raise ValueError("control_layers_places must be specified when enable_control=True")
+ self.control_layers_places = list(control_layers_places)
+ assert 0 in self.control_layers_places, "Layer 0 must be in control_layers_places"
+ self.control_layers_mapping = {i: n for n, i in enumerate(self.control_layers_places)}
+
+ # Main layers with block_id set for control injection
+ self.layers = nn.ModuleList(
+ [
+ ZImageTransformerBlock(
+ layer_id, dim, n_heads, n_kv_heads, norm_eps, qk_norm,
+ block_id=self.control_layers_mapping[layer_id] if layer_id in self.control_layers_places else None
+ )
+ for layer_id in range(n_layers)
+ ]
+ )
+
+ # Control blocks that generate hints
+ self.control_layers = nn.ModuleList(
+ [
+ ZImageControlTransformerBlock(
+ layer_pos, dim, n_heads, n_kv_heads, norm_eps, qk_norm,
+ modulation=True, block_id=idx
+ )
+ for idx, layer_pos in enumerate(self.control_layers_places)
+ ]
+ )
+
+ # Control input embedders (same structure as main embedders)
+ control_all_x_embedder = {}
+ for patch_size, f_patch_size in zip(all_patch_size, all_f_patch_size):
+ control_x_embedder = nn.Linear(f_patch_size * patch_size * patch_size * in_channels, dim, bias=True)
+ control_all_x_embedder[f"{patch_size}-{f_patch_size}"] = control_x_embedder
+ self.control_all_x_embedder = nn.ModuleDict(control_all_x_embedder)
+
+ # Control noise refiner
+ self.control_noise_refiner = nn.ModuleList(
+ [
+ ZImageTransformerBlock(
+ 1000 + layer_id, dim, n_heads, n_kv_heads, norm_eps, qk_norm,
+ modulation=True,
+ )
+ for layer_id in range(n_refiner_layers)
+ ]
+ )
+ else:
+ # Non-control mode: standard layers without block_id
+ self.layers = nn.ModuleList(
+ [
+ ZImageTransformerBlock(layer_id, dim, n_heads, n_kv_heads, norm_eps, qk_norm)
+ for layer_id in range(n_layers)
+ ]
+ )
+
head_dim = dim // n_heads
assert head_dim == sum(axes_dims)
self.axes_dims = axes_dims
@@ -434,6 +553,45 @@ class ZImageTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOr
self.rope_embedder = RopeEmbedder(theta=rope_theta, axes_dims=axes_dims, axes_lens=axes_lens)
+ @property
+ def has_control(self) -> bool:
+ """Returns True if the model has control layers enabled."""
+ return self.enable_control
+
+ def remap_state_dict(self, sd):
+ """Remap state dict keys for control layers to be attached to main layers."""
+ if not sd:
+ return sd
+ first = next(iter(sd.keys()))
+
+ # Remap control_layers.X.* to layers.Y.control.* where Y is the target layer
+ if first.startswith("control_layers."):
+ new_sd = {}
+ for k, v in sd.items():
+ if k.startswith("control_layers."):
+ parts = k.split(".")
+ control_idx = int(parts[1])
+ target_layer = self.control_layers_places[control_idx]
+ parts[0] = f"layers.{target_layer}"
+ parts[1] = "control"
+ k = ".".join(parts)
+ new_sd[k] = v
+ sd = new_sd
+
+ return sd
+
+ def adapt_control_model(self):
+ """Move control blocks to be submodules of their corresponding main layers."""
+ if not self.enable_control or not hasattr(self, 'control_layers'):
+ return
+
+ modules_dict = {k: m for k, m in self.named_modules()}
+ for model_layer, control_idx in self.control_layers_mapping.items():
+ control_module = modules_dict[f"control_layers.{control_idx}"]
+ target = modules_dict[f"layers.{model_layer}"]
+ setattr(target, "control", control_module)
+ delattr(self, "control_layers")
+
def unpatchify(self, x: List[torch.Tensor], size: List[Tuple], patch_size, f_patch_size) -> List[torch.Tensor]:
pH = pW = patch_size
pF = f_patch_size
@@ -559,6 +717,66 @@ class ZImageTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOr
all_cap_pad_mask,
)
+ def patchify(
+ self,
+ all_image: List[torch.Tensor],
+ patch_size: int,
+ f_patch_size: int,
+ cap_len: int,
+ ):
+ """Patchify control images without caption processing (for control context)."""
+ pH = pW = patch_size
+ pF = f_patch_size
+ device = all_image[0].device
+
+ all_image_out = []
+ all_image_size = []
+ all_image_pos_ids = []
+ all_image_pad_mask = []
+
+ for image in all_image:
+ C, F, H, W = image.size()
+ all_image_size.append((F, H, W))
+ F_tokens, H_tokens, W_tokens = F // pF, H // pH, W // pW
+
+ image = image.view(C, F_tokens, pF, H_tokens, pH, W_tokens, pW)
+ image = image.permute(1, 3, 5, 2, 4, 6, 0).reshape(F_tokens * H_tokens * W_tokens, pF * pH * pW * C)
+
+ image_ori_len = len(image)
+ image_padding_len = (-image_ori_len) % SEQ_MULTI_OF
+
+ image_ori_pos_ids = self.create_coordinate_grid(
+ size=(F_tokens, H_tokens, W_tokens),
+ start=(cap_len + 1, 0, 0),
+ device=device,
+ ).flatten(0, 2)
+ image_padding_pos_ids = (
+ self.create_coordinate_grid(
+ size=(1, 1, 1),
+ start=(0, 0, 0),
+ device=device,
+ )
+ .flatten(0, 2)
+ .repeat(image_padding_len, 1)
+ )
+ image_padded_pos_ids = torch.cat([image_ori_pos_ids, image_padding_pos_ids], dim=0)
+ all_image_pos_ids.append(image_padded_pos_ids)
+
+ all_image_pad_mask.append(
+ torch.cat(
+ [
+ torch.zeros((image_ori_len,), dtype=torch.bool, device=device),
+ torch.ones((image_padding_len,), dtype=torch.bool, device=device),
+ ],
+ dim=0,
+ )
+ )
+
+ image_padded_feat = torch.cat([image, image[-1:].repeat(image_padding_len, 1)], dim=0)
+ all_image_out.append(image_padded_feat)
+
+ return all_image_out, all_image_size, all_image_pos_ids, all_image_pad_mask
+
def forward(
self,
x: List[torch.Tensor],
@@ -568,6 +786,8 @@ class ZImageTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOr
f_patch_size=1,
callback=None,
pipeline=None,
+ control_latent: Optional[List[torch.Tensor]] = None,
+ control_context_scale: float = 1.0,
):
assert patch_size in self.all_patch_size
assert f_patch_size in self.all_f_patch_size
@@ -648,12 +868,55 @@ class ZImageTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOr
for i, seq_len in enumerate(unified_item_seqlens):
unified_attn_mask[i, :seq_len] = 1
+ # Prepare control hints if control is enabled and control_latent is provided
+ hints = None
+ if self.enable_control and control_latent is not None:
+ # Patchify control context
+ control_context, _, ctrl_pos_ids, ctrl_inner_pad_mask = self.patchify(
+ control_latent, patch_size, f_patch_size, cap_item_seqlens[0]
+ )
+
+ # Embed control context
+ ctrl_item_seqlens = [len(_) for _ in control_context]
+ ctrl_max_item_seqlen = max(ctrl_item_seqlens)
+
+ control_context = torch.cat(control_context, dim=0)
+ control_context = self.control_all_x_embedder[f"{patch_size}-{f_patch_size}"](control_context)
+
+ # Match adaln_input dtype to control_context
+ adaln_input_ctrl = adaln_input[:1].type_as(control_context)
+ control_context[torch.cat(ctrl_inner_pad_mask)] = self.x_pad_token
+ control_context = list(control_context.split(ctrl_item_seqlens, dim=0))
+ ctrl_freqs_cis = list(self.rope_embedder(torch.cat(ctrl_pos_ids, dim=0)).split(ctrl_item_seqlens, dim=0))
+
+ control_context = pad_sequence(control_context, batch_first=True, padding_value=0.0)
+ ctrl_freqs_cis = pad_sequence(ctrl_freqs_cis, batch_first=True, padding_value=0.0)
+ ctrl_attn_mask = torch.zeros((1, ctrl_max_item_seqlen), dtype=torch.bool, device=device)
+ for i, seq_len in enumerate(ctrl_item_seqlens):
+ ctrl_attn_mask[i, :seq_len] = 1
+
+ # Refine control context through control noise refiner
+ for layer in self.control_noise_refiner:
+ control_context = layer(control_context, ctrl_attn_mask, ctrl_freqs_cis, adaln_input_ctrl)
+
+ # Unify control context with caption features
+ control_context_unified = []
+ for i in range(1):
+ ctrl_len = ctrl_item_seqlens[i]
+ cap_len = cap_item_seqlens[i]
+ control_context_unified.append(torch.cat([control_context[i][:ctrl_len], cap_feats[i][:cap_len]]))
+ control_context_unified = pad_sequence(control_context_unified, batch_first=True, padding_value=0.0)
+
+ # Create hints as mutable list (just-in-time pattern)
+ hints = [control_context_unified]
+
for layer in self.layers:
if callback is not None:
callback(-1, None, False, True)
if pipeline is not None and getattr(pipeline, "_interrupt", False):
return [None] * bsz, {}
- unified = layer(unified, unified_attn_mask, unified_freqs_cis, adaln_input)
+ unified = layer(unified, unified_attn_mask, unified_freqs_cis, adaln_input,
+ hints=hints, context_scale=control_context_scale)
unified = self.all_final_layer[f"{patch_size}-{f_patch_size}"](unified, adaln_input)
unified = list(unified.unbind(dim=0))
diff --git a/models/z_image/z_image_handler.py b/models/z_image/z_image_handler.py
index ed895ae..9ec815b 100644
--- a/models/z_image/z_image_handler.py
+++ b/models/z_image/z_image_handler.py
@@ -20,11 +20,26 @@ class family_handler:
"profiles_dir": [],
"no_negative_prompt": True,
}
+
+ if base_model_type == "z_image_control":
+ extra_model_def["mask_preprocessing"] = {
+ "selection":[ ""],
+ "visible": False
+ }
+
+ extra_model_def["control_net_weight_name"] = "Control"
+ extra_model_def["control_net_weight_size"] = 1
+
+ extra_model_def["guide_preprocessing"] = {
+ "selection": ["", "PV", "DV", "EV", "V"],
+ "labels" : { "V": "Use Z-Image Raw Format"},
+ }
+
return extra_model_def
@staticmethod
def query_supported_types():
- return ["z_image"]
+ return ["z_image", "z_image_control"]
@staticmethod
def query_family_maps():
@@ -36,7 +51,7 @@ class family_handler:
@staticmethod
def query_family_infos():
- return {"z_image": (50, "Z-Image")}
+ return {"z_image": (50, "Z-Image"), "z_image_control": (51, "Z-Image ControlNet")}
@staticmethod
def register_lora_cli_args(parser):
@@ -88,6 +103,9 @@ class family_handler:
override_text_encoder if override_text_encoder is not None else get_z_image_text_encoder_filename(text_encoder_quantization)
)
+ # Detect if this is the control variant
+ is_control = base_model_type == "z_image_control"
+
pipe_processor = model_factory(
checkpoint_dir="ckpts",
model_filename=model_filename,
@@ -100,6 +118,7 @@ class family_handler:
VAE_dtype=VAE_dtype,
mixed_precision_transformer=mixed_precision_transformer,
save_quantized=save_quantized,
+ is_control=is_control,
)
pipe = {
@@ -122,3 +141,11 @@ class family_handler:
"num_inference_steps": ui_defaults.get("num_inference_steps", 9),
}
)
+
+ # Add control defaults for z_image_control
+ if base_model_type == "z_image_control":
+ ui_defaults.update(
+ {
+ "control_net_weight": 0.75,
+ }
+ )
diff --git a/models/z_image/z_image_main.py b/models/z_image/z_image_main.py
index 5d92b36..39ec4ae 100644
--- a/models/z_image/z_image_main.py
+++ b/models/z_image/z_image_main.py
@@ -81,25 +81,67 @@ class model_factory:
VAE_dtype=torch.float32,
mixed_precision_transformer=False,
save_quantized=False,
+ is_control=False,
**kwargs,
):
+
+
+ source = model_def.get("source", None)
+ module_source = model_def.get("module_source", None)
+
+
+ # model_filename can be a string or list of files (transformer + modules)
transformer_filename = model_filename[0] if isinstance(model_filename, (list, tuple)) else model_filename
if transformer_filename is None:
raise ValueError("No transformer filename provided for Z-Image.")
self.base_model_type = base_model_type
+ self.is_control = is_control
+
+ # Transformer - use control config if in control mode
+ if is_control:
+ default_transformer_config = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config_control.json")
+ else:
+ default_transformer_config = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")
- # Transformer
- default_transformer_config = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")
preprocess_sd = conv_state_dict
- transformer = offload.fast_load_transformers_model(transformer_filename, writable_tensors= False, modelClass=ZImageTransformer2DModel, defaultConfigPath= default_transformer_config, preprocess_sd=preprocess_sd)
+ kwargs_light= { "modelClass": ZImageTransformer2DModel, "writable_tensors": False, "preprocess_sd": preprocess_sd , "forcedConfigPath" : default_transformer_config}
+
+ if source is not None:
+ transformer = offload.fast_load_transformers_model(fl.locate_file(source), **kwargs_light)
+ elif module_source is not None:
+ transformer = offload.fast_load_transformers_model(model_filename[:1] + [fl.locate_file(module_source)], **kwargs_light)
+ else:
+ transformer= None
+
+ if transformer is not None:
+ from wgp import save_model
+ from mmgp.safetensors2 import torch_load_file
+ else:
+ # model_filename contains all files to load (transformer + modules merged by loader)
+ transformer = offload.fast_load_transformers_model( model_filename, **kwargs_light )
+
+
+
transformer.to(dtype)
+
+ if module_source is not None:
+ save_model(transformer, model_type, dtype, None, is_module=True, filter=list(torch_load_file(module_source)), module_source_no=1)
+
+ if not source is None:
+ save_model(transformer, model_type, dtype, None, submodel_no= 1)
+
if save_quantized:
from wgp import save_quantized_model
save_quantized_model(transformer, model_type, transformer_filename, dtype, default_transformer_config)
+
+ if is_control:
+ transformer.adapt_control_model()
+
+
# Text encoder
# text_encoder = Qwen3ForCausalLM.from_pretrained(os.path.dirname(text_encoder_filename), trust_remote_code=True)
@@ -154,6 +196,8 @@ class model_factory:
VAE_tile_size=None,
cfg_normalization: bool = False,
cfg_truncation: float = 1.0,
+ input_frames=None,
+ context_scale: float = [0],
**kwargs,
):
generator = torch.Generator(device="cuda" if torch.cuda.is_available() else "cpu")
@@ -192,6 +236,8 @@ class model_factory:
cfg_truncation=cfg_truncation,
callback=callback,
pipeline=self.pipeline,
+ control_image=input_frames,
+ control_context_scale=None if context_scale is None else context_scale[0],
)
if images is None:
diff --git a/requirements.txt b/requirements.txt
index 53b90d6..28a0ab5 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -63,6 +63,7 @@ nvidia-ml-py
misaki
gitdb==4.0.12
gitpython==3.1.45
+stringzilla==4.0.14
# Optional / commented out
# transformers==4.46.3 # for llamallava pre-patch
diff --git a/wgp.py b/wgp.py
index 468d5a0..a59c3d4 100644
--- a/wgp.py
+++ b/wgp.py
@@ -83,7 +83,7 @@ global_queue_ref = []
AUTOSAVE_FILENAME = "queue.zip"
PROMPT_VARS_MAX = 10
target_mmgp_version = "3.6.9"
-WanGP_version = "9.73"
+WanGP_version = "9.74"
settings_version = 2.41
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
@@ -820,10 +820,10 @@ def process_prompt_and_add_tasks(state, current_gallery_tab, model_choice):
if multi_prompts_gen_type in [0,2]:
if video_source is not None:
if len(image_end)> 1:
- gr.Info("If a Video is to be continued and the option 'Each Text Prompt Will create a new generated Video' is set, there can be only one End Image")
+ gr.Info("If a Video is to be continued and the option 'Each New Line Will create a new generated Video' is set, there can be only one End Image")
return ret()
elif len(image_start or []) != len(image_end or []):
- gr.Info("The number of Start and End Images should be the same when the option 'Each Text Prompt Will create a new generated Video'")
+ gr.Info("The number of Start and End Images should be the same when the option 'Each New Line Will create a new generated Video'")
return ret()
else:
image_end = None
@@ -2733,7 +2733,7 @@ def save_model(model, model_type, dtype, config_file, submodel_no = 1, is_mod
if is_module:
quanto_filename = model_filename.replace(dtypestr, "quanto_" + quanto_dtypestr + "_int8" )
- quanto_filename_path = os.path.join(fl.get_download_folder() , quanto_filename)
+ quanto_filename_path = os.path.join(fl.get_download_location() , quanto_filename)
if hasattr(model, "_quanto_map"):
print("unable to generate quantized module, the main model should at full 16 bits before quantization can be done")
elif fl.locate_file(quanto_filename, error_if_none= False) is None:
@@ -3924,14 +3924,15 @@ def select_video(state, current_gallery_tab, input_file_list, file_selected, aud
if video_motion_amplitude != 1:
values += [video_motion_amplitude]
labels += ["Motion Amplitude"]
+ control_net_weight_name = model_def.get("control_net_weight_name", "")
control_net_weight = ""
- if test_vace_module(video_model_type):
+ if len(control_net_weight_name):
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}"
+ control_net_weight = f"{control_net_weight_name} #1={video_control_net_weight}, {control_net_weight_name} #2={video_control_net_weight2}"
else:
- control_net_weight = f"Vace={video_control_net_weight}"
+ control_net_weight = f"{control_net_weight_name}={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 += ", "
@@ -6861,7 +6862,10 @@ def prepare_inputs_dict(target, inputs, model_type = None, model_filename = None
pop += ["image_refs_relative_size"]
if not vace:
- pop += ["frames_positions", "control_net_weight", "control_net_weight2"]
+ pop += ["frames_positions"]
+
+ if model_def.get("control_net_weight_name", None) is None:
+ pop += ["control_net_weight", "control_net_weight2"]
if not len(model_def.get("control_net_weight_alt_name", "")) >0:
pop += ["control_net_weight_alt"]
@@ -8796,10 +8800,13 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
)
flow_shift = gr.Slider(1.0, 25.0, value=ui_defaults.get("flow_shift",3), step=0.1, label="Shift Scale", visible = any_flow_shift, show_reset_button= False)
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, show_reset_button= False)
- 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, show_reset_button= False)
- control_net_weight_alt = gr.Slider(0.0, 2.0, value=ui_defaults.get("control_net_weight_alt",1), step=0.1, label=control_net_weight_alt_name + " Weight", visible=len(control_net_weight_alt_name) >0, show_reset_button= False)
+ control_net_weight_name = model_def.get("control_net_weight_name", "")
+ control_net_weight_size = model_def.get("control_net_weight_size", 0)
+
+ with gr.Row(len(control_net_weight_name) or len(control_net_weight_alt_name) ) as control_net_weights_row:
+ control_net_weight = gr.Slider(0.0, 2.0, value=ui_defaults.get("control_net_weight",1), step=0.01, label=f"{control_net_weight_name} Weight" + ("" if control_net_weight_size<=1 else " #1"), visible=control_net_weight_size >= 1, show_reset_button= False)
+ control_net_weight2 = gr.Slider(0.0, 2.0, value=ui_defaults.get("control_net_weight2",1), step=0.01, label=f"{control_net_weight_name} Weight" + ("" if control_net_weight_size<=1 else " #2"), visible=control_net_weight_size >=2, show_reset_button= False)
+ control_net_weight_alt = gr.Slider(0.0, 2.0, value=ui_defaults.get("control_net_weight_alt",1), step=0.01, label=control_net_weight_alt_name + " Weight", visible=len(control_net_weight_alt_name) >0, show_reset_button= False)
with gr.Row(visible = not (hunyuan_t2v or hunyuan_i2v or no_negative_prompt)) as negative_prompt_row:
negative_prompt = gr.Textbox(label="Negative Prompt (ignored if no Guidance that is if CFG = 1)", value=ui_defaults.get("negative_prompt", "") )
with gr.Column(visible = vace or t2v or test_class_i2v(model_type)) as NAG_col: