Skip to content
Python

added z-image

DeepBeepMeepfb9d2b0b5183
diff --git a/README.md b/README.md
index 897cdec..948288e 100644
--- a/README.md
+++ b/README.md
@@ -37,17 +37,22 @@ WanGP supports the Wan (and derived models), Hunyuan Video and LTV Video models
## 🔥 Latest Updates :
-### November 27 2025: WanGP v9.71, Flux Strikes Back
+### November 28 2025: WanGP v9.71, The Alpha & the Omega
-**Flux 2**, the best ever open source *Image Generator* has just landed. It does everything very well: generate an *Image* based a *Text Prompt* or combine up to 10 *Images References*
+- **Flux 2**: the best ever open source *Image Generator* has just landed. It does everything very well: generate an *Image* based a *Text Prompt* or combine up to 10 *Images References*
The only snag is that it is a 60B parameters for the *Transformer* part and 40B parameters for the *Text Encoder* part.
-Behold the *WanGP Miracle* ! Flux 2 wil work with only 10 GB of VRAM (maybe less!) if you are happy with 8 bits quantization (no need for 4bits). With 12GB of VRAM you can run the model at full power. You will need at least 64 GB of RAM. If not maybe *Memory Profile 5* will be your friend.
+Behold the WanGP Miracle ! Flux 2 wil work with only 8 GB of VRAM if you are happy with 8 bits quantization (no need for lower quality 4bits). With 9GB of VRAM you can run the model at full power. You will need at least 64 GB of RAM. If not maybe Memory Profile 5 will be your friend.
-I have added a new Memory Profile *Profile 4+* that is sligthly slower than *Profile 4* but can save you up to 1GB of VRAM.
+- **Z-Image**: a small model, very fast (8 steps), very low VRAM (optimized even more in WanGP for fun, just in case you want to generate 16 images at a time) that produces outstanding Image quality. Not yet the Flux 2 level, and no Image editing yet but a very good trade-off.
+
+I have added a new Memory Profile *Profile 4+* that is sligthly slower than *Profile 4* but can save you up to 1GB of VRAM with Flux 2.
+
+Also as we have now quite few models and Loras folders. *I have moved all the loras folder in the 'loras' folder*. There are also now unique subfolders for *Wan 5B* and *Wan 1.3B* models. A conversion script should have moved the loras in the right locations, but I advise that you check just in case.
*update 9.71* : added missing source file, have fun !
+*update 9.72* : added Z-Image & Loras reorg
### November 24 2025: WanGP v9.62, The Return of the King
diff --git a/docs/LORAS.md b/docs/LORAS.md
index e031e26..96bac0c 100644
--- a/docs/LORAS.md
+++ b/docs/LORAS.md
@@ -6,34 +6,34 @@ Loras (Low-Rank Adaptations) allow you to customize video generation models by a
Loras are organized in different folders based on the model they're designed for:
-### Wan Text-to-Video Models
-- `loras/` - General t2v loras for Wan 2.1 (t2v only) and for all Wan 2.2 models
-Optional sub folders:
-- `loras/1.3B/` - Loras specifically for 1.3B models
-- `loras/5B/` - Loras specifically for 1.3B models
-- `loras/14B/` - Loras specifically for 14B models
+All loras now live under the single `loras/` root:
-### Wan Image-to-Video Models
-- `loras_i2v/` - Image-to-video loras for Wan 2.1
+### Wan Models
+- `loras/wan/` - Wan t2v (14B / general) loras
+- `loras/wan_5B/` - Wan 5B loras
+- `loras/wan_1.3B/` - Wan 1.3B loras
+- `loras/wan_i2v/` - Wan i2v loras
### Other Models
-- `loras_hunyuan/` - Hunyuan Video t2v loras
-- `loras_hunyuan/1.5/` - Loras specifically for Hunyuan 1.5 models
-- `loras_hunyuan_i2v/` - Hunyuan Video i2v loras
-- `loras_ltxv/` - LTX Video loras
-- `loras_flux/` - Flux loras
-- `loras_qwen/` - Qwen loras
+- `loras/hunyuan/` - Hunyuan Video t2v loras
+- `loras/hunyuan/1.5/` - Loras specifically for Hunyuan 1.5 models
+- `loras/hunyuan_i2v/` - Hunyuan Video i2v loras
+- `loras/ltxv/` - LTX Video loras
+- `loras/flux/` and `loras/flux2/` - Flux loras
+- `loras/qwen/` - Qwen loras
+- `loras/z_image/` - Z-Image loras
+- `loras/tts/` - Chatterbox / TTS presets
## Custom Lora Directory
You can specify custom lora directories when launching the app:
```bash
-# Use shared lora directory for both t2v and i2v
-python wgp.py --lora-dir /path/to/shared/loras --lora-dir-i2v /path/to/shared/loras
+# Use shared lora directory for Wan t2v and i2v
+python wgp.py --lora-dir /path/to/loras/wan --lora-dir-i2v /path/to/loras/wan_i2v
# Specify different directories for different models
-python wgp.py --lora-dir-hunyuan /path/to/hunyuan/loras --lora-dir-ltxv /path/to/ltx/loras
+python wgp.py --lora-dir-hunyuan /path/to/loras/hunyuan --lora-dir-ltxv /path/to/loras/ltxv
```
## Using Loras
@@ -376,13 +376,19 @@ In the video, a man is presented. The man is in a city and looks at his watch.
```bash
# Lora-related command line options
---lora-dir path # Path to t2v loras directory
---lora-dir-i2v path # Path to i2v loras directory
---lora-dir-hunyuan path # Path to Hunyuan t2v loras
---lora-dir-hunyuan-i2v path # Path to Hunyuan i2v loras
---lora-dir-ltxv path # Path to LTX Video loras
---lora-dir-flux path # Path to Flux loras
---lora-dir-qwen path # Path to Qwen loras
+--lora-dir path # Path to Wan t2v loras (default loras/wan)
+--lora-dir-wan-5b path # Path to Wan 5B loras (default loras/wan_5B)
+--lora-dir-wan-1-3b path # Path to Wan 1.3B loras (default loras/wan_1.3B)
+--lora-dir-i2v path # Path to Wan i2v loras (default loras/wan_i2v)
+--lora-dir-wan-i2v path # Alias for Wan i2v loras
+--lora-dir-hunyuan path # Path to Hunyuan t2v loras (default loras/hunyuan)
+--lora-dir-hunyuan-i2v path # Path to Hunyuan i2v loras (default loras/hunyuan_i2v)
+--lora-dir-ltxv path # Path to LTX Video loras (default loras/ltxv)
+--lora-dir-flux path # Path to Flux loras (default loras/flux)
+--lora-dir-flux2 path # Path to Flux2 loras (default loras/flux2)
+--lora-dir-qwen path # Path to Qwen loras (default loras/qwen)
+--lora-dir-z-image path # Path to Z-Image loras (default loras/z_image)
+--lora-dir-tts path # Path to TTS presets (default loras/tts)
--lora-preset preset # Load preset on startup
--check-loras # Filter incompatible loras
-```
\ No newline at end of file
+```
diff --git a/loras/README.txt b/loras/README.txt
deleted file mode 100644
index dc6f661..0000000
--- a/loras/README.txt
+++ /dev/null
@@ -1 +0,0 @@
-Put here Loras
\ No newline at end of file
diff --git a/loras_flux/readme.txt b/loras_flux/readme.txt
deleted file mode 100644
index 2424800..0000000
--- a/loras_flux/readme.txt
+++ /dev/null
@@ -1 +0,0 @@
-flux loras go here
\ No newline at end of file
diff --git a/loras_flux2/readme.txt b/loras_flux2/readme.txt
deleted file mode 100644
index fad90af..0000000
--- a/loras_flux2/readme.txt
+++ /dev/null
@@ -1 +0,0 @@
-add here loras for flux2
\ No newline at end of file
diff --git a/loras_hunyuan/Readme.txt b/loras_hunyuan/Readme.txt
deleted file mode 100644
index 5eb63a3..0000000
--- a/loras_hunyuan/Readme.txt
+++ /dev/null
@@ -1 +0,0 @@
-loras for hunyuan t2v
\ No newline at end of file
diff --git a/loras_hunyuan_i2v/Readme.txt b/loras_hunyuan_i2v/Readme.txt
deleted file mode 100644
index 8845c85..0000000
--- a/loras_hunyuan_i2v/Readme.txt
+++ /dev/null
@@ -1 +0,0 @@
-loras for hunyuan i2v
\ No newline at end of file
diff --git a/loras_i2v/README.txt b/loras_i2v/README.txt
deleted file mode 100644
index dc6f661..0000000
--- a/loras_i2v/README.txt
+++ /dev/null
@@ -1 +0,0 @@
-Put here Loras
\ No newline at end of file
diff --git a/loras_ltxv/Readme.txt b/loras_ltxv/Readme.txt
deleted file mode 100644
index 14a70a8..0000000
--- a/loras_ltxv/Readme.txt
+++ /dev/null
@@ -1 +0,0 @@
-LTX Video loras
\ No newline at end of file
diff --git a/loras_qwen/Readme.txt b/loras_qwen/Readme.txt
deleted file mode 100644
index 14a70a8..0000000
--- a/loras_qwen/Readme.txt
+++ /dev/null
@@ -1 +0,0 @@
-LTX Video loras
\ No newline at end of file
diff --git a/models/chatterbox/chatterbox_handler.py b/models/chatterbox/chatterbox_handler.py
index 30576c9..fe754cc 100644
--- a/models/chatterbox/chatterbox_handler.py
+++ b/models/chatterbox/chatterbox_handler.py
@@ -1,3 +1,4 @@
+import os
from shared.utils import files_locator as fl
import gradio as gr
try:
@@ -52,6 +53,19 @@ class family_handler:
# The numeric weight controls ordering in the family dropdown.
return {"tts": (70, "TTS")}
+ @staticmethod
+ def register_lora_cli_args(parser):
+ parser.add_argument(
+ "--lora-dir-tts",
+ type=str,
+ default=os.path.join("loras", "tts"),
+ help="Path to a directory that contains TTS settings"
+ )
+
+ @staticmethod
+ def get_lora_dir(base_model_type, args):
+ return args.lora_dir_tts
+
@staticmethod
def query_model_def(base_model_type, model_def):
extra_model_def = {
diff --git a/models/flux/flux_handler.py b/models/flux/flux_handler.py
index a3c29c3..457f835 100644
--- a/models/flux/flux_handler.py
+++ b/models/flux/flux_handler.py
@@ -1,3 +1,4 @@
+import os
import torch
from PIL import Image
from shared.utils import files_locator as fl
@@ -158,6 +159,27 @@ class family_handler():
def query_family_infos():
return {"flux":(30, "Flux 1"), "flux2":(31, "Flux 2")}
+ @staticmethod
+ def register_lora_cli_args(parser):
+ parser.add_argument(
+ "--lora-dir-flux",
+ type=str,
+ default=os.path.join("loras", "flux"),
+ help="Path to a directory that contains flux images Loras"
+ )
+ parser.add_argument(
+ "--lora-dir-flux2",
+ type=str,
+ default=os.path.join("loras", "flux2"),
+ help="Path to a directory that contains flux2 images Loras"
+ )
+
+ @staticmethod
+ def get_lora_dir(base_model_type, args):
+ if test_flux2(base_model_type):
+ return args.lora_dir_flux2
+ return args.lora_dir_flux
+
@staticmethod
def query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization):
text_encoder_filename = get_flux_text_encoder_filename(text_encoder_quantization, base_model_type)
diff --git a/models/flux/flux_main.py b/models/flux/flux_main.py
index f2d510e..265b470 100644
--- a/models/flux/flux_main.py
+++ b/models/flux/flux_main.py
@@ -264,6 +264,7 @@ class model_factory:
if input_ref_images is not None and len(input_ref_images):
cond_latents, cond_ids = encode_image_refs(self.vae, input_ref_images)
+ cond_latents, cond_ids = cond_latents.expand(batch_size, -1, -1), cond_ids.expand(batch_size, -1, -1)
inp.update({"img_cond_seq": cond_latents, "img_cond_seq_ids": cond_ids})
noise_patch_size = 2
diff --git a/models/hyvideo/hunyuan_handler.py b/models/hyvideo/hunyuan_handler.py
index 16ae38d..3eb4af8 100644
--- a/models/hyvideo/hunyuan_handler.py
+++ b/models/hyvideo/hunyuan_handler.py
@@ -1,3 +1,4 @@
+import os
import torch
from shared.utils import files_locator as fl
@@ -150,6 +151,34 @@ class family_handler():
def query_family_infos():
return {"hunyuan":(20, "Hunyuan Video"), "hunyuan_1_5":(21, "Hunyuan Video 1.5")}
+ @staticmethod
+ def register_lora_cli_args(parser):
+ parser.add_argument(
+ "--lora-dir-hunyuan",
+ type=str,
+ default=os.path.join("loras", "hunyuan"),
+ help="Path to a directory that contains Hunyuan Video t2v Loras"
+ )
+ parser.add_argument(
+ "--lora-dir-hunyuan-i2v",
+ type=str,
+ default=os.path.join("loras", "hunyuan_i2v"),
+ help="Path to a directory that contains Hunyuan Video i2v Loras"
+ )
+
+ @staticmethod
+ def get_lora_dir(base_model_type, args):
+ i2v = "i2v" in base_model_type
+ if i2v:
+ return args.lora_dir_hunyuan_i2v
+
+ root_lora_dir = args.lora_dir_hunyuan
+ if "1_5" in base_model_type:
+ lora_dir_1_5 = os.path.join(root_lora_dir, "1.5")
+ if os.path.isdir(lora_dir_1_5):
+ return lora_dir_1_5
+ return root_lora_dir
+
@staticmethod
def get_rgb_factors(base_model_type ):
from shared.RGB_factors import get_rgb_factors
diff --git a/models/ltx_video/ltxv_handler.py b/models/ltx_video/ltxv_handler.py
index 9cd3f7c..7b7f8e4 100644
--- a/models/ltx_video/ltxv_handler.py
+++ b/models/ltx_video/ltxv_handler.py
@@ -1,3 +1,4 @@
+import os
import torch
from shared.utils import files_locator as fl
@@ -62,6 +63,19 @@ class family_handler():
def query_family_infos():
return {"ltxv":(10, "LTX Video")}
+ @staticmethod
+ def register_lora_cli_args(parser):
+ parser.add_argument(
+ "--lora-dir-ltxv",
+ type=str,
+ default=os.path.join("loras", "ltxv"),
+ help="Path to a directory that contains LTX Videos Loras"
+ )
+
+ @staticmethod
+ def get_lora_dir(base_model_type, args):
+ return args.lora_dir_ltxv
+
@staticmethod
def get_vae_block_size(base_model_type):
return 32
@@ -100,4 +114,4 @@ class family_handler():
@staticmethod
def update_default_settings(base_model_type, model_def, ui_defaults):
pass
-
\ No newline at end of file
+
diff --git a/models/qwen/qwen_handler.py b/models/qwen/qwen_handler.py
index 632181b..049a329 100644
--- a/models/qwen/qwen_handler.py
+++ b/models/qwen/qwen_handler.py
@@ -1,3 +1,4 @@
+import os
import torch
import gradio as gr
from shared.utils import files_locator as fl
@@ -73,6 +74,19 @@ class family_handler():
def query_family_infos():
return {"qwen":(40, "Qwen")}
+ @staticmethod
+ def register_lora_cli_args(parser):
+ parser.add_argument(
+ "--lora-dir-qwen",
+ type=str,
+ default=os.path.join("loras", "qwen"),
+ help="Path to a directory that contains qwen images Loras"
+ )
+
+ @staticmethod
+ def get_lora_dir(base_model_type, args):
+ return args.lora_dir_qwen
+
@staticmethod
def query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization):
text_encoder_filename = get_qwen_text_encoder_filename(text_encoder_quantization)
diff --git a/models/wan/df_handler.py b/models/wan/df_handler.py
index 1d2bc3c..fe6d150 100644
--- a/models/wan/df_handler.py
+++ b/models/wan/df_handler.py
@@ -67,6 +67,18 @@ class family_handler():
def query_family_infos():
return {}
+ @staticmethod
+ def register_lora_cli_args(parser):
+ from .wan_handler import family_handler as wan_family_handler
+
+ return wan_family_handler.register_lora_cli_args(parser)
+
+ @staticmethod
+ def get_lora_dir(base_model_type, args):
+ from .wan_handler import family_handler as wan_family_handler
+
+ return wan_family_handler.get_lora_dir(base_model_type, args)
+
@staticmethod
def get_rgb_factors(base_model_type ):
from shared.RGB_factors import get_rgb_factors
@@ -113,4 +125,4 @@ class family_handler():
"RIFLEx_setting": 2,
"guidance_scale": 6,
"flow_shift": 8,
- })
\ No newline at end of file
+ })
diff --git a/models/wan/ovi_handler.py b/models/wan/ovi_handler.py
index 8f6240e..4e42543 100644
--- a/models/wan/ovi_handler.py
+++ b/models/wan/ovi_handler.py
@@ -24,6 +24,12 @@ class family_handler:
def query_family_infos():
return {}
+ @staticmethod
+ def register_lora_cli_args(parser):
+ from .wan_handler import family_handler as wan_family_handler
+
+ return wan_family_handler.register_lora_cli_args(parser)
+
@staticmethod
def get_wan_text_encoder_filename(text_encoder_quantization):
text_encoder_filename = "umt5-xxl/models_t5_umt5-xxl-enc-bf16.safetensors"
@@ -76,6 +82,12 @@ class family_handler:
return download_def
+ @staticmethod
+ def get_lora_dir(base_model_type, args):
+ from .wan_handler import family_handler as wan_family_handler
+
+ return wan_family_handler.get_lora_dir(base_model_type, args)
+
@staticmethod
def load_model(
model_filename,
diff --git a/models/wan/wan_handler.py b/models/wan/wan_handler.py
index 77c9e2e..d0d6772 100644
--- a/models/wan/wan_handler.py
+++ b/models/wan/wan_handler.py
@@ -1,3 +1,5 @@
+
+import os
import torch
import numpy as np
import gradio as gr
@@ -74,6 +76,55 @@ class family_handler():
def query_family_infos():
return {"wan":(0, "Wan2.1"), "wan2_2":(1, "Wan2.2") }
+ @staticmethod
+ def register_lora_cli_args(parser):
+ parser.add_argument(
+ "--lora-dir-i2v",
+ type=str,
+ default=os.path.join("loras", "wan_i2v"),
+ help="Path to a directory that contains Wan i2v Loras "
+ )
+ parser.add_argument(
+ "--lora-dir",
+ type=str,
+ default=os.path.join("loras", "wan"),
+ help="Path to a directory that contains Wan t2v Loras"
+ )
+ parser.add_argument(
+ "--lora-dir-wan-1-3b",
+ type=str,
+ default=os.path.join("loras", "wan_1.3B"),
+ help="Path to a directory that contains Wan 1.3B Loras"
+ )
+ parser.add_argument(
+ "--lora-dir-wan-5b",
+ type=str,
+ default=os.path.join("loras", "wan_5B"),
+ help="Path to a directory that contains Wan 5B Loras"
+ )
+ parser.add_argument(
+ "--lora-dir-wan-i2v",
+ type=str,
+ default=os.path.join("loras", "wan_i2v"),
+ help="Path to a directory that contains Wan i2v Loras"
+ )
+
+ @staticmethod
+ def get_lora_dir(base_model_type, args):
+ i2v = test_class_i2v(base_model_type) and base_model_type not in ["i2v_2_2", "i2v_2_2_multitalk"]
+ wan_dir = getattr(args, "lora_dir_wan", None) or getattr(args, "lora_dir", None) or os.path.join("loras", "wan")
+ wan_i2v_dir = getattr(args, "lora_dir_wan_i2v", None) or getattr(args, "lora_dir_i2v", None) or os.path.join("loras", "wan_i2v")
+ wan_1_3b_dir = getattr(args, "lora_dir_wan_1_3b", None) or os.path.join("loras", "wan_1.3B")
+ wan_5b_dir = getattr(args, "lora_dir_wan_5b", None) or os.path.join("loras", "wan_5B")
+
+ if i2v:
+ return wan_i2v_dir
+ if "1.3B" in base_model_type:
+ return wan_1_3b_dir
+ if base_model_type in ["ti2v_2_2", "ovi"]:
+ return wan_5b_dir
+ return wan_dir
+
@staticmethod
def set_cache_parameters(cache_type, base_model_type, model_def, inputs, skip_steps_cache):
i2v = test_class_i2v(base_model_type)
diff --git a/loras_tts/readme.txt b/models/z_image/__init__.py
similarity index 100%
rename from loras_tts/readme.txt
rename to models/z_image/__init__.py
diff --git a/models/z_image/autoencoder_kl.py b/models/z_image/autoencoder_kl.py
new file mode 100644
index 0000000..295e05a
--- /dev/null
+++ b/models/z_image/autoencoder_kl.py
@@ -0,0 +1,570 @@
+# Copyright 2025 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.
+from typing import Dict, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import PeftAdapterMixin
+from diffusers.loaders.single_file_model import FromOriginalModelMixin
+from diffusers.utils import deprecate
+from diffusers.utils.accelerate_utils import apply_forward_hook
+from diffusers.models.attention_processor import (
+ ADDED_KV_ATTENTION_PROCESSORS,
+ CROSS_ATTENTION_PROCESSORS,
+ Attention,
+ AttentionProcessor,
+ AttnAddedKVProcessor,
+ AttnProcessor,
+ FusedAttnProcessor2_0,
+)
+from diffusers.models.modeling_outputs import AutoencoderKLOutput
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.models.autoencoders.vae import (
+ Decoder,
+ DecoderOutput,
+ DiagonalGaussianDistribution,
+ Encoder,
+)
+
+
+class AutoencoderMixin:
+ def enable_tiling(self):
+ r"""
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
+ processing larger images.
+ """
+ if not hasattr(self, "use_tiling"):
+ raise NotImplementedError(f"Tiling doesn't seem to be implemented for {self.__class__.__name__}.")
+ self.use_tiling = True
+
+ def disable_tiling(self):
+ r"""
+ Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing
+ decoding in one step.
+ """
+ self.use_tiling = False
+
+ def enable_slicing(self):
+ r"""
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
+ """
+ if not hasattr(self, "use_slicing"):
+ raise NotImplementedError(f"Slicing doesn't seem to be implemented for {self.__class__.__name__}.")
+ self.use_slicing = True
+
+ def disable_slicing(self):
+ r"""
+ Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing
+ decoding in one step.
+ """
+ self.use_slicing = False
+
+
+class AutoencoderKL(ModelMixin, AutoencoderMixin, ConfigMixin, FromOriginalModelMixin, PeftAdapterMixin):
+ r"""
+ A VAE model with KL loss for encoding images into latents and decoding latent representations into images.
+
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
+ for all models (such as downloading or saving).
+
+ Parameters:
+ in_channels (int, *optional*, defaults to 3): Number of channels in the input image.
+ out_channels (int, *optional*, defaults to 3): Number of channels in the output.
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("DownEncoderBlock2D",)`):
+ Tuple of downsample block types.
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("UpDecoderBlock2D",)`):
+ Tuple of upsample block types.
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`):
+ Tuple of block output channels.
+ act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
+ latent_channels (`int`, *optional*, defaults to 4): Number of channels in the latent space.
+ sample_size (`int`, *optional*, defaults to `32`): Sample input size.
+ scaling_factor (`float`, *optional*, defaults to 0.18215):
+ The component-wise standard deviation of the trained latent space computed using the first batch of the
+ training set. This is used to scale the latent space to have unit variance when training the diffusion
+ model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
+ diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1
+ / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image
+ Synthesis with Latent Diffusion Models](https://huggingface.co/papers/2112.10752) paper.
+ force_upcast (`bool`, *optional*, default to `True`):
+ If enabled it will force the VAE to run in float32 for high image resolution pipelines, such as SD-XL. VAE
+ can be fine-tuned / trained to a lower range without losing too much precision in which case `force_upcast`
+ can be set to `False` - see: https://huggingface.co/madebyollin/sdxl-vae-fp16-fix
+ mid_block_add_attention (`bool`, *optional*, default to `True`):
+ If enabled, the mid_block of the Encoder and Decoder will have attention blocks. If set to false, the
+ mid_block will only have resnet blocks
+ """
+
+ _supports_gradient_checkpointing = True
+ _no_split_modules = ["BasicTransformerBlock", "ResnetBlock2D"]
+
+ @register_to_config
+ def __init__(
+ self,
+ in_channels: int = 3,
+ out_channels: int = 3,
+ down_block_types: Tuple[str, ...] = ("DownEncoderBlock2D",),
+ up_block_types: Tuple[str, ...] = ("UpDecoderBlock2D",),
+ block_out_channels: Tuple[int, ...] = (64,),
+ layers_per_block: int = 1,
+ act_fn: str = "silu",
+ latent_channels: int = 4,
+ norm_num_groups: int = 32,
+ sample_size: int = 32,
+ scaling_factor: float = 0.18215,
+ shift_factor: Optional[float] = None,
+ latents_mean: Optional[Tuple[float]] = None,
+ latents_std: Optional[Tuple[float]] = None,
+ force_upcast: bool = True,
+ use_quant_conv: bool = True,
+ use_post_quant_conv: bool = True,
+ mid_block_add_attention: bool = True,
+ ):
+ super().__init__()
+
+ # pass init params to Encoder
+ self.encoder = Encoder(
+ in_channels=in_channels,
+ out_channels=latent_channels,
+ down_block_types=down_block_types,
+ block_out_channels=block_out_channels,
+ layers_per_block=layers_per_block,
+ act_fn=act_fn,
+ norm_num_groups=norm_num_groups,
+ double_z=True,
+ mid_block_add_attention=mid_block_add_attention,
+ )
+
+ # pass init params to Decoder
+ self.decoder = Decoder(
+ in_channels=latent_channels,
+ out_channels=out_channels,
+ up_block_types=up_block_types,
+ block_out_channels=block_out_channels,
+ layers_per_block=layers_per_block,
+ norm_num_groups=norm_num_groups,
+ act_fn=act_fn,
+ mid_block_add_attention=mid_block_add_attention,
+ )
+
+ self.quant_conv = nn.Conv2d(2 * latent_channels, 2 * latent_channels, 1) if use_quant_conv else None
+ self.post_quant_conv = nn.Conv2d(latent_channels, latent_channels, 1) if use_post_quant_conv else None
+
+ self.use_slicing = False
+ self.use_tiling = False
+
+ # only relevant if vae tiling is enabled
+ self.tile_sample_min_size = self.config.sample_size
+ sample_size = (
+ self.config.sample_size[0]
+ if isinstance(self.config.sample_size, (list, tuple))
+ else self.config.sample_size
+ )
+ self.tile_latent_min_size = int(sample_size / (2 ** (len(self.config.block_out_channels) - 1)))
+ self.tile_overlap_factor = 0.25
+
+ @property
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
+ r"""
+ Returns:
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
+ indexed by its weight name.
+ """
+ # set recursively
+ processors = {}
+
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
+ if hasattr(module, "get_processor"):
+ processors[f"{name}.processor"] = module.get_processor()
+
+ for sub_name, child in module.named_children():
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
+
+ return processors
+
+ for name, module in self.named_children():
+ fn_recursive_add_processors(name, module, processors)
+
+ return processors
+
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
+ r"""
+ Sets the attention processor to use to compute attention.
+
+ Parameters:
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
+ for **all** `Attention` layers.
+
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
+ processor. This is strongly recommended when setting trainable attention processors.
+
+ """
+ count = len(self.attn_processors.keys())
+
+ if isinstance(processor, dict) and len(processor) != count:
+ raise ValueError(
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
+ )
+
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
+ if hasattr(module, "set_processor"):
+ if not isinstance(processor, dict):
+ module.set_processor(processor)
+ else:
+ module.set_processor(processor.pop(f"{name}.processor"))
+
+ for sub_name, child in module.named_children():
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
+
+ for name, module in self.named_children():
+ fn_recursive_attn_processor(name, module, processor)
+
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
+ def set_default_attn_processor(self):
+ """
+ Disables custom attention processors and sets the default attention implementation.
+ """
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
+ processor = AttnAddedKVProcessor()
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
+ processor = AttnProcessor()
+ else:
+ raise ValueError(
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
+ )
+
+ self.set_attn_processor(processor)
+
+ def _encode(self, x: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, height, width = x.shape
+
+ if self.use_tiling and (width > self.tile_sample_min_size or height > self.tile_sample_min_size):
+ return self._tiled_encode(x)
+
+ enc = self.encoder(x)
+ if self.quant_conv is not None:
+ enc = self.quant_conv(enc)
+
+ return enc
+
+ @apply_forward_hook
+ def encode(
+ self, x: torch.Tensor, return_dict: bool = True
+ ) -> Union[AutoencoderKLOutput, Tuple[DiagonalGaussianDistribution]]:
+ """
+ Encode a batch of images into latents.
+
+ Args:
+ x (`torch.Tensor`): Input batch of images.
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.
+
+ Returns:
+ The latent representations of the encoded images. If `return_dict` is True, a
+ [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain `tuple` is returned.
+ """
+ if self.use_slicing and x.shape[0] > 1:
+ encoded_slices = [self._encode(x_slice) for x_slice in x.split(1)]
+ h = torch.cat(encoded_slices)
+ else:
+ h = self._encode(x)
+
+ posterior = DiagonalGaussianDistribution(h)
+
+ if not return_dict:
+ return (posterior,)
+
+ return AutoencoderKLOutput(latent_dist=posterior)
+
+ def _decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, torch.Tensor]:
+ if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size):
+ return self.tiled_decode(z, return_dict=return_dict)
+
+ if self.post_quant_conv is not None:
+ z = self.post_quant_conv(z)
+
+ dec = self.decoder(z)
+
+ if not return_dict:
+ return (dec,)
+
+ return DecoderOutput(sample=dec)
+
+ @apply_forward_hook
+ def decode(
+ self, z: torch.FloatTensor, return_dict: bool = True, generator=None
+ ) -> Union[DecoderOutput, torch.FloatTensor]:
+ """
+ Decode a batch of images.
+
+ Args:
+ z (`torch.Tensor`): Input batch of latent vectors.
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.
+
+ Returns:
+ [`~models.vae.DecoderOutput`] or `tuple`:
+ If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is
+ returned.
+
+ """
+ if self.use_slicing and z.shape[0] > 1:
+ decoded_slices = [self._decode(z_slice).sample for z_slice in z.split(1)]
+ decoded = torch.cat(decoded_slices)
+ else:
+ decoded = self._decode(z).sample
+
+ if not return_dict:
+ return (decoded,)
+
+ return DecoderOutput(sample=decoded)
+
+ def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
+ blend_extent = min(a.shape[2], b.shape[2], blend_extent)
+ for y in range(blend_extent):
+ b[:, :, y, :] = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent)
+ return b
+
+ def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
+ blend_extent = min(a.shape[3], b.shape[3], blend_extent)
+ for x in range(blend_extent):
+ b[:, :, :, x] = a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent)
+ return b
+
+ def _tiled_encode(self, x: torch.Tensor) -> torch.Tensor:
+ r"""Encode a batch of images using a tiled encoder.
+
+ When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
+ steps. This is useful to keep memory use constant regardless of image size. The end result of tiled encoding is
+ different from non-tiled encoding because each tile uses a different encoder. To avoid tiling artifacts, the
+ tiles overlap and are blended together to form a smooth output. You may still see tile-sized changes in the
+ output, but they should be much less noticeable.
+
+ Args:
+ x (`torch.Tensor`): Input batch of images.
+
+ Returns:
+ `torch.Tensor`:
+ The latent representation of the encoded videos.
+ """
+
+ overlap_size = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor))
+ blend_extent = int(self.tile_latent_min_size * self.tile_overlap_factor)
+ row_limit = self.tile_latent_min_size - blend_extent
+
+ # Split the image into 512x512 tiles and encode them separately.
+ rows = []
+ for i in range(0, x.shape[2], overlap_size):
+ row = []
+ for j in range(0, x.shape[3], overlap_size):
+ tile = x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size]
+ tile = self.encoder(tile)
+ if self.config.use_quant_conv:
+ tile = self.quant_conv(tile)
+ row.append(tile)
+ rows.append(row)
+ result_rows = []
+ for i, row in enumerate(rows):
+ result_row = []
+ for j, tile in enumerate(row):
+ # blend the above tile and the left tile
+ # to the current tile and add the current tile to the result row
+ if i > 0:
+ tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
+ if j > 0:
+ tile = self.blend_h(row[j - 1], tile, blend_extent)
+ result_row.append(tile[:, :, :row_limit, :row_limit])
+ result_rows.append(torch.cat(result_row, dim=3))
+
+ enc = torch.cat(result_rows, dim=2)
+ return enc
+
+ def tiled_encode(self, x: torch.Tensor, return_dict: bool = True) -> AutoencoderKLOutput:
+ r"""Encode a batch of images using a tiled encoder.
+
+ When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
+ steps. This is useful to keep memory use constant regardless of image size. The end result of tiled encoding is
+ different from non-tiled encoding because each tile uses a different encoder. To avoid tiling artifacts, the
+ tiles overlap and are blended together to form a smooth output. You may still see tile-sized changes in the
+ output, but they should be much less noticeable.
+
+ Args:
+ x (`torch.Tensor`): Input batch of images.
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether or not to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.
+
+ Returns:
+ [`~models.autoencoder_kl.AutoencoderKLOutput`] or `tuple`:
+ If return_dict is True, a [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain
+ `tuple` is returned.
+ """
+ deprecation_message = (
+ "The tiled_encode implementation supporting the `return_dict` parameter is deprecated. In the future, the "
+ "implementation of this method will be replaced with that of `_tiled_encode` and you will no longer be able "
+ "to pass `return_dict`. You will also have to create a `DiagonalGaussianDistribution()` from the returned value."
+ )
+ deprecate("tiled_encode", "1.0.0", deprecation_message, standard_warn=False)
+
+ overlap_size = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor))
+ blend_extent = int(self.tile_latent_min_size * self.tile_overlap_factor)
+ row_limit = self.tile_latent_min_size - blend_extent
+
+ # Split the image into 512x512 tiles and encode them separately.
+ rows = []
+ for i in range(0, x.shape[2], overlap_size):
+ row = []
+ for j in range(0, x.shape[3], overlap_size):
+ tile = x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size]
+ tile = self.encoder(tile)
+ if self.config.use_quant_conv:
+ tile = self.quant_conv(tile)
+ row.append(tile)
+ rows.append(row)
+ result_rows = []
+ for i, row in enumerate(rows):
+ result_row = []
+ for j, tile in enumerate(row):
+ # blend the above tile and the left tile
+ # to the current tile and add the current tile to the result row
+ if i > 0:
+ tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
+ if j > 0:
+ tile = self.blend_h(row[j - 1], tile, blend_extent)
+ result_row.append(tile[:, :, :row_limit, :row_limit])
+ result_rows.append(torch.cat(result_row, dim=3))
+
+ moments = torch.cat(result_rows, dim=2)
+ posterior = DiagonalGaussianDistribution(moments)
+
+ if not return_dict:
+ return (posterior,)
+
+ return AutoencoderKLOutput(latent_dist=posterior)
+
+ def tiled_decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, torch.Tensor]:
+ r"""
+ Decode a batch of images using a tiled decoder.
+
+ Args:
+ z (`torch.Tensor`): Input batch of latent vectors.
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether or not to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.
+
+ Returns:
+ [`~models.vae.DecoderOutput`] or `tuple`:
+ If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is
+ returned.
+ """
+ overlap_size = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor))
+ blend_extent = int(self.tile_sample_min_size * self.tile_overlap_factor)
+ row_limit = self.tile_sample_min_size - blend_extent
+
+ # Split z into overlapping 64x64 tiles and decode them separately.
+ # The tiles have an overlap to avoid seams between tiles.
+ rows = []
+ for i in range(0, z.shape[2], overlap_size):
+ row = []
+ for j in range(0, z.shape[3], overlap_size):
+ tile = z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size]
+ if self.config.use_post_quant_conv:
+ tile = self.post_quant_conv(tile)
+ decoded = self.decoder(tile)
+ row.append(decoded)
+ rows.append(row)
+ result_rows = []
+ for i, row in enumerate(rows):
+ result_row = []
+ for j, tile in enumerate(row):
+ # blend the above tile and the left tile
+ # to the current tile and add the current tile to the result row
+ if i > 0:
+ tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
+ if j > 0:
+ tile = self.blend_h(row[j - 1], tile, blend_extent)
+ result_row.append(tile[:, :, :row_limit, :row_limit])
+ result_rows.append(torch.cat(result_row, dim=3))
+
+ dec = torch.cat(result_rows, dim=2)
+ if not return_dict:
+ return (dec,)
+
+ return DecoderOutput(sample=dec)
+
+ def forward(
+ self,
+ sample: torch.Tensor,
+ sample_posterior: bool = False,
+ return_dict: bool = True,
+ generator: Optional[torch.Generator] = None,
+ ) -> Union[DecoderOutput, torch.Tensor]:
+ r"""
+ Args:
+ sample (`torch.Tensor`): Input sample.
+ sample_posterior (`bool`, *optional*, defaults to `False`):
+ Whether to sample from the posterior.
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
+ """
+ x = sample
+ posterior = self.encode(x).latent_dist
+ if sample_posterior:
+ z = posterior.sample(generator=generator)
+ else:
+ z = posterior.mode()
+ dec = self.decode(z).sample
+
+ if not return_dict:
+ return (dec,)
+
+ return DecoderOutput(sample=dec)
+
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections
+ def fuse_qkv_projections(self):
+ """
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
+ are fused. For cross-attention modules, key and value projection matrices are fused.
+
+ > [!WARNING] > This API is 🧪 experimental.
+ """
+ self.original_attn_processors = None
+
+ for _, attn_processor in self.attn_processors.items():
+ if "Added" in str(attn_processor.__class__.__name__):
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
+
+ self.original_attn_processors = self.attn_processors
+
+ for module in self.modules():
+ if isinstance(module, Attention):
+ module.fuse_projections(fuse=True)
+
+ self.set_attn_processor(FusedAttnProcessor2_0())
+
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
+ def unfuse_qkv_projections(self):
+ """Disables the fused QKV projection if enabled.
+
+ > [!WARNING] > This API is 🧪 experimental.
+
+ """
+ if self.original_attn_processors is not None:
+ self.set_attn_processor(self.original_attn_processors)
diff --git a/models/z_image/config.json b/models/z_image/config.json
new file mode 100644
index 0000000..c579190
--- /dev/null
+++ b/models/z_image/config.json
@@ -0,0 +1,31 @@
+{
+ "_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
+}
diff --git a/models/z_image/pipeline_output.py b/models/z_image/pipeline_output.py
new file mode 100644
index 0000000..69a320f
--- /dev/null
+++ b/models/z_image/pipeline_output.py
@@ -0,0 +1,35 @@
+# 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.
+
+from dataclasses import dataclass
+from typing import List, Union
+
+import numpy as np
+import PIL.Image
+
+from diffusers.utils import BaseOutput
+
+
+@dataclass
+class ZImagePipelineOutput(BaseOutput):
+ """
+ Output class for Z-Image pipelines.
+
+ Args:
+ images (`List[PIL.Image.Image]` or `np.ndarray`)
+ List of denoised PIL images of length `batch_size` or numpy array of shape `(batch_size, height, width,
+ num_channels)`. PIL images or numpy array present the denoised images of the diffusion pipeline.
+ """
+
+ images: Union[List[PIL.Image.Image], np.ndarray]
diff --git a/models/z_image/pipeline_z_image.py b/models/z_image/pipeline_z_image.py
new file mode 100644
index 0000000..6924512
--- /dev/null
+++ b/models/z_image/pipeline_z_image.py
@@ -0,0 +1,626 @@
+# 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 inspect
+from typing import Any, Callable, Dict, List, Optional, Union
+
+import torch
+from transformers import AutoTokenizer, PreTrainedModel
+
+from diffusers.image_processor import VaeImageProcessor
+from diffusers.loaders import FromSingleFileMixin
+from diffusers.models.autoencoders import AutoencoderKL
+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 .pipeline_output import ZImagePipelineOutput
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+EXAMPLE_DOC_STRING = """
+ Examples:
+ ```py
+ >>> import torch
+ >>> from diffusers import ZImagePipeline
+
+ >>> pipe = ZImagePipeline.from_pretrained("Z-a-o/Z-Image-Turbo", torch_dtype=torch.bfloat16)
+ >>> pipe.to("cuda")
+
+ >>> # Optionally, set the attention backend to flash-attn 2 or 3, default is SDPA in PyTorch.
+ >>> # (1) Use flash attention 2
+ >>> # pipe.transformer.set_attention_backend("flash")
+ >>> # (2) Use flash attention 3
+ >>> # pipe.transformer.set_attention_backend("_flash_3")
+
+ >>> prompt = "一幅为名为“造相「Z-IMAGE-TURBO」”的项目设计的创意海报。画面巧妙地将文字概念视觉化:一辆复古蒸汽小火车化身为巨大的拉链头,正拉开厚厚的冬日积雪,展露出一个生机盎然的春天。"
+ >>> image = pipe(
+ ... prompt,
+ ... height=1024,
+ ... width=1024,
+ ... num_inference_steps=9,
+ ... guidance_scale=0.0,
+ ... generator=torch.Generator("cuda").manual_seed(42),
+ ... ).images[0]
+ >>> image.save("zimage.png")
+ ```
+"""
+
+
+# Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
+def calculate_shift(
+ image_seq_len,
+ base_seq_len: int = 256,
+ max_seq_len: int = 4096,
+ base_shift: float = 0.5,
+ max_shift: float = 1.15,
+):
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
+ b = base_shift - m * base_seq_len
+ mu = image_seq_len * m + b
+ return mu
+
+
+# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
+def retrieve_timesteps(
+ scheduler,
+ num_inference_steps: Optional[int] = None,
+ device: Optional[Union[str, torch.device]] = None,
+ timesteps: Optional[List[int]] = None,
+ sigmas: Optional[List[float]] = None,
+ **kwargs,
+):
+ r"""
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
+
+ Args:
+ scheduler (`SchedulerMixin`):
+ The scheduler to get timesteps from.
+ num_inference_steps (`int`):
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
+ must be `None`.
+ device (`str` or `torch.device`, *optional*):
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
+ timesteps (`List[int]`, *optional*):
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
+ `num_inference_steps` and `sigmas` must be `None`.
+ sigmas (`List[float]`, *optional*):
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
+ `num_inference_steps` and `timesteps` must be `None`.
+
+ Returns:
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
+ second element is the number of inference steps.
+ """
+ if timesteps is not None and sigmas is not None:
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
+ if timesteps is not None:
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
+ if not accepts_timesteps:
+ raise ValueError(
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
+ f" timestep schedules. Please check whether you are using the correct scheduler."
+ )
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
+ timesteps = scheduler.timesteps
+ num_inference_steps = len(timesteps)
+ elif sigmas is not None:
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
+ if not accept_sigmas:
+ raise ValueError(
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
+ )
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
+ timesteps = scheduler.timesteps
+ num_inference_steps = len(timesteps)
+ else:
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
+ timesteps = scheduler.timesteps
+ return timesteps, num_inference_steps
+
+
+class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
+ _optional_components = []
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
+
+ def __init__(
+ self,
+ scheduler: FlowMatchEulerDiscreteScheduler,
+ vae: AutoencoderKL,
+ text_encoder: PreTrainedModel,
+ tokenizer: AutoTokenizer,
+ transformer: ZImageTransformer2DModel,
+ ):
+ super().__init__()
+
+ self.register_modules(
+ vae=vae,
+ text_encoder=text_encoder,
+ tokenizer=tokenizer,
+ scheduler=scheduler,
+ transformer=transformer,
+ )
+ self.vae_scale_factor = (
+ 2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
+ )
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)
+
+ def encode_prompt(
+ self,
+ prompt: Union[str, List[str]],
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+ num_images_per_prompt: int = 1,
+ do_classifier_free_guidance: bool = True,
+ negative_prompt: Optional[Union[str, List[str]]] = None,
+ prompt_embeds: Optional[List[torch.FloatTensor]] = None,
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
+ max_sequence_length: int = 512,
+ lora_scale: Optional[float] = None,
+ ):
+ prompt = [prompt] if isinstance(prompt, str) else prompt
+ prompt_embeds = self._encode_prompt(
+ prompt=prompt,
+ device=device,
+ dtype=dtype,
+ num_images_per_prompt=num_images_per_prompt,
+ prompt_embeds=prompt_embeds,
+ max_sequence_length=max_sequence_length,
+ )
+
+ if do_classifier_free_guidance:
+ if negative_prompt is None:
+ negative_prompt = ["" for _ in prompt]
+ else:
+ negative_prompt = [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
+ assert len(prompt) == len(negative_prompt)
+ negative_prompt_embeds = self._encode_prompt(
+ prompt=negative_prompt,
+ device=device,
+ dtype=dtype,
+ num_images_per_prompt=num_images_per_prompt,
+ prompt_embeds=negative_prompt_embeds,
+ max_sequence_length=max_sequence_length,
+ )
+ else:
+ negative_prompt_embeds = []
+ return prompt_embeds, negative_prompt_embeds
+
+ def _encode_prompt(
+ self,
+ prompt: Union[str, List[str]],
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+ num_images_per_prompt: int = 1,
+ prompt_embeds: Optional[List[torch.FloatTensor]] = None,
+ max_sequence_length: int = 512,
+ ) -> List[torch.FloatTensor]:
+ assert num_images_per_prompt == 1
+ device = device or self._execution_device
+
+ if prompt_embeds is not None:
+ return prompt_embeds
+
+ if isinstance(prompt, str):
+ prompt = [prompt]
+
+ for i, prompt_item in enumerate(prompt):
+ messages = [
+ {"role": "user", "content": prompt_item},
+ ]
+ prompt_item = self.tokenizer.apply_chat_template(
+ messages,
+ tokenize=False,
+ add_generation_prompt=True,
+ enable_thinking=True,
+ )
+ prompt[i] = prompt_item
+
+ text_inputs = self.tokenizer(
+ prompt,
+ padding="max_length",
+ max_length=max_sequence_length,
+ truncation=True,
+ return_tensors="pt",
+ )
+
+ text_input_ids = text_inputs.input_ids.to(device)
+ prompt_masks = text_inputs.attention_mask.to(device).bool()
+
+ prompt_embeds = self.text_encoder(
+ input_ids=text_input_ids,
+ attention_mask=prompt_masks,
+ output_hidden_states=True,
+ ).hidden_states[-2]
+
+ embeddings_list = []
+
+ for i in range(len(prompt_embeds)):
+ embeddings_list.append(prompt_embeds[i][prompt_masks[i]])
+
+ return embeddings_list
+
+ def prepare_latents(
+ self,
+ batch_size,
+ num_channels_latents,
+ height,
+ width,
+ dtype,
+ device,
+ generator,
+ latents=None,
+ ):
+ height = 2 * (int(height) // (self.vae_scale_factor * 2))
+ width = 2 * (int(width) // (self.vae_scale_factor * 2))
+
+ shape = (batch_size, num_channels_latents, height, width)
+
+ if latents is None:
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
+ else:
+ if latents.shape != shape:
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
+ latents = latents.to(device)
+ return latents
+
+ @property
+ def guidance_scale(self):
+ return self._guidance_scale
+
+ @property
+ def do_classifier_free_guidance(self):
+ return self._guidance_scale > 1
+
+ @property
+ def joint_attention_kwargs(self):
+ return self._joint_attention_kwargs
+
+ @property
+ def num_timesteps(self):
+ return self._num_timesteps
+
+ @property
+ def interrupt(self):
+ return self._interrupt
+
+ @torch.no_grad()
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
+ def __call__(
+ self,
+ prompt: Union[str, List[str]] = None,
+ height: Optional[int] = None,
+ width: Optional[int] = None,
+ num_inference_steps: int = 50,
+ sigmas: Optional[List[float]] = None,
+ guidance_scale: float = 5.0,
+ cfg_normalization: bool = False,
+ cfg_truncation: float = 1.0,
+ negative_prompt: Optional[Union[str, List[str]]] = None,
+ num_images_per_prompt: Optional[int] = 1,
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
+ latents: Optional[torch.FloatTensor] = None,
+ prompt_embeds: Optional[List[torch.FloatTensor]] = None,
+ negative_prompt_embeds: Optional[List[torch.FloatTensor]] = None,
+ output_type: Optional[str] = "pil",
+ return_dict: bool = True,
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
+ max_sequence_length: int = 512,
+ callback=None,
+ pipeline=None,
+ ):
+ r"""
+ Function invoked when calling the pipeline for generation.
+
+ Args:
+ prompt (`str` or `List[str]`, *optional*):
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
+ instead.
+ height (`int`, *optional*, defaults to 1024):
+ The height in pixels of the generated image.
+ width (`int`, *optional*, defaults to 1024):
+ The width in pixels of the generated image.
+ num_inference_steps (`int`, *optional*, defaults to 50):
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
+ expense of slower inference.
+ sigmas (`List[float]`, *optional*):
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
+ will be used.
+ guidance_scale (`float`, *optional*, defaults to 5.0):
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
+ usually at the expense of lower image quality.
+ cfg_normalization (`bool`, *optional*, defaults to False):
+ Whether to apply configuration normalization.
+ cfg_truncation (`float`, *optional*, defaults to 1.0):
+ The truncation value for configuration.
+ negative_prompt (`str` or `List[str]`, *optional*):
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
+ less than `1`).
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
+ The number of images to generate per prompt.
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
+ to make generation deterministic.
+ latents (`torch.FloatTensor`, *optional*):
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
+ tensor will be generated by sampling using the supplied random `generator`.
+ prompt_embeds (`List[torch.FloatTensor]`, *optional*):
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
+ provided, text embeddings will be generated from `prompt` input argument.
+ negative_prompt_embeds (`List[torch.FloatTensor]`, *optional*):
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
+ argument.
+ output_type (`str`, *optional*, defaults to `"pil"`):
+ The output format of the generate image. Choose between
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether or not to return a [`~pipelines.stable_diffusion.ZImagePipelineOutput`] instead of a plain
+ tuple.
+ joint_attention_kwargs (`dict`, *optional*):
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
+ `self.processor` in
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
+ callback_on_step_end (`Callable`, *optional*):
+ A function that calls at the end of each denoising steps during the inference. The function is called
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
+ `callback_on_step_end_tensor_inputs`.
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
+ `._callback_tensor_inputs` attribute of your pipeline class.
+ max_sequence_length (`int`, *optional*, defaults to 512):
+ Maximum sequence length to use with the `prompt`.
+
+ Examples:
+
+ Returns:
+ [`~pipelines.z_image.ZImagePipelineOutput`] or `tuple`: [`~pipelines.z_image.ZImagePipelineOutput`] if
+ `return_dict` is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the
+ generated images.
+ """
+ height = height or 1024
+ width = width or 1024
+
+ vae_scale = self.vae_scale_factor * 2
+ if height % vae_scale != 0:
+ raise ValueError(
+ f"Height must be divisible by {vae_scale} (got {height}). "
+ f"Please adjust the height to a multiple of {vae_scale}."
+ )
+ if width % vae_scale != 0:
+ raise ValueError(
+ f"Width must be divisible by {vae_scale} (got {width}). "
+ f"Please adjust the width to a multiple of {vae_scale}."
+ )
+
+ self._guidance_scale = guidance_scale
+ dtype = (
+ self.text_encoder.dtype
+ if prompt_embeds is None
+ else (prompt_embeds[0].dtype if isinstance(prompt_embeds, list) else prompt_embeds.dtype)
+ )
+ device = self._execution_device
+ self.vae.enable_slicing()
+ self._guidance_scale = guidance_scale
+ self._joint_attention_kwargs = joint_attention_kwargs
+ self._interrupt = False
+ self._cfg_normalization = cfg_normalization
+ self._cfg_truncation = cfg_truncation
+ # 2. Define call parameters
+ if prompt is not None and isinstance(prompt, str):
+ batch_size = 1
+ elif prompt is not None and isinstance(prompt, list):
+ batch_size = len(prompt)
+ else:
+ batch_size = len(prompt_embeds)
+
+ lora_scale = (
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
+ )
+
+ # If prompt_embeds is provided and prompt is None, skip encoding
+ if prompt_embeds is not None and prompt is None:
+ if self.do_classifier_free_guidance and negative_prompt_embeds is None:
+ raise ValueError(
+ "When `prompt_embeds` is provided without `prompt`, "
+ "`negative_prompt_embeds` must also be provided for classifier-free guidance."
+ )
+ else:
+ (
+ prompt_embeds,
+ negative_prompt_embeds,
+ ) = self.encode_prompt(
+ prompt=prompt,
+ negative_prompt=negative_prompt,
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
+ prompt_embeds=prompt_embeds,
+ negative_prompt_embeds=negative_prompt_embeds,
+ dtype=dtype,
+ device=device,
+ num_images_per_prompt=1,
+ max_sequence_length=max_sequence_length,
+ lora_scale=lora_scale,
+ )
+ batch_size = num_images_per_prompt
+ num_images_per_prompt = 1
+ if batch_size > 1:
+ prompt_embeds = prompt_embeds * batch_size
+ if len(negative_prompt_embeds) > 0:
+ negative_prompt_embeds = negative_prompt_embeds * batch_size
+
+ # if prompt_embeds is not None:
+ # prompt_embeds = prompt_embeds.expand(num_images_per_prompt, -1, -1)
+ # 4. Prepare latent variables
+
+ num_channels_latents = self.transformer.in_channels
+
+ latents = self.prepare_latents(
+ batch_size * num_images_per_prompt,
+ num_channels_latents,
+ height,
+ width,
+ torch.float32,
+ device,
+ generator,
+ latents,
+ )
+ image_seq_len = (latents.shape[2] // 2) * (latents.shape[3] // 2)
+
+ # 5. Prepare timesteps
+ mu = calculate_shift(
+ image_seq_len,
+ self.scheduler.config.get("base_image_seq_len", 256),
+ self.scheduler.config.get("max_image_seq_len", 4096),
+ self.scheduler.config.get("base_shift", 0.5),
+ self.scheduler.config.get("max_shift", 1.15),
+ )
+ self.scheduler.sigma_min = 0.0
+ scheduler_kwargs = {"mu": mu}
+ timesteps, num_inference_steps = retrieve_timesteps(
+ self.scheduler,
+ num_inference_steps,
+ device,
+ sigmas=sigmas,
+ **scheduler_kwargs,
+ )
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
+ self._num_timesteps = len(timesteps)
+
+ callback(-1, None, True, len(timesteps))
+
+ # 6. Denoising loop
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
+ for i, t in enumerate(timesteps):
+ if self.interrupt:
+ break
+
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
+ timestep = t.expand(latents.shape[0])
+ timestep = (1000 - timestep) / 1000
+ # Normalized time for time-aware config (0 at start, 1 at end)
+ t_norm = timestep[0].item()
+
+ # Handle cfg truncation
+ current_guidance_scale = self.guidance_scale
+ if (
+ self.do_classifier_free_guidance
+ and self._cfg_truncation is not None
+ and float(self._cfg_truncation) <= 1
+ ):
+ if t_norm > self._cfg_truncation:
+ current_guidance_scale = 0.0
+
+ # 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
+
+ latent_model_input = latent_model_input.unsqueeze(2)
+ latent_model_input_list = list(latent_model_input.unbind(dim=0))
+
+ model_out_list = self.transformer(
+ latent_model_input_list,
+ timestep_model_input,
+ prompt_embeds_model_input,
+ 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)
+ else:
+ noise_pred = torch.stack([t.float() for t in model_out_list], dim=0)
+
+ noise_pred = noise_pred.squeeze(2)
+ noise_pred = -noise_pred
+
+ # compute the previous noisy sample x_t -> x_t-1
+ latents = self.scheduler.step(noise_pred.to(torch.float32), t, latents, return_dict=False)[0]
+ assert latents.dtype == torch.float32
+
+ if self._interrupt:
+ break
+ if callback is not None:
+ latents_preview = latents.unsqueeze(2)
+ if len(latents_preview) > 1: latents_preview = latents_preview.transpose(0,2)
+ callback(i, latents_preview[0], False)
+ latents_preview = None
+
+
+ if self._interrupt:
+ return None
+
+ latents = latents.to(dtype)
+ if output_type == "latent":
+ image = latents
+ else:
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
+
+ image = self.vae.decode(latents, return_dict=False)[0]
+ if output_type == "pt":
+ image = self.image_processor.postprocess(
+ image, output_type=output_type, do_denormalize=[False] * image.shape[0]
+ )
+ else:
+ image = self.image_processor.postprocess(image, output_type=output_type)
+
+ return image
+
diff --git a/models/z_image/transformer_z_image.py b/models/z_image/transformer_z_image.py
new file mode 100644
index 0000000..7c46ecf
--- /dev/null
+++ b/models/z_image/transformer_z_image.py
@@ -0,0 +1,649 @@
+# 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)))
+
+
+@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,
+ ):
+ super().__init__()
+ self.dim = dim
+ self.head_dim = dim // n_heads
+
+ # 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.feed_forward = FeedForward(dim=dim, hidden_dim=int(dim / 3 * 8))
+ 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 // 6), 1)
+ for ffn_chunk in torch.split(ffn_in, chunk_size):
+ ffn_chunk.copy_(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,
+ ):
+ 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))
+
+ return x
+
+
+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"]
+
+ @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],
+ ) -> 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)))
+
+ 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)
+
+ 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 forward(
+ self,
+ x: List[torch.Tensor],
+ t,
+ cap_feats: List[torch.Tensor],
+ patch_size=2,
+ f_patch_size=1,
+ callback=None,
+ pipeline=None,
+ ):
+ 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
+
+ for layer in self.layers:
+ if callback is not None:
+ callback(-1, None, False, True)
+ if pipeline is not None and getattr(pipeline, "_interrupt", False):
+ return [None] * bsz, {}
+ unified = layer(unified, unified_attn_mask, unified_freqs_cis, adaln_input)
+
+ unified = 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
new file mode 100644
index 0000000..ed895ae
--- /dev/null
+++ b/models/z_image/z_image_handler.py
@@ -0,0 +1,124 @@
+import os
+import torch
+from shared.utils import files_locator as fl
+
+
+def get_z_image_text_encoder_filename(text_encoder_quantization=None):
+ text_encoder_filename = "Qwen3/qwen3_bf16.safetensors"
+ if text_encoder_quantization =="int8":
+ text_encoder_filename = text_encoder_filename.replace("bf16", "quanto_bf16_int8")
+ return fl.locate_file(text_encoder_filename, True)
+
+
+class family_handler:
+ @staticmethod
+ def query_model_def(base_model_type, model_def):
+ extra_model_def = {
+ "image_outputs": True,
+ "guidance_max_phases": 0,
+ "fit_into_canvas_image_refs": 0,
+ "profiles_dir": [],
+ "no_negative_prompt": True,
+ }
+ return extra_model_def
+
+ @staticmethod
+ def query_supported_types():
+ return ["z_image"]
+
+ @staticmethod
+ def query_family_maps():
+ return {}, {}
+
+ @staticmethod
+ def query_model_family():
+ return "z_image"
+
+ @staticmethod
+ def query_family_infos():
+ return {"z_image": (50, "Z-Image")}
+
+ @staticmethod
+ def register_lora_cli_args(parser):
+ parser.add_argument(
+ "--lora-dir-z-image",
+ type=str,
+ default=os.path.join("loras", "z_image"),
+ help="Path to a directory that contains z image settings"
+ )
+
+ @staticmethod
+ def get_lora_dir(base_model_type, args):
+ return args.lora_dir_z_image
+
+ @staticmethod
+ def query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization):
+ text_encoder_filename = get_z_image_text_encoder_filename(text_encoder_quantization)
+ download_def = [
+ {
+ "repoId": "DeepBeepMeep/Z-Image",
+ "sourceFolderList": ["Qwen3", ""],
+ "fileList": [
+ ["tokenizer.json", "tokenizer_config.json", "vocab.json", "config.json", "merges.txt"]+ computeList(text_encoder_filename),
+ ["ZImageTurbo_VAE_bf16_config.json", "ZImageTurbo_VAE_bf16.safetensors", "ZImageTurbo_scheduler_config.json"],
+ ],
+ }
+ ]
+ return download_def
+
+ @staticmethod
+ def load_model(
+ model_filename,
+ model_type=None,
+ base_model_type=None,
+ model_def=None,
+ quantizeTransformer=False,
+ text_encoder_quantization=None,
+ dtype=torch.bfloat16,
+ VAE_dtype=torch.float32,
+ mixed_precision_transformer=False,
+ save_quantized=False,
+ submodel_no_list=None,
+ override_text_encoder=None,
+ **kwargs,
+ ):
+ from .z_image_main import model_factory
+
+ text_encoder_filename = (
+ override_text_encoder if override_text_encoder is not None else get_z_image_text_encoder_filename(text_encoder_quantization)
+ )
+
+ pipe_processor = model_factory(
+ checkpoint_dir="ckpts",
+ model_filename=model_filename,
+ model_type=model_type,
+ model_def=model_def,
+ base_model_type=base_model_type,
+ text_encoder_filename=text_encoder_filename,
+ quantizeTransformer=quantizeTransformer,
+ dtype=dtype,
+ VAE_dtype=VAE_dtype,
+ mixed_precision_transformer=mixed_precision_transformer,
+ save_quantized=save_quantized,
+ )
+
+ pipe = {
+ "transformer": pipe_processor.transformer,
+ "text_encoder": pipe_processor.text_encoder,
+ "vae": pipe_processor.vae,
+ }
+ return pipe_processor, pipe
+
+ def get_rgb_factors(base_model_type ):
+ from shared.RGB_factors import get_rgb_factors
+ latent_rgb_factors, latent_rgb_factors_bias = get_rgb_factors("flux")
+ return latent_rgb_factors, latent_rgb_factors_bias
+
+ @staticmethod
+ def update_default_settings(base_model_type, model_def, ui_defaults):
+ ui_defaults.update(
+ {
+ "guidance_scale": 0.0,
+ "num_inference_steps": ui_defaults.get("num_inference_steps", 9),
+ }
+ )
diff --git a/models/z_image/z_image_main.py b/models/z_image/z_image_main.py
new file mode 100644
index 0000000..947b43a
--- /dev/null
+++ b/models/z_image/z_image_main.py
@@ -0,0 +1,180 @@
+import json
+import os
+import torch
+from accelerate import init_empty_weights
+from diffusers import FlowMatchEulerDiscreteScheduler
+from diffusers.utils import logging
+from mmgp import offload
+from shared.utils import files_locator as fl
+from transformers import AutoTokenizer, Qwen3ForCausalLM
+
+from .autoencoder_kl import AutoencoderKL
+from .pipeline_z_image import ZImagePipeline
+from .transformer_z_image import ZImageTransformer2DModel
+
+
+logger = logging.get_logger(__name__)
+
+
+def _first_existing(paths):
+ for path in paths:
+ if path is not None and os.path.isfile(path):
+ return path
+ return None
+
+
+def _load_json_config(path, component):
+ if path is None:
+ return None
+ try:
+ with open(path, "r", encoding="utf-8") as f:
+ return json.load(f)
+ except Exception as exc:
+ logger.warning(f"Could not load {component} config from {path}: {exc}")
+ return None
+
+
+class model_factory:
+ def __init__(
+ self,
+ checkpoint_dir,
+ model_filename=None,
+ model_type=None,
+ model_def=None,
+ base_model_type=None,
+ text_encoder_filename=None,
+ quantizeTransformer=False,
+ dtype=torch.bfloat16,
+ VAE_dtype=torch.float32,
+ mixed_precision_transformer=False,
+ save_quantized=False,
+ **kwargs,
+ ):
+ transformer_filename = model_filename[0] if isinstance(model_filename, (list, tuple)) else model_filename
+ if transformer_filename is None:
+ raise ValueError("No transformer filename provided for Z-Image.")
+
+ self.base_model_type = base_model_type
+
+ # Transformer
+ default_transformer_config = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")
+
+ transformer = offload.fast_load_transformers_model(transformer_filename, writable_tensors= False, modelClass=ZImageTransformer2DModel, defaultConfigPath= default_transformer_config)
+ transformer.to(dtype)
+ if save_quantized:
+ from wgp import save_quantized_model
+ save_quantized_model(transformer, model_type, transformer_filename, dtype, default_transformer_config)
+
+ # Text encoder
+
+ # text_encoder = Qwen3ForCausalLM.from_pretrained(os.path.dirname(text_encoder_filename), trust_remote_code=True)
+ # text_encoder.to(torch.bfloat16)
+ # offload.save_model(text_encoder, "c:/temp/qwnen3_bf16_.safetensors")
+
+ text_encoder = offload.fast_load_transformers_model( text_encoder_filename, writable_tensors=True, modelClass=Qwen3ForCausalLM,)
+
+ # Tokenizer
+ tokenizer_path = os.path.join(os.path.dirname(text_encoder_filename))
+ tokenizer = AutoTokenizer.from_pretrained(tokenizer_path, trust_remote_code=True)
+
+ # VAE
+ vae_filename = fl.locate_file("ZImageTurbo_VAE_bf16.safetensors")
+ vae_config_path = os.path.join(os.path.dirname(vae_filename), "ZImageTurbo_VAE_bf16_config.json")
+
+ vae = offload.fast_load_transformers_model(
+ vae_filename,
+ writable_tensors=True,
+ modelClass=AutoencoderKL,
+ defaultConfigPath=vae_config_path,
+ default_dtype=VAE_dtype,
+ )
+
+ # Scheduler
+ with open(fl.locate_file("ZImageTurbo_scheduler_config.json"), "r", encoding="utf-8") as f:
+ scheduler_config = json.load(f)
+
+ scheduler = FlowMatchEulerDiscreteScheduler(**scheduler_config)
+
+ self.pipeline = ZImagePipeline(
+ scheduler=scheduler, vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, transformer=transformer
+ )
+ self.transformer = transformer
+ self.text_encoder = text_encoder
+ self.tokenizer = tokenizer
+ self.vae = vae
+ self.scheduler = scheduler
+
+ def generate(
+ self,
+ seed: int | None = None,
+ input_prompt: str = "",
+ n_prompt: str | None = None,
+ sampling_steps: int = 20,
+ width: int = 1024,
+ height: int = 1024,
+ guide_scale: float = 0.0,
+ batch_size: int = 1,
+ callback=None,
+ max_sequence_length: int = 512,
+ VAE_tile_size=None,
+ cfg_normalization: bool = False,
+ cfg_truncation: float = 1.0,
+ **kwargs,
+ ):
+ generator = torch.Generator(device="cuda" if torch.cuda.is_available() else "cpu")
+ if seed is None or seed < 0:
+ generator.seed()
+ else:
+ generator.manual_seed(int(seed))
+
+ if VAE_tile_size is not None and hasattr(self.vae, "use_tiling"):
+ if isinstance(VAE_tile_size, int):
+ tiling = VAE_tile_size > 0
+ tile_size = max(VAE_tile_size, 0)
+ else:
+ tiling = bool(VAE_tile_size[0])
+ tile_size = VAE_tile_size[1] if len(VAE_tile_size) > 1 else 0
+ self.vae.use_tiling = tiling
+ self.vae.tile_latent_min_height = tile_size
+ self.vae.tile_latent_min_width = tile_size
+
+ guide_scale = 0
+
+ images = self.pipeline(
+ prompt=input_prompt,
+ negative_prompt=n_prompt,
+ num_inference_steps=sampling_steps,
+ guidance_scale=guide_scale,
+ num_images_per_prompt=batch_size,
+ generator=generator,
+ height=height,
+ width=width,
+ max_sequence_length=max_sequence_length,
+ callback_on_step_end=None,
+ output_type="pt",
+ return_dict=True,
+ cfg_normalization=cfg_normalization,
+ cfg_truncation=cfg_truncation,
+ callback=callback,
+ pipeline=self.pipeline,
+ )
+
+ if images is None:
+ return None
+
+ if not torch.is_tensor(images):
+ images = torch.tensor(images)
+
+ return images.transpose(0, 1)
+
+ def get_loras_transformer(self, *args, **kwargs):
+ return [], []
+
+ @property
+ def _interrupt(self):
+ return getattr(self.pipeline, "_interrupt", False)
+
+ @_interrupt.setter
+ def _interrupt(self, value):
+ if hasattr(self, "pipeline"):
+ self.pipeline._interrupt = value
diff --git a/shared/loras_migration.py b/shared/loras_migration.py
new file mode 100644
index 0000000..e140d12
--- /dev/null
+++ b/shared/loras_migration.py
@@ -0,0 +1,163 @@
+import os
+import shutil
+from pathlib import Path
+
+from safetensors import safe_open
+
+
+def _ensure_dir(path: Path):
+ path.mkdir(parents=True, exist_ok=True)
+
+
+def _move_with_collision_handling(src: Path, dst_dir: Path):
+ _ensure_dir(dst_dir)
+ target = dst_dir / src.name
+ if target.exists():
+ stem, suffix = os.path.splitext(src.name)
+ idx = 1
+ while True:
+ candidate = dst_dir / f"{stem}_{idx}{suffix}"
+ if not candidate.exists():
+ target = candidate
+ break
+ idx += 1
+ shutil.move(str(src), str(target))
+
+
+def _classify_wan_lora(file_path: Path, subfolder_hint: str | None = None) -> str:
+ if subfolder_hint in {"1.3B"}:
+ return "wan_1.3B"
+ if subfolder_hint in {"5B"}:
+ return "wan_5B"
+ if subfolder_hint in {"14B"}:
+ return "wan"
+
+ candidate_tokens = [
+ "to_q",
+ "to_k",
+ "to_v",
+ "proj_in",
+ "proj_out",
+ "ff.net",
+ "ffn",
+ "transformer",
+ "attn",
+ "gate_proj",
+ "up_proj",
+ "down_proj",
+ "lora_down",
+ "lora_up",
+ ]
+ try:
+ with safe_open(file_path, framework="pt", device="cpu") as f:
+ keys = f.keys()
+ if not keys:
+ return "wan"
+ max_dim = 0
+ # Prefer typical attention/ffn LoRA tensors; fall back to any tensor
+ for key in keys:
+ k_lower = key.lower()
+ if not any(token in k_lower for token in candidate_tokens):
+ continue
+ tensor = f.get_tensor(key)
+ max_dim = max(max_dim, max(tensor.shape) if tensor.ndim > 0 else 0)
+ if max_dim == 0:
+ tensor = f.get_tensor(keys[0])
+ max_dim = max(tensor.shape) if tensor.ndim > 0 else 0
+ if max_dim >= 5000:
+ return "wan"
+ if max_dim >= 3000:
+ return "wan_5B"
+ return "wan_1.3B"
+ except Exception:
+ return "wan"
+
+
+def _move_dir_contents(src_dir: Path, dst_dir: Path):
+ if not src_dir.exists():
+ return
+ for item in src_dir.iterdir():
+ _move_with_collision_handling(item, dst_dir)
+ try:
+ src_dir.rmdir()
+ except OSError:
+ pass
+
+
+def migrate_loras_layout(root_dir: Path | str | None = None):
+ """
+ Reorganize lora folders into a single 'loras' tree.
+ Migration is skipped if root/loras_i2v is already gone.
+ """
+ root = Path(root_dir or ".").resolve()
+ marker = root / "loras_i2v"
+ if not marker.exists():
+ return
+
+ loras_root = root / "loras"
+ _ensure_dir(loras_root)
+
+ # Move dedicated per-family folders (loras_foo -> loras/foo)
+ for entry in root.iterdir():
+ if not entry.is_dir():
+ continue
+ if entry.name in {"loras", "loras_i2v"}:
+ continue
+ if entry.name.startswith("loras_"):
+ target_name = entry.name[len("loras_") :]
+ _move_dir_contents(entry, loras_root / target_name)
+
+ # Move Wan i2v
+ _move_dir_contents(marker, loras_root / "wan_i2v")
+
+ # Handle Wan core folders inside loras
+ wan_dir = loras_root / "wan"
+ wan_1_3b_dir = loras_root / "wan_1.3B"
+ wan_5b_dir = loras_root / "wan_5B"
+ wan_i2v_dir = loras_root / "wan_i2v"
+ optional_hints = {"1.3B", "5B", "14B"}
+ moved_wan_by_signature = {}
+ for legacy_name, target in [
+ ("14B", wan_dir),
+ ("1.3B", wan_1_3b_dir),
+ ("5B", wan_5b_dir),
+ ]:
+ _move_dir_contents(loras_root / legacy_name, target)
+
+ # Classify remaining loose Wan loras at the old loras root
+ for item in list(loras_root.iterdir()):
+ if item.is_dir() and item.name.startswith("wan"):
+ continue
+ if item.is_dir():
+ # Non-Wan folders already handled above
+ continue
+ if not item.is_file():
+ continue
+ subfolder_hint = item.parent.name
+ used_hint = subfolder_hint in optional_hints
+ target_bucket = _classify_wan_lora(item, subfolder_hint=subfolder_hint if used_hint else None)
+ target_dir = {"wan": wan_dir, "wan_1.3B": wan_1_3b_dir, "wan_5B": wan_5b_dir}.get(
+ target_bucket, wan_dir
+ )
+ _move_with_collision_handling(item, target_dir)
+ if target_bucket.startswith("wan") and not used_hint:
+ moved_wan_by_signature[item.name] = target_dir
+
+ # Move any remaining files under loras root (unlikely) into wan
+ for item in list(loras_root.iterdir()):
+ if item.is_file():
+ _move_with_collision_handling(item, wan_dir)
+
+ # Move .lset files referencing Wan loras that were reclassified by tensor signature
+ for lset_file in loras_root.glob("*.lset"):
+ try:
+ content = lset_file.read_text(errors="ignore")
+ except Exception:
+ continue
+ for lora_name, dest_dir in moved_wan_by_signature.items():
+ if lora_name in content:
+ _move_with_collision_handling(lset_file, dest_dir)
+ break
+
+ for folder in [wan_dir, wan_1_3b_dir, wan_5b_dir, wan_i2v_dir]:
+ _ensure_dir(folder)
diff --git a/wgp.py b/wgp.py
index 970ad6d..9a2b6c4 100644
--- a/wgp.py
+++ b/wgp.py
@@ -45,6 +45,7 @@ from shared.match_archi import match_nvidia_architecture
from shared.attention import get_attention_modes, get_supported_attention_modes
from shared.utils.utils import truncate_for_filesystem, sanitize_file_name, process_images_multithread, get_default_workers
from shared.utils.process_locks import acquire_GPU_ressources, release_GPU_ressources, gen_lock
+from shared.loras_migration import migrate_loras_layout
from huggingface_hub import hf_hub_download, snapshot_download
from shared.utils import files_locator as fl
from shared.gradio.audio_gallery import AudioGallery
@@ -82,7 +83,7 @@ global_queue_ref = []
AUTOSAVE_FILENAME = "queue.zip"
PROMPT_VARS_MAX = 10
target_mmgp_version = "3.6.9"
-WanGP_version = "9.71"
+WanGP_version = "9.72"
settings_version = 2.41
max_source_video_frames = 3000
prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer = None, None, None, None
@@ -1709,6 +1710,20 @@ def update_generation_status(html_content):
if(html_content):
return gr.update(value=html_content)
+family_handlers = ["models.wan.wan_handler", "models.wan.ovi_handler", "models.wan.df_handler", "models.hyvideo.hunyuan_handler", "models.ltx_video.ltxv_handler", "models.flux.flux_handler", "models.qwen.qwen_handler", "models.z_image.z_image_handler", "models.chatterbox.chatterbox_handler"]
+
+def register_family_lora_args(parser):
+ registered_families = set()
+ for path in family_handlers:
+ handler = importlib.import_module(path).family_handler
+ family_name = handler.query_model_family()
+ family_key = family_name or path
+ if family_key in registered_families:
+ continue
+ if hasattr(handler, "register_lora_cli_args"):
+ handler.register_lora_cli_args(parser)
+ registered_families.add(family_key)
+
def _parse_args():
parser = argparse.ArgumentParser(
description="Generate a video from a text prompt or image using Gradio")
@@ -1783,70 +1798,7 @@ def _parse_args():
)
- parser.add_argument(
- "--lora-dir-i2v",
- type=str,
- default="",
- help="Path to a directory that contains Wan i2v Loras "
- )
-
-
- parser.add_argument(
- "--lora-dir",
- type=str,
- default="",
- help="Path to a directory that contains Wan t2v Loras"
- )
-
- parser.add_argument(
- "--lora-dir-hunyuan",
- type=str,
- default="loras_hunyuan",
- help="Path to a directory that contains Hunyuan Video t2v Loras"
- )
-
- parser.add_argument(
- "--lora-dir-hunyuan-i2v",
- type=str,
- default="loras_hunyuan_i2v",
- help="Path to a directory that contains Hunyuan Video i2v Loras"
- )
-
-
- parser.add_argument(
- "--lora-dir-ltxv",
- type=str,
- default="loras_ltxv",
- help="Path to a directory that contains LTX Videos Loras"
- )
-
- parser.add_argument(
- "--lora-dir-flux",
- type=str,
- default="loras_flux",
- help="Path to a directory that contains flux images Loras"
- )
-
- parser.add_argument(
- "--lora-dir-flux2",
- type=str,
- default="loras_flux2",
- help="Path to a directory that contains flux2 images Loras"
- )
-
- parser.add_argument(
- "--lora-dir-qwen",
- type=str,
- default="loras_qwen",
- help="Path to a directory that contains qwen images Loras"
- )
-
- parser.add_argument(
- "--lora-dir-tts",
- type=str,
- default="loras_tts",
- help="Path to a directory that contains TTS settings"
- )
+ register_family_lora_args(parser)
parser.add_argument(
"--check-loras",
@@ -2065,57 +2017,28 @@ def _parse_args():
return args
def get_lora_dir(model_type):
- model_family = get_model_family(model_type)
base_model_type = get_base_model_type(model_type)
- i2v = test_class_i2v(model_type) and not base_model_type in ["i2v_2_2", "i2v_2_2_multitalk"]
- if model_family == "wan":
- lora_dir =args.lora_dir
- if i2v and len(lora_dir)==0:
- lora_dir =args.lora_dir_i2v
- if len(lora_dir) > 0:
- return lora_dir
- root_lora_dir = "loras_i2v" if i2v else "loras"
-
- if "1.3B" in model_type :
- lora_dir_1_3B = os.path.join(root_lora_dir, "1.3B")
- if os.path.isdir(lora_dir_1_3B ):
- return lora_dir_1_3B
- elif base_model_type in ["ti2v_2_2", "ovi"]:
- lora_dir_5B = os.path.join(root_lora_dir, "5B")
- if os.path.isdir(lora_dir_5B ):
- return lora_dir_5B
- else:
- lora_dir_14B = os.path.join(root_lora_dir, "14B")
- if os.path.isdir(lora_dir_14B ):
- return lora_dir_14B
- return root_lora_dir
- elif model_family == "ltxv":
- return args.lora_dir_ltxv
- elif model_family == "flux":
- if base_model_type in ["flux2_dev"]:
- return args.lora_dir_flux2
- else:
- return args.lora_dir_flux
- elif model_family =="hunyuan":
- if i2v:
- return args.lora_dir_hunyuan_i2v
- else:
- root_lora_dir=args.lora_dir_hunyuan
- if "1_5" in base_model_type:
- lora_dir_1_5 = os.path.join(root_lora_dir, "1.5")
- if os.path.isdir(lora_dir_1_5 ):
- return lora_dir_1_5
- return root_lora_dir
- elif model_family =="qwen":
- return args.lora_dir_qwen
- elif model_family =="tts":
- return args.lora_dir_tts
- else:
+ if base_model_type is None:
+ raise Exception("loras unknown")
+
+ handler = get_model_handler(model_type)
+ get_dir = getattr(handler, "get_lora_dir", None)
+ if get_dir is None:
raise Exception("loras unknown")
+ lora_dir = get_dir(base_model_type, args)
+ if lora_dir is None:
+ raise Exception("loras unknown")
+ if os.path.isfile(lora_dir):
+ raise Exception(f"loras path '{lora_dir}' exists and is not a directory")
+ if not os.path.isdir(lora_dir):
+ os.makedirs(lora_dir, exist_ok=True)
+ return lora_dir
+
attention_modes_installed = get_attention_modes()
attention_modes_supported = get_supported_attention_modes()
args = _parse_args()
+migrate_loras_layout()
gpu_major, gpu_minor = torch.cuda.get_device_capability(args.gpu if len(args.gpu) > 0 else None)
if gpu_major < 8:
@@ -2217,7 +2140,6 @@ for f, s in [(fl.locate_file("Florence2/modeling_florence2.py", error_if_none= F
except: pass
models_def = {}
-family_handlers = ["models.wan.wan_handler", "models.wan.ovi_handler", "models.wan.df_handler", "models.hyvideo.hunyuan_handler", "models.ltx_video.ltxv_handler", "models.flux.flux_handler", "models.qwen.qwen_handler", "models.chatterbox.chatterbox_handler"]
# only needed for imported old settings files
@@ -2849,7 +2771,7 @@ def save_quantized_model(model, model_type, model_filename, dtype, config_file,
break
if not "quanto" in model_filename:
pos = model_filename.rfind(".")
- model_filename = model_filename[:pos] + "_quanto_int8" + model_filename[pos+1:]
+ model_filename = model_filename[:pos] + "_quanto_int8" + model_filename[pos:]
model_filename = os.path.basename(model_filename)
if fl.locate_file(model_filename, error_if_none= False) is not None:
@@ -3185,10 +3107,12 @@ def init_pipe(pipe, kwargs, override_profile):
kwargs["pinnedMemory"] = ["transformer", "transformer2"]
if profile == 4.5:
- profile = 4
+ mmgp_profile = 4
kwargs["asyncTransfers"] = False
+ else:
+ mmgp_profile = profile
- return profile
+ return profile, mmgp_profile
def reset_prompt_enhancer():
global prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer, enhancer_offloadobj
@@ -3328,7 +3252,7 @@ def load_models(model_type, override_profile = -1, **model_kwargs):
pipe = kwargs.pop("pipe")
if "coTenantsMap" not in kwargs: kwargs["coTenantsMap"] = {}
- profile = init_pipe(pipe, kwargs, override_profile)
+ profile, mmgp_profile = init_pipe(pipe, kwargs, override_profile)
if server_config.get("enhancer_mode", 0) == 0:
setup_prompt_enhancer(pipe, kwargs)
loras_transformer = []
@@ -3339,7 +3263,7 @@ def load_models(model_type, override_profile = -1, **model_kwargs):
if len(compile) > 0 and hasattr(wan_model, "custom_compile"):
wan_model.custom_compile(backend= "inductor", mode ="default")
compile_modules = model_def.get("compile", compile) if len(compile) > 0 else ""
- offloadobj = offload.profile(pipe, profile_no= profile, compile = compile_modules, quantizeTransformer = False, loras = loras_transformer, perc_reserved_mem_max = perc_reserved_mem_max , vram_safety_coefficient = vram_safety_coefficient , convertWeightsFloatTo = transformer_dtype, **kwargs)
+ offloadobj = offload.profile(pipe, profile_no= mmgp_profile, compile = compile_modules, quantizeTransformer = False, loras = loras_transformer, perc_reserved_mem_max = perc_reserved_mem_max , vram_safety_coefficient = vram_safety_coefficient , convertWeightsFloatTo = transformer_dtype, **kwargs)
if len(args.gpu) > 0:
torch.set_default_device(args.gpu)
transformer_type = model_type