Skip to content
Python

added z-image controlnet v2 support

DeepBeepMeepfb8b43fc239a
diff --git a/README.md b/README.md
index c007de1..8e36747 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 11 2025: WanGP v9.84, Simple Pleasures...
+### December 14 2025: WanGP v9.84, Simple Pleasures...
These two features are going to change the life of many people:
- **Pause Button**: ever had a urge to use your GPU for a very important task that can't wait (a game for instance ?), here comes your new friend the *Pause* button. Not only it will suspend the current gen in progress but it will free most of the VRAM used by WanGP (please note that the RAM by WanGP used wont be released). When you are done just click the *Resume* button to restart exactly from where you stopped.
@@ -63,11 +63,13 @@ Processing Settings can be useful to do some quick gen / testing if you don't ne
- **Wan-Move** : Another model specialized to control motion using a *Start Image* and *Trajectories*. According to the author's paper it is the best one. *Motion Designer* has been upgraded to generate also trajectories for *Wan-Move*.
+- **Z-Image Control Net v2** : This is an upgrade of Z-Image Control Net. It offers much better results but requires much more processing an VRAM. But don't panic yet, as it was VRAM optimized. It was not an easy trick as this one is complex. It has also Inpainting support,but I need more info to release this feature.
*update 9.81*: added Hunyuan Video 1.5 i2v distilled + magcache\
*update 9.82*: added Settings headless processing, output file customization, refactored Task edition and queue processing\
*update 9.83*: Qwen Edit+ upgraded: no more any zoom out at 1080p, enabled mask, enabled image refs with inpainting\
-*update 9.84*: added Wan-Move support
+*update 9.84*: added Wan-Move support\
+*update 9.85*: added Z-Image Control net v2
### December 4 2025: WanGP v9.74, The Alpha & the Omega ... and the Dancer
diff --git a/defaults/z_image_control.json b/defaults/z_image_control.json
index 0dfc192..b0eee66 100644
--- a/defaults/z_image_control.json
+++ b/defaults/z_image_control.json
@@ -1,6 +1,6 @@
{
"model": {
- "name": "Z-Image Turbo Fun ControlNet 6B",
+ "name": "Z-Image Turbo Fun ControlNet v1 6B",
"architecture": "z_image_control",
"modules": [
[
@@ -11,6 +11,7 @@
"description": "Z-Image Turbo with ControlNet Union supporting Pose, Canny, Depth, and Scribble control types.",
"URLs": "z_image"
},
+ "resolution": "1024x1024",
"batch_size": 1,
"num_inference_steps": 9,
"guidance_scale": 0,
diff --git a/defaults/z_image_control2.json b/defaults/z_image_control2.json
new file mode 100644
index 0000000..5c0b96f
--- /dev/null
+++ b/defaults/z_image_control2.json
@@ -0,0 +1,19 @@
+{
+ "model": {
+ "name": "Z-Image Turbo Fun ControlNet v2 6B",
+ "architecture": "z_image_control2",
+ "modules": [
+ [
+ "https://huggingface.co/DeepBeepMeep/Z-Image/resolve/main/Z-Image-Turbo-Fun-Controlnet-Union2_bf16.safetensors",
+ "https://huggingface.co/DeepBeepMeep/Z-Image/resolve/main/Z-Image-Turbo-Fun-Controlnet-Union2_quanto_bf16_int8.safetensors"
+ ]
+ ],
+ "description": "Z-Image Turbo with ControlNet Union supporting Pose, Canny, Depth, and Scribble control types. V2 has more control layers and support inpainting (disabled for the moment).",
+ "URLs": "z_image"
+ },
+ "resolution": "1024x1024",
+ "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/qwen/qwen_handler.py b/models/qwen/qwen_handler.py
index 90bec4d..9a45e69 100644
--- a/models/qwen/qwen_handler.py
+++ b/models/qwen/qwen_handler.py
@@ -40,8 +40,8 @@ class family_handler():
extra_model_def["video_guide_outpainting"] = [2]
extra_model_def["model_modes"] = {
"choices": [
- ("Lora Inpainting: Inpainted area completely unrelated to occulted content", 1),
- ("Masked Denoising : Inpainted area may reuse some content that has been occulted", 0),
+ ("Lora Inpainting: Inpainted area completely unrelated to masked content", 1),
+ ("Masked Denoising : Inpainted area may reuse some content that has been masked", 0),
],
"default": 1,
"label" : "Inpainting Method",
diff --git a/models/qwen/transformer_qwenimage.py b/models/qwen/transformer_qwenimage.py
index b9eafba..a5fa38b 100644
--- a/models/qwen/transformer_qwenimage.py
+++ b/models/qwen/transformer_qwenimage.py
@@ -82,52 +82,44 @@ def get_timestep_embedding(
return emb
-def apply_rotary_emb_qwen(
- x: torch.Tensor,
- freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor]],
- use_real: bool = True,
- use_real_unbind_dim: int = -1,
-) -> Tuple[torch.Tensor, torch.Tensor]:
+def apply_rotary_emb_qwen_inplace(x_list: list, freqs_cis: torch.Tensor) -> torch.Tensor:
"""
- Apply rotary embeddings to input tensors using the given frequency tensor. This function applies rotary embeddings
- to the given query or key 'x' tensors using the provided frequency tensor 'freqs_cis'. The input tensors are
- reshaped as complex numbers, and the frequency tensor is reshaped for broadcasting compatibility. The resulting
- tensors contain rotary embeddings and are returned as real tensors.
+ Apply rotary embeddings in-place using real arithmetic (no complex numbers).
Args:
- x (`torch.Tensor`):
- Query or key tensor to apply rotary embeddings. [B, S, H, D] xk (torch.Tensor): Key tensor to apply
- freqs_cis (`Tuple[torch.Tensor]`): Precomputed frequency tensor for complex exponentials. ([S, D], [S, D],)
+ x_list: Single-element list containing query or key tensor [B, S, H, D].
+ The list is cleared after use to free memory early.
+ freqs_cis: Precomputed frequency tensor with cos/sin stacked [S, D//2, 2]
Returns:
- Tuple[torch.Tensor, torch.Tensor]: Tuple of modified query tensor and key tensor with rotary embeddings.
+ Tensor with rotary embeddings applied [B, S, H, D]
"""
- if use_real:
- cos, sin = freqs_cis # [S, D]
- cos = cos[None, None]
- sin = sin[None, None]
- cos, sin = cos.to(x.device), sin.to(x.device)
-
- if use_real_unbind_dim == -1:
- # Used for flux, cogvideox, hunyuan-dit
- x_real, x_imag = x.reshape(*x.shape[:-1], -1, 2).unbind(-1) # [B, S, H, D//2]
- x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(3)
- elif use_real_unbind_dim == -2:
- # Used for Stable Audio, OmniGen, CogView4 and Cosmos
- x_real, x_imag = x.reshape(*x.shape[:-1], 2, -1).unbind(-2) # [B, S, H, D//2]
- x_rotated = torch.cat([-x_imag, x_real], dim=-1)
- else:
- raise ValueError(f"`use_real_unbind_dim={use_real_unbind_dim}` but should be -1 or -2.")
-
- out = (x.float() * cos + x_rotated.float() * sin).to(x.dtype)
-
- return out
- else:
- x_rotated = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2))
- freqs_cis = freqs_cis.unsqueeze(1)
- x_out = torch.view_as_real(x_rotated * freqs_cis).flatten(3)
-
- return x_out.type_as(x)
+ x_in = x_list[0]
+ dtype = x_in.dtype
+ # Reshape to separate real/imag pairs: [B, S, H, D] -> [B, S, H, D//2, 2]
+ x = x_in.float().reshape(*x_in.shape[:-1], -1, 2)
+ x_in = None
+ x_list.clear()
+
+ # freqs_cis shape: [S, D//2, 2] where [..., 0] is cos, [..., 1] is sin
+ # Add batch and head dims: [1, S, 1, D//2]
+ cos = freqs_cis[..., 0].unsqueeze(0).unsqueeze(2)
+ sin = freqs_cis[..., 1].unsqueeze(0).unsqueeze(2)
+
+ # Get views into x for in-place modification
+ x0 = x[..., 0] # real part
+ x1 = x[..., 1] # imag part
+
+ # Apply rotation in-place:
+ # new_x0 = x0 * cos - x1 * sin
+ # new_x1 = x1 * cos + x0 * sin
+ x0_orig = x0.clone()
+ x0.mul_(cos)
+ x0.addcmul_(x1, sin, value=-1)
+ x1.mul_(cos)
+ x1.addcmul_(x0_orig, sin)
+
+ return x.flatten(3).to(dtype)
class QwenTimestepProjEmbeddings(nn.Module):
@@ -171,18 +163,19 @@ class QwenEmbedRope(nn.Module):
)
self.rope_cache = {}
- # DO NOT USING REGISTER BUFFER HERE, IT WILL CAUSE COMPLEX NUMBERS LOSE ITS IMAGINARY PART
self.scale_rope = scale_rope
def rope_params(self, index, dim, theta=10000):
"""
Args:
index: [0, 1, 2, 3] 1D Tensor representing the position index of the token
+ Returns:
+ Tensor of shape [len(index), dim//2, 2] with cos/sin stacked in last dim
"""
assert dim % 2 == 0
freqs = torch.outer(index, 1.0 / torch.pow(theta, torch.arange(0, dim, 2).to(torch.float32).div(dim)))
- freqs = torch.polar(torch.ones_like(freqs), freqs)
- return freqs
+ # Stack cos and sin instead of using complex numbers (better for torch.compile)
+ return torch.stack([torch.cos(freqs), torch.sin(freqs)], dim=-1)
def forward(self, video_fhw, txt_seq_lens, device):
"""
@@ -226,20 +219,26 @@ class QwenEmbedRope(nn.Module):
def _compute_video_freqs(self, frame, height, width, idx=0):
seq_lens = frame * height * width
+ # freqs_pos/neg now have shape [4096, axes_dim[i]//2, 2] with cos/sin in last dim
freqs_pos = self.pos_freqs.split([x // 2 for x in self.axes_dim], dim=1)
freqs_neg = self.neg_freqs.split([x // 2 for x in self.axes_dim], dim=1)
- freqs_frame = freqs_pos[0][idx : idx + frame].view(frame, 1, 1, -1).expand(frame, height, width, -1)
+ # Keep the cos/sin dimension (2) separate throughout
+ freqs_frame = freqs_pos[0][idx : idx + frame] # [frame, d0//2, 2]
+ freqs_frame = freqs_frame.view(frame, 1, 1, -1, 2).expand(frame, height, width, -1, 2)
+
if self.scale_rope:
freqs_height = torch.cat([freqs_neg[1][-(height - height // 2) :], freqs_pos[1][: height // 2]], dim=0)
- freqs_height = freqs_height.view(1, height, 1, -1).expand(frame, height, width, -1)
+ freqs_height = freqs_height.view(1, height, 1, -1, 2).expand(frame, height, width, -1, 2)
freqs_width = torch.cat([freqs_neg[2][-(width - width // 2) :], freqs_pos[2][: width // 2]], dim=0)
- freqs_width = freqs_width.view(1, 1, width, -1).expand(frame, height, width, -1)
+ freqs_width = freqs_width.view(1, 1, width, -1, 2).expand(frame, height, width, -1, 2)
else:
- freqs_height = freqs_pos[1][:height].view(1, height, 1, -1).expand(frame, height, width, -1)
- freqs_width = freqs_pos[2][:width].view(1, 1, width, -1).expand(frame, height, width, -1)
+ freqs_height = freqs_pos[1][:height].view(1, height, 1, -1, 2).expand(frame, height, width, -1, 2)
+ freqs_width = freqs_pos[2][:width].view(1, 1, width, -1, 2).expand(frame, height, width, -1, 2)
- freqs = torch.cat([freqs_frame, freqs_height, freqs_width], dim=-1).reshape(seq_lens, -1)
+ # Concatenate on freq dimension (dim -2), keep cos/sin dimension (dim -1) intact
+ freqs = torch.cat([freqs_frame, freqs_height, freqs_width], dim=-2) # [F, H, W, total//2, 2]
+ freqs = freqs.reshape(seq_lens, -1, 2) # [seq_lens, total//2, 2]
return freqs.clone().contiguous()
@@ -260,14 +259,14 @@ class QwenDoubleStreamAttnProcessor2_0:
def __call__(
self,
attn: Attention,
- hidden_states: torch.FloatTensor, # Image stream
- encoder_hidden_states: torch.FloatTensor = None, # Text stream
+ hidden_states_list = None,
encoder_hidden_states_mask: torch.FloatTensor = None,
attention_mask: Optional[torch.FloatTensor] = None,
image_rotary_emb: Optional[torch.Tensor] = None,
) -> torch.FloatTensor:
- if encoder_hidden_states is None:
- raise ValueError("QwenDoubleStreamAttnProcessor2_0 requires encoder_hidden_states (text stream)")
+
+ hidden_states, encoder_hidden_states = hidden_states_list
+ hidden_states_list.clear()
seq_txt = encoder_hidden_states.shape[1]
@@ -275,12 +274,12 @@ class QwenDoubleStreamAttnProcessor2_0:
img_query = attn.to_q(hidden_states)
img_key = attn.to_k(hidden_states)
img_value = attn.to_v(hidden_states)
-
+ del hidden_states
# Compute QKV for text stream (context projections)
txt_query = attn.add_q_proj(encoder_hidden_states)
txt_key = attn.add_k_proj(encoder_hidden_states)
txt_value = attn.add_v_proj(encoder_hidden_states)
-
+ del encoder_hidden_states
# Reshape for multi-head attention
img_query = img_query.unflatten(-1, (attn.heads, -1))
img_key = img_key.unflatten(-1, (attn.heads, -1))
@@ -300,24 +299,35 @@ class QwenDoubleStreamAttnProcessor2_0:
if attn.norm_added_k is not None:
txt_key = attn.norm_added_k(txt_key)
- # Apply RoPE
+ # Apply RoPE (in-place, no complex numbers for better torch.compile support)
if image_rotary_emb is not None:
img_freqs, txt_freqs = image_rotary_emb
- img_query = apply_rotary_emb_qwen(img_query, img_freqs, use_real=False)
- img_key = apply_rotary_emb_qwen(img_key, img_freqs, use_real=False)
- txt_query = apply_rotary_emb_qwen(txt_query, txt_freqs, use_real=False)
- txt_key = apply_rotary_emb_qwen(txt_key, txt_freqs, use_real=False)
+ x_list = [img_query]
+ del img_query
+ img_query = apply_rotary_emb_qwen_inplace(x_list, img_freqs)
+ x_list = [img_key]
+ del img_key
+ img_key = apply_rotary_emb_qwen_inplace(x_list, img_freqs)
+ x_list = [txt_query]
+ del txt_query
+ txt_query = apply_rotary_emb_qwen_inplace(x_list, txt_freqs)
+ x_list = [txt_key]
+ del txt_key
+ txt_key = apply_rotary_emb_qwen_inplace(x_list, txt_freqs)
# Concatenate for joint attention
# Order: [text, image]
joint_query = torch.cat([txt_query, img_query], dim=1)
+ del txt_query, img_query
joint_key = torch.cat([txt_key, img_key], dim=1)
+ del txt_key, img_key
joint_value = torch.cat([txt_value, img_value], dim=1)
+ del txt_value, img_value
# Compute joint attention
dtype = joint_query.dtype
qkv_list = [joint_query, joint_key, joint_value ]
- joint_query = joint_key = joint_value = None
+ del joint_query, joint_key, joint_value
joint_hidden_states = pay_attention(qkv_list)
# Reshape back
@@ -327,7 +337,7 @@ class QwenDoubleStreamAttnProcessor2_0:
# Split attention outputs back
txt_attn_output = joint_hidden_states[:, :seq_txt, :] # Text part
img_attn_output = joint_hidden_states[:, seq_txt:, :] # Image part
-
+ del joint_hidden_states
# Apply output projections
img_attn_output = attn.to_out[0](img_attn_output)
if len(attn.to_out) > 1:
@@ -380,10 +390,22 @@ class QwenImageTransformerBlock(nn.Module):
self.txt_norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=eps)
self.txt_mlp = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
- def _modulate(self, x, mod_params):
- """Apply modulation to input tensor"""
- shift, scale, gate = mod_params.chunk(3, dim=-1)
- return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1), gate.unsqueeze(1)
+ # FFN expansion factor for chunking (diffusers FeedForward default is 4x)
+ self.ffn_mult = 4
+
+ def _apply_ffn_chunked(self, ffn_in: torch.Tensor, mlp: nn.Module) -> None:
+ _, seq_len, dim = ffn_in.shape
+ ffn_in_flat = ffn_in.reshape(-1, dim)
+ chunk_size = max(seq_len // self.ffn_mult, 1)
+ for ffn_chunk in torch.split(ffn_in_flat, chunk_size):
+ ffn_chunk[...] = mlp(ffn_chunk)
+ # ffn_in is already modified in-place via ffn_in_flat view
+
+ def _modulate_inplace(self, x, shift, scale, gate):
+ scale.add_(1.0)
+ x.mul_(scale.unsqueeze(1))
+ x.add_(shift.unsqueeze(1))
+ return gate.unsqueeze(1)
def forward(
self,
@@ -394,55 +416,45 @@ class QwenImageTransformerBlock(nn.Module):
image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
- # Get modulation parameters for both streams
- img_mod_params = self.img_mod(temb) # [B, 6*dim]
- txt_mod_params = self.txt_mod(temb) # [B, 6*dim]
+ # Get modulation parameters for both streams and split into shift, scale, gate
+ img_shift1, img_scale1, img_gate1, img_shift2, img_scale2, img_gate2 = self.img_mod(temb).chunk(6, dim=-1)
+ txt_shift1, txt_scale1, txt_gate1, txt_shift2, txt_scale2, txt_gate2 = self.txt_mod(temb).chunk(6, dim=-1)
- # Split modulation parameters for norm1 and norm2
- img_mod1, img_mod2 = img_mod_params.chunk(2, dim=-1) # Each [B, 3*dim]
- txt_mod1, txt_mod2 = txt_mod_params.chunk(2, dim=-1) # Each [B, 3*dim]
-
- # Process image stream - norm1 + modulation
+ # Process image stream - norm1 + modulation (in-place)
img_normed = self.img_norm1(hidden_states)
- img_modulated, img_gate1 = self._modulate(img_normed, img_mod1)
+ img_gate1 = self._modulate_inplace(img_normed, img_shift1, img_scale1, img_gate1)
- # Process text stream - norm1 + modulation
+ # Process text stream - norm1 + modulation (in-place)
txt_normed = self.txt_norm1(encoder_hidden_states)
- txt_modulated, txt_gate1 = self._modulate(txt_normed, txt_mod1)
-
- # Use QwenAttnProcessor2_0 for joint attention computation
- # This directly implements the DoubleStreamLayerMegatron logic:
- # 1. Computes QKV for both streams
- # 2. Applies QK normalization and RoPE
- # 3. Concatenates and runs joint attention
- # 4. Splits results back to separate streams
+ txt_gate1 = self._modulate_inplace(txt_normed, txt_shift1, txt_scale1, txt_gate1)
+
+
+ hidden_states_list = [img_normed, txt_normed]
+ del img_normed, txt_normed
joint_attention_kwargs = joint_attention_kwargs or {}
- attn_output = self.attn(
- hidden_states=img_modulated, # Image stream (will be processed as "sample")
- encoder_hidden_states=txt_modulated, # Text stream (will be processed as "context")
+ img_attn_output, txt_attn_output = self.attn.processor(self.attn,
+ hidden_states_list=hidden_states_list,
encoder_hidden_states_mask=encoder_hidden_states_mask,
image_rotary_emb=image_rotary_emb,
**joint_attention_kwargs,
)
- # QwenAttnProcessor2_0 returns (img_output, txt_output) when encoder_hidden_states is provided
- img_attn_output, txt_attn_output = attn_output
-
- # Apply attention gates and add residual (like in Megatron)
- hidden_states = hidden_states + img_gate1 * img_attn_output
- encoder_hidden_states = encoder_hidden_states + txt_gate1 * txt_attn_output
+ # Apply attention gates and add residual in-place
+ hidden_states.addcmul_(img_attn_output, img_gate1)
+ encoder_hidden_states.addcmul_(txt_attn_output, txt_gate1)
- # Process image stream - norm2 + MLP
img_normed2 = self.img_norm2(hidden_states)
- img_modulated2, img_gate2 = self._modulate(img_normed2, img_mod2)
- img_mlp_output = self.img_mlp(img_modulated2)
- hidden_states = hidden_states + img_gate2 * img_mlp_output
+ img_gate2 = self._modulate_inplace(img_normed2, img_shift2, img_scale2, img_gate2)
+ self._apply_ffn_chunked(img_normed2, self.img_mlp)
+ # img_normed2 = self.img_mlp(img_normed2)
+
+ hidden_states.addcmul_(img_normed2, img_gate2)
- # Process text stream - norm2 + MLP
txt_normed2 = self.txt_norm2(encoder_hidden_states)
- txt_modulated2, txt_gate2 = self._modulate(txt_normed2, txt_mod2)
- txt_mlp_output = self.txt_mlp(txt_modulated2)
- encoder_hidden_states = encoder_hidden_states + txt_gate2 * txt_mlp_output
+ txt_gate2 = self._modulate_inplace(txt_normed2, txt_shift2, txt_scale2, txt_gate2)
+ txt_normed2 = self.txt_mlp(txt_normed2)
+
+ encoder_hidden_states.addcmul_(txt_normed2, txt_gate2)
# Clip to prevent overflow for fp16
if encoder_hidden_states.dtype == torch.float16:
diff --git a/models/z_image/config.json b/models/z_image/configs/z_image.json
similarity index 100%
rename from models/z_image/config.json
rename to models/z_image/configs/z_image.json
diff --git a/models/z_image/config_control.json b/models/z_image/configs/z_image_control.json
similarity index 86%
rename from models/z_image/config_control.json
rename to models/z_image/configs/z_image_control.json
index 00ea8b7..4e5255c 100644
--- a/models/z_image/config_control.json
+++ b/models/z_image/configs/z_image_control.json
@@ -29,5 +29,6 @@
"rope_theta": 256.0,
"t_scale": 1000.0,
"enable_control": true,
- "control_layers_places": [0, 5, 10, 15, 20, 25]
+ "control_layers_places": [0, 5, 10, 15, 20, 25],
+ "control_in_dim": 16
}
diff --git a/models/z_image/configs/z_image_control2.json b/models/z_image/configs/z_image_control2.json
new file mode 100644
index 0000000..bdaf44b
--- /dev/null
+++ b/models/z_image/configs/z_image_control2.json
@@ -0,0 +1,36 @@
+{
+ "_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, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28],
+ "control_refiner_layers_places": [0, 1],
+ "add_control_noise_refiner": true,
+ "control_in_dim": 33
+}
diff --git a/models/z_image/pipeline_z_image.py b/models/z_image/pipeline_z_image.py
index b105f98..765e44f 100644
--- a/models/z_image/pipeline_z_image.py
+++ b/models/z_image/pipeline_z_image.py
@@ -25,8 +25,9 @@ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
from diffusers.utils import logging, replace_example_docstring
from diffusers.utils.torch_utils import randn_tensor
-from .transformer_z_image import ZImageTransformer2DModel
+from .z_image_transformer2d import ZImageTransformer2DModel
from .pipeline_output import ZImagePipelineOutput
+from shared.utils.utils import get_outpainting_frame_location, resize_lanczos, calculate_new_dimensions, convert_image_to_tensor, fit_image_into_canvas
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
@@ -327,7 +328,9 @@ class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):
callback=None,
pipeline=None,
control_image: Optional[torch.Tensor] = None,
+ inpaint_mask: Optional[torch.Tensor] = None,
control_context_scale: float = 0.75,
+ input_ref_images = None,
):
r"""
Function invoked when calling the pipeline for generation.
@@ -516,6 +519,7 @@ class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):
# Encode control image if provided and transformer supports it
control_latent = None
+ control_in_dim = self.transformer.control_in_dim
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
@@ -526,9 +530,48 @@ class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):
# 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 = self.vae.encode(control_image_tensor).latent_dist.mode()
control_latent = (control_latent - self.vae.config.shift_factor) * self.vae.config.scaling_factor
+ # Build control_latent_input outside the loop (doesn't change per step)
+ control_latent_input = None
+ if control_latent is not None:
+ # For v2 control (control_in_dim=33): concat [control_latent(16), keep_mask(1), inpaint_latent(16)]
+ if control_in_dim is not None and control_in_dim > num_channels_latents:
+ if inpaint_mask is not None:
+ mask = inpaint_mask
+ if mask.dim() == 3:
+ mask = mask.unsqueeze(0) # Add batch dim
+ if mask.dim() == 4 and mask.shape[1] > 1:
+ mask = mask[:, :1] # Take first channel only
+ if mask.shape[-2:] != control_latent.shape[-2:]:
+ mask = torch.nn.functional.interpolate(
+ mask.float(), size=control_latent.shape[-2:], mode='nearest'
+ )
+ mask = mask.to(device=control_latent.device, dtype=control_latent.dtype)
+ keep_mask = 1.0 - mask
+ inpaint_mask = inpaint_mask.to(device)
+ inpaint_image = control_image_tensor #* (1-inpaint_mask) + inpaint_mask
+ control_image_tensor = convert_image_to_tensor(input_ref_images[0]).unsqueeze(0)
+ control_image_tensor = control_image_tensor.to(device=device, dtype=self.vae.dtype)
+ control_latent = self.vae.encode(control_image_tensor).latent_dist.mode()
+ control_latent = (control_latent - self.vae.config.shift_factor) * self.vae.config.scaling_factor
+
+ inpaint_latent = self.vae.encode(inpaint_image).latent_dist.mode()
+ inpaint_latent = (inpaint_latent - self.vae.config.shift_factor) * self.vae.config.scaling_factor
+ control_context = torch.cat([control_latent, keep_mask, inpaint_latent], dim=1)
+ else:
+ keep_mask = torch.zeros(
+ (control_latent.shape[0], 1, control_latent.shape[2], control_latent.shape[3]),
+ device=control_latent.device, dtype=control_latent.dtype
+ )
+ inpaint_latent = torch.zeros_like(control_latent)
+ control_context = torch.cat([control_latent, keep_mask, inpaint_latent], dim=1)
+ control_latent_input = control_context.unsqueeze(2)
+ else:
+ # v1 control: just use the control latent directly (16 channels)
+ control_latent_input = control_latent.unsqueeze(2)
+
callback(-1, None, True, len(timesteps))
# 6. Denoising loop
@@ -556,66 +599,56 @@ class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):
# Run CFG only if configured AND scale is non-zero
apply_cfg = self.do_classifier_free_guidance and current_guidance_scale > 0
- if apply_cfg:
- latents_typed = latents if latents.dtype == dtype else latents.to(dtype)
- latent_model_input = latents_typed.repeat(2, 1, 1, 1)
- prompt_embeds_model_input = prompt_embeds + negative_prompt_embeds
- timestep_model_input = timestep.repeat(2)
- else:
- latent_model_input = latents if latents.dtype == dtype else latents.to(dtype)
- prompt_embeds_model_input = prompt_embeds
- timestep_model_input = timestep
-
+ # Prepare latent list (same latents used for both pos and neg in CFG)
+ latent_model_input = latents if latents.dtype == dtype else latents.to(dtype)
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]
-
- if model_out_list is None or (isinstance(model_out_list, list) and model_out_list and model_out_list[0] is None):
- return None
if apply_cfg:
- # Perform CFG
- pos_out = model_out_list[:batch_size]
- neg_out = model_out_list[batch_size:]
-
- noise_pred = []
- for j in range(batch_size):
- pos = pos_out[j].float()
- neg = neg_out[j].float()
-
- pred = pos + current_guidance_scale * (pos - neg)
-
- # Renormalization
- if self._cfg_normalization and float(self._cfg_normalization) > 0.0:
- ori_pos_norm = torch.linalg.vector_norm(pos)
- new_pos_norm = torch.linalg.vector_norm(pred)
- max_new_norm = ori_pos_norm * float(self._cfg_normalization)
- if new_pos_norm > max_new_norm:
- pred = pred * (max_new_norm / new_pos_norm)
-
- noise_pred.append(pred)
-
- noise_pred = torch.stack(noise_pred, dim=0)
+ model_out_list = self.transformer(
+ [latent_model_input, latent_model_input],
+ timestep,
+ [prompt_embeds[0], negative_prompt_embeds[0]] ,
+ control_context_list=[control_latent_input, control_latent_input] if control_latent_input is not None else None,
+ control_context_scale=control_context_scale,
+ callback=callback,
+ pipeline=self,
+ )
+
+ if model_out_list is None:
+ return None
+
+ pos, neg = model_out_list
+ model_out_list = None
+ pos, neg = pos.float(), neg.float()
+
+ noise_pred = pos + current_guidance_scale * (pos - neg)
+
+ # Renormalization
+ if self._cfg_normalization and float(self._cfg_normalization) > 0.0:
+ ori_pos_norm = torch.linalg.vector_norm(pos)
+ new_pos_norm = torch.linalg.vector_norm(noise_pred)
+ max_new_norm = ori_pos_norm * float(self._cfg_normalization)
+ if new_pos_norm > max_new_norm:
+ noise_pred = noise_pred * (max_new_norm / new_pos_norm)
+ pos = neg = None
else:
- noise_pred = torch.stack([t.float() for t in model_out_list], dim=0)
+ # Non-CFG mode: single forward pass
+
+ model_out_list = self.transformer(
+ [latent_model_input],
+ timestep,
+ [prompt_embeds[0]],
+ control_context_list=[control_latent_input] if control_latent_input is not None else None,
+ control_context_scale=control_context_scale,
+ callback=callback,
+ pipeline=self,
+ )
+
+ if model_out_list is None:
+ return None
+ noise_pred = model_out_list[0]
+ model_out_list = None
+
noise_pred = noise_pred.squeeze(2)
noise_pred = -noise_pred
diff --git a/models/z_image/transformer_z_image.py b/models/z_image/transformer_z_image.py
deleted file mode 100644
index 682262f..0000000
--- a/models/z_image/transformer_z_image.py
+++ /dev/null
@@ -1,925 +0,0 @@
-# Copyright 2025 Alibaba Z-Image Team and The HuggingFace Team. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-import math
-from typing import List, Optional, Tuple
-
-import torch
-import torch.nn as nn
-import torch.nn.functional as F
-from torch.nn.utils.rnn import pad_sequence
-
-from diffusers.configuration_utils import ConfigMixin, register_to_config
-from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
-from diffusers.models.attention_processor import Attention
-from diffusers.models.modeling_utils import ModelMixin
-from diffusers.models.normalization import RMSNorm
-from diffusers.utils.torch_utils import maybe_allow_in_graph
-from shared.attention import pay_attention
-
-
-ADALN_EMBED_DIM = 256
-SEQ_MULTI_OF = 32
-
-
-class TimestepEmbedder(nn.Module):
- def __init__(self, out_size, mid_size=None, frequency_embedding_size=256):
- super().__init__()
- if mid_size is None:
- mid_size = out_size
- self.mlp = nn.Sequential(
- nn.Linear(
- frequency_embedding_size,
- mid_size,
- bias=True,
- ),
- nn.SiLU(),
- nn.Linear(
- mid_size,
- out_size,
- bias=True,
- ),
- )
-
- self.frequency_embedding_size = frequency_embedding_size
-
- @staticmethod
- def timestep_embedding(t, dim, max_period=10000):
- with torch.amp.autocast("cuda", enabled=False):
- half = dim // 2
- freqs = torch.exp(
- -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=t.device) / half
- )
- args = t[:, None].float() * freqs[None]
- embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
- if dim % 2:
- embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
- return embedding
-
- def forward(self, t):
- t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
- t_emb = self.mlp(t_freq.to(self.mlp[0].weight.dtype))
- return t_emb
-
-
-class ZSingleStreamAttnProcessor:
- """
- Processor for Z-Image single stream attention that adapts the existing Attention class to match the behavior of the
- original Z-ImageAttention module.
- """
-
- _attention_backend = None
- _parallel_config = None
-
- def __init__(self):
- if not hasattr(F, "scaled_dot_product_attention"):
- raise ImportError(
- "ZSingleStreamAttnProcessor requires PyTorch 2.0. To use it, please upgrade PyTorch to version 2.0 or higher."
- )
-
- def __call__(
- self,
- attn: Attention,
- hidden_states: torch.Tensor,
- encoder_hidden_states: Optional[torch.Tensor] = None,
- attention_mask: Optional[torch.Tensor] = None,
- freqs_cis: Optional[torch.Tensor] = None,
- ) -> torch.Tensor:
- query = attn.to_q(hidden_states)
- key = attn.to_k(hidden_states)
- value = attn.to_v(hidden_states)
-
- query = query.unflatten(-1, (attn.heads, -1))
- key = key.unflatten(-1, (attn.heads, -1))
- value = value.unflatten(-1, (attn.heads, -1))
-
- # Apply Norms
- if attn.norm_q is not None:
- query = attn.norm_q(query)
- if attn.norm_k is not None:
- key = attn.norm_k(key)
-
- # Apply RoPE
- def apply_rotary_emb(x_list: torch.Tensor, freqs_cis: torch.Tensor) -> torch.Tensor:
- x_in = x_list[0]
- dtype = x_in.dtype
- x = x_in.float().reshape(*x_in.shape[:-1], -1, 2)
- x_in = None
- x_list.clear()
- cos = freqs_cis[..., 0].unsqueeze(2)
- sin = freqs_cis[..., 1].unsqueeze(2)
- x0 = x[..., 0]
- x1 = x[..., 1]
- x0_orig = x0.clone()
- x0.mul_(cos)
- x0.addcmul_(x1, sin, value=-1)
- x1.mul_(cos)
- x1.addcmul_(x0_orig, sin)
- return x.flatten(3).to(dtype)
-
- dtype = query.dtype
- if freqs_cis is not None:
- x_list= [query]
- del query
- query = apply_rotary_emb(x_list, freqs_cis).to(dtype)
- x_list= [key]
- del key
- key = apply_rotary_emb(x_list, freqs_cis).to(dtype)
-
-
- # Compute joint attention
- qkv_list = [query, key, value]
- hidden_states = pay_attention(
- qkv_list,
- )
-
- # Reshape back
- hidden_states = hidden_states.flatten(2, 3)
- hidden_states = hidden_states.to(dtype)
-
- output = attn.to_out[0](hidden_states)
- if len(attn.to_out) > 1: # dropout
- output = attn.to_out[1](output)
-
- return output
-
-
-class FeedForward(nn.Module):
- def __init__(self, dim: int, hidden_dim: int):
- super().__init__()
- self.w1 = nn.Linear(dim, hidden_dim, bias=False)
- self.w2 = nn.Linear(hidden_dim, dim, bias=False)
- self.w3 = nn.Linear(dim, hidden_dim, bias=False)
-
- def _forward_silu_gating(self, x1, x3):
- return F.silu(x1) * x3
-
- def forward(self, x):
- return self.w2(self._forward_silu_gating(self.w1(x), self.w3(x)))
-
- def forward_into(self, x, out):
- assert out.shape == x.shape
- x1 = self.w1(x) # (..., hidden_dim)
- x3 = self.w3(x) # (..., hidden_dim)
- F.silu(x1, inplace=True) # x1 = silu(x1)
- x1.mul_(x3) # x1 = x1 * x3
- torch.matmul(
- x1.view(-1, self.hidden_dim),
- self.w2.weight.t(),
- out=out.view(-1, self.dim),
- )
- return out
-
-@maybe_allow_in_graph
-class ZImageTransformerBlock(nn.Module):
- 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=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
- self.attention = Attention(
- query_dim=dim,
- cross_attention_dim=None,
- dim_head=dim // n_heads,
- heads=n_heads,
- qk_norm="rms_norm" if qk_norm else None,
- eps=1e-5,
- bias=False,
- out_bias=False,
- processor=ZSingleStreamAttnProcessor(),
- )
- self.ffn_mult = 8 / 3
- self.feed_forward = FeedForward(dim=dim, hidden_dim=int(dim * self.ffn_mult))
- self.layer_id = layer_id
-
- self.attention_norm1 = RMSNorm(dim, eps=norm_eps)
- self.ffn_norm1 = RMSNorm(dim, eps=norm_eps)
-
- self.attention_norm2 = RMSNorm(dim, eps=norm_eps)
- self.ffn_norm2 = RMSNorm(dim, eps=norm_eps)
-
- self.modulation = modulation
- if modulation:
- self.adaLN_modulation = nn.Sequential(
- nn.Linear(min(dim, ADALN_EMBED_DIM), 4 * dim, bias=True),
- )
-
- def _apply_ffn(self, x: torch.Tensor, scale: Optional[torch.Tensor] = None) -> torch.Tensor:
- batch, seq_len, dim = x.shape
- ffn_in = self.ffn_norm1(x)
- if scale is not None:
- ffn_in.mul_(scale)
- ffn_in = ffn_in.reshape(-1, dim)
- chunk_size = max(int(seq_len // self.ffn_mult), 1)
- for ffn_chunk in torch.split(ffn_in, chunk_size):
- ffn_chunk[...]= self.feed_forward(ffn_chunk)
-
- return self.ffn_norm2(ffn_in.view(batch, seq_len, dim))
-
- def forward(
- self,
- x: torch.Tensor,
- 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)
- gate_msa.tanh_()
- gate_mlp.tanh_()
- scale_msa.add_(1.0)
- scale_mlp.add_(1.0)
-
- attn_in = self.attention_norm1(x)
- attn_in.mul_(scale_msa)
- attn_out = self.attention(
- attn_in,
- attention_mask=attn_mask,
- freqs_cis=freqs_cis,
- )
- x.addcmul_(self.attention_norm2(attn_out), gate_msa)
-
- x.addcmul_(self._apply_ffn(x, scale_mlp), gate_mlp)
- else:
- attn_out = self.attention(
- self.attention_norm1(x),
- attention_mask=attn_mask,
- freqs_cis=freqs_cis,
- )
- x.add_(self.attention_norm2(attn_out))
-
- 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__()
- self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
- self.linear = nn.Linear(hidden_size, out_channels, bias=True)
-
- self.adaLN_modulation = nn.Sequential(
- nn.SiLU(),
- nn.Linear(min(hidden_size, ADALN_EMBED_DIM), hidden_size, bias=True),
- )
-
- def forward(self, x, c):
- scale = 1.0 + self.adaLN_modulation(c)
- x = self.norm_final(x) * scale.unsqueeze(1)
- x = self.linear(x)
- return x
-
-
-class RopeEmbedder:
- def __init__(
- self,
- theta: float = 256.0,
- axes_dims: List[int] = (16, 56, 56),
- axes_lens: List[int] = (64, 128, 128),
- ):
- self.theta = theta
- self.axes_dims = axes_dims
- self.axes_lens = axes_lens
- assert len(axes_dims) == len(axes_lens), "axes_dims and axes_lens must have the same length"
- self.freqs_cis = None
-
- @staticmethod
- def precompute_freqs_cis(dim: List[int], end: List[int], theta: float = 256.0):
- with torch.device("cpu"):
- freqs_cis = []
- for i, (d, e) in enumerate(zip(dim, end)):
- freqs = 1.0 / (theta ** (torch.arange(0, d, 2, dtype=torch.float64, device="cpu") / d))
- timestep = torch.arange(e, device=freqs.device, dtype=torch.float64)
- freqs = torch.outer(timestep, freqs).float()
- freqs_cis_i = torch.stack([torch.cos(freqs), torch.sin(freqs)], dim=-1)
- freqs_cis.append(freqs_cis_i)
-
- return freqs_cis
-
- def __call__(self, ids: torch.Tensor):
- assert ids.ndim == 2
- assert ids.shape[-1] == len(self.axes_dims)
- device = ids.device
-
- if self.freqs_cis is None:
- self.freqs_cis = self.precompute_freqs_cis(self.axes_dims, self.axes_lens, theta=self.theta)
- self.freqs_cis = [freqs_cis.to(device) for freqs_cis in self.freqs_cis]
-
- result = []
- for i in range(len(self.axes_dims)):
- index = ids[:, i]
- result.append(self.freqs_cis[i][index])
- return torch.cat(result, dim=1)
-
-
-class ZImageTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
- _supports_gradient_checkpointing = True
- _no_split_modules = ["ZImageTransformerBlock", "ZImageControlTransformerBlock"]
-
- @register_to_config
- def __init__(
- self,
- all_patch_size=(2,),
- all_f_patch_size=(1,),
- in_channels=16,
- dim=3840,
- n_layers=30,
- n_refiner_layers=2,
- n_heads=30,
- n_kv_heads=30,
- norm_eps=1e-5,
- qk_norm=True,
- cap_feat_dim=2560,
- rope_theta=256.0,
- 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
- self.out_channels = in_channels
- self.all_patch_size = all_patch_size
- self.all_f_patch_size = all_f_patch_size
- self.dim = dim
- self.n_heads = n_heads
-
- self.rope_theta = rope_theta
- self.t_scale = t_scale
- self.gradient_checkpointing = False
-
- assert len(all_patch_size) == len(all_f_patch_size)
-
- all_x_embedder = {}
- all_final_layer = {}
- for patch_idx, (patch_size, f_patch_size) in enumerate(zip(all_patch_size, all_f_patch_size)):
- x_embedder = nn.Linear(f_patch_size * patch_size * patch_size * in_channels, dim, bias=True)
- all_x_embedder[f"{patch_size}-{f_patch_size}"] = x_embedder
-
- final_layer = FinalLayer(dim, patch_size * patch_size * f_patch_size * self.out_channels)
- all_final_layer[f"{patch_size}-{f_patch_size}"] = final_layer
-
- self.all_x_embedder = nn.ModuleDict(all_x_embedder)
- self.all_final_layer = nn.ModuleDict(all_final_layer)
- self.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)
- ]
- )
- self.context_refiner = nn.ModuleList(
- [
- ZImageTransformerBlock(
- layer_id,
- dim,
- n_heads,
- n_kv_heads,
- norm_eps,
- qk_norm,
- modulation=False,
- )
- for layer_id in range(n_refiner_layers)
- ]
- )
- self.t_embedder = TimestepEmbedder(min(dim, ADALN_EMBED_DIM), mid_size=1024)
- self.cap_embedder = nn.Sequential(
- RMSNorm(cap_feat_dim, eps=norm_eps),
- nn.Linear(cap_feat_dim, dim, bias=True),
- )
-
- self.x_pad_token = nn.Parameter(torch.empty((1, dim)))
- self.cap_pad_token = nn.Parameter(torch.empty((1, dim)))
-
- # 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
- self.axes_lens = axes_lens
-
- 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
- bsz = len(x)
- assert len(size) == bsz
- for i in range(bsz):
- F, H, W = size[i]
- ori_len = (F // pF) * (H // pH) * (W // pW)
- # "f h w pf ph pw c -> c (f pf) (h ph) (w pw)"
- x[i] = (
- x[i][:ori_len]
- .view(F // pF, H // pH, W // pW, pF, pH, pW, self.out_channels)
- .permute(6, 0, 3, 1, 4, 2, 5)
- .reshape(self.out_channels, F, H, W)
- )
- return x
-
- @staticmethod
- def create_coordinate_grid(size, start=None, device=None):
- if start is None:
- start = (0 for _ in size)
-
- axes = [torch.arange(x0, x0 + span, dtype=torch.int32, device=device) for x0, span in zip(start, size)]
- grids = torch.meshgrid(axes, indexing="ij")
- return torch.stack(grids, dim=-1)
-
- def patchify_and_embed(
- self,
- all_image: List[torch.Tensor],
- all_cap_feats: List[torch.Tensor],
- patch_size: int,
- f_patch_size: int,
- ):
- 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 = []
- all_cap_pos_ids = []
- all_cap_pad_mask = []
- all_cap_feats_out = []
-
- for i, (image, cap_feat) in enumerate(zip(all_image, all_cap_feats)):
- ### Process Caption
- cap_ori_len = len(cap_feat)
- cap_padding_len = (-cap_ori_len) % SEQ_MULTI_OF
- # padded position ids
- cap_padded_pos_ids = self.create_coordinate_grid(
- size=(cap_ori_len + cap_padding_len, 1, 1),
- start=(1, 0, 0),
- device=device,
- ).flatten(0, 2)
- all_cap_pos_ids.append(cap_padded_pos_ids)
- # pad mask
- all_cap_pad_mask.append(
- torch.cat(
- [
- torch.zeros((cap_ori_len,), dtype=torch.bool, device=device),
- torch.ones((cap_padding_len,), dtype=torch.bool, device=device),
- ],
- dim=0,
- )
- )
- # padded feature
- cap_padded_feat = torch.cat(
- [cap_feat, cap_feat[-1:].repeat(cap_padding_len, 1)],
- dim=0,
- )
- all_cap_feats_out.append(cap_padded_feat)
-
- ### Process 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)
- # "c f pf h ph w pw -> (f h w) (pf ph pw c)"
- 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_ori_len + cap_padding_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)
- # pad mask
- 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,
- )
- )
- # padded feature
- 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_cap_feats_out,
- all_image_size,
- all_image_pos_ids,
- all_cap_pos_ids,
- all_image_pad_mask,
- 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],
- t,
- cap_feats: List[torch.Tensor],
- patch_size=2,
- 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
-
- bsz = len(x)
- device = x[0].device
- t = t * self.t_scale
- t = self.t_embedder(t)
-
- adaln_input = t
-
- (
- x,
- cap_feats,
- x_size,
- x_pos_ids,
- cap_pos_ids,
- x_inner_pad_mask,
- cap_inner_pad_mask,
- ) = self.patchify_and_embed(x, cap_feats, patch_size, f_patch_size)
-
- # x embed & refine
- x_item_seqlens = [len(_) for _ in x]
- assert all(_ % SEQ_MULTI_OF == 0 for _ in x_item_seqlens)
- x_max_item_seqlen = max(x_item_seqlens)
-
- x = torch.cat(x, dim=0)
- x = self.all_x_embedder[f"{patch_size}-{f_patch_size}"](x)
- x[torch.cat(x_inner_pad_mask)] = self.x_pad_token
- x = list(x.split(x_item_seqlens, dim=0))
- x_freqs_cis = list(self.rope_embedder(torch.cat(x_pos_ids, dim=0)).split(x_item_seqlens, dim=0))
-
- x = pad_sequence(x, batch_first=True, padding_value=0.0)
- x_freqs_cis = pad_sequence(x_freqs_cis, batch_first=True, padding_value=0.0)
- # x_attn_mask = torch.zeros((bsz, x_max_item_seqlen), dtype=torch.bool, device=device)
- # for i, seq_len in enumerate(x_item_seqlens):
- # x_attn_mask[i, :seq_len] = 1
- x_attn_mask = None
-
- for layer in self.noise_refiner:
- x = layer(x, x_attn_mask, x_freqs_cis, adaln_input)
-
- # cap embed & refine
- cap_item_seqlens = [len(_) for _ in cap_feats]
- assert all(_ % SEQ_MULTI_OF == 0 for _ in cap_item_seqlens)
- cap_max_item_seqlen = max(cap_item_seqlens)
-
- cap_feats = torch.cat(cap_feats, dim=0)
- cap_feats = self.cap_embedder(cap_feats)
- cap_feats[torch.cat(cap_inner_pad_mask)] = self.cap_pad_token
- cap_feats = list(cap_feats.split(cap_item_seqlens, dim=0))
- cap_freqs_cis = list(self.rope_embedder(torch.cat(cap_pos_ids, dim=0)).split(cap_item_seqlens, dim=0))
-
- cap_feats = pad_sequence(cap_feats, batch_first=True, padding_value=0.0)
- cap_freqs_cis = pad_sequence(cap_freqs_cis, batch_first=True, padding_value=0.0)
- cap_attn_mask = torch.zeros((bsz, cap_max_item_seqlen), dtype=torch.bool, device=device)
- for i, seq_len in enumerate(cap_item_seqlens):
- cap_attn_mask[i, :seq_len] = 1
-
- for layer in self.context_refiner:
- cap_feats = layer(cap_feats, cap_attn_mask, cap_freqs_cis)
-
- # unified
- unified = []
- unified_freqs_cis = []
- for i in range(bsz):
- x_len = x_item_seqlens[i]
- cap_len = cap_item_seqlens[i]
- unified.append(torch.cat([x[i][:x_len], cap_feats[i][:cap_len]]))
- unified_freqs_cis.append(torch.cat([x_freqs_cis[i][:x_len], cap_freqs_cis[i][:cap_len]]))
- unified_item_seqlens = [a + b for a, b in zip(cap_item_seqlens, x_item_seqlens)]
- assert unified_item_seqlens == [len(_) for _ in unified]
- unified_max_item_seqlen = max(unified_item_seqlens)
-
- unified = pad_sequence(unified, batch_first=True, padding_value=0.0)
- unified_freqs_cis = pad_sequence(unified_freqs_cis, batch_first=True, padding_value=0.0)
- unified_attn_mask = torch.zeros((bsz, unified_max_item_seqlen), dtype=torch.bool, device=device)
- 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,
- 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))
- x = self.unpatchify(unified, x_size, patch_size, f_patch_size)
-
- return x, {}
diff --git a/models/z_image/z_image_handler.py b/models/z_image/z_image_handler.py
index 9ec815b..da3e1e6 100644
--- a/models/z_image/z_image_handler.py
+++ b/models/z_image/z_image_handler.py
@@ -21,7 +21,7 @@ class family_handler:
"no_negative_prompt": True,
}
- if base_model_type == "z_image_control":
+ if base_model_type in ["z_image_control", "z_image_control2"]:
extra_model_def["mask_preprocessing"] = {
"selection":[ ""],
"visible": False
@@ -35,11 +35,24 @@ class family_handler:
"labels" : { "V": "Use Z-Image Raw Format"},
}
+ if base_model_type in ["z_image_control2"]:
+ extra_model_def["mask_preprocessing"] = {
+ "selection":[ "", "A", "NA"],
+ "visible": False,
+ }
+ extra_model_def["image_ref_choices"] = {
+ "choices":[("No Reference Image",""), ("Image is a Reference Image", "KI")],
+ "default": "",
+ "letters_filter": "KI",
+ "label": "Reference Image for Inpainting",
+ "visible": False,
+ }
+
return extra_model_def
@staticmethod
def query_supported_types():
- return ["z_image", "z_image_control"]
+ return ["z_image", "z_image_control", "z_image_control2"]
@staticmethod
def query_family_maps():
@@ -51,7 +64,7 @@ class family_handler:
@staticmethod
def query_family_infos():
- return {"z_image": (50, "Z-Image"), "z_image_control": (51, "Z-Image ControlNet")}
+ return {"z_image": (50, "Z-Image") }
@staticmethod
def register_lora_cli_args(parser):
@@ -103,8 +116,8 @@ 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"
+ # Detect if this is a control variant (v1 or v2)
+ is_control = base_model_type in ["z_image_control", "z_image_control2"]
pipe_processor = model_factory(
checkpoint_dir="ckpts",
@@ -142,8 +155,8 @@ class family_handler:
}
)
- # Add control defaults for z_image_control
- if base_model_type == "z_image_control":
+ # Add control defaults for z_image_control and z_image_control2
+ if base_model_type in ["z_image_control", "z_image_control2"]:
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 39ec4ae..ac0d45b 100644
--- a/models/z_image/z_image_main.py
+++ b/models/z_image/z_image_main.py
@@ -10,7 +10,7 @@ from transformers import AutoTokenizer, Qwen3ForCausalLM
from .autoencoder_kl import AutoencoderKL
from .pipeline_z_image import ZImagePipeline
-from .transformer_z_image import ZImageTransformer2DModel
+from .z_image_transformer2d import ZImageTransformer2DModel
logger = logging.get_logger(__name__)
@@ -98,37 +98,38 @@ class model_factory:
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")
-
+ default_transformer_config = os.path.join(os.path.dirname(os.path.abspath(__file__)), "configs", f"{base_model_type}.json")
preprocess_sd = conv_state_dict
- kwargs_light= { "modelClass": ZImageTransformer2DModel, "writable_tensors": False, "preprocess_sd": preprocess_sd , "forcedConfigPath" : default_transformer_config}
+ model_class = ZImageTransformer2DModel
+
+ kwargs_light= { "writable_tensors": False, "preprocess_sd": preprocess_sd }
+ # model_filename contains all files to load (transformer + modules merged by loader)
+ import json
+ import accelerate
+ with open(default_transformer_config, "r") as f:
+ config = json.load(f)
+ config.pop("_class_name", None)
+ config.pop("_diffusers_version", None)
+
+ with accelerate.init_empty_weights():
+ transformer = model_class(**config)
if source is not None:
- transformer = offload.fast_load_transformers_model(fl.locate_file(source), **kwargs_light)
+ offload.load_model_data(transformer, 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
+ offload.load_model_data(transformer, model_filename[:1] + [fl.locate_file(module_source)], **kwargs_light)
else:
- # model_filename contains all files to load (transformer + modules merged by loader)
- transformer = offload.fast_load_transformers_model( model_filename, **kwargs_light )
-
+ offload.load_model_data(transformer, model_filename, **kwargs_light)
+ from wgp import save_model
+ from mmgp.safetensors2 import torch_load_file
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)
+ save_model(transformer, model_type, dtype, None, is_module=True, filter=list(torch_load_file(fl.locate_file(module_source))), module_source_no=1)
if not source is None:
save_model(transformer, model_type, dtype, None, submodel_no= 1)
@@ -137,11 +138,6 @@ class model_factory:
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)
@@ -197,7 +193,9 @@ class model_factory:
cfg_normalization: bool = False,
cfg_truncation: float = 1.0,
input_frames=None,
+ input_masks=None,
context_scale: float = [0],
+ input_ref_images = None,
**kwargs,
):
generator = torch.Generator(device="cuda" if torch.cuda.is_available() else "cpu")
@@ -237,7 +235,9 @@ class model_factory:
callback=callback,
pipeline=self.pipeline,
control_image=input_frames,
+ inpaint_mask=input_masks,
control_context_scale=None if context_scale is None else context_scale[0],
+ input_ref_images= input_ref_images ,
)
if images is None:
diff --git a/models/z_image/z_image_transformer2d.py b/models/z_image/z_image_transformer2d.py
new file mode 100644
index 0000000..cf12605
--- /dev/null
+++ b/models/z_image/z_image_transformer2d.py
@@ -0,0 +1,1086 @@
+# Copyright 2025 Alibaba Z-Image Team and The HuggingFace Team. All rights reserved.
+##### Enjoy this spagheti VRAM optimizations done by DeepBeepMeep !
+# I am sure you are a nice person and as you copy this code, you will give me officially proper credits:
+# Please link to https://github.com/deepbeepmeep/Wan2GP and @deepbeepmeep on twitter
+
+import math
+from typing import List, Optional, Tuple
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.nn.utils.rnn import pad_sequence
+
+from diffusers.models.normalization import RMSNorm
+
+from shared.attention import pay_attention
+
+class ModuleWrapper:
+ def __init__(self, module):
+ self.module = module
+
+ def __call__(self):
+ return self.module
+
+def apply_rotary_emb_inplace(x_list: list, freqs_cis: torch.Tensor) -> torch.Tensor:
+ x_in = x_list.pop()
+ dtype = x_in.dtype
+ x = x_in.float().reshape(*x_in.shape[:-1], -1, 2) # [B, S, H, D//2, 2]
+ x_in = None
+ # freqs_cis shape: [B, S, rope_dim, 2] -> cos/sin: [B, S, 1, rope_dim] to broadcast over heads
+ cos = freqs_cis[..., 0].unsqueeze(2) # [B, S, 1, rope_dim]
+ sin = freqs_cis[..., 1].unsqueeze(2) # [B, S, 1, rope_dim]
+ x0, x1 = x[..., 0], x[..., 1] # [B, S, H, D//2]
+ x0_orig = x0.clone()
+ x0.mul_(cos).addcmul_(x1, sin, value=-1)
+ x1.mul_(cos).addcmul_(x0_orig, sin)
+ return x.flatten(3).to(dtype)
+
+
+ADALN_EMBED_DIM = 256
+SEQ_MULTI_OF = 32
+
+
+class TimestepEmbedder(nn.Module):
+ def __init__(self, out_size, mid_size=None, frequency_embedding_size=256):
+ super().__init__()
+ if mid_size is None:
+ mid_size = out_size
+ self.mlp = nn.Sequential(
+ nn.Linear(
+ frequency_embedding_size,
+ mid_size,
+ bias=True,
+ ),
+ nn.SiLU(),
+ nn.Linear(
+ mid_size,
+ out_size,
+ bias=True,
+ ),
+ )
+
+ self.frequency_embedding_size = frequency_embedding_size
+
+ @staticmethod
+ def timestep_embedding(t, dim, max_period=10000):
+ with torch.amp.autocast("cuda", enabled=False):
+ half = dim // 2
+ freqs = torch.exp(
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=t.device) / half
+ )
+ args = t[:, None].float() * freqs[None]
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
+ if dim % 2:
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
+ return embedding
+
+ def forward(self, t):
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
+ weight_dtype = self.mlp[0].weight.dtype
+ if weight_dtype.is_floating_point:
+ t_freq = t_freq.to(weight_dtype)
+ t_emb = self.mlp(t_freq)
+ return t_emb
+
+
+class FeedForward(nn.Module):
+ def __init__(self, dim: int, hidden_dim: int):
+ super().__init__()
+ self.w1 = nn.Linear(dim, hidden_dim, bias=False)
+ self.w2 = nn.Linear(hidden_dim, dim, bias=False)
+ self.w3 = nn.Linear(dim, hidden_dim, bias=False)
+
+ def _forward_silu_gating(self, x1, x3):
+ return F.silu(x1) * x3
+
+ def forward(self, x):
+ return self.w2(self._forward_silu_gating(self.w1(x), self.w3(x)))
+
+
+class Attention(nn.Module):
+ """Simple attention module to match weight key structure."""
+ def __init__(self, dim: int, n_heads: int, qk_norm: bool):
+ super().__init__()
+ self.n_heads = n_heads
+ self.head_dim = dim // n_heads
+
+ self.to_q = nn.Linear(dim, dim, bias=False)
+ self.to_k = nn.Linear(dim, dim, bias=False)
+ self.to_v = nn.Linear(dim, dim, bias=False)
+ # Sequential to match weight keys: to_out.0.weight
+ self.to_out = nn.Sequential(nn.Linear(dim, dim, bias=False))
+
+ self.norm_q = RMSNorm(self.head_dim, eps=1e-5) if qk_norm else None
+ self.norm_k = RMSNorm(self.head_dim, eps=1e-5) if qk_norm else None
+
+ def forward(self, h_list: list, freqs_cis: torch.Tensor) -> torch.Tensor:
+ """Compute self-attention with RoPE. h_list is cleared to free memory early."""
+ h = h_list.pop()
+ query = self.to_q(h)
+ key = self.to_k(h)
+ value = self.to_v(h); del h
+ # Reshape to [batch, seq, heads, head_dim]
+ query = query.unflatten(-1, (self.n_heads, -1))
+ key = key.unflatten(-1, (self.n_heads, -1))
+ value = value.unflatten(-1, (self.n_heads, -1))
+ # Apply QK normalization
+ if self.norm_q is not None:
+ query = self.norm_q(query)
+ if self.norm_k is not None:
+ key = self.norm_k(key)
+ if freqs_cis is not None:
+ q_list = [query]; del query
+ query = apply_rotary_emb_inplace(q_list, freqs_cis)
+ k_list = [key]; del key
+ key = apply_rotary_emb_inplace(k_list, freqs_cis)
+ # Compute attention
+ dtype = query.dtype
+ out = pay_attention([query, key, value]); del query, key, value
+ return self.to_out(out.flatten(2, 3).to(dtype))
+
+
+class ZImageTransformerBlock(nn.Module):
+ def __init__(
+ self,
+ layer_id: int,
+ dim: int,
+ n_heads: int,
+ n_kv_heads: int, # kept for API compatibility
+ norm_eps: float,
+ qk_norm: bool,
+ modulation=True,
+ ):
+ super().__init__()
+ self.dim = dim
+ self.n_heads = n_heads
+ self.head_dim = dim // n_heads
+
+ # Attention module (named 'attention' to match weight keys)
+ self.attention = Attention(dim, n_heads, qk_norm)
+
+ # SwiGLU FFN: hidden_dim = dim * 8/3 ≈ 2.67x expansion
+ self.feed_forward = FeedForward(dim=dim, hidden_dim=int(dim / 3 * 8))
+ self.ffn_mult = 8 / 3 # For chunking: matches SwiGLU expansion factor
+ self.layer_id = layer_id
+
+ self.attention_norm1 = RMSNorm(dim, eps=norm_eps)
+ self.ffn_norm1 = RMSNorm(dim, eps=norm_eps)
+
+ self.attention_norm2 = RMSNorm(dim, eps=norm_eps)
+ self.ffn_norm2 = RMSNorm(dim, eps=norm_eps)
+
+ self.modulation = modulation
+ if modulation:
+ self.adaLN_modulation = nn.Sequential(
+ nn.Linear(min(dim, ADALN_EMBED_DIM), 4 * dim, bias=True),
+ )
+
+ def _apply_ffn_chunked(self, ffn_in: torch.Tensor) -> None:
+ _, seq_len, dim = ffn_in.shape
+ ffn_in_flat = ffn_in.reshape(-1, dim)
+ chunk_size = max(int(seq_len // self.ffn_mult), 1)
+ for ffn_chunk in torch.split(ffn_in_flat, chunk_size):
+ ffn_chunk[...] = self.feed_forward(ffn_chunk)
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ attn_mask: torch.Tensor,
+ freqs_cis: torch.Tensor,
+ adaln_input: Optional[torch.Tensor] = None,
+ ):
+ if self.modulation:
+ scale_msa, gate_msa, scale_mlp, gate_mlp = self.adaLN_modulation(adaln_input).unsqueeze(1).chunk(4, dim=2)
+ # In-place modulation for attention block
+ scale_msa.add_(1.0)
+ normed = self.attention_norm1(x)
+ normed.mul_(scale_msa)
+ attn_out = self.attention_norm2(self.attention([normed], freqs_cis))
+ attn_out.mul_(gate_msa.tanh_())
+ x.add_(attn_out); attn_out = None
+ # In-place modulation for FFN block (chunked)
+ scale_mlp.add_(1.0)
+ normed = self.ffn_norm1(x)
+ normed.mul_(scale_mlp)
+ self._apply_ffn_chunked(normed)
+ ffn_out = self.ffn_norm2(normed); normed = None
+ ffn_out.mul_(gate_mlp.tanh_())
+ x.add_(ffn_out); ffn_out = None
+ else:
+ x.add_(self.attention_norm2(self.attention([self.attention_norm1(x)], freqs_cis)))
+ normed = self.ffn_norm1(x)
+ self._apply_ffn_chunked(normed)
+ x.add_(self.ffn_norm2(normed)); normed = None
+ return x
+
+
+class ZImageControlTransformerBlock(ZImageTransformerBlock):
+ """Control block that processes control signals and produces skip connections."""
+ 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)
+ self.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):
+ # behold dbm magic !
+ c = hints[0]
+ hints[0] = None
+ if self.block_id == 0:
+ c = self.before_proj(c)
+ bz = x.shape[0]
+ if bz > c.shape[0]: c = c.repeat(bz, 1, 1 )
+ c += x
+ c = super().forward(c, **kwargs)
+ c_skip = self.after_proj(c)
+ hints[0] = c
+ return c_skip
+
+
+
+class BaseZImageTransformerBlock(ZImageTransformerBlock):
+ """Base block that can optionally apply control 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=None
+ ):
+ super().__init__(layer_id, dim, n_heads, n_kv_heads, norm_eps, qk_norm, modulation)
+ self.block_id = block_id
+
+ def forward(self, hidden_states, hints=None, hints_kwargs=None, context_scale=1.0, **kwargs):
+ hints_processed = None
+ if self.block_id is not None and hints is not None:
+ hints_processed = self.control()(hints, **hints_kwargs)
+ hidden_states = super().forward(hidden_states, **kwargs)
+ if hints_processed is not None:
+ hidden_states.add_(hints_processed, alpha=context_scale); hints_processed = None
+ return hidden_states
+
+
+class FinalLayer(nn.Module):
+ def __init__(self, hidden_size, out_channels):
+ super().__init__()
+ self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
+ self.linear = nn.Linear(hidden_size, out_channels, bias=True)
+
+ self.adaLN_modulation = nn.Sequential(
+ nn.SiLU(),
+ nn.Linear(min(hidden_size, ADALN_EMBED_DIM), hidden_size, bias=True),
+ )
+
+ def forward(self, x, c):
+ scale = self.adaLN_modulation(c)
+ scale.add_(1.0)
+ x = self.norm_final(x)
+ x.mul_(scale.unsqueeze(1))
+ return self.linear(x)
+
+
+class RopeEmbedder:
+ def __init__(
+ self,
+ theta: float = 256.0,
+ axes_dims: List[int] = (16, 56, 56),
+ axes_lens: List[int] = (64, 128, 128),
+ ):
+ self.theta = theta
+ self.axes_dims = axes_dims
+ self.axes_lens = axes_lens
+ assert len(axes_dims) == len(axes_lens), "axes_dims and axes_lens must have the same length"
+ self.freqs_cis = None
+
+ @staticmethod
+ def precompute_freqs_cis(dim: List[int], end: List[int], theta: float = 256.0):
+ """Precompute cos/sin frequencies for RoPE (real arithmetic, no complex)."""
+ with torch.device("cpu"):
+ freqs_cis = []
+ for d, e in zip(dim, end):
+ freqs = 1.0 / (theta ** (torch.arange(0, d, 2, dtype=torch.float64) / d))
+ timestep = torch.arange(e, dtype=torch.float64)
+ freqs = torch.outer(timestep, freqs).float()
+ # Stack cos/sin in last dim: [end, dim//2, 2]
+ freqs_cis.append(torch.stack([freqs.cos(), freqs.sin()], dim=-1))
+ return freqs_cis
+
+ def __call__(self, ids: torch.Tensor):
+ assert ids.ndim == 2
+ assert ids.shape[-1] == len(self.axes_dims)
+ device = ids.device
+
+ if self.freqs_cis is None:
+ self.freqs_cis = self.precompute_freqs_cis(self.axes_dims, self.axes_lens, theta=self.theta)
+ self.freqs_cis = [freqs_cis.to(device) for freqs_cis in self.freqs_cis]
+ else:
+ # Ensure freqs_cis are on the same device as ids
+ if self.freqs_cis[0].device != device:
+ self.freqs_cis = [freqs_cis.to(device) for freqs_cis in self.freqs_cis]
+
+ result = []
+ for i in range(len(self.axes_dims)):
+ index = ids[:, i]
+ result.append(self.freqs_cis[i][index])
+ # Cat on dim=-2 (D//2 dimension) since format is [S, D//2, 2]
+ return torch.cat(result, dim=-2)
+
+
+class ZImageTransformer2DModel(nn.Module):
+ def __init__(
+ self,
+ # Control-specific parameters (optional)
+ control_layers_places=None,
+ control_refiner_layers_places=None,
+ control_in_dim=None,
+ add_control_noise_refiner=False,
+ enable_control=False,
+ # Base model parameters
+ all_patch_size=(2,),
+ all_f_patch_size=(1,),
+ in_channels=16,
+ dim=3840,
+ n_layers=30,
+ n_refiner_layers=2,
+ n_heads=30,
+ n_kv_heads=30,
+ norm_eps=1e-5,
+ qk_norm=True,
+ cap_feat_dim=2560,
+ rope_theta=256.0,
+ t_scale=1000.0,
+ axes_dims=[32, 48, 48],
+ axes_lens=[1024, 512, 512],
+ ) -> None:
+ super().__init__()
+ self.in_channels = in_channels
+ self.out_channels = in_channels
+ self.all_patch_size = all_patch_size
+ self.all_f_patch_size = all_f_patch_size
+ self.dim = dim
+ self.n_heads = n_heads
+
+ self.rope_theta = rope_theta
+ self.t_scale = t_scale
+
+ # Control-specific attributes
+ self.control_in_dim = control_in_dim if control_in_dim is not None else in_channels
+ self.control_layers_places = [i for i in range(0, n_layers, 2)] if control_layers_places is None else control_layers_places
+ self.control_refiner_layers_places = [i for i in range(0, n_refiner_layers)] if control_refiner_layers_places is None else control_refiner_layers_places
+ self.add_control_noise_refiner = add_control_noise_refiner
+ self.enable_control = enable_control
+
+ assert 0 in self.control_layers_places
+ self.control_layers_mapping = {i: n for n, i in enumerate(self.control_layers_places)}
+ self.control_refiner_layers_mapping = {i: n for n, i in enumerate(self.control_refiner_layers_places)}
+
+ assert len(all_patch_size) == len(all_f_patch_size)
+
+ all_x_embedder = {}
+ all_final_layer = {}
+ for patch_idx, (patch_size, f_patch_size) in enumerate(zip(all_patch_size, all_f_patch_size)):
+ x_embedder = nn.Linear(f_patch_size * patch_size * patch_size * in_channels, dim, bias=True)
+ all_x_embedder[f"{patch_size}-{f_patch_size}"] = x_embedder
+
+ final_layer = FinalLayer(dim, patch_size * patch_size * f_patch_size * self.out_channels)
+ all_final_layer[f"{patch_size}-{f_patch_size}"] = final_layer
+
+ self.all_x_embedder = nn.ModuleDict(all_x_embedder)
+ self.all_final_layer = nn.ModuleDict(all_final_layer)
+
+ # Noise refiner - use control version if enable_control and add_control_noise_refiner
+ if enable_control and add_control_noise_refiner:
+ self.noise_refiner = nn.ModuleList(
+ [
+ BaseZImageTransformerBlock(
+ 1000 + layer_id,
+ dim,
+ n_heads,
+ n_kv_heads,
+ norm_eps,
+ qk_norm,
+ modulation=True,
+ block_id=self.control_refiner_layers_mapping[layer_id] if layer_id in self.control_refiner_layers_places else None
+ )
+ for layer_id in range(n_refiner_layers)
+ ]
+ )
+ else:
+ self.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)
+ ]
+ )
+
+ self.context_refiner = nn.ModuleList(
+ [
+ ZImageTransformerBlock(
+ layer_id,
+ dim,
+ n_heads,
+ n_kv_heads,
+ norm_eps,
+ qk_norm,
+ modulation=False,
+ )
+ for layer_id in range(n_refiner_layers)
+ ]
+ )
+ self.t_embedder = TimestepEmbedder(min(dim, ADALN_EMBED_DIM), mid_size=1024)
+ self.cap_embedder = nn.Sequential(
+ RMSNorm(cap_feat_dim, eps=norm_eps),
+ nn.Linear(cap_feat_dim, dim, bias=True),
+ )
+
+ self.x_pad_token = nn.Parameter(torch.empty((1, dim)))
+ self.cap_pad_token = nn.Parameter(torch.empty((1, dim)))
+
+ # Main layers - use control version if enable_control
+ if enable_control:
+ self.layers = nn.ModuleList(
+ [
+ BaseZImageTransformerBlock(
+ i,
+ dim,
+ n_heads,
+ n_kv_heads,
+ norm_eps,
+ qk_norm,
+ block_id=self.control_layers_mapping[i] if i in self.control_layers_places else None
+ )
+ for i in range(n_layers)
+ ]
+ )
+ else:
+ 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
+ self.axes_lens = axes_lens
+
+ self.rope_embedder = RopeEmbedder(theta=rope_theta, axes_dims=axes_dims, axes_lens=axes_lens)
+
+ # Control-specific layers (only created when enable_control=True)
+ if enable_control:
+ # Control blocks
+ self.control_layers = nn.ModuleList(
+ [
+ ZImageControlTransformerBlock(
+ i,
+ dim,
+ n_heads,
+ n_kv_heads,
+ norm_eps,
+ qk_norm,
+ block_id=i
+ )
+ for i in self.control_layers_places
+ ]
+ )
+
+ # Control patch embeddings
+ control_all_x_embedder = {}
+ for patch_idx, (patch_size, f_patch_size) in enumerate(zip(all_patch_size, all_f_patch_size)):
+ x_embedder = nn.Linear(f_patch_size * patch_size * patch_size * self.control_in_dim, dim, bias=True)
+ control_all_x_embedder[f"{patch_size}-{f_patch_size}"] = x_embedder
+ self.control_all_x_embedder = nn.ModuleDict(control_all_x_embedder)
+
+ # Control noise refiner (for v2 control)
+ if add_control_noise_refiner:
+ self.control_noise_refiner = nn.ModuleList(
+ [
+ ZImageControlTransformerBlock(
+ 1000 + layer_id,
+ dim,
+ n_heads,
+ n_kv_heads,
+ norm_eps,
+ qk_norm,
+ modulation=True,
+ block_id=layer_id
+ )
+ for layer_id in range(n_refiner_layers)
+ ]
+ )
+ else:
+ # For v1 control
+ 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)
+ ]
+ )
+
+ self.adapt_control_model()
+
+ 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
+ bsz = len(x)
+ assert len(size) == bsz
+ x_out_list = []
+ for i in range(bsz):
+ F, H, W = size[i]
+ ori_len = (F // pF) * (H // pH) * (W // pW)
+ # "f h w pf ph pw c -> c (f pf) (h ph) (w pw)"
+ x_out_list.append(
+ x[i][:ori_len]
+ .view(F // pF, H // pH, W // pW, pF, pH, pW, self.out_channels)
+ .permute(6, 0, 3, 1, 4, 2, 5)
+ .reshape(self.out_channels, F, H, W)
+ )
+ return torch.stack(x_out_list)
+
+ @staticmethod
+ def create_coordinate_grid(size, start=None, device=None):
+ if start is None:
+ start = (0 for _ in size)
+
+ axes = [torch.arange(x0, x0 + span, dtype=torch.int32, device=device) for x0, span in zip(start, size)]
+ grids = torch.meshgrid(axes, indexing="ij")
+ return torch.stack(grids, dim=-1)
+
+ def patchify(
+ self,
+ all_image: List[torch.Tensor],
+ patch_size: int,
+ f_patch_size: int,
+ cap_padding_len: int,
+ ):
+ 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 i, image in enumerate(all_image):
+ ### Process 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)
+ # "c f pf h ph w pw -> (f h w) (pf ph pw c)"
+ 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_padding_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)
+ # pad mask
+ 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,
+ )
+ )
+ # padded feature
+ 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 patchify_and_embed(
+ self,
+ all_image: List[torch.Tensor],
+ all_cap_feats: List[torch.Tensor],
+ patch_size: int,
+ f_patch_size: int,
+ ):
+ 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 = []
+ all_cap_pos_ids = []
+ all_cap_pad_mask = []
+ all_cap_feats_out = []
+
+ for i, (image, cap_feat) in enumerate(zip(all_image, all_cap_feats)):
+ ### Process Caption
+ cap_ori_len = len(cap_feat)
+ cap_padding_len = (-cap_ori_len) % SEQ_MULTI_OF
+ # padded position ids
+ cap_padded_pos_ids = self.create_coordinate_grid(
+ size=(cap_ori_len + cap_padding_len, 1, 1),
+ start=(1, 0, 0),
+ device=device,
+ ).flatten(0, 2)
+ all_cap_pos_ids.append(cap_padded_pos_ids)
+ # pad mask
+ all_cap_pad_mask.append(
+ torch.cat(
+ [
+ torch.zeros((cap_ori_len,), dtype=torch.bool, device=device),
+ torch.ones((cap_padding_len,), dtype=torch.bool, device=device),
+ ],
+ dim=0,
+ )
+ )
+ # padded feature
+ cap_padded_feat = torch.cat(
+ [cap_feat, cap_feat[-1:].repeat(cap_padding_len, 1)],
+ dim=0,
+ )
+ all_cap_feats_out.append(cap_padded_feat)
+
+ ### Process 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)
+ # "c f pf h ph w pw -> (f h w) (pf ph pw c)"
+ 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_ori_len + cap_padding_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)
+ # pad mask
+ 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,
+ )
+ )
+ # padded feature
+ 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_cap_feats_out,
+ all_image_size,
+ all_image_pos_ids,
+ all_cap_pos_ids,
+ all_image_pad_mask,
+ all_cap_pad_mask,
+ )
+
+ @property
+ def has_control(self) -> bool:
+ """Returns True if the model has control layers enabled."""
+ return self.enable_control
+
+ 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", ModuleWrapper(control_module))
+
+
+ for model_layer, control_idx in self.control_refiner_layers_mapping.items():
+ control_module = modules_dict[f"control_layers.{control_idx}"]
+ target = modules_dict[f"noise_refiner.{model_layer}"]
+ setattr(target, "control", ModuleWrapper(control_module))
+
+ def prepare_forward_control_1_0(
+ self,
+ x,
+ cap_feats,
+ control_context,
+ kwargs,
+ t=None,
+ patch_size=2,
+ f_patch_size=1,
+ ):
+ """Control v1.0 processing (without noise refiner control)."""
+ # embeddings
+ bsz = len(control_context)
+ device = control_context[0].device
+ (
+ control_context,
+ x_size,
+ x_pos_ids,
+ x_inner_pad_mask,
+ ) = self.patchify(control_context, patch_size, f_patch_size, cap_feats[0].size(0))
+
+ # control_context embed & refine
+ x_item_seqlens = [len(_) for _ in control_context]
+ assert all(_ % SEQ_MULTI_OF == 0 for _ in x_item_seqlens)
+ x_max_item_seqlen = max(x_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 t_embedder output dtype to control_context for layerwise casting compatibility
+ adaln_input = t.type_as(control_context)
+ control_context[torch.cat(x_inner_pad_mask)] = self.x_pad_token
+ control_context = list(control_context.split(x_item_seqlens, dim=0))
+ x_freqs_cis = list(self.rope_embedder(torch.cat(x_pos_ids, dim=0)).split(x_item_seqlens, dim=0))
+
+ control_context = pad_sequence(control_context, batch_first=True, padding_value=0.0)
+ x_freqs_cis = pad_sequence(x_freqs_cis, batch_first=True, padding_value=0.0)
+ x_attn_mask = torch.zeros((bsz, x_max_item_seqlen), dtype=torch.bool, device=device)
+ for i, seq_len in enumerate(x_item_seqlens):
+ x_attn_mask[i, :seq_len] = 1
+
+ for layer in self.control_noise_refiner:
+ control_context = layer(control_context, x_attn_mask, x_freqs_cis, adaln_input)
+
+ # unified
+ cap_item_seqlens = [len(_) for _ in cap_feats]
+ control_context_unified = []
+ for i in range(bsz):
+ x_len = x_item_seqlens[i]
+ cap_len = cap_item_seqlens[i]
+ control_context_unified.append(torch.cat([control_context[i][:x_len], cap_feats[i][:cap_len]]))
+ control_context_unified = pad_sequence(control_context_unified, batch_first=True, padding_value=0.0)
+ c = control_context_unified
+
+ new_kwargs = dict(x=x)
+ new_kwargs.update(kwargs)
+
+ return new_kwargs, c
+
+ def prepare_forward_control_2_0_refiner(
+ self,
+ x,
+ cap_feats,
+ control_context,
+ kwargs,
+ t=None,
+ patch_size=2,
+ f_patch_size=1,
+ ):
+ """Control v2.0 refiner processing."""
+ # embeddings
+ bsz = len(control_context)
+ device = control_context[0].device
+ (
+ control_context,
+ control_context_size,
+ control_context_pos_ids,
+ control_context_inner_pad_mask,
+ ) = self.patchify(control_context, patch_size, f_patch_size, cap_feats[0].size(0))
+
+ # control_context embed & refine
+ control_context_item_seqlens = [len(_) for _ in control_context]
+ assert all(_ % SEQ_MULTI_OF == 0 for _ in control_context_item_seqlens)
+ control_context_max_item_seqlen = max(control_context_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 t_embedder output dtype to control_context for layerwise casting compatibility
+ adaln_input = t.type_as(control_context)
+ control_context[torch.cat(control_context_inner_pad_mask)] = self.x_pad_token
+ control_context = list(control_context.split(control_context_item_seqlens, dim=0))
+ control_context_freqs_cis = list(self.rope_embedder(torch.cat(control_context_pos_ids, dim=0)).split(control_context_item_seqlens, dim=0))
+
+ control_context = pad_sequence(control_context, batch_first=True, padding_value=0.0)
+ control_context_freqs_cis = pad_sequence(control_context_freqs_cis, batch_first=True, padding_value=0.0)
+ control_context_attn_mask = torch.zeros((bsz, control_context_max_item_seqlen), dtype=torch.bool, device=device)
+ for i, seq_len in enumerate(control_context_item_seqlens):
+ control_context_attn_mask[i, :seq_len] = 1
+ c = control_context
+
+ new_kwargs = dict(
+ x=x,
+ attn_mask=control_context_attn_mask,
+ freqs_cis=control_context_freqs_cis,
+ adaln_input=adaln_input,
+ )
+ new_kwargs.update(kwargs)
+
+ return new_kwargs, c, control_context_item_seqlens
+
+ def prepare_forward_control_2_0_layers(
+ self,
+ x,
+ cap_feats,
+ control_context,
+ control_context_item_seqlens,
+ kwargs,
+ ):
+ """Control v2.0 layers processing."""
+ control_context_len = control_context_item_seqlens
+ cap_len = cap_feats.shape[1]
+ control_context_unified= torch.cat([control_context[:control_context_len], cap_feats[:cap_len]], dim=1)
+
+ c = pad_sequence(control_context_unified, batch_first=True, padding_value=0.0)
+
+ new_kwargs = dict(x=x)
+ new_kwargs.update(kwargs)
+
+ return new_kwargs, c
+
+ def forward(
+ self,
+ x_list: List[torch.Tensor],
+ t,
+ cap_feats_list: List[torch.Tensor],
+ patch_size=2,
+ f_patch_size=1,
+ control_context_list=None,
+ control_context_scale=1.0,
+ callback=None,
+ pipeline=None,
+ ):
+ """Forward pass with list-based processing (outer loop over layers, inner loop over samples)."""
+ assert patch_size in self.all_patch_size
+ assert f_patch_size in self.all_f_patch_size
+
+ num_noise_samples = len(x_list)
+ assert len(cap_feats_list) == num_noise_samples, "cap_feats_list must match x_list length"
+
+ device = x_list[0].device
+ t = t * self.t_scale
+ t = self.t_embedder(t)
+
+ # Patchify and embed each (x, cap_feats) pair
+ x_embedder = self.all_x_embedder[f"{patch_size}-{f_patch_size}"]
+ embedded_x_list = []
+ cap_embedded_list = []
+ x_seqlen = None
+ cap_seqlen = None
+ x_freqs_cis = None
+ cap_freqs_cis = None
+
+ for i,(x,cap_feats) in enumerate(zip(x_list, cap_feats_list)):
+ bsz = x.shape[0]
+ ( x_patches, cap_out, x_i_size, x_pos_ids, cap_pos_ids, x_inner_pad_mask, cap_inner_pad_mask) = self.patchify_and_embed(x, [cap_feats]* bsz, patch_size, f_patch_size)
+
+ # Store x_size from first sample (all should be same shape)
+ if i==0:
+ x_seqlen = len(x_patches[0])
+ cap_seqlen = len(cap_out[0])
+ x_freqs_cis = self.rope_embedder(torch.cat(x_pos_ids[:1], dim=0))
+ cap_freqs_cis = self.rope_embedder(torch.cat(cap_pos_ids[:1], dim=0))
+ x_size = x_i_size
+ # Embed x
+ # x_patches =
+ x_embedded = x_embedder(torch.stack(x_patches))
+ x_embedded[torch.stack(x_inner_pad_mask)] = self.x_pad_token
+ embedded_x_list.append(x_embedded)
+ # Embed cap_feats
+ cap_embedded = self.cap_embedder(torch.stack(cap_out))
+ cap_embedded[torch.stack(cap_inner_pad_mask)] = self.cap_pad_token
+ cap_embedded_list.append(cap_embedded)
+ x = cap_feats = None
+
+ # Match t_embedder output dtype
+ adaln_input = t.type_as(embedded_x_list[0])[:1] # Same timestep for all samples
+
+ # Prepare attention masks and freqs
+ x_attn_mask = torch.ones((1, x_seqlen), dtype=torch.bool, device=device)
+ x_freqs_i = x_freqs_cis.unsqueeze(0)
+
+ # Control processing - compute hints with batch dimension [num_samples, seq, dim]
+ refiner_hints_tuple_list = [] # List of tensors with batch dim, one per layer
+ ctrl_ctx_tensor_list = [] # control context for v2.0 layers
+ ctrl_seqlens_list = []
+ refiner_hints_kwargs_list= []
+ any_control = control_context_list is not None and self.enable_control
+ control_V2 = any_control and self.add_control_noise_refiner
+ if control_V2:
+ # Control v2.0 refiner - process all samples together (no duplication)
+ # Stack all embedded_x into batch: [num_samples, seq, dim]
+ kwargs = dict(
+ attn_mask=x_attn_mask,
+ freqs_cis=x_freqs_i,
+ adaln_input=adaln_input,
+ )
+ for i,(x_batch,cap_embedded_ref, control_ctx_input) in enumerate(zip(embedded_x_list, cap_embedded_list, control_context_list)):
+
+ # Pass all samples at once - hints will have shape [num_samples, seq, dim] each #ctrl_ctx_tensor,
+ refiner_hints_kwargs, refiner_hints_tuple, ctrl_seqlens = self.prepare_forward_control_2_0_refiner(
+ x_batch,
+ [cap_embedded_ref] ,
+ [control_ctx_input.squeeze(0)] ,
+ kwargs = kwargs,
+ t=adaln_input, patch_size=patch_size, f_patch_size=f_patch_size
+ )
+ refiner_hints_kwargs_list.append(refiner_hints_kwargs)
+ refiner_hints_tuple_list.append([refiner_hints_tuple])
+ # ctrl_ctx_tensor_list.append(ctrl_ctx_tensor)
+ ctrl_seqlens_list.append(ctrl_seqlens[0])
+ x_batch = cap_embedded_ref = control_ctx_input = None
+
+ # Noise refiner
+ for layer in self.noise_refiner:
+ for i, x_i in enumerate(embedded_x_list):
+ kwargs = dict(attn_mask=x_attn_mask, freqs_cis=x_freqs_i, adaln_input=adaln_input)
+ if control_V2: # v2 control
+ # kwargs["hints"] = refiner_hints_tuple_list[i]
+ kwargs["hints"] = refiner_hints_tuple_list[i]
+ kwargs["hints_kwargs"] = refiner_hints_kwargs_list[i]
+ kwargs["context_scale"] = control_context_scale
+ embedded_x_list[i] = layer(x_i, **kwargs)
+ x_i = None
+
+ if control_V2:
+ # finish processing v2 control hints
+ for hints, hints_kwargs in zip(refiner_hints_tuple_list, refiner_hints_kwargs_list):
+ for layer in self.control_layers[len(self.control_refiner_layers_places):]:
+ layer(hints, **hints_kwargs)
+ ctrl_ctx_tensor_list.append(hints[0])
+ hints = hints_kwargs = None
+
+ # Context refiner
+ cap_attn_mask = torch.ones((1, cap_seqlen), dtype=torch.bool, device=device)
+ cap_freqs_i = cap_freqs_cis.unsqueeze(0)
+ for layer in self.context_refiner:
+ for i, cap_i in enumerate(cap_embedded_list):
+ cap_embedded_list[i] = layer( cap_i, attn_mask=cap_attn_mask, freqs_cis=cap_freqs_i)
+ cap_i = None
+
+ # Create unified (x + cap) for each sample
+ unified_list = []
+ for i,(embedded_x, cap_embedded) in enumerate(zip(embedded_x_list, cap_embedded_list)):
+ unified_list.append(torch.cat([embedded_x, cap_embedded], dim=1))
+ embedded_x_list[i] = None
+ unified_freqs_i = torch.cat([x_freqs_i, cap_freqs_i], dim=1)
+ unified_seqlen = x_seqlen + cap_seqlen
+ unified_attn_mask = torch.ones((1, unified_seqlen), dtype=torch.bool, device=device)
+ hints_list = []
+ hints_kwargs_list = []
+
+ # Compute control hints for main layers
+ if any_control:
+ cap_embedded_ref = cap_embedded_list[0]
+ control_kwargs = dict(
+ attn_mask=unified_attn_mask,
+ freqs_cis=unified_freqs_i,
+ adaln_input=adaln_input.expand(num_noise_samples, -1),
+ )
+ if control_V2:
+ # Control v2.0
+ for unified_batch, ctrl_ctx_tensor, ctrl_seqlens in zip(unified_list, ctrl_ctx_tensor_list, ctrl_seqlens_list):
+ hints_kwargs, hints_tuple = self.prepare_forward_control_2_0_layers( unified_batch, cap_embedded_ref , ctrl_ctx_tensor, ctrl_seqlens, control_kwargs )
+ hints_kwargs_list.append(hints_kwargs)
+ hints_list.append([hints_tuple])
+ unified_batch = ctrl_ctx_tensor = ctrl_seqlens = None
+ else:
+ # Control v1.0
+ for unified_batch, ctrl_ctx_tensor in zip(unified_list, control_context_list):
+ hints_kwargs, hints_tuple = self.prepare_forward_control_1_0( unified_batch, cap_embedded_ref, ctrl_ctx_tensor, control_kwargs, t=adaln_input, patch_size=patch_size, f_patch_size=f_patch_size)
+ hints_kwargs_list.append(hints_kwargs)
+ hints_list.append([hints_tuple])
+ unified_batch = ctrl_ctx_tensor = None
+
+ if len(hints_list) == 0:
+ hints_list = [None] * len(x_list)
+ hints_kwargs_list = [None] * len(x_list)
+
+ # Main layers
+ 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
+
+ for i, (unified_i, hints, hints_kwargs) in enumerate(zip(unified_list, hints_list, hints_kwargs_list)):
+ kwargs = {}
+ if hints is not None:
+ kwargs.update(dict(hints= hints, hints_kwargs = hints_kwargs, context_scale = control_context_scale))
+ unified_list[i] = layer(unified_i, attn_mask=unified_attn_mask, freqs_cis=unified_freqs_i, adaln_input=adaln_input, **kwargs)
+ unified_i = hints = kwargs = hints_kwargs = None
+
+ # Final layer and unpatchify
+ output_list = []
+ final_layer = self.all_final_layer[f"{patch_size}-{f_patch_size}"]
+ for i in range(num_noise_samples):
+ final_out = final_layer(unified_list[i], adaln_input)
+ final_out = final_out[:, :x_seqlen]
+ unpatchified = self.unpatchify(final_out, x_size, patch_size, f_patch_size)
+ output_list.append(unpatchified)
+ final_out = None
+
+ return output_list
diff --git a/wgp.py b/wgp.py
index 19e043a..e0363b0 100644
--- a/wgp.py
+++ b/wgp.py
@@ -1974,6 +1974,13 @@ def _parse_args():
default="",
help="Override output directory for CLI processing (use with --process)"
)
+ parser.add_argument(
+ "--z-image-engine",
+ type=str,
+ choices=["original", "wangp"],
+ default="original",
+ help="Z-Image transformer engine: 'original' (VideoX-Fun) or 'wangp' (modified)"
+ )
args = parser.parse_args()