Skip to content
Python

Added Alpha 2, Long Cat, Z Image ControlNet 2.1

deepbeepmeep221f5eb9fc63
diff --git a/defaults/alpha.json b/defaults/alpha.json
index 641fbde..aff895e 100644
--- a/defaults/alpha.json
+++ b/defaults/alpha.json
@@ -1,7 +1,7 @@
{
"model":
{
- "name": "Wan2.1 Alpha 14B",
+ "name": "Wan2.1 Alpha v1.0 14B",
"architecture" : "alpha",
"description": "This model successfully generates various scenes with accurate and clearly rendered transparency. Notably, it can synthesize diverse semi-transparent objects, glowing effects, and fine-grained details such as hair. For each video generated you will find a Zip file with the same name that will contain the corresponding RGBA images.",
"URLs": "t2v",
diff --git a/defaults/alpha2.json b/defaults/alpha2.json
new file mode 100644
index 0000000..9534fb2
--- /dev/null
+++ b/defaults/alpha2.json
@@ -0,0 +1,19 @@
+{
+ "model":
+ {
+ "name": "Wan2.1 Alpha v2.0 14B",
+ "architecture" : "alpha2",
+ "description": "Wan-Alpha v2.0 generates transparent videos with fine-grained alpha detail (hair, glow, smoke). For each video, a Zip file with RGBA frames is produced.",
+ "URLs": "t2v",
+ "preload_URLs": [
+ "https://huggingface.co/DeepBeepMeep/Wan2.1/resolve/main/wan_alpha_2.1_vae_rgb_channel_v2.safetensors",
+ "https://huggingface.co/DeepBeepMeep/Wan2.1/resolve/main/wan_alpha_2.1_vae_alpha_channel_v2.safetensors",
+ "https://huggingface.co/DeepBeepMeep/Wan2.1/resolve/main/gauss_mask"
+ ],
+ "loras": [
+ "https://huggingface.co/DeepBeepMeep/Wan2.1/resolve/main/wan_alpha_2.1_dora_v2.safetensors"
+ ],
+ "loras_multipliers": [ 1 ]
+ },
+ "prompt": "A large orange octopus is seen resting. The background of the video is transparent."
+}
diff --git a/defaults/alpha2_sf.json b/defaults/alpha2_sf.json
new file mode 100644
index 0000000..e2e2430
--- /dev/null
+++ b/defaults/alpha2_sf.json
@@ -0,0 +1,17 @@
+{
+ "model":
+ {
+ "name": "Wan2.1 Alpha v2.0 Lightning 14B",
+ "architecture" : "alpha2",
+ "description": "Wan-Alpha v2.0 Lightning with transparent video output and RGBA frames zip.",
+ "URLs": "t2v_sf",
+ "preload_URLs": "alpha2",
+ "loras": "alpha2",
+ "loras_multipliers": [ 1 ],
+ "profiles_dir" : [""]
+ },
+ "prompt": "A large orange octopus is seen resting. The background of the video is transparent.",
+ "num_inference_steps": 4,
+ "guidance_scale": 1,
+ "flow_shift": 3
+}
diff --git a/defaults/alpha_sf.json b/defaults/alpha_sf.json
index 4d273b9..718a78d 100644
--- a/defaults/alpha_sf.json
+++ b/defaults/alpha_sf.json
@@ -1,7 +1,7 @@
{
"model":
{
- "name": "Wan2.1 Alpha Lightning 14B",
+ "name": "Wan2.1 Alpha v1.0 Lightning 14B",
"architecture" : "alpha",
"description": "This model is accelerated by the Lightning / SelfForcing process. It successfully generates various scenes with accurate and clearly rendered transparency. Notably, it can synthesize diverse semi-transparent objects, glowing effects, and fine-grained details such as hair. For each video generated you will find a Zip file with the same name that will contain the corresponding RGBA images.",
"URLs": "t2v_sf",
diff --git a/defaults/longcat_avatar.json b/defaults/longcat_avatar.json
new file mode 100644
index 0000000..e2b3444
--- /dev/null
+++ b/defaults/longcat_avatar.json
@@ -0,0 +1,16 @@
+{
+ "model": {
+ "name": "LongCat Avatar Single 13.6B",
+ "architecture": "longcat_avatar",
+ "description": "LongCat Avatar (single speaker) for audio-driven character video.",
+ "one_speaker_only": true,
+ "URLs": [
+ "https://huggingface.co/DeepBeepMeep/LongCat/resolve/main/longcat_avatar_single_bf16.safetensors",
+ "https://huggingface.co/DeepBeepMeep/LongCat/resolve/main/longcat_avatar_single_quanto_bf16_int8.safetensors"
+ ],
+ "reference_image_enabled": true,
+ "ref_img_index": 10,
+ "mask_frame_range": 3
+ },
+ "num_inference_steps": 50
+}
diff --git a/defaults/longcat_avatar_multi.json b/defaults/longcat_avatar_multi.json
new file mode 100644
index 0000000..b0e98c8
--- /dev/null
+++ b/defaults/longcat_avatar_multi.json
@@ -0,0 +1,16 @@
+{
+ "model": {
+ "name": "LongCat Avatar Multi 13.6B",
+ "architecture": "longcat_avatar",
+ "description": "LongCat Avatar (multi speaker) for dual-audio driven character video.",
+ "multi_speakers_only": true,
+ "URLs": [
+ "https://huggingface.co/DeepBeepMeep/LongCat/resolve/main/longcat_avatar_multi_bf16.safetensors",
+ "https://huggingface.co/DeepBeepMeep/LongCat/resolve/main/longcat_avatar_multi_quanto_bf16_int8.safetensors"
+ ],
+ "reference_image_enabled": true,
+ "ref_img_index": 10,
+ "mask_frame_range": 3
+ },
+ "num_inference_steps": 50
+}
diff --git a/defaults/longcat_video.json b/defaults/longcat_video.json
new file mode 100644
index 0000000..b16f495
--- /dev/null
+++ b/defaults/longcat_video.json
@@ -0,0 +1,12 @@
+{
+ "model": {
+ "name": "LongCat Video 13.6B",
+ "architecture": "longcat_video",
+ "description": "LongCat Video supports text-to-video, image-to-video, and video continuation with a unified transformer.",
+ "URLs": [
+ "https://huggingface.co/DeepBeepMeep/LongCat/resolve/main/longcat_video_bf16.safetensors",
+ "https://huggingface.co/DeepBeepMeep/LongCat/resolve/main/longcat_video_quanto_bf16_int8.safetensors"
+ ]
+ },
+ "num_inference_steps": 50
+}
diff --git a/defaults/scail.json b/defaults/scail.json
index 42b79dc..0950f74 100644
--- a/defaults/scail.json
+++ b/defaults/scail.json
@@ -9,5 +9,5 @@
"https://huggingface.co/DeepBeepMeep/Wan2.1/resolve/main/wan2.1_scail_preview_14B_quanto_fp16_int8.safetensors"
]
},
- "color_correction_strength": 1
+ "sliding_window_color_correction_strength": 1
}
\ No newline at end of file
diff --git a/defaults/z_image_control2_1.json b/defaults/z_image_control2_1.json
new file mode 100644
index 0000000..f67a592
--- /dev/null
+++ b/defaults/z_image_control2_1.json
@@ -0,0 +1,19 @@
+{
+ "model": {
+ "name": "Z-Image Turbo Fun ControlNet v2.1 6B",
+ "architecture": "z_image_control2_1",
+ "modules": [
+ [
+ "https://huggingface.co/DeepBeepMeep/Z-Image/resolve/main/Z-Image-Turbo-Fun-Controlnet-Union2.1_bf16.safetensors",
+ "https://huggingface.co/DeepBeepMeep/Z-Image/resolve/main/Z-Image-Turbo-Fun-Controlnet-Union2.1_quanto_bf16_int8.safetensors"
+ ]
+ ],
+ "description": "Z-Image Turbo with ControlNet Union supporting Pose, Canny, Depth, and Scribble control types. V2.1 has more control layers and support inpainting (disabled for the moment).",
+ "URLs": "z_image"
+ },
+ "resolution": "1920x1088",
+ "batch_size": 1,
+ "num_inference_steps": 9,
+ "guidance_scale": 0,
+ "control_net_weight_alt": 0.65
+}
\ No newline at end of file
diff --git a/defaults/z_image_control2_1_8s.json b/defaults/z_image_control2_1_8s.json
new file mode 100644
index 0000000..e1f2ea9
--- /dev/null
+++ b/defaults/z_image_control2_1_8s.json
@@ -0,0 +1,20 @@
+{
+ "model": {
+ "name": "Z-Image Turbo Fun ControlNet v2.1 8 Steps 6B",
+ "architecture": "z_image_control2_1",
+ "modules": [
+ [
+ "https://huggingface.co/DeepBeepMeep/Z-Image/resolve/main/Z-Image-Turbo-Fun-Controlnet-Union2.1-8steps_bf16.safetensors",
+ "https://huggingface.co/DeepBeepMeep/Z-Image/resolve/main/Z-Image-Turbo-Fun-Controlnet-Union2.1-8steps_quanto_bf16_int8.safetensors"
+ ]
+ ],
+ "description": "Z-Image Turbo with ControlNet Union supporting Pose, Canny, Depth, and Scribble control types. V2.1 has more control layers and support inpainting (disabled for the moment).",
+ "URLs": "z_image",
+ "visible": false
+ },
+ "resolution": "1920x1088",
+ "batch_size": 1,
+ "num_inference_steps": 8,
+ "guidance_scale": 0,
+ "control_net_weight_alt": 0.65
+}
\ No newline at end of file
diff --git a/defaults/z_image_nunchaku_r256_int4.json b/defaults/z_image_nunchaku_r256_int4.json
new file mode 100644
index 0000000..805e24f
--- /dev/null
+++ b/defaults/z_image_nunchaku_r256_int4.json
@@ -0,0 +1,14 @@
+{
+ "model": {
+ "name": "Z-Image Turbo Nunchaku INT4 (r32)",
+ "architecture": "z_image",
+ "description": "Nunchaku SVDQ INT4 weights for Z-Image Turbo.",
+ "URLs": [
+ "https://huggingface.co/DeepBeepMeep/Z-Image/resolve/main//svdq-int4_r256-z-image-turbo.safetensors"
+ ]
+ },
+ "resolution": "1024x1024",
+ "batch_size": 1,
+ "num_inference_steps": 8,
+ "guidance_scale": 0
+}
diff --git a/models/chatterbox/chatterbox_handler.py b/models/chatterbox/chatterbox_handler.py
index fe754cc..19d32ae 100644
--- a/models/chatterbox/chatterbox_handler.py
+++ b/models/chatterbox/chatterbox_handler.py
@@ -51,7 +51,7 @@ class family_handler:
@staticmethod
def query_family_infos():
# The numeric weight controls ordering in the family dropdown.
- return {"tts": (70, "TTS")}
+ return {"tts": (200, "TTS")}
@staticmethod
def register_lora_cli_args(parser):
diff --git a/models/flux/flux_handler.py b/models/flux/flux_handler.py
index d51930e..5d2cc89 100644
--- a/models/flux/flux_handler.py
+++ b/models/flux/flux_handler.py
@@ -183,7 +183,7 @@ class family_handler():
@staticmethod
def query_family_infos():
- return {"flux":(30, "Flux 1"), "flux2":(31, "Flux 2")}
+ return {"flux":(100, "Flux 1"), "flux2":(101, "Flux 2")}
@staticmethod
def register_lora_cli_args(parser):
diff --git a/models/flux/flux_main.py b/models/flux/flux_main.py
index a11520d..6dc04f8 100644
--- a/models/flux/flux_main.py
+++ b/models/flux/flux_main.py
@@ -15,13 +15,9 @@ from shared.utils.utils import convert_image_to_tensor, convert_tensor_to_image
from shared.utils import files_locator as fl
from transformers import Qwen2_5_VLForConditionalGeneration, Qwen2VLProcessor
from .modules.autoencoder_flux2 import AutoencoderKLFlux2, AutoEncoderParamsFlux2
+from shared.qtypes import nunchaku_int4 as _nunchaku_int4
-from .util import (
- load_ae,
- load_clip,
- load_flow_model,
- load_t5,
-)
+from .util import load_ae, load_clip, load_flow_model, load_t5, preprocess_flux_state_dict
from .flux2_adapter import (
scatter_ids ,
batched_prc_img,
@@ -103,7 +99,12 @@ class model_factory:
source = model_def.get("source", None)
self.clip = self.t5 = self.vision_encoder = self.mistal = None
if self.is_flux2:
- self.model = load_flow_model(self.name, model_filename if source is None else source, torch_device)
+ self.model = load_flow_model(
+ self.name,
+ model_filename if source is None else source,
+ torch_device,
+ preprocess_sd=preprocess_flux_state_dict,
+ )
from .modules.text_encoder_mistral import Mistral3SmallEmbedder
self.mistral = Mistral3SmallEmbedder( model_spec = text_encoder_filename)
@@ -120,7 +121,12 @@ class model_factory:
# self.name= "flux-dev"
# self.name= "flux-schnell"
source = model_def.get("source", None)
- self.model = load_flow_model(self.name, model_filename[0] if source is None else source, torch_device)
+ self.model = load_flow_model(
+ self.name,
+ model_filename[0] if source is None else source,
+ torch_device,
+ preprocess_sd=preprocess_flux_state_dict,
+ )
self.model_def = model_def
self.vae = None if getattr(self.model, "radiance", False) else load_ae(self.name, device=torch_device)
@@ -168,7 +174,21 @@ class model_factory:
getattr(self.model.params, "double_linear1_mlp_ratio", None),
)
self.model.split_linear_modules_map = split_linear_modules_map
- offload.split_linear_modules(self.model, split_linear_modules_map )
+ split_kwargs = None
+ for module in self.model.modules():
+ qtype = getattr(module, "weight_qtype", None)
+ if getattr(qtype, "name", None) == _nunchaku_int4._NUNCHAKU_INT4_QTYPE_NAME:
+ split_kwargs = _nunchaku_int4.get_nunchaku_split_kwargs()
+ break
+ if split_kwargs:
+ offload.split_linear_modules(
+ self.model,
+ split_linear_modules_map,
+ split_handlers=split_kwargs.get("split_handlers"),
+ share_fields=split_kwargs.get("share_fields"),
+ )
+ else:
+ offload.split_linear_modules(self.model, split_linear_modules_map)
def infer_vlm(self, input_img_path,input_instruction,prefix):
tp=[]
diff --git a/models/flux/sampling.py b/models/flux/sampling.py
index 313ca0a..ff6f88f 100644
--- a/models/flux/sampling.py
+++ b/models/flux/sampling.py
@@ -241,7 +241,7 @@ def prepare_kontext(
"img_cond_seq_ids": img_cond_seq_ids,
}
if img_mask is not None:
- return_dict.update(build_mask(target_width, target_height, img_mask), device)
+ return_dict.update(build_mask(target_width, target_height, img_mask, device))
img = get_noise(
bs,
diff --git a/models/flux/util.py b/models/flux/util.py
index 2befddf..68ce78d 100644
--- a/models/flux/util.py
+++ b/models/flux/util.py
@@ -15,6 +15,7 @@ from .model import Flux, FluxLoraWrapper, FluxParams
from .modules.autoencoder import AutoEncoder, AutoEncoderParams
from .modules.conditioner import HFEmbedder
from shared.utils import files_locator as fl
+from shared.convert import convert_diffusers_to_flux
CHECKPOINTS_DIR = Path("checkpoints")
@@ -920,7 +921,17 @@ def preprocess_flux2_state_dict(state_dict: dict, params: FluxParams) -> dict:
return sd
-def load_flow_model(name: str, model_filename, device: str | torch.device = "cuda", verbose: bool = True) -> Flux:
+def preprocess_flux_state_dict(state_dict: dict) -> dict:
+ return convert_diffusers_to_flux.convert_state_dict(state_dict)
+
+
+def load_flow_model(
+ name: str,
+ model_filename,
+ device: str | torch.device = "cuda",
+ verbose: bool = True,
+ preprocess_sd=preprocess_flux_state_dict,
+) -> Flux:
# Loading Flux
config = configs[name]
@@ -934,7 +945,7 @@ def load_flow_model(name: str, model_filename, device: str | torch.device = "cud
# print(f"Loading checkpoint: {ckpt_path}")
from mmgp import offload
- offload.load_model_data(model, model_filename)
+ offload.load_model_data(model, model_filename, preprocess_sd=preprocess_sd)
# # load_sft doesn't support torch.device
# sd = load_sft(ckpt_path, device=str(device))
diff --git a/models/hyvideo/hunyuan_handler.py b/models/hyvideo/hunyuan_handler.py
index b2c9872..45fa251 100644
--- a/models/hyvideo/hunyuan_handler.py
+++ b/models/hyvideo/hunyuan_handler.py
@@ -65,6 +65,8 @@ class family_handler():
else:
extra_model_def["profiles_dir"] = ["hunyuan_1_5"]
+ if base_model_type in [ "hunyuan_avatar", "hunyuan_custom_audio"]:
+ extra_model_def["any_audio_prompt"] = True
extra_model_def["fps"] = fps
extra_model_def["frames_minimum"] = 5
diff --git a/models/kandinsky5/kandinsky_handler.py b/models/kandinsky5/kandinsky_handler.py
index 8d98d42..8830907 100644
--- a/models/kandinsky5/kandinsky_handler.py
+++ b/models/kandinsky5/kandinsky_handler.py
@@ -103,7 +103,7 @@ class family_handler:
@staticmethod
def query_family_infos():
return {
- "kandinsky5": (60, "Kandinsky 5"),
+ "kandinsky5": (50, "Kandinsky 5"),
}
@staticmethod
diff --git a/models/ltx_video/ltxv_handler.py b/models/ltx_video/ltxv_handler.py
index 7b7f8e4..026e6af 100644
--- a/models/ltx_video/ltxv_handler.py
+++ b/models/ltx_video/ltxv_handler.py
@@ -61,7 +61,7 @@ class family_handler():
@staticmethod
def query_family_infos():
- return {"ltxv":(10, "LTX Video")}
+ return {"ltxv":(30, "LTX Video")}
@staticmethod
def register_lora_cli_args(parser):
diff --git a/models/qwen/qwen_handler.py b/models/qwen/qwen_handler.py
index e3507b6..2d62f8f 100644
--- a/models/qwen/qwen_handler.py
+++ b/models/qwen/qwen_handler.py
@@ -38,6 +38,8 @@ class family_handler():
if base_model_type in ["qwen_image_edit_20B", "qwen_image_edit_plus_20B", "qwen_image_edit_plus2_20B"]:
extra_model_def["inpaint_support"] = True
+ if base_model_type in ["qwen_image_edit_plus_20B", "qwen_image_edit_plus2_20B"]:
+ extra_model_def["inpaint_video_prompt_type"]= "VAGI"
extra_model_def["image_ref_inpaint"]= base_model_type in ["qwen_image_edit_plus_20B", "qwen_image_edit_plus2_20B"]
extra_model_def["image_ref_choices"] = {
"choices": [
@@ -93,7 +95,7 @@ class family_handler():
@staticmethod
def query_family_infos():
- return {"qwen":(40, "Qwen")}
+ return {"qwen":(110, "Qwen")}
@staticmethod
def register_lora_cli_args(parser):
diff --git a/models/qwen/qwen_main.py b/models/qwen/qwen_main.py
index 728716d..8041fc9 100644
--- a/models/qwen/qwen_main.py
+++ b/models/qwen/qwen_main.py
@@ -20,6 +20,16 @@ from PIL import Image
from shared.utils.utils import calculate_new_dimensions, convert_tensor_to_image
from shared.utils import files_locator as fl
+_QWEN_FUSED_SPLIT_MAP = {
+ "attn.to_qkv": {"mapped_modules": ("attn.to_q", "attn.to_k", "attn.to_v")},
+ "attn.add_qkv_proj": {"mapped_modules": ("attn.add_q_proj", "attn.add_k_proj", "attn.add_v_proj")},
+}
+
+
+from shared.qtypes import nunchaku_int4 as _nunchaku_int4
+_split_nunchaku_fused_qkv = _nunchaku_int4.make_nunchaku_splitter(_QWEN_FUSED_SPLIT_MAP)
+
+
def stitch_images(img1, img2):
# Resize img2 to match img1's height
width1, height1 = img1.size
@@ -76,9 +86,9 @@ class model_factory():
source = model_def.get("source", None)
if source is not None:
- offload.load_model_data(transformer, source)
+ offload.load_model_data(transformer, source, preprocess_sd=_split_nunchaku_fused_qkv)
else:
- offload.load_model_data(transformer, transformer_filename)
+ offload.load_model_data(transformer, transformer_filename, preprocess_sd=_split_nunchaku_fused_qkv)
# transformer = offload.fast_load_transformers_model("transformer_quanto.safetensors", writable_tensors= True , modelClass=QwenImageTransformer2DModel, defaultConfigPath="transformer_config.json")
if not source is None:
diff --git a/models/wan/alpha/utils.py b/models/wan/alpha/utils.py
index 8bc5a8a..fb386b6 100644
--- a/models/wan/alpha/utils.py
+++ b/models/wan/alpha/utils.py
@@ -1,11 +1,50 @@
+import os
import torchvision
from PIL import Image, ImageDraw
import imageio
import cv2
import torch
+import torch.nn.functional as F
import numpy as np
import zipfile
+_gauss_mask_cache = {}
+
+
+def load_gauss_mask(mask_path):
+ if not mask_path:
+ return None
+ abs_path = os.path.abspath(mask_path)
+ mask = _gauss_mask_cache.get(abs_path)
+ if mask is None:
+ mask = torch.load(abs_path, weights_only=False, map_location="cpu")
+ if not torch.is_tensor(mask):
+ mask = torch.tensor(mask)
+ _gauss_mask_cache[abs_path] = mask
+ return mask
+
+
+def apply_alpha_shift(latents, gauss_mask, shift_mean):
+ if gauss_mask is None:
+ return latents
+ mask = gauss_mask
+ if mask.ndim == 3:
+ mask = mask.unsqueeze(0).unsqueeze(0)
+ elif mask.ndim == 4:
+ if mask.shape[0] != 1:
+ mask = mask.unsqueeze(0)
+ if mask.shape[1] != 1:
+ mask = mask.unsqueeze(1)
+ elif mask.ndim != 5:
+ return latents
+
+ mask = mask.to(device=latents.device, dtype=latents.dtype)
+ target_shape = latents.shape[2:]
+ if mask.shape[-3:] != target_shape:
+ mask = F.interpolate(mask, size=target_shape, mode="trilinear", align_corners=False)
+ shift_mean = torch.as_tensor(shift_mean, dtype=latents.dtype, device=latents.device)
+ return latents + (1.0 - mask) * shift_mean
+
def render_video(tensor_fgr,
tensor_pha,
nrow=8,
@@ -90,4 +129,4 @@ def write_zip_file(zip_path, frames):
continue
filename = f"img_{idx:03d}.png"
- zipf.writestr(filename, buffer.tobytes())
\ No newline at end of file
+ zipf.writestr(filename, buffer.tobytes())
diff --git a/models/wan/any2video.py b/models/wan/any2video.py
index b4716e6..b6372c5 100644
--- a/models/wan/any2video.py
+++ b/models/wan/any2video.py
@@ -37,6 +37,7 @@ from shared.utils.lcm_scheduler import LCMScheduler
from shared.utils.utils import get_outpainting_frame_location, resize_lanczos, calculate_new_dimensions, convert_image_to_tensor, fit_image_into_canvas
from .multitalk.multitalk_utils import MomentumBuffer, adaptive_projected_guidance, match_and_blend_colors, match_and_blend_colors_with_mask
from .wanmove.trajectory import replace_feature, create_pos_feature_map
+from .alpha.utils import load_gauss_mask, apply_alpha_shift
from shared.utils.audio_video import save_video
from mmgp import safetensors2
from shared.utils import files_locator as fl
@@ -91,6 +92,7 @@ class WanAny2V:
self.model2 = None
self.transformer_switch = model_def.get("URLs2", None) is not None
self.is_mocha = model_def.get("mocha_mode", False)
+ self.alpha2 = base_model_type == "alpha2"
self.text_encoder = T5EncoderModel(
text_len=config.text_len,
dtype=config.t5_dtype,
@@ -120,8 +122,12 @@ class WanAny2V:
vae_upsampler_factor = 2
vae_checkpoint ="Wan2.1_VAE_upscale2x_imageonly_real_v1.safetensors"
elif model_def.get("alpha_class", False):
- vae_checkpoint ="wan_alpha_2.1_vae_rgb_channel.safetensors"
- vae_checkpoint2 ="wan_alpha_2.1_vae_alpha_channel.safetensors"
+ if self.alpha2:
+ vae_checkpoint = "wan_alpha_2.1_vae_rgb_channel_v2.safetensors"
+ vae_checkpoint2 = "wan_alpha_2.1_vae_alpha_channel_v2.safetensors"
+ else:
+ vae_checkpoint ="wan_alpha_2.1_vae_rgb_channel.safetensors"
+ vae_checkpoint2 ="wan_alpha_2.1_vae_alpha_channel.safetensors"
else:
vae_checkpoint = "Wan2.1_VAE.safetensors"
self.patch_size = config.patch_size
@@ -555,6 +561,7 @@ class WanAny2V:
recam = model_type in ["recam_1.3B"]
ti2v = model_def.get("wan_5B_class", False)
alpha_class = model_def.get("alpha_class", False)
+ alpha2 = self.alpha2
lucy_edit= model_type in ["lucy_edit"]
animate= model_type in ["animate"]
chrono_edit = model_type in ["chrono_edit"]
@@ -1080,6 +1087,9 @@ class WanAny2V:
scheduler_kwargs = {"generator": seed_g}
# b, c, lat_f, lat_h, lat_w
latents = torch.randn(batch_size, *target_shape, dtype=torch.float32, device=self.device, generator=seed_g)
+ if alpha_class and alpha2:
+ gauss_mask = load_gauss_mask(fl.locate_file("gauss_mask"))
+ latents = apply_alpha_shift(latents, gauss_mask, 0.03)
if "G" in video_prompt_type: randn = latents
if apg_switch != 0:
apg_momentum = -0.75
diff --git a/models/wan/modules/vae.py b/models/wan/modules/vae.py
index 9db4bab..1b4c173 100644
--- a/models/wan/modules/vae.py
+++ b/models/wan/modules/vae.py
@@ -1,5 +1,6 @@
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
import logging
+import os
from mmgp import offload
import torch
import torch.cuda.amp as amp
diff --git a/models/wan/wan_handler.py b/models/wan/wan_handler.py
index b205cc9..730f9e7 100644
--- a/models/wan/wan_handler.py
+++ b/models/wan/wan_handler.py
@@ -15,7 +15,7 @@ def test_class_i2v(base_model_type):
return base_model_type in ["i2v", "i2v_2_2", "fun_inp_1.3B", "fun_inp", "flf2v_720p", "fantasy", "multitalk", "infinitetalk", "i2v_2_2_multitalk", "animate", "chrono_edit", "steadydancer", "wanmove", "scail" ]
def test_class_t2v(base_model_type):
- return base_model_type in ["t2v", "t2v_2_2", "alpha", "lynx"]
+ return base_model_type in ["t2v", "t2v_2_2", "alpha", "alpha2", "lynx"]
def test_oneframe_overlap(base_model_type):
return test_class_i2v(base_model_type) and not (test_multitalk(base_model_type) or base_model_type in ["animate", "scail"]) or test_wan_5B(base_model_type)
@@ -33,7 +33,7 @@ def test_lynx(base_model_type):
return base_model_type in ["lynx_lite", "vace_lynx_lite_14B", "lynx", "vace_lynx_14B", "alpha_lynx"]
def test_alpha(base_model_type):
- return base_model_type in ["alpha", "alpha_lynx"]
+ return base_model_type in ["alpha", "alpha2", "alpha_lynx"]
def test_wan_5B(base_model_type):
return base_model_type in ["ti2v_2_2", "lucy_edit"]
@@ -43,7 +43,7 @@ class family_handler():
def query_supported_types():
return ["multitalk", "infinitetalk", "fantasy", "vace_14B", "vace_14B_2_2", "vace_multitalk_14B", "vace_standin_14B", "vace_lynx_14B",
"t2v_1.3B", "standin", "lynx_lite", "lynx", "t2v", "t2v_2_2", "vace_1.3B", "vace_ditto_14B", "phantom_1.3B", "phantom_14B",
- "recam_1.3B", "animate", "alpha", "alpha_lynx", "chrono_edit",
+ "recam_1.3B", "animate", "alpha", "alpha2", "alpha_lynx", "chrono_edit",
"i2v", "i2v_2_2", "i2v_2_2_multitalk", "ti2v_2_2", "lucy_edit", "flf2v_720p", "fun_inp_1.3B", "fun_inp", "mocha", "steadydancer", "wanmove", "scail"]
@@ -55,6 +55,7 @@ class family_handler():
"t2v_1.3B" : "t2v",
"t2v_2_2" : "t2v",
"alpha" : "t2v",
+ "alpha2" : "t2v",
"lynx" : "t2v",
"standin" : "t2v",
"vace_standin_14B" : "vace_14B",
@@ -64,7 +65,7 @@ class family_handler():
models_comp_map = {
"vace_14B" : [ "vace_multitalk_14B", "vace_standin_14B", "vace_lynx_lite_14B", "vace_lynx_14B", "vace_14B_2_2"],
- "t2v" : [ "vace_14B", "vace_1.3B" "vace_multitalk_14B", "vace_standin_14B", "vace_lynx_lite_14B", "vace_lynx_14B", "vace_14B_2_2", "t2v_1.3B", "phantom_1.3B","phantom_14B", "standin", "lynx_lite", "lynx", "alpha"],
+ "t2v" : [ "vace_14B", "vace_1.3B" "vace_multitalk_14B", "vace_standin_14B", "vace_lynx_lite_14B", "vace_lynx_14B", "vace_14B_2_2", "t2v_1.3B", "phantom_1.3B","phantom_14B", "standin", "lynx_lite", "lynx", "alpha", "alpha2"],
"i2v" : [ "fantasy", "multitalk", "flf2v_720p" ],
"i2v_2_2" : ["i2v_2_2_multitalk"],
"fantasy": ["multitalk"],
@@ -194,7 +195,12 @@ class family_handler():
extra_model_def["wan_5B_class"] = wan_5B = test_wan_5B(base_model_type)
extra_model_def["vace_class"] = vace_class = test_vace(base_model_type)
extra_model_def["color_correction"] = True
-
+
+ if multitalk or base_model_type in ["fantasy"]:
+ if multitalk:
+ extra_model_def["audio_prompt_choices"] = True
+ extra_model_def["any_audio_prompt"] = True
+
if base_model_type in ["vace_multitalk_14B", "vace_standin_14B", "vace_lynx_14B"]:
extra_model_def["parent_model_type"] = "vace_14B"
@@ -211,12 +217,12 @@ class family_handler():
group = "wan2_2"
elif test_class_1_3B(base_model_type):
profiles_dir = "wan_1.3B"
- elif base_model_type in ["alpha"]:
+ elif base_model_type in ["alpha", "alpha2"]:
profiles_dir = "wan_alpha"
else:
profiles_dir = "wan"
- if (test_class_t2v(base_model_type) or vace_class or base_model_type in ["chrono_edit"]) and not base_model_type in ["alpha"]:
+ if (test_class_t2v(base_model_type) or vace_class or base_model_type in ["chrono_edit"]) and not base_model_type in ["alpha", "alpha2"]:
extra_model_def["vae_upsampler"] = [1,2]
extra_model_def["profiles_dir"] = [profiles_dir]
@@ -946,7 +952,7 @@ class family_handler():
if test_oneframe_overlap(base_model_type):
ui_defaults["sliding_window_overlap"] = 1
- ui_defaults["color_correction_strength"]= 0
+ ui_defaults["sliding_window_color_correction_strength"]= 0
if test_multitalk(base_model_type):
ui_defaults["audio_guidance_scale"] = 4
diff --git a/models/z_image/configs/z_image_control2_1.json b/models/z_image/configs/z_image_control2_1.json
new file mode 100644
index 0000000..f37d8fe
--- /dev/null
+++ b/models/z_image/configs/z_image_control2_1.json
@@ -0,0 +1,37 @@
+{
+ "_class_name": "ZImageTransformer2DModel",
+ "_diffusers_version": "0.36.0.dev0",
+ "all_f_patch_size": [
+ 1
+ ],
+ "all_patch_size": [
+ 2
+ ],
+ "axes_dims": [
+ 32,
+ 48,
+ 48
+ ],
+ "axes_lens": [
+ 1536,
+ 512,
+ 512
+ ],
+ "cap_feat_dim": 2560,
+ "dim": 3840,
+ "in_channels": 16,
+ "n_heads": 30,
+ "n_kv_heads": 30,
+ "n_layers": 30,
+ "n_refiner_layers": 2,
+ "norm_eps": 1e-05,
+ "qk_norm": true,
+ "rope_theta": 256.0,
+ "t_scale": 1000.0,
+ "enable_control": true,
+ "control_layers_places": [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28],
+ "control_refiner_layers_places": [0, 1],
+ "add_control_noise_refiner": true,
+ "use_separate_control_refiner": true,
+ "control_in_dim": 33
+}
diff --git a/models/z_image/pipeline_z_image.py b/models/z_image/pipeline_z_image.py
index 1a9c1c5..9aac76c 100644
--- a/models/z_image/pipeline_z_image.py
+++ b/models/z_image/pipeline_z_image.py
@@ -530,7 +530,7 @@ class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):
self._num_timesteps = len(timesteps)
# Encode control image if provided and transformer supports it
- control_latent = None
+ control_latent = control_image_tensor = None
control_in_dim = self.transformer.control_in_dim
if control_image is not None and hasattr(self.transformer, 'has_control') and self.transformer.has_control:
# input_frames comes in video format [C, F, H, W] - convert to image format [B, C, H, W]
@@ -542,35 +542,40 @@ class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):
# Shape is [C, H, W] - just add batch dim
control_image_tensor = control_image_tensor.unsqueeze(0) # [1, C, H, W]
control_image_tensor = control_image_tensor.to(device=device, dtype=self.vae.dtype)
- control_latent = self.vae.encode(control_image_tensor).latent_dist.mode()
- control_latent = (control_latent - self.vae.config.shift_factor) * self.vae.config.scaling_factor
+ if inpaint_mask is None:
+ control_latent = self.vae.encode(control_image_tensor).latent_dist.mode()
+ control_latent = (control_latent - self.vae.config.shift_factor) * self.vae.config.scaling_factor
# Build control_latent_input outside the loop (doesn't change per step)
control_latent_input = None
- if control_latent is not None:
+ if control_image_tensor is not None:
# For v2 control (control_in_dim=33): concat [control_latent(16), keep_mask(1), inpaint_latent(16)]
if control_in_dim is not None and control_in_dim > num_channels_latents:
if inpaint_mask is not None:
+ inpaint_mask = inpaint_mask.to(device)
+ inpaint_image = control_image_tensor * (1-inpaint_mask) #+ inpaint_mask
+ inpaint_latent = self.vae.encode(inpaint_image).latent_dist.mode()
+ inpaint_latent = (inpaint_latent - self.vae.config.shift_factor) * self.vae.config.scaling_factor
+
+ if input_ref_images is not None and len(input_ref_images):
+ control_image_tensor = convert_image_to_tensor(input_ref_images[0]).unsqueeze(0)
+
+ control_image_tensor = control_image_tensor.to(device=device, dtype=self.vae.dtype)
+ control_latent = self.vae.encode(control_image_tensor).latent_dist.mode()
+ control_latent = (control_latent - self.vae.config.shift_factor) * self.vae.config.scaling_factor
+
mask = inpaint_mask
if mask.dim() == 3:
mask = mask.unsqueeze(0) # Add batch dim
if mask.dim() == 4 and mask.shape[1] > 1:
mask = mask[:, :1] # Take first channel only
- if mask.shape[-2:] != control_latent.shape[-2:]:
+ if mask.shape[-2:] != inpaint_latent.shape[-2:]:
mask = torch.nn.functional.interpolate(
- mask.float(), size=control_latent.shape[-2:], mode='nearest'
+ mask.float(), size=inpaint_latent.shape[-2:], mode='nearest'
)
- mask = mask.to(device=control_latent.device, dtype=control_latent.dtype)
+ mask = mask.to(device=control_latent.device, dtype=inpaint_latent.dtype)
keep_mask = 1.0 - mask
- inpaint_mask = inpaint_mask.to(device)
- inpaint_image = control_image_tensor #* (1-inpaint_mask) + inpaint_mask
- control_image_tensor = convert_image_to_tensor(input_ref_images[0]).unsqueeze(0)
- control_image_tensor = control_image_tensor.to(device=device, dtype=self.vae.dtype)
- control_latent = self.vae.encode(control_image_tensor).latent_dist.mode()
- control_latent = (control_latent - self.vae.config.shift_factor) * self.vae.config.scaling_factor
- inpaint_latent = self.vae.encode(inpaint_image).latent_dist.mode()
- inpaint_latent = (inpaint_latent - self.vae.config.shift_factor) * self.vae.config.scaling_factor
control_context = torch.cat([control_latent, keep_mask, inpaint_latent], dim=1)
else:
keep_mask = torch.zeros(
diff --git a/models/z_image/z_image_handler.py b/models/z_image/z_image_handler.py
index 2eea21a..7c0d43c 100644
--- a/models/z_image/z_image_handler.py
+++ b/models/z_image/z_image_handler.py
@@ -20,7 +20,7 @@ class family_handler:
"profiles_dir": [],
}
- if base_model_type in ["z_image_control", "z_image_control2"]:
+ if base_model_type in ["z_image_control", "z_image_control2", "z_image_control2_1"]:
extra_model_def["mask_preprocessing"] = {
"selection":[ ""],
"visible": False
@@ -34,28 +34,39 @@ class family_handler:
"labels" : { "V": "Use Z-Image Raw Format"},
}
- if base_model_type in ["z_image_control2"]:
+ if base_model_type in ["z_image_control2", "z_image_control2_1"]:
extra_model_def["mask_preprocessing"] = {
"selection":[ "", "A", "NA"],
- "visible": False,
+ "visible": False,
}
+
+ extra_model_def["inpaint_support"] = True
+ extra_model_def["inpaint_video_prompt_type"]= "VA"
+
# extra_model_def["image_ref_choices"] = {
# "choices":[("No Reference Image",""), ("Image is a Reference Image", "KI")],
# "default": "",
# "letters_filter": "KI",
# "label": "Reference Image for Inpainting",
- # "visible": False,
+ # "visible": True,
# }
extra_model_def["NAG"] = base_model_type in ["z_image"]
return extra_model_def
@staticmethod
def query_supported_types():
- return ["z_image", "z_image_control", "z_image_control2"]
+ return ["z_image", "z_image_control", "z_image_control2", "z_image_control2_1"]
@staticmethod
def query_family_maps():
- return {}, {}
+
+ models_eqv_map = {
+ "z_image_control2_1" : "z_image_control2",
+ }
+
+ models_comp_map = {}
+
+ return models_eqv_map, models_comp_map
@staticmethod
def query_model_family():
@@ -63,7 +74,7 @@ class family_handler:
@staticmethod
def query_family_infos():
- return {"z_image": (50, "Z-Image") }
+ return {"z_image": (120, "Z-Image") }
@staticmethod
def register_lora_cli_args(parser):
@@ -116,7 +127,7 @@ class family_handler:
)
# Detect if this is a control variant (v1 or v2)
- is_control = base_model_type in ["z_image_control", "z_image_control2"]
+ is_control = base_model_type in ["z_image_control", "z_image_control2", "z_image_control2_1"]
pipe_processor = model_factory(
checkpoint_dir="ckpts",
@@ -158,7 +169,7 @@ class family_handler:
)
# Add control defaults for z_image_control and z_image_control2
- if base_model_type in ["z_image_control", "z_image_control2"]:
+ if base_model_type in ["z_image_control", "z_image_control2", "z_image_control2_1"]:
ui_defaults.update(
{
"control_net_weight": 0.75,
diff --git a/models/z_image/z_image_main.py b/models/z_image/z_image_main.py
index 0368313..93ad9cd 100644
--- a/models/z_image/z_image_main.py
+++ b/models/z_image/z_image_main.py
@@ -67,6 +67,17 @@ def conv_state_dict(sd: dict) -> dict:
return out_sd
+_ZIMAGE_FUSED_SPLIT_MAP = {
+ "attention.to_qkv": {"mapped_modules": ("attention.to_q", "attention.to_k", "attention.to_v")},
+ "feed_forward.net.0.proj": {"mapped_modules": ("feed_forward.w3", "feed_forward.w1")},
+ "feed_forward.net.2": {"mapped_modules": ("feed_forward.w2",)},
+}
+
+
+from shared.qtypes import nunchaku_int4 as _nunchaku_int4
+_split_nunchaku_fused = _nunchaku_int4.make_nunchaku_splitter(_ZIMAGE_FUSED_SPLIT_MAP)
+
+
class model_factory:
def __init__(
self,
@@ -100,7 +111,9 @@ class model_factory:
default_transformer_config = os.path.join(os.path.dirname(os.path.abspath(__file__)), "configs", f"{base_model_type}.json")
- preprocess_sd = conv_state_dict
+ def preprocess_sd(state_dict, verboseLevel=1):
+ state_dict = conv_state_dict(state_dict)
+ return _split_nunchaku_fused(state_dict, verboseLevel=verboseLevel)
model_class = ZImageTransformer2DModel
diff --git a/models/z_image/z_image_transformer2d.py b/models/z_image/z_image_transformer2d.py
index 6397f79..300b7ff 100644
--- a/models/z_image/z_image_transformer2d.py
+++ b/models/z_image/z_image_transformer2d.py
@@ -394,6 +394,7 @@ class ZImageTransformer2DModel(nn.Module):
control_in_dim=None,
add_control_noise_refiner=False,
enable_control=False,
+ use_separate_control_refiner=False,
# Base model parameters
all_patch_size=(2,),
all_f_patch_size=(1,),
@@ -428,6 +429,10 @@ class ZImageTransformer2DModel(nn.Module):
self.control_refiner_layers_places = [i for i in range(0, n_refiner_layers)] if control_refiner_layers_places is None else control_refiner_layers_places
self.add_control_noise_refiner = add_control_noise_refiner
self.enable_control = enable_control
+ self.use_separate_control_refiner = use_separate_control_refiner
+
+ # Track whether the refiner uses its own control blocks (v2.1 fix)
+ self._control_noise_uses_dedicated_layers = False
assert 0 in self.control_layers_places
self.control_layers_mapping = {i: n for n, i in enumerate(self.control_layers_places)}
@@ -797,6 +802,8 @@ class ZImageTransformer2DModel(nn.Module):
if not self.enable_control or not hasattr(self, 'control_layers'):
return
+ # Assume we will fall back to legacy behavior unless we wire dedicated control refiner blocks.
+ self._control_noise_uses_dedicated_layers = False
modules_dict = {k: m for k, m in self.named_modules()}
for model_layer, control_idx in self.control_layers_mapping.items():
control_module = modules_dict[f"control_layers.{control_idx}"]
@@ -805,7 +812,20 @@ class ZImageTransformer2DModel(nn.Module):
for model_layer, control_idx in self.control_refiner_layers_mapping.items():
- control_module = modules_dict[f"control_layers.{control_idx}"]
+ control_module = None
+ if (
+ self.add_control_noise_refiner
+ and self.use_separate_control_refiner
+ and hasattr(self, "control_noise_refiner")
+ ):
+ noise_key = f"control_noise_refiner.{control_idx}"
+ control_module = modules_dict.get(noise_key, None)
+ if control_module is not None:
+ self._control_noise_uses_dedicated_layers = True
+ if control_module is None:
+ control_module = modules_dict.get(f"control_layers.{control_idx}")
+ if control_module is None:
+ continue
target = modules_dict[f"noise_refiner.{model_layer}"]
setattr(target, "control", ModuleWrapper(control_module))
@@ -1051,8 +1071,10 @@ class ZImageTransformer2DModel(nn.Module):
if control_V2:
# finish processing v2 control hints
+ control_layer_offset = 0 if getattr(self, "_control_noise_uses_dedicated_layers", False) else len(self.control_refiner_layers_places)
+ control_layers_seq = self.control_layers[control_layer_offset:]
for hints, hints_kwargs in zip(refiner_hints_tuple_list, refiner_hints_kwargs_list):
- for layer in self.control_layers[len(self.control_refiner_layers_places):]:
+ for layer in control_layers_seq:
layer(hints, **hints_kwargs)
ctrl_ctx_tensor_list.append(hints[0])
hints = hints_kwargs = None
diff --git a/profiles/qwen/Lightning Qwen Edit 2511 - 4 Steps.json b/profiles/qwen/Lightning Qwen Edit 2511 - 4 Steps.json
new file mode 100644
index 0000000..beed1ef
--- /dev/null
+++ b/profiles/qwen/Lightning Qwen Edit 2511 - 4 Steps.json
@@ -0,0 +1,8 @@
+{
+ "activated_loras": [
+ "https://huggingface.co/DeepBeepMeep/Qwen_image/resolve/main/loras_accelerators/Qwen-Image-Edit-2511-Lightning-4steps-V1.0-bf16.safetensors"
+ ],
+ "loras_multipliers": "1",
+ "num_inference_steps": 4,
+ "guidance_scale": 1
+}
diff --git a/shared/convert/convert_diffusers_to_flux.py b/shared/convert/convert_diffusers_to_flux.py
index 608b176..5c837ec 100644
--- a/shared/convert/convert_diffusers_to_flux.py
+++ b/shared/convert/convert_diffusers_to_flux.py
@@ -67,40 +67,118 @@ DIFFUSERS_MAP = {
"double_blocks.().txt_mod.lin.weight": ["norm1_context.linear.weight"],
"double_blocks.().txt_mod.lin.bias": ["norm1_context.linear.bias"],
- "double_blocks.().img_attn.qkv.weight": ["attn.to_q.weight", "attn.to_k.weight", "attn.to_v.weight"],
- "double_blocks.().img_attn.qkv.bias": ["attn.to_q.bias", "attn.to_k.bias", "attn.to_v.bias"],
- "double_blocks.().txt_attn.qkv.weight": ["attn.add_q_proj.weight", "attn.add_k_proj.weight", "attn.add_v_proj.weight"],
- "double_blocks.().txt_attn.qkv.bias": ["attn.add_q_proj.bias", "attn.add_k_proj.bias", "attn.add_v_proj.bias"],
-
- "double_blocks.().img_attn.norm.query_norm.scale": ["attn.norm_q.weight"],
- "double_blocks.().img_attn.norm.key_norm.scale": ["attn.norm_k.weight"],
- "double_blocks.().txt_attn.norm.query_norm.scale": ["attn.norm_added_q.weight"],
- "double_blocks.().txt_attn.norm.key_norm.scale": ["attn.norm_added_k.weight"],
-
- "double_blocks.().img_mlp.0.weight": ["ff.net.0.proj.weight"],
- "double_blocks.().img_mlp.0.bias": ["ff.net.0.proj.bias"],
- "double_blocks.().img_mlp.2.weight": ["ff.net.2.weight"],
- "double_blocks.().img_mlp.2.bias": ["ff.net.2.bias"],
-
- "double_blocks.().txt_mlp.0.weight": ["ff_context.net.0.proj.weight"],
- "double_blocks.().txt_mlp.0.bias": ["ff_context.net.0.proj.bias"],
- "double_blocks.().txt_mlp.2.weight": ["ff_context.net.2.weight"],
- "double_blocks.().txt_mlp.2.bias": ["ff_context.net.2.bias"],
-
- "double_blocks.().img_attn.proj.weight": ["attn.to_out.0.weight"],
- "double_blocks.().img_attn.proj.bias": ["attn.to_out.0.bias"],
- "double_blocks.().txt_attn.proj.weight": ["attn.to_add_out.weight"],
- "double_blocks.().txt_attn.proj.bias": ["attn.to_add_out.bias"],
+ "double_blocks.().img_attn.qkv.weight": [
+ ["attn.to_q.weight", "attn.to_k.weight", "attn.to_v.weight"],
+ ["qkv_proj.weight"],
+ ],
+ "double_blocks.().img_attn.qkv.bias": [
+ ["attn.to_q.bias", "attn.to_k.bias", "attn.to_v.bias"],
+ ["qkv_proj.bias"],
+ ],
+ "double_blocks.().txt_attn.qkv.weight": [
+ ["attn.add_q_proj.weight", "attn.add_k_proj.weight", "attn.add_v_proj.weight"],
+ ["qkv_proj_context.weight"],
+ ],
+ "double_blocks.().txt_attn.qkv.bias": [
+ ["attn.add_q_proj.bias", "attn.add_k_proj.bias", "attn.add_v_proj.bias"],
+ ["qkv_proj_context.bias"],
+ ],
+
+ "double_blocks.().img_attn.norm.query_norm.scale": [
+ ["attn.norm_q.weight"],
+ ["norm_q.weight"],
+ ],
+ "double_blocks.().img_attn.norm.key_norm.scale": [
+ ["attn.norm_k.weight"],
+ ["norm_k.weight"],
+ ],
+ "double_blocks.().txt_attn.norm.query_norm.scale": [
+ ["attn.norm_added_q.weight"],
+ ["norm_added_q.weight"],
+ ],
+ "double_blocks.().txt_attn.norm.key_norm.scale": [
+ ["attn.norm_added_k.weight"],
+ ["norm_added_k.weight"],
+ ],
+
+ "double_blocks.().img_mlp.0.weight": [
+ ["ff.net.0.proj.weight"],
+ ["mlp_fc1.weight"],
+ ],
+ "double_blocks.().img_mlp.0.bias": [
+ ["ff.net.0.proj.bias"],
+ ["mlp_fc1.bias"],
+ ],
+ "double_blocks.().img_mlp.2.weight": [
+ ["ff.net.2.weight"],
+ ["mlp_fc2.weight"],
+ ],
+ "double_blocks.().img_mlp.2.bias": [
+ ["ff.net.2.bias"],
+ ["mlp_fc2.bias"],
+ ],
+
+ "double_blocks.().txt_mlp.0.weight": [
+ ["ff_context.net.0.proj.weight"],
+ ["mlp_context_fc1.weight"],
+ ],
+ "double_blocks.().txt_mlp.0.bias": [
+ ["ff_context.net.0.proj.bias"],
+ ["mlp_context_fc1.bias"],
+ ],
+ "double_blocks.().txt_mlp.2.weight": [
+ ["ff_context.net.2.weight"],
+ ["mlp_context_fc2.weight"],
+ ],
+ "double_blocks.().txt_mlp.2.bias": [
+ ["ff_context.net.2.bias"],
+ ["mlp_context_fc2.bias"],
+ ],
+
+ "double_blocks.().img_attn.proj.weight": [
+ ["attn.to_out.0.weight"],
+ ["out_proj.weight"],
+ ],
+ "double_blocks.().img_attn.proj.bias": [
+ ["attn.to_out.0.bias"],
+ ["out_proj.bias"],
+ ],
+ "double_blocks.().txt_attn.proj.weight": [
+ ["attn.to_add_out.weight"],
+ ["out_proj_context.weight"],
+ ],
+ "double_blocks.().txt_attn.proj.bias": [
+ ["attn.to_add_out.bias"],
+ ["out_proj_context.bias"],
+ ],
# single-stream blocks
"single_blocks.().modulation.lin.weight": ["norm.linear.weight"],
"single_blocks.().modulation.lin.bias": ["norm.linear.bias"],
- "single_blocks.().linear1.weight": ["attn.to_q.weight", "attn.to_k.weight", "attn.to_v.weight", "proj_mlp.weight"],
- "single_blocks.().linear1.bias": ["attn.to_q.bias", "attn.to_k.bias", "attn.to_v.bias", "proj_mlp.bias"],
- "single_blocks.().norm.query_norm.scale": ["attn.norm_q.weight"],
- "single_blocks.().norm.key_norm.scale": ["attn.norm_k.weight"],
- "single_blocks.().linear2.weight": ["proj_out.weight"],
- "single_blocks.().linear2.bias": ["proj_out.bias"],
+ "single_blocks.().linear1.weight": [
+ ["attn.to_q.weight", "attn.to_k.weight", "attn.to_v.weight", "proj_mlp.weight"],
+ ["qkv_proj.weight", "mlp_fc1.weight"],
+ ],
+ "single_blocks.().linear1.bias": [
+ ["attn.to_q.bias", "attn.to_k.bias", "attn.to_v.bias", "proj_mlp.bias"],
+ ["qkv_proj.bias", "mlp_fc1.bias"],
+ ],
+ "single_blocks.().norm.query_norm.scale": [
+ ["attn.norm_q.weight"],
+ ["norm_q.weight"],
+ ],
+ "single_blocks.().norm.key_norm.scale": [
+ ["attn.norm_k.weight"],
+ ["norm_k.weight"],
+ ],
+ "single_blocks.().linear2.weight": [
+ ["proj_out.weight"],
+ ["out_proj.weight", "mlp_fc2.weight"],
+ ],
+ "single_blocks.().linear2.bias": [
+ ["proj_out.bias"],
+ ["out_proj.bias", "mlp_fc2.bias"],
+ ],
# final
"final_layer.linear.weight": ["proj_out.weight"],
@@ -110,6 +188,522 @@ DIFFUSERS_MAP = {
"final_layer.adaLN_modulation.1.bias": ["norm_out.linear.bias"],
}
+_TARGET_SUFFIXES = {}
+for _tgt_key in DIFFUSERS_MAP:
+ _base, _suffix = _tgt_key.rsplit(".", 1)
+ _TARGET_SUFFIXES.setdefault(_base, set()).add("." + _suffix)
+
+
+def _strip_prefix(key: str) -> str:
+ return key[6:] if key.startswith("model.") else key
+
+
+class StateDictSource:
+ """
+ Provide DiffusersSource-like access over an in-memory state dict.
+ """
+
+ POSSIBLE_PREFIXES = ["", "model."]
+
+ def __init__(self, state_dict: dict):
+ self._state_dict = state_dict
+ self._all_keys = list(state_dict.keys())
+
+ def _resolve(self, want: str):
+ for pref in self.POSSIBLE_PREFIXES:
+ key = pref + want
+ if key in self._state_dict:
+ return key
+ return None
+
+ def has(self, want: str) -> bool:
+ return self._resolve(want) is not None
+
+ def get(self, want: str) -> torch.Tensor:
+ real_key = self._resolve(want)
+ if real_key is None:
+ raise KeyError(f"Missing key: {want}")
+ return self._state_dict[real_key]
+
+ @property
+ def base_keys(self):
+ return [_strip_prefix(k) for k in self._all_keys]
+
+
+def detect_diffusers_state_dict(state_dict: dict) -> bool:
+ base_keys = [_strip_prefix(k) for k in state_dict.keys()]
+ if any(k.startswith(("double_blocks.", "single_blocks.")) for k in base_keys):
+ return False
+ return any(k.startswith(("transformer_blocks.", "single_transformer_blocks.")) for k in base_keys)
+
+
+def convert_state_dict(state_dict: dict, *, verbose: bool = False) -> dict:
+ if not detect_diffusers_state_dict(state_dict):
+ return state_dict
+ converted = _convert_from_source(StateDictSource(state_dict), verbose=verbose)
+ return converted if converted else state_dict
+
+
+def _count_blocks(base_keys):
+ num_dual = 0
+ num_single = 0
+ for key in base_keys:
+ if key.startswith("transformer_blocks."):
+ try:
+ idx = int(key.split(".")[1])
+ num_dual = max(num_dual, idx + 1)
+ except Exception:
+ pass
+ elif key.startswith("single_transformer_blocks."):
+ try:
+ idx = int(key.split(".")[1])
+ num_single = max(num_single, idx + 1)
+ except Exception:
+ pass
+ return num_dual, num_single
+
+
+def _swap_scale_shift(vec: torch.Tensor) -> torch.Tensor:
+ if vec is None or vec.ndim != 1 or vec.numel() % 2 != 0:
+ return vec
+ shift, scale = vec.chunk(2, dim=0)
+ return torch.cat([scale, shift], dim=0)
+
+
+def _swap_scale_shift_matrix(mat: torch.Tensor) -> torch.Tensor:
+ if mat is None or mat.ndim != 2 or mat.size(0) % 2 != 0:
+ return mat
+ shift, scale = mat.chunk(2, dim=0)
+ return torch.cat([scale, shift], dim=0)
+
+
+def _collect_suffixes(base_keys, base):
+ prefix = base + "."
+ suffixes = set()
+ for key in base_keys:
+ if key.startswith(prefix):
+ suffixes.add("." + key[len(prefix):])
+ return suffixes
+
+
+def _normalize_suffix(suffix: str) -> str:
+ if suffix == ".smooth":
+ return ".smooth_factor"
+ if suffix == ".smooth_orig":
+ return ".smooth_factor_orig"
+ if suffix == ".lora_down":
+ return ".proj_down"
+ if suffix == ".lora_up":
+ return ".proj_up"
+ return suffix
+
+
+def _match_dtype_device(ref: torch.Tensor, other: torch.Tensor) -> torch.Tensor:
+ if ref.dtype != other.dtype or ref.device != other.device:
+ return other.to(device=ref.device, dtype=ref.dtype)
+ return other
+
+
+def _concat(values, dim=0):
+ if any(v is None for v in values):
+ return None
+ ref = values[0]
+ if ref.ndim == 0:
+ return ref
+ merged = [ref] + [_match_dtype_device(ref, v) for v in values[1:]]
+ return torch.cat(merged, dim=dim)
+
+
+def _maybe_load_nunchaku():
+ try:
+ from shared.qtypes import nunchaku_int4 as _nunchaku_int4 # pylint: disable=import-outside-toplevel
+ except Exception:
+ return None
+ return _nunchaku_int4
+
+
+def _get_qweight_dims(qweight: torch.Tensor | None) -> tuple[int | None, int | None]:
+ if not torch.is_tensor(qweight):
+ return None, None
+ if qweight.dtype == torch.int8:
+ out_features = qweight.size(0)
+ else:
+ out_features = qweight.size(0) * 4
+ in_features = qweight.size(1) * 2
+ return out_features, in_features
+
+
+def _merge_packed_scales_out(values, qweights, group_size: int = 64):
+ if any(v is None for v in values):
+ return None
+ nunchaku = _maybe_load_nunchaku()
+ if nunchaku is None or any(q is None for q in qweights):
+ return _concat(values, dim=1)
+ unpacked = []
+ out_total = 0
+ in_features = None
+ for value, qweight in zip(values, qweights):
+ out_i, in_i = _get_qweight_dims(qweight)
+ if out_i is None or in_i is None:
+ return _concat(values, dim=1)
+ if in_features is None:
+ in_features = in_i
+ if in_i != in_features:
+ return _concat(values, dim=1)
+ unpacked_i = nunchaku._unpack_nunchaku_wscales(value, out_i, in_i, group_size)
+ if not torch.is_tensor(unpacked_i):
+ return _concat(values, dim=1)
+ unpacked.append(unpacked_i)
+ out_total += out_i
+ merged = [unpacked[0]] + [_match_dtype_device(unpacked[0], u) for u in unpacked[1:]]
+ merged = torch.cat(merged, dim=1)
+ return nunchaku._pack_nunchaku_wscales(merged, out_total, in_features, group_size)
+
+
+def _merge_packed_scales_in(values, qweights, group_size: int = 64):
+ if any(v is None for v in values):
+ return None
+ nunchaku = _maybe_load_nunchaku()
+ if nunchaku is None or any(q is None for q in qweights):
+ return _concat(values, dim=0)
+ out_a, in_a = _get_qweight_dims(qweights[0])
+ out_b, in_b = _get_qweight_dims(qweights[1])
+ if out_a is None or in_a is None or out_b is None or in_b is None:
+ return _concat(values, dim=0)
+ if out_a != out_b:
+ return _concat(values, dim=0)
+ unpack_a = nunchaku._unpack_nunchaku_wscales(values[0], out_a, in_a, group_size)
+ unpack_b = nunchaku._unpack_nunchaku_wscales(values[1], out_b, in_b, group_size)
+ if not torch.is_tensor(unpack_a) or not torch.is_tensor(unpack_b):
+ return _concat(values, dim=0)
+ if unpack_a.dtype != unpack_b.dtype or unpack_a.device != unpack_b.device:
+ unpack_b = unpack_b.to(device=unpack_a.device, dtype=unpack_a.dtype)
+ merged = torch.cat([unpack_a, unpack_b], dim=0)
+ return nunchaku._pack_nunchaku_wscales(merged, out_a, in_a + in_b, group_size)
+
+
+def _pad_to_multiple(tensor: torch.Tensor | None, divisor: int | tuple[int, int]):
+ if tensor is None:
+ return None
+ if isinstance(divisor, int):
+ div0 = div1 = divisor
+ else:
+ div0, div1 = divisor
+ height, width = tensor.shape
+ new_h = ((height + div0 - 1) // div0) * div0
+ new_w = ((width + div1 - 1) // div1) * div1
+ if new_h == height and new_w == width:
+ return tensor
+ padded = torch.zeros((new_h, new_w), dtype=tensor.dtype, device=tensor.device)
+ padded[:height, :width] = tensor
+ return padded
+
+
+def _pack_lowrank_weight(weight: torch.Tensor | None, down: bool):
+ if weight is None or weight.ndim != 2:
+ return weight
+ lane_n, lane_k = 1, 2
+ n_pack_size, k_pack_size = 2, 2
+ num_n_lanes, num_k_lanes = 8, 4
+ frag_n = n_pack_size * num_n_lanes * lane_n
+ frag_k = k_pack_size * num_k_lanes * lane_k
+ weight = _pad_to_multiple(weight, (frag_n, frag_k))
+ if weight is None:
+ return None
+ if down:
+ rows, cols = weight.shape
+ r_frags, c_frags = rows // frag_n, cols // frag_k
+ weight = weight.view(r_frags, frag_n, c_frags, frag_k).permute(2, 0, 1, 3)
+ else:
+ cols, rows = weight.shape
+ c_frags, r_frags = cols // frag_n, rows // frag_k
+ weight = weight.view(c_frags, frag_n, r_frags, frag_k).permute(0, 2, 1, 3)
+ weight = weight.reshape(c_frags, r_frags, n_pack_size, num_n_lanes, k_pack_size, num_k_lanes, lane_k)
+ weight = weight.permute(0, 1, 3, 5, 2, 4, 6).contiguous()
+ return weight.view(cols, rows)
+
+
+def _pack_nunchaku_w4a4_weight(qvals, out_features, in_features):
+ if qvals is None or qvals.ndim != 2:
+ return qvals
+ if qvals.dtype not in (torch.int8, torch.int16, torch.int32):
+ qvals = qvals.to(torch.int32)
+ if qvals.dtype != torch.int32:
+ qvals = qvals.to(torch.int32)
+ if qvals.shape != (out_features, in_features):
+ return None
+ mem_n = 128
+ mem_k = 64
+ num_k_unrolls = 2
+ if out_features % mem_n != 0 or in_features % (mem_k * num_k_unrolls) != 0:
+ return None
+ n_pack_size = 2
+ k_pack_size = 2
+ num_n_lanes = 8
+ num_k_lanes = 4
+ reg_n = 1
+ reg_k = 8
+ num_n_packs = mem_n // (n_pack_size * num_n_lanes * reg_n)
+ num_k_packs = mem_k // (k_pack_size * num_k_lanes * reg_k)
+ n_tiles = out_features // mem_n
+ k_tiles = in_features // mem_k
+ weight = qvals.reshape(
+ n_tiles,
+ num_n_packs,
+ n_pack_size,
+ num_n_lanes,
+ reg_n,
+ k_tiles,
+ num_k_packs,
+ k_pack_size,
+ num_k_lanes,
+ reg_k,
+ )
+ weight = weight.permute(0, 5, 6, 1, 3, 8, 2, 7, 4, 9).contiguous()
+ weight = weight.bitwise_and_(0xF)
+ shifts = torch.arange(0, 32, 4, dtype=torch.int32, device=weight.device)
+ weight = weight.bitwise_left_shift_(shifts)
+ weight = weight.sum(dim=-1, dtype=torch.int32)
+ return weight.view(dtype=torch.int8).view(out_features, -1)
+
+
+def _unpack_lowrank_weight(weight: torch.Tensor | None, down: bool):
+ if weight is None:
+ return None
+ nunchaku = _maybe_load_nunchaku()
+ if nunchaku is None:
+ return weight
+ return nunchaku._unpack_lowrank_weight(weight, down)
+
+
+def _block_diag_out(mats):
+ if not mats:
+ return None
+ ref = mats[0]
+ total_rows = sum(m.size(0) for m in mats)
+ total_cols = sum(m.size(1) for m in mats)
+ out = torch.zeros((total_rows, total_cols), dtype=ref.dtype, device=ref.device)
+ row = 0
+ col = 0
+ for mat in mats:
+ mat = _match_dtype_device(ref, mat)
+ out[row : row + mat.size(0), col : col + mat.size(1)] = mat
+ row += mat.size(0)
+ col += mat.size(1)
+ return out
+
+
+def _merge_lowrank_down(values):
+ if any(v is None for v in values):
+ return None
+ unpacked = [_unpack_lowrank_weight(v, down=True) for v in values]
+ ref = unpacked[0]
+ merged = [ref] + [_match_dtype_device(ref, v) for v in unpacked[1:]]
+ merged = torch.cat(merged, dim=0)
+ return _pack_lowrank_weight(merged, down=True)
+
+
+def _merge_lowrank_up(values):
+ if any(v is None for v in values):
+ return None
+ unpacked = [_unpack_lowrank_weight(v, down=False) for v in values]
+ merged = _block_diag_out(unpacked)
+ return _pack_lowrank_weight(merged, down=False)
+
+
+def _merge_lowrank_down_block_diag(values):
+ if any(v is None for v in values):
+ return None
+ unpacked = [_unpack_lowrank_weight(v, down=True) for v in values]
+ merged = _block_diag_out(unpacked)
+ return _pack_lowrank_weight(merged, down=True)
+
+
+def _merge_lowrank_up_concat(values):
+ if any(v is None for v in values):
+ return None
+ unpacked = [_unpack_lowrank_weight(v, down=False) for v in values]
+ ref = unpacked[0]
+ merged = [ref] + [_match_dtype_device(ref, v) for v in unpacked[1:]]
+ merged = torch.cat(merged, dim=1)
+ return _pack_lowrank_weight(merged, down=False)
+
+
+def _merge_qweight_in(values):
+ if any(v is None for v in values):
+ return None
+ a, b = values
+ out_a, in_a = _get_qweight_dims(a)
+ out_b, in_b = _get_qweight_dims(b)
+ if out_a is None or in_a is None or out_b is None or in_b is None:
+ return _concat(values, dim=1)
+ if out_a != out_b:
+ return _concat(values, dim=1)
+ nunchaku = _maybe_load_nunchaku()
+ if nunchaku is None or a.dtype != torch.int8 or b.dtype != torch.int8:
+ return _concat(values, dim=1)
+ unpack_a = nunchaku._unpack_nunchaku_w4a4_weight(a, out_a, in_a)
+ unpack_b = nunchaku._unpack_nunchaku_w4a4_weight(b, out_b, in_b)
+ if not torch.is_tensor(unpack_a) or not torch.is_tensor(unpack_b):
+ return _concat(values, dim=1)
+ if unpack_a.dtype != torch.int32:
+ unpack_a = unpack_a.to(torch.int32)
+ if unpack_b.dtype != torch.int32:
+ unpack_b = unpack_b.to(torch.int32)
+ if unpack_a.dtype != unpack_b.dtype or unpack_a.device != unpack_b.device:
+ unpack_b = unpack_b.to(device=unpack_a.device, dtype=unpack_a.dtype)
+ merged = torch.cat([unpack_a, unpack_b], dim=1)
+ packed = _pack_nunchaku_w4a4_weight(merged, out_a, in_a + in_b)
+ if packed is None:
+ return _concat(values, dim=1)
+ return packed
+
+
+def _merge_multi(values, suffix, qweights):
+ if any(v is None for v in values):
+ return None
+ if suffix in (".wscales", ".wzeros"):
+ return _merge_packed_scales_out(values, qweights)
+ if suffix == ".proj_down":
+ return _merge_lowrank_down(values)
+ if suffix == ".proj_up":
+ return _merge_lowrank_up(values)
+ if suffix in (".smooth_factor", ".smooth_factor_orig", ".input_scale", ".output_scale", ".scale_weight"):
+ return values[0]
+ return _concat(values, dim=0)
+
+
+def _merge_multi_in(values, suffix, qweights):
+ if any(v is None for v in values):
+ return None
+ if suffix == ".qweight":
+ return _merge_qweight_in(values)
+ if suffix in (".wscales", ".wzeros"):
+ return _merge_packed_scales_in(values, qweights)
+ if suffix == ".proj_down":
+ return _merge_lowrank_down_block_diag(values)
+ if suffix == ".proj_up":
+ return _merge_lowrank_up_concat(values)
+ if suffix in (".smooth_factor", ".smooth_factor_orig"):
+ return _concat(values, dim=0)
+ if suffix == ".bias":
+ ref = values[0]
+ total = ref
+ for val in values[1:]:
+ total = total + _match_dtype_device(ref, val)
+ return total
+ if suffix in (".input_scale", ".output_scale", ".scale_weight"):
+ return values[0]
+ return _concat(values, dim=1)
+
+
+def _convert_from_source(src, *, verbose: bool = False) -> dict:
+ base_keys = src.base_keys
+ num_dual, num_single = _count_blocks(base_keys)
+ if verbose:
+ print(f"Found {num_dual} dual-stream blocks, {num_single} single-stream blocks")
+
+ out = {}
+ quant_suffixes = {
+ ".qweight",
+ ".wscales",
+ ".wzeros",
+ ".smooth",
+ ".smooth_orig",
+ ".lora_down",
+ ".lora_up",
+ ".bias",
+ ".input_scale",
+ ".output_scale",
+ ".scale_weight",
+ }
+
+ def _map_entry(src_prefix, tgt_template, dvals):
+ tgt_base_template, tgt_suffix = tgt_template.rsplit(".", 1)
+ tgt_suffix = "." + tgt_suffix
+ candidates = dvals if isinstance(dvals[0], (list, tuple)) else [dvals]
+
+ for candidate in candidates:
+ src_suffix = "." + candidate[0].rsplit(".", 1)[1]
+ if any(d.rsplit(".", 1)[1] != src_suffix.lstrip(".") for d in candidate):
+ continue
+ src_bases = [d.rsplit(".", 1)[0] for d in candidate]
+ suffix_sets = [_collect_suffixes(base_keys, src_prefix + base) for base in src_bases]
+ if any(not suffix_set for suffix_set in suffix_sets):
+ continue
+ common_suffixes = set.intersection(*suffix_sets)
+ if not common_suffixes:
+ continue
+
+ explicit_suffixes = _TARGET_SUFFIXES.get(tgt_base_template, set())
+ allow_extra = src_suffix == tgt_suffix
+ if src_suffix in common_suffixes:
+ suffixes = {src_suffix}
+ if allow_extra and tgt_suffix == ".weight":
+ suffixes |= (common_suffixes - explicit_suffixes)
+ else:
+ suffixes = common_suffixes & quant_suffixes
+ if not suffixes:
+ continue
+
+ tgt_base = (
+ tgt_base_template.replace("()", str(block_idx))
+ if "()" in tgt_base_template
+ else tgt_base_template
+ )
+ merge_in_features = tgt_base_template.endswith(".linear2") and len(src_bases) > 1
+
+ for suffix in suffixes:
+ values = [src.get(src_prefix + base + suffix) for base in src_bases]
+ if len(values) == 1:
+ merged = values[0]
+ else:
+ qweights = [
+ src.get(src_prefix + base + ".qweight") if src.has(src_prefix + base + ".qweight") else None
+ for base in src_bases
+ ]
+ norm_suffix = _normalize_suffix(suffix)
+ if merge_in_features:
+ merged = _merge_multi_in(values, norm_suffix, qweights)
+ else:
+ merged = _merge_multi(values, norm_suffix, qweights)
+ if merged is None:
+ continue
+ out_suffix = tgt_suffix if suffix == src_suffix else _normalize_suffix(suffix)
+ out[tgt_base + out_suffix] = merged
+ break
+
+ for block_idx in range(num_dual):
+ prefix = f"transformer_blocks.{block_idx}."
+ for tgt_key, dvals in DIFFUSERS_MAP.items():
+ if not tgt_key.startswith("double_blocks."):
+ continue
+ _map_entry(prefix, tgt_key, dvals)
+
+ for block_idx in range(num_single):
+ prefix = f"single_transformer_blocks.{block_idx}."
+ for tgt_key, dvals in DIFFUSERS_MAP.items():
+ if not tgt_key.startswith("single_blocks."):
+ continue
+ _map_entry(prefix, tgt_key, dvals)
+
+ block_idx = None
+ for tgt_key, dvals in DIFFUSERS_MAP.items():
+ if tgt_key.startswith(("double_blocks.", "single_blocks.")):
+ continue
+ _map_entry("", tgt_key, dvals)
+
+ if "final_layer.adaLN_modulation.1.weight" in out:
+ out["final_layer.adaLN_modulation.1.weight"] = _swap_scale_shift_matrix(
+ out["final_layer.adaLN_modulation.1.weight"]
+ )
+ if "final_layer.adaLN_modulation.1.bias" in out:
+ out["final_layer.adaLN_modulation.1.bias"] = _swap_scale_shift(
+ out["final_layer.adaLN_modulation.1.bias"]
+ )
+
+ return out
+
class DiffusersSource:
"""
@@ -212,81 +806,7 @@ class DiffusersSource:
def main():
args = parse_args()
src = DiffusersSource(Path(args.diffusers_path))
-
- # Count blocks by scanning base keys (with any 'model.' prefix removed)
- num_dual = 0
- num_single = 0
- for k in src.base_keys:
- if k.startswith("transformer_blocks."):
- try:
- i = int(k.split(".")[1])
- num_dual = max(num_dual, i + 1)
- except Exception:
- pass
- elif k.startswith("single_transformer_blocks."):
- try:
- i = int(k.split(".")[1])
- num_single = max(num_single, i + 1)
- except Exception:
- pass
- print(f"Found {num_dual} dual-stream blocks, {num_single} single-stream blocks")
-
- # Swap [shift, scale] -> [scale, shift] (weights are concatenated along dim=0)
- def swap_scale_shift(vec: torch.Tensor) -> torch.Tensor:
- shift, scale = vec.chunk(2, dim=0)
- return torch.cat([scale, shift], dim=0)
-
- orig = {}
-
- # Per-block (dual)
- for b in range(num_dual):
- prefix = f"transformer_blocks.{b}."
- for okey, dvals in DIFFUSERS_MAP.items():
- if not okey.startswith("double_blocks."):
- continue
- dkeys = [prefix + v for v in dvals]
- if not all(src.has(k) for k in dkeys):
- continue
- if len(dkeys) == 1:
- orig[okey.replace("()", str(b))] = src.get(dkeys[0])
- else:
- orig[okey.replace("()", str(b))] = torch.cat([src.get(k) for k in dkeys], dim=0)
-
- # Per-block (single)
- for b in range(num_single):
- prefix = f"single_transformer_blocks.{b}."
- for okey, dvals in DIFFUSERS_MAP.items():
- if not okey.startswith("single_blocks."):
- continue
- dkeys = [prefix + v for v in dvals]
- if not all(src.has(k) for k in dkeys):
- continue
- if len(dkeys) == 1:
- orig[okey.replace("()", str(b))] = src.get(dkeys[0])
- else:
- orig[okey.replace("()", str(b))] = torch.cat([src.get(k) for k in dkeys], dim=0)
-
- # Globals (non-block)
- for okey, dvals in DIFFUSERS_MAP.items():
- if okey.startswith(("double_blocks.", "single_blocks.")):
- continue
- dkeys = dvals
- if not all(src.has(k) for k in dkeys):
- continue
- if len(dkeys) == 1:
- orig[okey] = src.get(dkeys[0])
- else:
- orig[okey] = torch.cat([src.get(k) for k in dkeys], dim=0)
-
- # Fix final_layer.adaLN_modulation.1.{weight,bias} by swapping scale/shift halves
- if "final_layer.adaLN_modulation.1.weight" in orig:
- orig["final_layer.adaLN_modulation.1.weight"] = swap_scale_shift(
- orig["final_layer.adaLN_modulation.1.weight"]
- )
- if "final_layer.adaLN_modulation.1.bias" in orig:
- orig["final_layer.adaLN_modulation.1.bias"] = swap_scale_shift(
- orig["final_layer.adaLN_modulation.1.bias"]
- )
+ orig = _convert_from_source(src, verbose=True)
# Optional FP8 variants (experimental; not required for ComfyUI/BFL)
if args.fp8 or args.fp8_scaled:
diff --git a/shared/qtypes/__init__.py b/shared/qtypes/__init__.py
new file mode 100644
index 0000000..2b23acd
--- /dev/null
+++ b/shared/qtypes/__init__.py
@@ -0,0 +1 @@
+"""Shared qtypes registry for custom quantization handlers."""
diff --git a/shared/qtypes/nunchaku_int4.py b/shared/qtypes/nunchaku_int4.py
new file mode 100644
index 0000000..2b7a75f
--- /dev/null
+++ b/shared/qtypes/nunchaku_int4.py
@@ -0,0 +1,1102 @@
+import ast
+import sys
+import types
+from types import SimpleNamespace
+from pathlib import Path
+
+import torch
+
+from optimum.quanto import QModuleMixin
+from optimum.quanto.tensor.qtensor import QTensor
+from optimum.quanto.tensor.qtype import qtype as _quanto_qtype, qtypes as _quanto_qtypes
+
+
+HANDLER_NAME = "nunchaku_int4"
+
+_NUNCHAKU_INT4_QTYPE_NAME = "nunchaku_int4"
+if _NUNCHAKU_INT4_QTYPE_NAME not in _quanto_qtypes:
+ _quanto_qtypes[_NUNCHAKU_INT4_QTYPE_NAME] = _quanto_qtype(
+ _NUNCHAKU_INT4_QTYPE_NAME,
+ is_floating_point=False,
+ bits=4,
+ dtype=torch.int8,
+ qmin=-8.0,
+ qmax=7.0,
+ )
+
+_NUNCHAKU_INT4_QTYPE = _quanto_qtypes[_NUNCHAKU_INT4_QTYPE_NAME]
+_NUNCHAKU_OPS = None
+_NUNCHAKU_SPLIT_FIELDS = {
+ "qweight": 0,
+ "wscales": 1,
+ "wzeros": 1,
+ "proj_up": 0,
+ "bias": 0,
+}
+_NUNCHAKU_SHARED_FIELDS = (
+ "proj_down",
+ "smooth_factor",
+ "smooth_factor_orig",
+ "input_scale",
+ "output_scale",
+)
+
+
+def get_nunchaku_split_kwargs():
+ return {
+ "split_fields": dict(_NUNCHAKU_SPLIT_FIELDS),
+ "share_fields": _NUNCHAKU_SHARED_FIELDS,
+ "split_handlers": {
+ "wscales": split_packed_wscales,
+ "wzeros": split_packed_wscales,
+ },
+ }
+
+
+def make_nunchaku_splitter(split_map):
+ def _split(state_dict, verboseLevel=1):
+ from mmgp import offload
+ split_kwargs = get_nunchaku_split_kwargs()
+ return offload.sd_split_linear(
+ state_dict,
+ split_map,
+ verboseLevel=verboseLevel,
+ **split_kwargs,
+ )
+ return _split
+
+
+def _install_nunchaku_shim(candidate_root):
+ candidate_pkg = candidate_root / "nunchaku"
+ if not candidate_pkg.exists():
+ return False
+ if "nunchaku" in sys.modules:
+ del sys.modules["nunchaku"]
+ shim = types.ModuleType("nunchaku")
+ shim.__path__ = [str(candidate_pkg)]
+ sys.modules["nunchaku"] = shim
+ return True
+
+
+def _load_nunchaku_ops():
+ global _NUNCHAKU_OPS
+ # _NUNCHAKU_OPS = False
+ if _NUNCHAKU_OPS is not None:
+ return _NUNCHAKU_OPS
+
+ try:
+ from nunchaku.ops.gemm import svdq_gemm_w4a4_cuda
+ from nunchaku.ops.quantize import svdq_quantize_w4a4_act_fuse_lora_cuda
+ from nunchaku.ops.gemv import awq_gemv_w4a16_cuda
+ except Exception:
+ repo_root = Path(__file__).resolve().parents[1]
+ candidate = repo_root / "kernels" / "nunchaku"
+ if candidate.exists() and str(candidate) not in sys.path:
+ sys.path.insert(0, str(candidate))
+ _install_nunchaku_shim(candidate)
+ try:
+ from nunchaku.ops.gemm import svdq_gemm_w4a4_cuda
+ from nunchaku.ops.quantize import svdq_quantize_w4a4_act_fuse_lora_cuda
+ from nunchaku.ops.gemv import awq_gemv_w4a16_cuda
+ except Exception:
+ _NUNCHAKU_OPS = False
+ return _NUNCHAKU_OPS
+
+ _NUNCHAKU_OPS = SimpleNamespace(
+ svdq_gemm_w4a4_cuda=svdq_gemm_w4a4_cuda,
+ svdq_quantize_w4a4_act_fuse_lora_cuda=svdq_quantize_w4a4_act_fuse_lora_cuda,
+ awq_gemv_w4a16_cuda=awq_gemv_w4a16_cuda,
+ )
+ return _NUNCHAKU_OPS
+
+
+def _as_dtype_name(dtype_str):
+ if dtype_str.startswith("torch."):
+ return dtype_str.split(".", 1)[1]
+ return dtype_str
+
+
+def _expand_group_scales(scales, group_size):
+ scales_t = scales.transpose(0, 1)
+ return scales_t.repeat_interleave(group_size, dim=1)
+
+
+def _unpack_nunchaku_wscales(wscales, out_features, in_features, group_size):
+ if wscales is None or wscales.ndim != 2:
+ return wscales
+ if in_features % group_size != 0:
+ return wscales
+ groups = in_features // group_size
+ if wscales.shape != (groups, out_features):
+ return wscales
+ warp_n = 128
+ num_lanes = 32
+ s_pack_size = min(max(warp_n // num_lanes, 2), 8)
+ num_s_lanes = min(num_lanes, warp_n // s_pack_size)
+ num_s_packs = warp_n // (s_pack_size * num_s_lanes)
+ warp_s = num_s_packs * num_s_lanes * s_pack_size
+ if out_features % warp_s != 0:
+ return wscales
+ packed = wscales.view(
+ out_features // warp_s,
+ groups,
+ num_s_packs,
+ num_s_lanes // 4,
+ 4,
+ s_pack_size // 2,
+ 2,
+ )
+ unpacked = packed.permute(0, 2, 3, 5, 4, 6, 1).contiguous()
+ return unpacked.view(out_features, groups).transpose(0, 1).contiguous()
+
+
+def _pack_nunchaku_wscales(wscales, out_features, in_features, group_size):
+ if wscales is None or wscales.ndim != 2:
+ return wscales
+ if in_features % group_size != 0:
+ return wscales
+ groups = in_features // group_size
+ if wscales.shape != (groups, out_features):
+ return wscales
+ warp_n = 128
+ num_lanes = 32
+ s_pack_size = min(max(warp_n // num_lanes, 2), 8)
+ num_s_lanes = min(num_lanes, warp_n // s_pack_size)
+ num_s_packs = warp_n // (s_pack_size * num_s_lanes)
+ warp_s = num_s_packs * num_s_lanes * s_pack_size
+ if out_features % warp_s != 0:
+ return wscales
+ unpacked = wscales.transpose(0, 1).contiguous()
+ unpacked = unpacked.view(
+ out_features // warp_s,
+ num_s_packs,
+ num_s_lanes // 4,
+ s_pack_size // 2,
+ 4,
+ 2,
+ groups,
+ )
+ packed = unpacked.permute(0, 6, 1, 2, 4, 3, 5).contiguous()
+ return packed.view(groups, out_features)
+
+
+def split_packed_wscales(src, *, dim, split_sizes, context):
+ if src is None or dim != 1:
+ return None
+ ctx = context or {}
+ field_tensors = ctx.get("field_tensors") or {}
+ qweight = field_tensors.get("qweight")
+ if not torch.is_tensor(qweight) or qweight.dtype not in (torch.int8, torch.int32):
+ return None
+ info = ctx.get("info") or {}
+ group_size = info.get("group_size", ctx.get("group_size", 64))
+ if not isinstance(group_size, int) or group_size <= 0:
+ group_size = 64
+ if qweight.dtype == torch.int8:
+ out_features = qweight.size(0)
+ else:
+ out_features = qweight.size(0) * 4
+ in_features = qweight.size(1) * 2
+ total = sum(split_sizes)
+ unpacked = _unpack_nunchaku_wscales(src, out_features, in_features, group_size)
+ if not torch.is_tensor(unpacked):
+ return None
+ if unpacked.shape != (in_features // group_size, total):
+ return None
+ unpacked_chunks = torch.split(unpacked, split_sizes, dim=1)
+ return [
+ _pack_nunchaku_wscales(chunk, size, in_features, group_size)
+ for chunk, size in zip(unpacked_chunks, split_sizes)
+ ]
+
+
+def _unpack_nunchaku_scale_vector(scale, size):
+ if scale is None or scale.ndim != 1 or scale.numel() != size:
+ return scale
+ warp_n = 128
+ num_lanes = 32
+ s_pack_size = min(max(warp_n // num_lanes, 2), 8)
+ num_s_lanes = min(num_lanes, warp_n // s_pack_size)
+ num_s_packs = warp_n // (s_pack_size * num_s_lanes)
+ warp_s = num_s_packs * num_s_lanes * s_pack_size
+ if size % warp_s != 0:
+ return scale
+ packed = scale.reshape(size // warp_s, 1, num_s_packs, num_s_lanes // 4, 4, s_pack_size // 2, 2)
+ unpacked = packed.permute(0, 2, 3, 5, 4, 6, 1).contiguous()
+ return unpacked.view(size)
+
+
+def _unpack_int4_from_int8(qweight):
+ q = qweight.to(torch.uint8)
+ low = q & 0x0F
+ high = (q >> 4) & 0x0F
+ low = low.to(torch.int16)
+ high = high.to(torch.int16)
+ low -= (low >= 8).to(torch.int16) * 16
+ high -= (high >= 8).to(torch.int16) * 16
+ stacked = torch.stack((low, high), dim=-1)
+ out = stacked.reshape(qweight.shape[0], qweight.shape[1] * 2)
+ return out
+
+
+def _unpack_nunchaku_w4a4_weight(qweight, out_features, in_features):
+ if qweight.dtype != torch.int8:
+ return _unpack_int4_from_int8(qweight)
+ if qweight.numel() != out_features * in_features // 2:
+ return _unpack_int4_from_int8(qweight)
+ mem_n = 128
+ mem_k = 64
+ num_k_unrolls = 2
+ if out_features % mem_n != 0 or in_features % (mem_k * num_k_unrolls) != 0:
+ return _unpack_int4_from_int8(qweight)
+
+ n_tiles = out_features // mem_n
+ k_tiles = in_features // mem_k
+ packed_i32 = qweight.view(torch.int32)
+ packed_i32 = packed_i32.view(n_tiles, k_tiles, 1, 8, 8, 4, 2, 2, 1)
+ shifts = torch.tensor([0, 4, 8, 12, 16, 20, 24, 28], device=packed_i32.device, dtype=torch.int32)
+ vals = (packed_i32.unsqueeze(-1) >> shifts) & 0xF
+ vals = vals.permute(0, 3, 6, 4, 8, 1, 2, 7, 5, 9).contiguous()
+ vals = vals.view(out_features, in_features).to(torch.int16)
+ vals -= (vals >= 8).to(torch.int16) * 16
+ return vals
+
+
+def _unpack_int4_from_int32(qweight, out_features, in_features):
+ if (
+ qweight.dtype == torch.int32
+ and out_features % 4 == 0
+ and in_features % 64 == 0
+ and qweight.shape[0] * 4 == out_features
+ and qweight.shape[1] * 2 == in_features
+ ):
+ packed_i16 = qweight.view(torch.int16)
+ packed = packed_i16.view(out_features // 4, in_features // 64, 4, 16)
+ packed = packed.permute(0, 2, 1, 3).contiguous().view(-1, 8)
+ packed = packed.to(torch.int32) & 0xFFFF
+ vals0 = packed & 0xF
+ vals1 = (packed >> 4) & 0xF
+ vals2 = (packed >> 8) & 0xF
+ vals3 = (packed >> 12) & 0xF
+ vals = torch.stack((vals0, vals1, vals2, vals3), dim=1)
+ return vals.reshape(out_features, in_features)
+
+ q = qweight.view(torch.int32).reshape(out_features, in_features // 8)
+ q = q.to(torch.int64) & 0xFFFFFFFF
+ shifts = torch.arange(0, 32, 4, device=q.device, dtype=torch.int64)
+ mask = torch.tensor(0x0F, device=q.device, dtype=torch.int64)
+ vals = (q.unsqueeze(-1) >> shifts) & mask
+ return vals.reshape(out_features, in_features)
+
+
+def _unpack_lowrank_weight(weight, down):
+ if weight is None or weight.ndim != 2:
+ return weight
+ c, r = weight.shape
+ reg_n = 1
+ reg_k = 2
+ n_pack_size = 2
+ k_pack_size = 2
+ num_n_lanes = 8
+ num_k_lanes = 4
+ pack_n = n_pack_size * num_n_lanes * reg_n
+ pack_k = k_pack_size * num_k_lanes * reg_k
+ if down:
+ if r % pack_n != 0 or c % pack_k != 0:
+ return weight
+ r_packs, c_packs = r // pack_n, c // pack_k
+ else:
+ if c % pack_n != 0 or r % pack_k != 0:
+ return weight
+ c_packs, r_packs = c // pack_n, r // pack_k
+ weight = weight.view(
+ c_packs, r_packs, num_n_lanes, num_k_lanes, n_pack_size, k_pack_size, reg_n, reg_k
+ )
+ weight = weight.permute(0, 1, 4, 2, 6, 5, 3, 7).contiguous()
+ weight = weight.view(c_packs, r_packs, pack_n, pack_k)
+ if down:
+ weight = weight.permute(1, 2, 0, 3).contiguous().view(r, c)
+ else:
+ weight = weight.permute(0, 2, 1, 3).contiguous().view(c, r)
+ return weight
+
+
+def _nunchaku_qfallback(callable, *args, **kwargs):
+ args, kwargs = torch.utils._pytree.tree_map_only(
+ NunchakuBaseWeightTensor, lambda x: x.dequantize(), (args, kwargs or {})
+ )
+ return callable(*args, **kwargs)
+
+
+class NunchakuBaseWeightTensor(QTensor):
+ def __init__(self, qtype, axis):
+ super().__init__(qtype, axis)
+
+ def get_quantized_subtensors(self):
+ raise NotImplementedError
+
+ def set_quantized_subtensors(self, sub_tensors):
+ raise NotImplementedError
+
+
+class NunchakuSVDQWeightTensor(NunchakuBaseWeightTensor):
+ @staticmethod
+ def create(
+ qweight,
+ wscales,
+ smooth_factor,
+ proj_down,
+ proj_up,
+ size,
+ stride,
+ dtype,
+ device=None,
+ requires_grad=False,
+ ):
+ device = qweight.device if device is None else device
+ if qweight.device != device:
+ qweight = qweight.to(device)
+ if wscales.device != device:
+ wscales = wscales.to(device)
+ if smooth_factor.device != device:
+ smooth_factor = smooth_factor.to(device)
+ if proj_down.device != device:
+ proj_down = proj_down.to(device)
+ if proj_up.device != device:
+ proj_up = proj_up.to(device)
+ if dtype in (torch.float16, torch.bfloat16):
+ if wscales.dtype in (torch.float16, torch.bfloat16) and wscales.dtype != dtype:
+ wscales = wscales.to(dtype)
+ if smooth_factor.dtype in (torch.float16, torch.bfloat16) and smooth_factor.dtype != dtype:
+ smooth_factor = smooth_factor.to(dtype)
+ if proj_down.dtype in (torch.float16, torch.bfloat16) and proj_down.dtype != dtype:
+ proj_down = proj_down.to(dtype)
+ if proj_up.dtype in (torch.float16, torch.bfloat16) and proj_up.dtype != dtype:
+ proj_up = proj_up.to(dtype)
+ return NunchakuSVDQWeightTensor(
+ qtype=_NUNCHAKU_INT4_QTYPE,
+ axis=0,
+ size=size,
+ stride=stride,
+ qweight=qweight,
+ wscales=wscales,
+ smooth_factor=smooth_factor,
+ proj_down=proj_down,
+ proj_up=proj_up,
+ dtype=dtype,
+ requires_grad=requires_grad,
+ )
+
+ @staticmethod
+ def __new__(
+ cls,
+ qtype,
+ axis,
+ size,
+ stride,
+ qweight,
+ wscales,
+ smooth_factor,
+ proj_down,
+ proj_up,
+ dtype,
+ requires_grad=False,
+ ):
+ return torch.Tensor._make_wrapper_subclass(
+ cls,
+ size,
+ strides=stride,
+ dtype=dtype,
+ device=qweight.device,
+ requires_grad=requires_grad,
+ )
+
+ def __init__(
+ self,
+ qtype,
+ axis,
+ size,
+ stride,
+ qweight,
+ wscales,
+ smooth_factor,
+ proj_down,
+ proj_up,
+ dtype,
+ requires_grad=False,
+ ):
+ super().__init__(qtype, axis)
+ self._qweight = qweight
+ self._wscales = wscales
+ self._smooth_factor = smooth_factor
+ self._proj_down = proj_down
+ self._proj_up = proj_up
+ self._group_size = 64
+ self._act_unsigned = False
+
+ def dequantize(self, dtype=None, device=None):
+ if dtype is None:
+ dtype = self.dtype
+ if device is None:
+ device = self.device
+ qweight = self._qweight.to(device)
+ wscales = self._wscales.to(device)
+ proj_down = self._proj_down.to(device)
+ proj_up = self._proj_up.to(device)
+
+ qvals = _unpack_nunchaku_w4a4_weight(qweight, *self.shape).to(dtype)
+ wscales = _unpack_nunchaku_wscales(wscales, self.shape[0], self.shape[1], self._group_size)
+ scales = _expand_group_scales(wscales, self._group_size).to(dtype)
+ weight = qvals * scales
+ proj_down = _unpack_lowrank_weight(proj_down, down=True)
+ proj_up = _unpack_lowrank_weight(proj_up, down=False)
+ weight = weight + proj_up.to(dtype) @ proj_down.to(dtype)
+ smooth = self._smooth_factor
+ if smooth is not None and smooth.ndim == 1 and smooth.numel() == self.shape[1]:
+ smooth = _unpack_nunchaku_scale_vector(smooth, self.shape[1])
+ smooth = smooth.to(device)
+ if smooth.dtype != dtype:
+ smooth = smooth.to(dtype)
+ weight = weight / smooth.unsqueeze(0)
+ return weight
+
+ def _linear_fallback(self, input, bias=None):
+ x = input.reshape(-1, input.shape[-1])
+ weight = self.dequantize(dtype=x.dtype, device=x.device)
+ out = x.matmul(weight.t())
+ if bias is not None:
+ out.add_(bias)
+ return out.reshape(*input.shape[:-1], weight.shape[0])
+
+ def _linear_cuda(self, input, bias=None):
+ ops = _load_nunchaku_ops()
+ if not ops:
+ return self._linear_fallback(input, bias=bias)
+
+ x = input.reshape(-1, input.shape[-1])
+ qx, ascales, lora_act = ops.svdq_quantize_w4a4_act_fuse_lora_cuda(
+ x,
+ lora_down=self._proj_down,
+ smooth=self._smooth_factor,
+ fp4=False,
+ pad_size=256,
+ )
+ out = torch.empty(qx.shape[0], self.shape[0], dtype=self._proj_up.dtype, device=qx.device)
+ if bias is not None and bias.dtype != out.dtype:
+ bias = bias.to(out.dtype)
+ ops.svdq_gemm_w4a4_cuda(
+ act=qx,
+ wgt=self._qweight,
+ out=out,
+ ascales=ascales,
+ wscales=self._wscales,
+ lora_act_in=lora_act,
+ lora_up=self._proj_up,
+ bias=bias,
+ fp4=False,
+ alpha=1.0,
+ wcscales=None,
+ act_unsigned=self._act_unsigned,
+ )
+ out = out[: x.shape[0]]
+ return out.reshape(*input.shape[:-1], self.shape[0])
+
+ def linear(self, input, bias=None):
+ if torch.is_tensor(input) and input.device.type == "cuda":
+ return self._linear_cuda(input, bias=bias)
+ return self._linear_fallback(input, bias=bias)
+
+ def get_quantized_subtensors(self):
+ return [
+ ("qweight", self._qweight),
+ ("wscales", self._wscales),
+ ("smooth_factor", self._smooth_factor),
+ ("proj_down", self._proj_down),
+ ("proj_up", self._proj_up),
+ ]
+
+ def set_quantized_subtensors(self, sub_tensors):
+ if isinstance(sub_tensors, dict):
+ sub_map = sub_tensors
+ else:
+ sub_map = {name: tensor for name, tensor in sub_tensors}
+ if "qweight" in sub_map and sub_map["qweight"] is not None:
+ self._qweight = sub_map["qweight"]
+ if "wscales" in sub_map and sub_map["wscales"] is not None:
+ self._wscales = sub_map["wscales"]
+ if "smooth_factor" in sub_map and sub_map["smooth_factor"] is not None:
+ self._smooth_factor = sub_map["smooth_factor"]
+ if "proj_down" in sub_map and sub_map["proj_down"] is not None:
+ self._proj_down = sub_map["proj_down"]
+ if "proj_up" in sub_map and sub_map["proj_up"] is not None:
+ self._proj_up = sub_map["proj_up"]
+
+ def __tensor_flatten__(self):
+ inner_tensors = ["_qweight", "_wscales", "_smooth_factor", "_proj_down", "_proj_up"]
+ meta = {
+ "qtype": self._qtype.name,
+ "axis": str(self._axis),
+ "size": str(list(self.size())),
+ "stride": str(list(self.stride())),
+ "dtype": str(self.dtype),
+ "group_size": str(self._group_size),
+ "kind": "svdq",
+ }
+ return inner_tensors, meta
+
+ @staticmethod
+ def __tensor_unflatten__(inner_tensors, meta, outer_size, outer_stride):
+ qtype = _quanto_qtypes[meta["qtype"]]
+ axis = ast.literal_eval(meta["axis"])
+ size = ast.literal_eval(meta["size"])
+ stride = ast.literal_eval(meta["stride"])
+ dtype_name = _as_dtype_name(meta.get("dtype", "torch.float16"))
+ dtype = getattr(torch, dtype_name, torch.float16)
+ return NunchakuSVDQWeightTensor(
+ qtype=qtype,
+ axis=axis,
+ size=size,
+ stride=stride,
+ qweight=inner_tensors["_qweight"],
+ wscales=inner_tensors["_wscales"],
+ smooth_factor=inner_tensors["_smooth_factor"],
+ proj_down=inner_tensors["_proj_down"],
+ proj_up=inner_tensors["_proj_up"],
+ dtype=dtype,
+ )
+
+ @classmethod
+ def __torch_dispatch__(cls, op, types, args, kwargs=None):
+ op = op.overloadpacket
+ kwargs = kwargs or {}
+ if op is torch.ops.aten.linear:
+ input = args[0]
+ weight = args[1]
+ bias = args[2] if len(args) > 2 else None
+ if isinstance(weight, NunchakuSVDQWeightTensor):
+ return weight.linear(input, bias=bias)
+ if op is torch.ops.aten.detach:
+ t = args[0]
+ return NunchakuSVDQWeightTensor.create(
+ qweight=op(t._qweight),
+ wscales=op(t._wscales),
+ smooth_factor=op(t._smooth_factor),
+ proj_down=op(t._proj_down),
+ proj_up=op(t._proj_up),
+ size=t.size(),
+ stride=t.stride(),
+ dtype=t.dtype,
+ device=t.device,
+ requires_grad=t.requires_grad,
+ )
+ if op in (torch.ops.aten._to_copy, torch.ops.aten.to):
+ t = args[0]
+ dtype = kwargs.pop("dtype", t.dtype) if kwargs else t.dtype
+ device = kwargs.pop("device", t.device) if kwargs else t.device
+ if dtype != t.dtype:
+ return t.dequantize(dtype=dtype, device=device)
+ out_qweight = op(t._qweight, device=device, **(kwargs or {}))
+ out_wscales = op(t._wscales, device=device, **(kwargs or {}))
+ out_smooth = op(t._smooth_factor, device=device, **(kwargs or {}))
+ out_proj_down = op(t._proj_down, device=device, **(kwargs or {}))
+ out_proj_up = op(t._proj_up, device=device, **(kwargs or {}))
+ return NunchakuSVDQWeightTensor.create(
+ qweight=out_qweight,
+ wscales=out_wscales,
+ smooth_factor=out_smooth,
+ proj_down=out_proj_down,
+ proj_up=out_proj_up,
+ size=t.size(),
+ stride=t.stride(),
+ dtype=t.dtype,
+ device=device,
+ requires_grad=t.requires_grad,
+ )
+ return _nunchaku_qfallback(op, *args, **(kwargs or {}))
+
+
+class NunchakuAWQWeightTensor(NunchakuBaseWeightTensor):
+ @staticmethod
+ def create(
+ qweight,
+ wscales,
+ wzeros,
+ size,
+ stride,
+ dtype,
+ device=None,
+ requires_grad=False,
+ ):
+ device = qweight.device if device is None else device
+ if qweight.device != device:
+ qweight = qweight.to(device)
+ if wscales.device != device:
+ wscales = wscales.to(device)
+ if wzeros.device != device:
+ wzeros = wzeros.to(device)
+ if dtype in (torch.float16, torch.bfloat16):
+ if wscales.dtype in (torch.float16, torch.bfloat16) and wscales.dtype != dtype:
+ wscales = wscales.to(dtype)
+ if wzeros.dtype in (torch.float16, torch.bfloat16) and wzeros.dtype != dtype:
+ wzeros = wzeros.to(dtype)
+ return NunchakuAWQWeightTensor(
+ qtype=_NUNCHAKU_INT4_QTYPE,
+ axis=0,
+ size=size,
+ stride=stride,
+ qweight=qweight,
+ wscales=wscales,
+ wzeros=wzeros,
+ dtype=dtype,
+ requires_grad=requires_grad,
+ )
+
+ @staticmethod
+ def __new__(
+ cls,
+ qtype,
+ axis,
+ size,
+ stride,
+ qweight,
+ wscales,
+ wzeros,
+ dtype,
+ requires_grad=False,
+ ):
+ return torch.Tensor._make_wrapper_subclass(
+ cls,
+ size,
+ strides=stride,
+ dtype=dtype,
+ device=qweight.device,
+ requires_grad=requires_grad,
+ )
+
+ def __init__(
+ self,
+ qtype,
+ axis,
+ size,
+ stride,
+ qweight,
+ wscales,
+ wzeros,
+ dtype,
+ requires_grad=False,
+ ):
+ super().__init__(qtype, axis)
+ self._qweight = qweight
+ self._wscales = wscales
+ self._wzeros = wzeros
+ self._group_size = 64
+
+ def dequantize(self, dtype=None, device=None):
+ if dtype is None:
+ dtype = self.dtype
+ if device is None:
+ device = self.device
+ out_features, in_features = self.shape
+ qweight = self._qweight.to(device)
+ wscales = self._wscales.to(device)
+ wzeros = self._wzeros.to(device)
+ qvals = _unpack_int4_from_int32(qweight, out_features, in_features).to(dtype)
+ wscales = _unpack_nunchaku_wscales(wscales, out_features, in_features, self._group_size)
+ wzeros = _unpack_nunchaku_wscales(wzeros, out_features, in_features, self._group_size)
+ scales = _expand_group_scales(wscales, self._group_size).to(dtype)
+ zeros = _expand_group_scales(wzeros, self._group_size).to(dtype)
+ return qvals * scales + zeros
+
+ def _linear_fallback(self, input, bias=None):
+ x = input.reshape(-1, input.shape[-1])
+ weight = self.dequantize(dtype=x.dtype, device=x.device)
+ out = x.matmul(weight.t())
+ if bias is not None:
+ out.add_(bias)
+ return out.reshape(*input.shape[:-1], weight.shape[0])
+
+ def _linear_cuda(self, input, bias=None):
+ ops = _load_nunchaku_ops()
+ if not ops:
+ return self._linear_fallback(input, bias=bias)
+
+ x = input.reshape(-1, input.shape[-1])
+ out = ops.awq_gemv_w4a16_cuda(
+ in_feats=x,
+ kernel=self._qweight,
+ scaling_factors=self._wscales,
+ zeros=self._wzeros,
+ m=x.shape[0],
+ n=self.shape[0],
+ k=x.shape[1],
+ group_size=self._group_size,
+ )
+ if bias is not None:
+ view_shape = [1] * (out.ndim - 1) + [-1]
+ out.add_(bias.view(view_shape))
+ return out.reshape(*input.shape[:-1], out.shape[-1])
+
+ def linear(self, input, bias=None):
+ if torch.is_tensor(input) and input.device.type == "cuda":
+ return self._linear_cuda(input, bias=bias)
+ return self._linear_fallback(input, bias=bias)
+
+ def get_quantized_subtensors(self):
+ return [
+ ("qweight", self._qweight),
+ ("wscales", self._wscales),
+ ("wzeros", self._wzeros),
+ ]
+
+ def set_quantized_subtensors(self, sub_tensors):
+ if isinstance(sub_tensors, dict):
+ sub_map = sub_tensors
+ else:
+ sub_map = {name: tensor for name, tensor in sub_tensors}
+ if "qweight" in sub_map and sub_map["qweight"] is not None:
+ self._qweight = sub_map["qweight"]
+ if "wscales" in sub_map and sub_map["wscales"] is not None:
+ self._wscales = sub_map["wscales"]
+ if "wzeros" in sub_map and sub_map["wzeros"] is not None:
+ self._wzeros = sub_map["wzeros"]
+
+ def __tensor_flatten__(self):
+ inner_tensors = ["_qweight", "_wscales", "_wzeros"]
+ meta = {
+ "qtype": self._qtype.name,
+ "axis": str(self._axis),
+ "size": str(list(self.size())),
+ "stride": str(list(self.stride())),
+ "dtype": str(self.dtype),
+ "group_size": str(self._group_size),
+ "kind": "awq",
+ }
+ return inner_tensors, meta
+
+ @staticmethod
+ def __tensor_unflatten__(inner_tensors, meta, outer_size, outer_stride):
+ qtype = _quanto_qtypes[meta["qtype"]]
+ axis = ast.literal_eval(meta["axis"])
+ size = ast.literal_eval(meta["size"])
+ stride = ast.literal_eval(meta["stride"])
+ dtype_name = _as_dtype_name(meta.get("dtype", "torch.float16"))
+ dtype = getattr(torch, dtype_name, torch.float16)
+ return NunchakuAWQWeightTensor(
+ qtype=qtype,
+ axis=axis,
+ size=size,
+ stride=stride,
+ qweight=inner_tensors["_qweight"],
+ wscales=inner_tensors["_wscales"],
+ wzeros=inner_tensors["_wzeros"],
+ dtype=dtype,
+ )
+
+ @classmethod
+ def __torch_dispatch__(cls, op, types, args, kwargs=None):
+ op = op.overloadpacket
+ kwargs = kwargs or {}
+ if op is torch.ops.aten.linear:
+ input = args[0]
+ weight = args[1]
+ bias = args[2] if len(args) > 2 else None
+ if isinstance(weight, NunchakuAWQWeightTensor):
+ return weight.linear(input, bias=bias)
+ if op is torch.ops.aten.detach:
+ t = args[0]
+ return NunchakuAWQWeightTensor.create(
+ qweight=op(t._qweight),
+ wscales=op(t._wscales),
+ wzeros=op(t._wzeros),
+ size=t.size(),
+ stride=t.stride(),
+ dtype=t.dtype,
+ device=t.device,
+ requires_grad=t.requires_grad,
+ )
+ if op in (torch.ops.aten._to_copy, torch.ops.aten.to):
+ t = args[0]
+ dtype = kwargs.pop("dtype", t.dtype) if kwargs else t.dtype
+ device = kwargs.pop("device", t.device) if kwargs else t.device
+ if dtype != t.dtype:
+ return t.dequantize(dtype=dtype, device=device)
+ out_qweight = op(t._qweight, device=device, **(kwargs or {}))
+ out_wscales = op(t._wscales, device=device, **(kwargs or {}))
+ out_wzeros = op(t._wzeros, device=device, **(kwargs or {}))
+ return NunchakuAWQWeightTensor.create(
+ qweight=out_qweight,
+ wscales=out_wscales,
+ wzeros=out_wzeros,
+ size=t.size(),
+ stride=t.stride(),
+ dtype=t.dtype,
+ device=device,
+ requires_grad=t.requires_grad,
+ )
+ return _nunchaku_qfallback(op, *args, **(kwargs or {}))
+
+
+class QLinearNunchakuInt4(QModuleMixin, torch.nn.Linear):
+ @classmethod
+ def qcreate(
+ cls,
+ module,
+ weights,
+ activations=None,
+ optimizer=None,
+ device=None,
+ ):
+ if torch.is_tensor(module.weight) and module.weight.dtype.is_floating_point:
+ weight_dtype = module.weight.dtype
+ elif torch.is_tensor(getattr(module, "bias", None)) and module.bias.dtype.is_floating_point:
+ weight_dtype = module.bias.dtype
+ else:
+ weight_dtype = torch.float16
+ return cls(
+ module.in_features,
+ module.out_features,
+ module.bias is not None,
+ device=device,
+ dtype=weight_dtype,
+ weights=weights,
+ activations=activations,
+ optimizer=optimizer,
+ quantize_input=True,
+ )
+
+ def __init__(
+ self,
+ in_features,
+ out_features,
+ bias=True,
+ device=None,
+ dtype=None,
+ weights=None,
+ activations=None,
+ optimizer=None,
+ quantize_input=True,
+ ):
+ super().__init__(
+ in_features,
+ out_features,
+ bias=bias,
+ device=device,
+ dtype=dtype,
+ weights=weights,
+ activations=activations,
+ optimizer=optimizer,
+ quantize_input=quantize_input,
+ )
+ self._nunchaku_default_dtype = dtype
+
+ def set_default_dtype(self, dtype):
+ self._nunchaku_default_dtype = dtype
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ qweight = self.qweight
+ if isinstance(qweight, NunchakuBaseWeightTensor):
+ out = qweight.linear(input, bias=self.bias)
+ else:
+ out = torch.nn.functional.linear(input, qweight, bias=self.bias)
+ if getattr(self, "_nunchaku_mod_reorder", False):
+ out = _reorder_mod_params_output(out)
+ if getattr(self, "_nunchaku_mod_scale_shift", False):
+ out = _apply_mod_scale_shift(out)
+ return out
+
+ @property
+ def qweight(self):
+ if self.weight_qtype == _NUNCHAKU_INT4_QTYPE:
+ return self.weight
+ return super().qweight
+
+ def _load_from_state_dict(
+ self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ ):
+ if self.weight_qtype != _NUNCHAKU_INT4_QTYPE:
+ return super()._load_from_state_dict(
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ )
+
+ qweight_key = prefix + "qweight"
+ wscales_key = prefix + "wscales"
+ wzeros_key = prefix + "wzeros"
+ smooth_key = prefix + "smooth_factor"
+ smooth_orig_key = prefix + "smooth_factor_orig"
+ proj_down_key = prefix + "proj_down"
+ proj_up_key = prefix + "proj_up"
+ bias_key = prefix + "bias"
+ input_scale_key = prefix + "input_scale"
+ output_scale_key = prefix + "output_scale"
+
+ qweight = state_dict.pop(qweight_key, None)
+ wscales = state_dict.pop(wscales_key, None)
+ wzeros = state_dict.pop(wzeros_key, None)
+ smooth_factor = state_dict.pop(smooth_key, None)
+ state_dict.pop(smooth_orig_key, None)
+ proj_down = state_dict.pop(proj_down_key, None)
+ proj_up = state_dict.pop(proj_up_key, None)
+ bias = state_dict.pop(bias_key, None)
+ input_scale = state_dict.pop(input_scale_key, None)
+ output_scale = state_dict.pop(output_scale_key, None)
+
+ if qweight is None:
+ missing_keys.append(qweight_key)
+ if wscales is None:
+ missing_keys.append(wscales_key)
+
+ target_dtype = self._nunchaku_default_dtype or self.weight.dtype
+ if qweight is not None and wscales is not None:
+ if qweight.dtype == torch.int8:
+ if smooth_factor is None:
+ missing_keys.append(smooth_key)
+ if proj_down is None:
+ missing_keys.append(proj_down_key)
+ if proj_up is None:
+ missing_keys.append(proj_up_key)
+ if smooth_factor is not None and proj_down is not None and proj_up is not None:
+ nunchaku_weight = NunchakuSVDQWeightTensor.create(
+ qweight=qweight,
+ wscales=wscales,
+ smooth_factor=smooth_factor,
+ proj_down=proj_down,
+ proj_up=proj_up,
+ size=self.weight.size(),
+ stride=self.weight.stride(),
+ dtype=target_dtype,
+ device=qweight.device,
+ requires_grad=False,
+ )
+ self.weight = torch.nn.Parameter(nunchaku_weight, requires_grad=False)
+ if prefix.endswith("img_mlp.net.2.") or prefix.endswith("txt_mlp.net.2."):
+ self.weight._act_unsigned = True
+ elif qweight.dtype == torch.int32:
+ if wzeros is None:
+ missing_keys.append(wzeros_key)
+ if wzeros is not None:
+ nunchaku_weight = NunchakuAWQWeightTensor.create(
+ qweight=qweight,
+ wscales=wscales,
+ wzeros=wzeros,
+ size=self.weight.size(),
+ stride=self.weight.stride(),
+ dtype=target_dtype,
+ device=qweight.device,
+ requires_grad=False,
+ )
+ self.weight = torch.nn.Parameter(nunchaku_weight, requires_grad=False)
+ if prefix.endswith("img_mod.1.") or prefix.endswith("txt_mod.1."):
+ self._nunchaku_mod_reorder = True
+ self._nunchaku_mod_scale_shift = True
+
+ if bias is not None:
+ if target_dtype is not None and bias.dtype != target_dtype:
+ bias = bias.to(target_dtype)
+ self.bias = torch.nn.Parameter(bias)
+
+ if torch.is_tensor(qweight):
+ scale_device = qweight.device
+ elif torch.is_tensor(self.weight):
+ scale_device = self.weight.device
+ elif torch.is_tensor(bias):
+ scale_device = bias.device
+ else:
+ scale_device = torch.device("cpu")
+
+ if input_scale is not None:
+ self.input_scale = input_scale.to(scale_device)
+ else:
+ if not hasattr(self, "input_scale") or self.input_scale.is_meta:
+ scale_dtype = self.input_scale.dtype if hasattr(self, "input_scale") else torch.float32
+ self.input_scale = torch.ones((), dtype=scale_dtype, device=scale_device)
+
+ if output_scale is not None:
+ self.output_scale = output_scale.to(scale_device)
+ else:
+ if not hasattr(self, "output_scale") or self.output_scale.is_meta:
+ scale_dtype = self.output_scale.dtype if hasattr(self, "output_scale") else torch.float32
+ self.output_scale = torch.ones((), dtype=scale_dtype, device=scale_device)
+
+ return
+
+
+def _collect_nunchaku_specs(state_dict):
+ specs = []
+ for key, tensor in state_dict.items():
+ if not key.endswith(".qweight"):
+ continue
+ base = key[:-8]
+ wscales = state_dict.get(base + ".wscales", None)
+ if wscales is None:
+ continue
+ if tensor.dtype == torch.int8:
+ if (
+ base + ".smooth_factor" in state_dict
+ and base + ".proj_down" in state_dict
+ and base + ".proj_up" in state_dict
+ ):
+ specs.append({"name": base, "kind": "svdq"})
+ elif tensor.dtype == torch.int32:
+ if base + ".wzeros" in state_dict:
+ specs.append({"name": base, "kind": "awq"})
+ return specs
+
+
+def _patch_mod_bias_scale_shift(state_dict, verboseLevel=1):
+ patched = 0
+ for key, bias in state_dict.items():
+ if not (key.endswith(".img_mod.1.bias") or key.endswith(".txt_mod.1.bias")):
+ continue
+ base = key[:-5]
+ qweight = state_dict.get(base + ".qweight", None)
+ if qweight is None or qweight.dtype != torch.int32:
+ continue
+ if bias.numel() % 6 != 0:
+ continue
+ dim = bias.numel() // 6
+ if dim == 0:
+ continue
+ one = torch.ones(dim, device=bias.device, dtype=bias.dtype)
+ bias[dim : 2 * dim].sub_(one)
+ bias[4 * dim : 5 * dim].sub_(one)
+ patched += 1
+ if patched and verboseLevel >= 1:
+ print(f"[nunchaku_int4] Patched {patched} mod bias scale shifts")
+
+
+def _reorder_mod_params_output(out):
+ if out.shape[-1] % 6 != 0:
+ return out
+ dim = out.shape[-1] // 6
+ return out.reshape(*out.shape[:-1], dim, 6).transpose(-2, -1).reshape(*out.shape[:-1], out.shape[-1])
+
+
+def _apply_mod_scale_shift(out):
+ if out.shape[-1] % 6 != 0:
+ return out
+ dim = out.shape[-1] // 6
+ out[..., dim : 2 * dim].sub_(1.0)
+ out[..., 4 * dim : 5 * dim].sub_(1.0)
+ return out
+
+
+def detect(state_dict, verboseLevel=1):
+ specs = _collect_nunchaku_specs(state_dict)
+ if not specs:
+ return {"matched": False, "kind": "none", "details": {}}
+ names = [spec["name"] for spec in specs][:8]
+ return {"matched": True, "kind": "nunchaku_int4", "details": {"count": len(specs), "names": names}}
+
+
+def convert_to_quanto(state_dict, default_dtype, verboseLevel=1, detection=None):
+ if detection is not None and not detection.get("matched", False):
+ return {"state_dict": state_dict, "quant_map": {}}
+ specs = _collect_nunchaku_specs(state_dict)
+ if not specs:
+ return {"state_dict": state_dict, "quant_map": {}}
+ quant_map = {spec["name"]: {"weights": "nunchaku_int4", "activations": "none"} for spec in specs}
+ return {"state_dict": state_dict, "quant_map": quant_map}
+
+
+def apply_pre_quantization(model, state_dict, quantization_map, default_dtype=None, verboseLevel=1):
+ return quantization_map or {}, []
diff --git a/shared/qtypes/nvfp4.py b/shared/qtypes/nvfp4.py
new file mode 100644
index 0000000..62cf336
--- /dev/null
+++ b/shared/qtypes/nvfp4.py
@@ -0,0 +1,588 @@
+import ast
+import torch
+from torch.utils import _pytree as pytree
+
+from optimum.quanto import QModuleMixin
+from optimum.quanto.tensor.qtensor import QTensor
+from optimum.quanto.tensor.qtype import qtype as _quanto_qtype, qtypes as _quanto_qtypes
+
+try:
+ from lightx2v_kernel.gemm import scaled_nvfp4_quant, cutlass_scaled_nvfp4_mm
+ _KERNEL_AVAILABLE = True
+except Exception:
+ scaled_nvfp4_quant = None
+ cutlass_scaled_nvfp4_mm = None
+ _KERNEL_AVAILABLE = False
+
+_NVFP4_QTYPE_NAME = "nvfp4"
+if _NVFP4_QTYPE_NAME not in _quanto_qtypes:
+ _quanto_qtypes[_NVFP4_QTYPE_NAME] = _quanto_qtype(
+ _NVFP4_QTYPE_NAME,
+ is_floating_point=True,
+ bits=4,
+ dtype=torch.uint8,
+ qmin=-6.0,
+ qmax=6.0,
+ )
+_NVFP4_QTYPE = _quanto_qtypes[_NVFP4_QTYPE_NAME]
+
+def _supports_nvfp4_kernel(device):
+ if not _KERNEL_AVAILABLE:
+ return False
+ if device.type != "cuda":
+ return False
+ major, _ = torch.cuda.get_device_capability(device)
+ return major >= 12
+
+
+def _is_float8_dtype(dtype):
+ return "float8" in str(dtype).lower() or "f8" in str(dtype).lower()
+
+_FP4_LUT_BASE = torch.tensor(
+ [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0],
+ dtype=torch.float32,
+)
+_FP4_LUT_CACHE = {}
+_FP4_BYTE_LUT_CACHE = {}
+
+
+def _get_fp4_lut(device, dtype):
+ key = (device, dtype)
+ lut = _FP4_LUT_CACHE.get(key)
+ if lut is None:
+ lut = _FP4_LUT_BASE.to(device=device, dtype=dtype)
+ _FP4_LUT_CACHE[key] = lut
+ return lut
+
+
+def _get_fp4_byte_lut(device, dtype):
+ key = (device, dtype)
+ byte_lut = _FP4_BYTE_LUT_CACHE.get(key)
+ if byte_lut is None:
+ lut16 = _get_fp4_lut(device, dtype)
+ b = torch.arange(256, device=device, dtype=torch.int32)
+ byte_lut = torch.empty((256, 2), device=device, dtype=dtype)
+ byte_lut[:, 0] = lut16[b & 0x0F]
+ byte_lut[:, 1] = lut16[b >> 4]
+ _FP4_BYTE_LUT_CACHE[key] = byte_lut
+ return byte_lut
+
+
+def _deswizzle_nvfp4_scale(scale, in_features, block_size=16, dtype=None):
+ k_groups = in_features // block_size
+ if scale.shape[1] < k_groups:
+ raise RuntimeError(
+ f"NVFP4 scale shape mismatch: expected at least {k_groups} groups, got {scale.shape[1]}"
+ )
+ if scale.shape[1] > k_groups:
+ scale = scale[:, :k_groups]
+
+ m, _ = scale.shape
+ m_tiles = (m + 128 - 1) // 128
+ f = block_size * 4
+ k_tiles = (in_features + f - 1) // f
+ tmp = scale if dtype is None else scale.to(dtype)
+ tmp = tmp.reshape(1, m_tiles, k_tiles, 32, 4, 4)
+ tmp = tmp.permute(0, 1, 4, 3, 2, 5)
+ out = tmp.reshape(m_tiles * 128, k_tiles * 4)
+ return out[:m, :k_groups]
+
+
+def _dequantize_nvfp4_weight(
+ weight_u8,
+ weight_scale,
+ input_global_scale,
+ alpha,
+ dtype,
+ device,
+ block_size=16,
+):
+ if weight_u8.device != device:
+ weight_u8 = weight_u8.to(device)
+ scale = weight_scale if weight_scale.device == device else weight_scale.to(device)
+ if alpha.device != device:
+ alpha = alpha.to(device)
+ if input_global_scale.device != device:
+ input_global_scale = input_global_scale.to(device)
+
+ m, k_bytes = weight_u8.shape
+ byte_lut = _get_fp4_byte_lut(device, dtype)
+ idx = weight_u8.to(torch.int32)
+ out = byte_lut[idx].reshape(m, k_bytes * 2)
+
+ scale = _deswizzle_nvfp4_scale(scale, out.shape[1], block_size=block_size, dtype=dtype)
+ out = out.view(out.shape[0], scale.shape[1], block_size)
+ out.mul_(scale.unsqueeze(-1))
+ out = out.view(out.shape[0], -1)
+
+ scale_factor = alpha.to(dtype) * input_global_scale.to(dtype)
+ out.mul_(scale_factor)
+ return out
+
+
+def _collect_nvfp4_specs(state_dict):
+ specs = []
+ for key, tensor in state_dict.items():
+ if not key.endswith(".weight"):
+ continue
+ if tensor.dtype != torch.uint8:
+ continue
+ base = key[:-7]
+ scale_key = base + ".weight_scale"
+ input_global_key = base + ".input_global_scale"
+ alpha_key = base + ".alpha"
+ if scale_key not in state_dict or input_global_key not in state_dict or alpha_key not in state_dict:
+ continue
+ if not _is_float8_dtype(state_dict[scale_key].dtype):
+ continue
+ specs.append(
+ {
+ "name": base,
+ "weight": tensor,
+ "weight_scale": state_dict[scale_key],
+ "input_global_scale": state_dict[input_global_key],
+ "alpha": state_dict[alpha_key],
+ "bias": state_dict.get(base + ".bias", None),
+ }
+ )
+ return specs
+
+
+def detect_nvfp4_state_dict(state_dict):
+ return len(_collect_nvfp4_specs(state_dict)) > 0
+
+
+def describe_nvfp4_state_dict(state_dict, max_names=8):
+ specs = _collect_nvfp4_specs(state_dict)
+ names = [spec["name"] for spec in specs]
+ return {"count": len(names), "names": names[:max_names]}
+
+
+def convert_nvfp4_to_quanto(state_dict, default_dtype=None, verboseLevel=1):
+ specs = _collect_nvfp4_specs(state_dict)
+ if not specs:
+ return {"state_dict": state_dict, "quant_map": {}}
+ quant_map = {spec["name"]: {"weights": "nvfp4", "activations": "none"} for spec in specs}
+ return {"state_dict": state_dict, "quant_map": quant_map}
+
+
+def detect(state_dict, verboseLevel=1):
+ matched = detect_nvfp4_state_dict(state_dict)
+ details = describe_nvfp4_state_dict(state_dict) if matched else {}
+ return {"matched": matched, "kind": "nvfp4" if matched else "none", "details": details}
+
+
+def convert_to_quanto(state_dict, default_dtype, verboseLevel=1, detection=None):
+ if detection is not None and not detection.get("matched", False):
+ return {"state_dict": state_dict, "quant_map": {}}
+ return convert_nvfp4_to_quanto(state_dict, default_dtype=default_dtype, verboseLevel=verboseLevel)
+
+
+def apply_pre_quantization(model, state_dict, quantization_map, default_dtype=None, verboseLevel=1):
+ return quantization_map, []
+
+
+def _nvfp4_qfallback(callable, *args, **kwargs):
+ args, kwargs = pytree.tree_map_only(NVFP4WeightTensor, lambda x: x.dequantize(), (args, kwargs or {}))
+ return callable(*args, **kwargs)
+
+
+class NVFP4WeightTensor(QTensor):
+ @staticmethod
+ def create(
+ weight_u8,
+ weight_scale,
+ input_global_scale,
+ alpha,
+ size,
+ stride,
+ dtype,
+ device=None,
+ requires_grad=False,
+ ):
+ device = weight_u8.device if device is None else device
+ if weight_u8.device != device:
+ weight_u8 = weight_u8.to(device)
+ if weight_scale.device != device:
+ weight_scale = weight_scale.to(device)
+ if input_global_scale.device != device:
+ input_global_scale = input_global_scale.to(device)
+ if alpha.device != device:
+ alpha = alpha.to(device)
+ return NVFP4WeightTensor(
+ qtype=_NVFP4_QTYPE,
+ axis=0,
+ size=size,
+ stride=stride,
+ weight_u8=weight_u8,
+ weight_scale=weight_scale,
+ input_global_scale=input_global_scale,
+ alpha=alpha,
+ dtype=dtype,
+ requires_grad=requires_grad,
+ )
+
+ @staticmethod
+ def __new__(
+ cls,
+ qtype,
+ axis,
+ size,
+ stride,
+ weight_u8,
+ weight_scale,
+ input_global_scale,
+ alpha,
+ dtype,
+ requires_grad=False,
+ ):
+ return torch.Tensor._make_wrapper_subclass(
+ cls,
+ size,
+ strides=stride,
+ dtype=dtype,
+ device=weight_u8.device,
+ requires_grad=requires_grad,
+ )
+
+ def __init__(
+ self,
+ qtype,
+ axis,
+ size,
+ stride,
+ weight_u8,
+ weight_scale,
+ input_global_scale,
+ alpha,
+ dtype,
+ requires_grad=False,
+ ):
+ super().__init__(qtype, axis)
+ self._data = weight_u8
+ self._scale = weight_scale
+ self._input_global_scale = input_global_scale
+ self._alpha = alpha
+ self._block_size = 16
+
+ def dequantize(self, dtype=None, device=None):
+ if dtype is None:
+ dtype = self.dtype
+ if device is None:
+ device = self.device
+ return _dequantize_nvfp4_weight(
+ weight_u8=self._data,
+ weight_scale=self._scale,
+ input_global_scale=self._input_global_scale,
+ alpha=self._alpha,
+ dtype=dtype,
+ device=device,
+ block_size=self._block_size,
+ )
+
+ def get_quantized_subtensors(self):
+ return [
+ ("weight_u8", self._data),
+ ("weight_scale", self._scale),
+ ("input_global_scale", self._input_global_scale),
+ ("alpha", self._alpha),
+ ]
+
+ def set_quantized_subtensors(self, sub_tensors):
+ if isinstance(sub_tensors, dict):
+ sub_map = sub_tensors
+ else:
+ sub_map = {name: tensor for name, tensor in sub_tensors}
+ data = sub_map.get("weight_u8", sub_map.get("data"))
+ if data is not None:
+ self._data = data
+ if "weight_scale" in sub_map and sub_map["weight_scale"] is not None:
+ self._scale = sub_map["weight_scale"]
+ if "input_global_scale" in sub_map and sub_map["input_global_scale"] is not None:
+ self._input_global_scale = sub_map["input_global_scale"]
+ if "alpha" in sub_map and sub_map["alpha"] is not None:
+ self._alpha = sub_map["alpha"]
+
+ def __tensor_flatten__(self):
+ inner_tensors = ["_data", "_scale", "_input_global_scale", "_alpha"]
+ meta = {
+ "qtype": self._qtype.name,
+ "axis": str(self._axis),
+ "size": str(list(self.size())),
+ "stride": str(list(self.stride())),
+ "dtype": str(self.dtype),
+ }
+ return inner_tensors, meta
+
+ @staticmethod
+ def __tensor_unflatten__(inner_tensors, meta, outer_size, outer_stride):
+ qtype = _quanto_qtypes[meta["qtype"]]
+ axis = ast.literal_eval(meta["axis"])
+ size = ast.literal_eval(meta["size"])
+ stride = ast.literal_eval(meta["stride"])
+ dtype_str = meta.get("dtype", "torch.float16")
+ if dtype_str.startswith("torch."):
+ dtype_name = dtype_str.split(".", 1)[1]
+ dtype = getattr(torch, dtype_name, torch.float16)
+ else:
+ dtype = getattr(torch, dtype_str, torch.float16)
+ return NVFP4WeightTensor(
+ qtype=qtype,
+ axis=axis,
+ size=size,
+ stride=stride,
+ weight_u8=inner_tensors["_data"],
+ weight_scale=inner_tensors["_scale"],
+ input_global_scale=inner_tensors["_input_global_scale"],
+ alpha=inner_tensors["_alpha"],
+ dtype=dtype,
+ )
+
+ @classmethod
+ def __torch_function__(cls, func, types, args=(), kwargs=None):
+ kwargs = kwargs or {}
+ if func is torch.nn.functional.linear:
+ input = args[0] if len(args) > 0 else kwargs.get("input", None)
+ weight = args[1] if len(args) > 1 else kwargs.get("weight", None)
+ bias = args[2] if len(args) > 2 else kwargs.get("bias", None)
+ if isinstance(weight, NVFP4WeightTensor):
+ if torch.is_tensor(input) and _supports_nvfp4_kernel(input.device):
+ x2d = input.reshape(-1, input.shape[-1])
+ if not x2d.is_floating_point():
+ x2d = x2d.to(torch.float16)
+ orig_dtype = x2d.dtype
+ input_quant, input_scale = scaled_nvfp4_quant(x2d, weight._input_global_scale)
+ if bias is not None and torch.is_tensor(bias) and bias.dtype != orig_dtype:
+ bias = bias.to(orig_dtype)
+ out = cutlass_scaled_nvfp4_mm(
+ input_quant,
+ weight._data,
+ input_scale,
+ weight._scale,
+ alpha=weight._alpha,
+ bias=bias,
+ )
+ if out.dtype != orig_dtype:
+ out = out.to(orig_dtype)
+ return out.reshape(*input.shape[:-1], weight.size(0))
+ dtype = input.dtype if torch.is_tensor(input) else weight.dtype
+ device = input.device if torch.is_tensor(input) else weight.device
+ w = weight.dequantize(dtype=dtype, device=device)
+ if bias is not None and torch.is_tensor(bias) and bias.dtype != dtype:
+ bias = bias.to(dtype)
+ return torch.nn.functional.linear(input, w, bias)
+ with torch._C.DisableTorchFunctionSubclass():
+ return func(*args, **kwargs)
+
+ @classmethod
+ def __torch_dispatch__(cls, op, types, args, kwargs=None):
+ op = op.overloadpacket
+ if op is torch.ops.aten.linear:
+ input = args[0]
+ weight = args[1]
+ bias = args[2] if len(args) > 2 else None
+ if isinstance(weight, NVFP4WeightTensor):
+ if torch.is_tensor(input) and _supports_nvfp4_kernel(input.device):
+ x2d = input.reshape(-1, input.shape[-1])
+ if not x2d.is_floating_point():
+ x2d = x2d.to(torch.float16)
+ orig_dtype = x2d.dtype
+ input_quant, input_scale = scaled_nvfp4_quant(x2d, weight._input_global_scale)
+ if bias is not None and torch.is_tensor(bias) and bias.dtype != orig_dtype:
+ bias = bias.to(orig_dtype)
+ out = cutlass_scaled_nvfp4_mm(
+ input_quant,
+ weight._data,
+ input_scale,
+ weight._scale,
+ alpha=weight._alpha,
+ bias=bias,
+ )
+ if out.dtype != orig_dtype:
+ out = out.to(orig_dtype)
+ return out.reshape(*input.shape[:-1], weight.size(0))
+ dtype = input.dtype if torch.is_tensor(input) else weight.dtype
+ device = input.device if torch.is_tensor(input) else weight.device
+ w = weight.dequantize(dtype=dtype, device=device)
+ if bias is not None and torch.is_tensor(bias) and bias.dtype != dtype:
+ bias = bias.to(dtype)
+ return op(input, w, bias)
+ if op is torch.ops.aten.detach:
+ t = args[0]
+ return NVFP4WeightTensor.create(
+ weight_u8=op(t._data),
+ weight_scale=op(t._scale),
+ input_global_scale=op(t._input_global_scale),
+ alpha=op(t._alpha),
+ size=t.size(),
+ stride=t.stride(),
+ dtype=t.dtype,
+ device=t.device,
+ requires_grad=t.requires_grad,
+ )
+ if op in (torch.ops.aten._to_copy, torch.ops.aten.to):
+ t = args[0]
+ dtype = kwargs.pop("dtype", t.dtype) if kwargs else t.dtype
+ device = kwargs.pop("device", t.device) if kwargs else t.device
+ if dtype != t.dtype:
+ return t.dequantize(dtype=dtype, device=device)
+ out_data = op(t._data, device=device, **(kwargs or {}))
+ out_scale = op(t._scale, device=device, **(kwargs or {}))
+ out_igs = op(t._input_global_scale, device=device, **(kwargs or {}))
+ out_alpha = op(t._alpha, device=device, **(kwargs or {}))
+ return NVFP4WeightTensor.create(
+ weight_u8=out_data,
+ weight_scale=out_scale,
+ input_global_scale=out_igs,
+ alpha=out_alpha,
+ size=t.size(),
+ stride=t.stride(),
+ dtype=t.dtype,
+ device=device,
+ requires_grad=t.requires_grad,
+ )
+ return _nvfp4_qfallback(op, *args, **(kwargs or {}))
+
+
+class QLinearNVFP4(QModuleMixin, torch.nn.Linear):
+ def __init__(
+ self,
+ in_features,
+ out_features,
+ bias=True,
+ device=None,
+ dtype=None,
+ weights=None,
+ activations=None,
+ optimizer=None,
+ quantize_input=True,
+ ):
+ super().__init__(
+ in_features,
+ out_features,
+ bias=bias,
+ device=device,
+ dtype=dtype,
+ weights=weights,
+ activations=activations,
+ optimizer=optimizer,
+ quantize_input=quantize_input,
+ )
+ self._nvfp4_default_dtype = dtype
+
+ @classmethod
+ def qcreate(
+ cls,
+ module,
+ weights,
+ activations=None,
+ optimizer=None,
+ device=None,
+ ):
+ if torch.is_tensor(module.weight) and module.weight.dtype.is_floating_point:
+ weight_dtype = module.weight.dtype
+ elif torch.is_tensor(getattr(module, "bias", None)) and module.bias.dtype.is_floating_point:
+ weight_dtype = module.bias.dtype
+ else:
+ weight_dtype = torch.float16
+ return cls(
+ module.in_features,
+ module.out_features,
+ module.bias is not None,
+ device=device,
+ dtype=weight_dtype,
+ weights=weights,
+ activations=activations,
+ optimizer=optimizer,
+ quantize_input=True,
+ )
+
+ def set_default_dtype(self, dtype):
+ self._nvfp4_default_dtype = dtype
+
+ @property
+ def qweight(self):
+ if self.weight_qtype == _NVFP4_QTYPE:
+ return self.weight
+ return super().qweight
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ return torch.nn.functional.linear(input, self.qweight, bias=self.bias)
+
+ def _load_from_state_dict(
+ self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ ):
+ if self.weight_qtype != _NVFP4_QTYPE:
+ return super()._load_from_state_dict(
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ )
+
+ weight_key = prefix + "weight"
+ scale_key = prefix + "weight_scale"
+ igs_key = prefix + "input_global_scale"
+ alpha_key = prefix + "alpha"
+ bias_key = prefix + "bias"
+ input_scale_key = prefix + "input_scale"
+ output_scale_key = prefix + "output_scale"
+
+ weight_u8 = state_dict.pop(weight_key, None)
+ weight_scale = state_dict.pop(scale_key, None)
+ input_global_scale = state_dict.pop(igs_key, None)
+ alpha = state_dict.pop(alpha_key, None)
+ bias = state_dict.pop(bias_key, None)
+ input_scale = state_dict.pop(input_scale_key, None)
+ output_scale = state_dict.pop(output_scale_key, None)
+
+ if weight_u8 is None:
+ missing_keys.append(weight_key)
+ if weight_scale is None:
+ missing_keys.append(scale_key)
+ if input_global_scale is None:
+ missing_keys.append(igs_key)
+ if alpha is None:
+ missing_keys.append(alpha_key)
+
+ target_dtype = self._nvfp4_default_dtype or self.weight.dtype
+ if weight_u8 is not None and weight_scale is not None and input_global_scale is not None and alpha is not None:
+ nvfp4_weight = NVFP4WeightTensor.create(
+ weight_u8=weight_u8,
+ weight_scale=weight_scale,
+ input_global_scale=input_global_scale,
+ alpha=alpha,
+ size=self.weight.size(),
+ stride=self.weight.stride(),
+ dtype=target_dtype,
+ device=weight_u8.device,
+ requires_grad=False,
+ )
+ self.weight = torch.nn.Parameter(nvfp4_weight, requires_grad=False)
+
+ if bias is not None:
+ if target_dtype is not None and bias.dtype != target_dtype:
+ bias = bias.to(target_dtype)
+ self.bias = torch.nn.Parameter(bias)
+
+ if torch.is_tensor(weight_u8):
+ scale_device = weight_u8.device
+ elif torch.is_tensor(self.weight):
+ scale_device = self.weight.device
+ elif torch.is_tensor(bias):
+ scale_device = bias.device
+ else:
+ scale_device = torch.device("cpu")
+
+ if input_scale is not None:
+ self.input_scale = input_scale.to(scale_device)
+ else:
+ if not hasattr(self, "input_scale") or self.input_scale.is_meta:
+ scale_dtype = self.input_scale.dtype if hasattr(self, "input_scale") else torch.float32
+ self.input_scale = torch.ones((), dtype=scale_dtype, device=scale_device)
+
+ if output_scale is not None:
+ self.output_scale = output_scale.to(scale_device)
+ else:
+ if not hasattr(self, "output_scale") or self.output_scale.is_meta:
+ scale_dtype = self.output_scale.dtype if hasattr(self, "output_scale") else torch.float32
+ self.output_scale = torch.ones((), dtype=scale_dtype, device=scale_device)
+
+ return
diff --git a/wgp.py b/wgp.py
index 4bed627..212cbb4 100644
--- a/wgp.py
+++ b/wgp.py
@@ -19,7 +19,7 @@ import threading
import argparse
import warnings
warnings.filterwarnings('ignore', message='Failed to find.*', module='triton')
-from mmgp import offload, safetensors2, profile_type , fp8_quanto_bridge
+from mmgp import offload, safetensors2, profile_type , fp8_quanto_bridge, quant_router
if not os.name == "nt": fp8_quanto_bridge.enable_fp8_marlin_fallback()
try:
import triton
@@ -107,6 +107,12 @@ unique_id = 0
unique_id_lock = threading.Lock()
offloadobj = enhancer_offloadobj = wan_model = None
reload_needed = True
+_HANDLER_MODULES = [
+ "shared.qtypes.nvfp4",
+ "shared.qtypes.nunchaku_int4",
+]
+for handler in _HANDLER_MODULES:
+ quant_router.register_handler(handler)
def set_wgp_global(variable_name: str, new_value: any) -> str:
if variable_name not in globals():
@@ -1093,7 +1099,7 @@ def _save_queue_to_zip(queue, output):
params_copy.pop(runtime_key, None)
params_copy['settings_version'] = settings_version
- params_copy['base_model_type'] = get_base_model_type(model_type)
+ params_copy['base_model_type'] = get_base_model_type(params_copy["model_type"])
manifest_entry = {"id": task.get('id'), "params": params_copy}
manifest_entry = {k: v for k, v in manifest_entry.items() if v is not None}
@@ -1680,7 +1686,7 @@ 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.kandinsky5.kandinsky_handler", "models.z_image.z_image_handler", "models.chatterbox.chatterbox_handler"]
+family_handlers = ["models.wan.wan_handler", "models.wan.ovi_handler", "models.wan.df_handler", "models.hyvideo.hunyuan_handler", "models.ltx_video.ltxv_handler", "models.longcat.longcat_handler", "models.flux.flux_handler", "models.qwen.qwen_handler", "models.kandinsky5.kandinsky_handler", "models.z_image.z_image_handler", "models.chatterbox.chatterbox_handler"]
def register_family_lora_args(parser):
registered_families = set()
@@ -2191,6 +2197,9 @@ def map_family_handlers(family_handlers):
models_eqv_map.update(eq_map); models_comp_map.update(comp_map)
return base_types_handlers, families_infos, models_eqv_map, models_comp_map
+# models_eqv_map: bidirectional compatibility between base model types
+# models_comp_map : mono directional compatibility between base model types {"A" : {"B", "C"} } means B & C model types can accept A model types (but not the other way). Said otherwise B & C are derived data types
+
model_types_handlers, families_infos, models_eqv_map, models_comp_map = map_family_handlers(family_handlers)
def get_base_model_type(model_type):
@@ -2206,7 +2215,7 @@ def get_parent_model_type(model_type):
if base_model_type is None: return None
model_def = get_model_def(base_model_type)
return model_def.get("parent_model_type", base_model_type)
-"vace_14B"
+
def get_model_handler(model_type):
base_model_type = get_base_model_type(model_type)
if base_model_type is None:
@@ -2219,12 +2228,16 @@ def get_model_handler(model_type):
def are_model_types_compatible(imported_model_type, current_model_type):
imported_base_model_type = get_base_model_type(imported_model_type)
curent_base_model_type = get_base_model_type(current_model_type)
- if imported_base_model_type == curent_base_model_type:
- return True
if imported_base_model_type in models_eqv_map:
imported_base_model_type = models_eqv_map[imported_base_model_type]
+ if curent_base_model_type in models_eqv_map:
+ curent_base_model_type = models_eqv_map[curent_base_model_type]
+
+ if imported_base_model_type == curent_base_model_type:
+ return True
+
comp_list= models_comp_map.get(imported_base_model_type, None)
if comp_list == None: return False
return curent_base_model_type in comp_list
@@ -2384,11 +2397,15 @@ def get_model_filename(model_type, quantization ="int8", dtype_policy = "", modu
if len(choices) <= 1:
raw_filename = choices[0]
else:
- if quantization.lower() in ("int8", "fp8", "nvfp4"):
- q = quantization.lower()
- sub_choices = [name for name in choices if q in os.path.basename(name).lower()]
+ quant_tokens = offload.get_quantization_tokens(quantization)
+ if quant_tokens:
+ sub_choices = [
+ name
+ for name in choices
+ if any(token in os.path.basename(name).lower() for token in quant_tokens)
+ ]
else:
- sub_choices = [ name for name in choices if "quanto" not in os.path.basename(name)]
+ sub_choices = [name for name in choices if "quanto" not in os.path.basename(name)]
if len(sub_choices) > 0:
dtype_str = "fp16" if dtype == torch.float16 else "bf16"
@@ -3312,7 +3329,8 @@ def generate_header(model_type, compile, attention_mode):
description_container = [""]
get_model_name(model_type, description_container)
- model_filename = os.path.basename(get_model_filename(model_type, transformer_quantization, transformer_dtype_policy)) or ""
+ full_filename = get_model_filename(model_type, transformer_quantization, transformer_dtype_policy)
+ model_filename = os.path.basename(full_filename)
description = description_container[0]
header = f"<DIV style=height:{60 if server_config.get('display_stats', 0) == 1 else 40}px>{description}</DIV>"
overridden_attention = get_overridden_attention(model_type)
@@ -3333,10 +3351,9 @@ def generate_header(model_type, compile, attention_mode):
else:
header += ", Data Type <B>BF16</B>"
- if "nvfp4" in model_filename.lower():
- header += ", Quantization <B>NVFP4</B>"
- elif "int8" in model_filename:
- header += ", Quantization <B>Scaled Int8</B>"
+ quant_label = offload.detect_quantization_label_from_filename(get_local_model_filename(full_filename))
+ if quant_label:
+ header += f", Quantization <B>{quant_label}</B>"
header += "<FONT></DIV>"
return header
@@ -4546,16 +4563,12 @@ def perform_spatial_upsampling(sample, spatial_upsampling):
frames_to_upsample = None
return sample
+
def any_audio_track(model_type):
- base_model_type = get_base_model_type(model_type)
- if base_model_type in ["fantasy", "hunyuan_avatar", "hunyuan_custom_audio", "chatterbox"]:
- return True
model_def = get_model_def(model_type)
if not model_def:
return False
- if model_def.get("returns_audio", False):
- return True
- return model_def.get("multitalk_class", False)
+ return ( model_def.get("returns_audio", False) or model_def.get("any_audio_prompt", False) )
def get_available_filename(target_path, video_source, suffix = "", force_extension = None):
name, extension = os.path.splitext(os.path.basename(video_source))
@@ -6154,6 +6167,7 @@ def generate_preview(model_type, payload):
latents = payload
if latents is None:
return None
+ # latents shape should be C, T, H, W (no batch)
if not torch.is_tensor(latents):
return None
model_handler = get_model_handler(model_type)
@@ -7455,6 +7469,7 @@ def use_video_settings(state, input_file_list, choice, source):
defaults = get_model_settings(state, model_type)
defaults = get_default_settings(model_type) if defaults == None else defaults
defaults.update(configs)
+ defaults["model_type"] = model_type
prompt = configs.get("prompt", "")
if has_audio_file_extension(file_name):
@@ -7618,7 +7633,7 @@ def switch_image_mode(state):
model_cache = inpaint_cache.get(model_type, None)
if model_cache is None:
inpaint_cache[model_type] = model_cache ={}
- video_prompt_inpaint_mode = "VAGI" if model_def.get("image_ref_inpaint", False) else "VAG"
+ video_prompt_inpaint_mode = model_def.get("inpaint_video_prompt_type", "VAG")
video_prompt_image_mode = "KI"
old_video_prompt_type = video_prompt_type
if image_mode == 1:
@@ -8664,8 +8679,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
image_ref_inpaint = False
if image_mode_value==2:
dropdown_selectable = False
- image_ref_inpaint = model_def.get("image_ref_inpaint", False)
-
+ image_ref_inpaint = "I" in model_def.get("inpaint_video_prompt_type", "")
with gr.Row(visible = dropdown_selectable or image_ref_inpaint) as guide_selection_row:
# Control Video Preprocessing
@@ -8902,7 +8916,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
audio_prompt_type_sources = gr.Dropdown(
choices=speaker_choices,
value= filter_letters(audio_prompt_type_value, "XCPAB"),
- label="Voices", scale = 3, visible = multitalk and not image_outputs
+ label="Voices", scale = 3, visible = model_def.get("audio_prompt_choices") is not None and not image_outputs
)
else:
audio_prompt_type_sources = gr.Dropdown( choices= [""], value = "", visible=False)
@@ -9676,7 +9690,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
outputs= None
).then( fn=use_video_settings, inputs =[state, output, last_choice, gr.State("video")] , outputs= [model_family, model_base_type_choice, model_choice, refresh_form_trigger])
- gr.on( triggers=[video_info_extract_audio_settings_btn.click, video_info_extract_image_settings_btn.click], fn=validate_wizard_prompt,
+ gr.on( triggers=[video_info_extract_audio_settings_btn.click], fn=validate_wizard_prompt,
inputs= [state, wizard_prompt_activated_var, wizard_variables_var, prompt, wizard_prompt, *prompt_vars] ,
show_progress="hidden",
outputs= [prompt],