Python
added Z Image Twin Flow Turbo, fixed crash Nunchaku with pytorch compiler
DeepBeepMeepd20e06d22971
diff --git a/defaults/z_image_twinflow_turbo.json b/defaults/z_image_twinflow_turbo.jsonnew file mode 100644index 0000000..ed4e40d--- /dev/null+++ b/defaults/z_image_twinflow_turbo.json@@ -0,0 +1,16 @@+{+ "model": {+ "name": "TwinFlow Z-Image Turbo",+ "architecture": "z_image",+ "description": "TwinFlow is a distilled Z-Image Turbo Finetune optimized for 1 to 4 steps Image Generations.",+ "unified_solver": true,+ "URLs": [+ "https://huggingface.co/DeepBeepMeep/Z-Image/TwinFlow-Z-Image-Turbo_bf16.safetensors",+ "https://huggingface.co/DeepBeepMeep/Z-Image/TwinFlow-Z-Image-Turbo_quanto_bf16_int8.safetensors"+ ]+ },+ "resolution": "1024x1024",+ "batch_size": 1,+ "num_inference_steps": 2,+ "guidance_scale": 0+}diff --git a/models/z_image/pipeline_z_image.py b/models/z_image/pipeline_z_image.pyindex 1a41098..9f5e768 100644--- a/models/z_image/pipeline_z_image.py+++ b/models/z_image/pipeline_z_image.py@@ -27,6 +27,7 @@ from diffusers.utils import logging, replace_example_docstringfrom diffusers.utils.torch_utils import randn_tensorfrom mmgp import offloadfrom .z_image_transformer2d import ZImageTransformer2DModel+from .unified_sampler import UnifiedSamplerfrom .pipeline_output import ZImagePipelineOutputfrom shared.utils.utils import get_outpainting_frame_location, resize_lanczos, calculate_new_dimensions, convert_image_to_tensor, fit_image_into_canvasfrom shared.utils.loras_mutipliers import update_loras_slists@@ -137,6 +138,60 @@ def retrieve_timesteps(return timesteps, num_inference_steps+_UNIFIED_SOLVERS = {"unified", "unified_2s", "unified_4s", "twinflow"}+_UNIFIED_PRESET_GAP = {+ "unified_2s": [0.001, 0.6],+ "unified_4s": [0.001, 0.5],+ "unified_mul": [0.001, 0.0],+}+++class _UnifiedSamplerInterrupted(RuntimeError):+ pass+++def _is_unified_solver(sample_solver: Optional[str]) -> bool:+ solver = (sample_solver or "").strip().lower()+ return solver in _UNIFIED_SOLVERS or solver.startswith("unified_")+++def _resolve_unified_sampler_config(+ sample_solver: Optional[str],+ num_inference_steps: int,+ unified_sampler_config: Optional[Dict[str, Any]],+) -> Dict[str, Any]:+ solver = (sample_solver or "").strip().lower()+ sampling_steps = max(int(num_inference_steps), 1)+ if solver == "unified_2s":+ sampling_steps = 2+ elif solver == "unified_4s":+ sampling_steps = 4++ if sampling_steps <= 2:+ preset_key = "unified_2s"+ sampling_style = "few"+ elif sampling_steps <= 4:+ preset_key = "unified_4s"+ sampling_style = "any"+ else:+ preset_key = "unified_mul"+ sampling_style = "mul"++ rfba_gap_steps = _UNIFIED_PRESET_GAP[preset_key]+ config = {+ "sampling_steps": sampling_steps,+ "stochast_ratio": 1.0,+ "extrapol_ratio": 0.0,+ "sampling_order": 1,+ "sampling_style": sampling_style,+ "time_dist_ctrl": [1.0, 1.0, 1.0],+ "rfba_gap_steps": list(rfba_gap_steps),+ }+ if unified_sampler_config:+ config.update(unified_sampler_config)+ return config++class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):model_cpu_offload_seq = "text_encoder->transformer->vae"_optional_components = []@@ -312,6 +367,8 @@ class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):width: Optional[int] = None,num_inference_steps: int = 50,sigmas: Optional[List[float]] = None,+ sample_solver: str = "default",+ unified_sampler_config: Optional[Dict[str, Any]] = None,guidance_scale: float = 5.0,cfg_normalization: bool = False,cfg_truncation: float = 1.0,@@ -356,6 +413,11 @@ class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument intheir `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passedwill be used.+ sample_solver (`str`, *optional*, defaults to `"default"`):+ Sampler selection. Use `"unified"` for the TwinFlow unified sampler (2-step vs 4-step preset is chosen+ from `num_inference_steps`). `"unified_2s"`/`"unified_4s"` are still accepted for compatibility.+ unified_sampler_config (`dict`, *optional*):+ Optional overrides for unified sampler parameters.guidance_scale (`float`, *optional*, defaults to 5.0):Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).`guidance_scale` is defined as `w` of equation 2. of [Imagen@@ -512,25 +574,27 @@ class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):)image_seq_len = (latents.shape[2] // 2) * (latents.shape[3] // 2)- # 5. Prepare timesteps- mu = calculate_shift(- image_seq_len,- self.scheduler.config.get("base_image_seq_len", 256),- self.scheduler.config.get("max_image_seq_len", 4096),- self.scheduler.config.get("base_shift", 0.5),- self.scheduler.config.get("max_shift", 1.15),- )- self.scheduler.sigma_min = 0.0- scheduler_kwargs = {"mu": mu}- timesteps, num_inference_steps = retrieve_timesteps(- self.scheduler,- num_inference_steps,- device,- sigmas=sigmas,- **scheduler_kwargs,- )- num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)- self._num_timesteps = len(timesteps)+ use_unified = _is_unified_solver(sample_solver)+ if not use_unified:+ # 5. Prepare timesteps+ mu = calculate_shift(+ image_seq_len,+ self.scheduler.config.get("base_image_seq_len", 256),+ self.scheduler.config.get("max_image_seq_len", 4096),+ self.scheduler.config.get("base_shift", 0.5),+ self.scheduler.config.get("max_shift", 1.15),+ )+ self.scheduler.sigma_min = 0.0+ scheduler_kwargs = {"mu": mu}+ timesteps, num_inference_steps = retrieve_timesteps(+ self.scheduler,+ num_inference_steps,+ device,+ sigmas=sigmas,+ **scheduler_kwargs,+ )+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)+ self._num_timesteps = len(timesteps)# Encode control image if provided and transformer supports itcontrol_latent = control_image_tensor = None@@ -592,27 +656,57 @@ class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):# v1 control: just use the control latent directly (16 channels)control_latent_input = control_latent.unsqueeze(2)- callback(-1, None, True, len(timesteps))-- # Initialize LoRA scales if multipliers are provided- if hasattr(self.transformer, 'loras_slists') and self.transformer.loras_slists is not None:- update_loras_slists(self.transformer, self.transformer.loras_slists, len(timesteps))-- # 6. Denoising loop- with self.progress_bar(total=num_inference_steps) as progress_bar:- for i, t in enumerate(timesteps):- # Set LoRA step number for dynamic weight updates- offload.set_step_no_for_lora(self.transformer, i)- if self.interrupt:- break+ if use_unified:+ unified_cfg = _resolve_unified_sampler_config(sample_solver, num_inference_steps, unified_sampler_config)+ sampler = UnifiedSampler()+ sampling_steps = int(unified_cfg.get("sampling_steps", num_inference_steps))+ sampling_order = int(unified_cfg.get("sampling_order", 1))+ sampling_style = str(unified_cfg.get("sampling_style", "few")).lower()+ stochast_ratio = unified_cfg.get("stochast_ratio", 0.0)+ extrapol_ratio = unified_cfg.get("extrapol_ratio", 0.0)+ time_dist_ctrl = unified_cfg.get("time_dist_ctrl", [1.0, 1.0, 1.0])+ rfba_gap_steps = unified_cfg.get("rfba_gap_steps", [0.0, 0.0])+ if sampling_style not in {"few", "mul", "any"}:+ raise ValueError(f"Unknown unified sampling_style '{sampling_style}'")++ num_steps = (sampling_steps + 1) // 2 if sampling_order == 2 else sampling_steps+ if (rfba_gap_steps[1] - 0.0) == 0.0:+ num_steps += 1+ t_steps = torch.linspace(+ rfba_gap_steps[0],+ 1.0 - rfba_gap_steps[1],+ num_steps,+ dtype=torch.float64,+ ).to(latents)+ if (rfba_gap_steps[1] - 0.0) == 0.0:+ t_steps = t_steps[:-1]+ t_steps = sampler.kumaraswamy_transform(t_steps, *time_dist_ctrl)+ t_steps = torch.cat([(1 - t_steps), torch.zeros_like(t_steps[:1])])+ total_steps = max(int(t_steps.numel() - 1), 0)+ self._num_timesteps = total_steps++ callback(-1, None, True, total_steps)+ if hasattr(self.transformer, 'loras_slists') and self.transformer.loras_slists is not None:+ update_loras_slists(self.transformer, self.transformer.loras_slists, total_steps)++ def model_fn(x_t, t, tt=None):+ if self._interrupt:+ raise _UnifiedSamplerInterrupted()- # broadcast to batch dimension in a way that's compatible with ONNX/Core ML- timestep = t.expand(latents.shape[0])- timestep = (1000 - timestep) / 1000- # Normalized time for time-aware config (0 at start, 1 at end)+ t = t.flatten()+ t_sign = t.sign()+ t_abs = t.abs()+ t_mapped = t_sign * (1.0 - t_abs)+ timestep = t_mapped.expand(x_t.shape[0]).to(torch.float32)t_norm = timestep[0].item()+ target_timestep = None+ if tt is not None:+ tt = tt.flatten()+ tt_sign = tt.sign()+ tt_abs = tt.abs()+ tt_mapped = tt_sign * (1.0 - tt_abs)+ target_timestep = tt_mapped.expand(x_t.shape[0]).to(torch.float32)- # Handle cfg truncationcurrent_guidance_scale = self.guidance_scaleif (self.do_classifier_free_guidance@@ -622,27 +716,25 @@ class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):if t_norm > self._cfg_truncation:current_guidance_scale = 0.0- # Run CFG only if configured AND scale is non-zeroapply_cfg = self.do_classifier_free_guidance and current_guidance_scale > 0-- # Prepare latent list (same latents used for both pos and neg in CFG)- latent_model_input = latents if latents.dtype == dtype else latents.to(dtype)+ latent_model_input = x_t if x_t.dtype == dtype else x_t.to(dtype)latent_model_input = latent_model_input.unsqueeze(2)if apply_cfg:model_out_list = self.transformer([latent_model_input, latent_model_input],timestep,- [prompt_embeds[0], negative_prompt_embeds[0]] ,+ [prompt_embeds[0], negative_prompt_embeds[0]],control_context_list=[control_latent_input, control_latent_input] if control_latent_input is not None else None,control_context_scale=control_context_scale,+ target_timestep=target_timestep,callback=callback,pipeline=self,**kwargs,)if model_out_list is None:- return None+ raise _UnifiedSamplerInterrupted()pos, neg = model_out_listmodel_out_list = None@@ -650,7 +742,6 @@ class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):noise_pred = pos + current_guidance_scale * (pos - neg)- # Renormalizationif self._cfg_normalization and float(self._cfg_normalization) > 0.0:ori_pos_norm = torch.linalg.vector_norm(pos)new_pos_norm = torch.linalg.vector_norm(noise_pred)@@ -659,39 +750,207 @@ class ZImagePipeline(DiffusionPipeline, FromSingleFileMixin):noise_pred = noise_pred * (max_new_norm / new_pos_norm)pos = neg = Noneelse:- # Non-CFG mode: single forward pass-model_out_list = self.transformer([latent_model_input],timestep,[prompt_embeds[0]],control_context_list=[control_latent_input] if control_latent_input is not None else None,control_context_scale=control_context_scale,+ target_timestep=target_timestep,callback=callback,pipeline=self,**kwargs,)if model_out_list is None:- return None+ raise _UnifiedSamplerInterrupted()noise_pred = model_out_list[0]model_out_list = None-noise_pred = noise_pred.squeeze(2)noise_pred = -noise_pred+ return noise_pred++ input_dtype = latents.dtype+ x_cur = latents.to(torch.float64)+ x_hats, z_hats = [], []+ buffer_freq = 1+ final_x_hat = None++ with self.progress_bar(total=total_steps) as progress_bar:+ for i, (t_cur, t_next) in enumerate(zip(t_steps[:-1], t_steps[1:])):+ offload.set_step_no_for_lora(self.transformer, i)+ if self.interrupt:+ break++ if sampling_style == "few":+ t_tgt = torch.zeros_like(t_cur)+ elif sampling_style == "mul":+ t_tgt = t_cur+ else:+ t_tgt = t_next++ try:+ x_hat, z_hat, _, _ = sampler.forward(+ model_fn,+ x_cur.to(input_dtype),+ t_cur.to(input_dtype),+ t_tgt.to(input_dtype),+ )+ except _UnifiedSamplerInterrupted:+ self._interrupt = True+ break++ final_x_hat = x_hat.to(torch.float32)+ x_hat, z_hat = x_hat.to(torch.float64), z_hat.to(torch.float64)++ if buffer_freq > 0 and extrapol_ratio > 0:+ z_hats.append(z_hat)+ x_hats.append(x_hat)+ if i > buffer_freq:+ z_hat = z_hat + extrapol_ratio * (z_hat - z_hats[-buffer_freq - 1])+ x_hat = x_hat + extrapol_ratio * (x_hat - x_hats[-buffer_freq - 1])+ z_hats.pop(0)+ x_hats.pop(0)++ if stochast_ratio == "SDE":+ stochast_ratio = (+ torch.sqrt((t_next - t_cur).abs())+ * torch.sqrt(2 * sampler.alpha_in(t_cur))+ / sampler.alpha_in(t_next)+ )+ stochast_ratio = torch.clamp(stochast_ratio ** (1 / 0.50), min=0, max=1)+ noi = torch.randn(x_cur.size()).to(x_cur)+ else:+ noi = torch.randn(x_cur.size()).to(x_cur) if stochast_ratio > 0 else 0.0+ x_next = sampler.gamma_in(t_next) * x_hat + sampler.alpha_in(t_next) * (+ z_hat * ((1 - stochast_ratio) ** 0.5) + noi * (stochast_ratio**0.5)+ )++ if sampling_order == 2 and i < num_steps - 1:+ if sampling_style == "few":+ t_tgt = torch.zeros_like(t_next)+ elif sampling_style == "mul":+ t_tgt = t_next+ else:+ t_tgt = t_next+ x_pri, z_pri, _, _ = sampler.forward(+ model_fn,+ x_next.to(input_dtype),+ t_next.to(input_dtype),+ t_tgt.to(input_dtype),+ )+ x_pri, z_pri = x_pri.to(torch.float64), z_pri.to(torch.float64)- # compute the previous noisy sample x_t -> x_t-1- latents = self.scheduler.step(noise_pred.to(torch.float32), t, latents, return_dict=False)[0]- assert latents.dtype == torch.float32+ x_next = x_cur * sampler.gamma_in(t_next) / sampler.gamma_in(t_cur) + (+ sampler.alpha_in(t_next)+ - sampler.gamma_in(t_next) * sampler.alpha_in(t_cur) / sampler.gamma_in(t_cur)+ ) * (0.5 * z_hat + 0.5 * z_pri)- if self._interrupt:- break- if callback is not None:- latents_preview = latents.unsqueeze(2)- if len(latents_preview) > 1: latents_preview = latents_preview.transpose(0,2)- callback(i, latents_preview[0], False)- latents_preview = None+ x_cur = x_next++ if self._interrupt:+ break+ if callback is not None and final_x_hat is not None:+ latents_preview = final_x_hat.unsqueeze(2)+ if len(latents_preview) > 1:+ latents_preview = latents_preview.transpose(0, 2)+ callback(i, latents_preview[0], False)+ latents_preview = None++ if self._interrupt or final_x_hat is None:+ return None++ latents = final_x_hat+ else:+ callback(-1, None, True, len(timesteps))++ if hasattr(self.transformer, 'loras_slists') and self.transformer.loras_slists is not None:+ update_loras_slists(self.transformer, self.transformer.loras_slists, len(timesteps))++ with self.progress_bar(total=num_inference_steps) as progress_bar:+ for i, t in enumerate(timesteps):+ offload.set_step_no_for_lora(self.transformer, i)+ if self.interrupt:+ break++ timestep = t.expand(latents.shape[0])+ timestep = (1000 - timestep) / 1000+ t_norm = timestep[0].item()++ current_guidance_scale = self.guidance_scale+ if (+ self.do_classifier_free_guidance+ and self._cfg_truncation is not None+ and float(self._cfg_truncation) <= 1+ ):+ if t_norm > self._cfg_truncation:+ current_guidance_scale = 0.0++ apply_cfg = self.do_classifier_free_guidance and current_guidance_scale > 0++ latent_model_input = latents if latents.dtype == dtype else latents.to(dtype)+ latent_model_input = latent_model_input.unsqueeze(2)++ if apply_cfg:+ model_out_list = self.transformer(+ [latent_model_input, latent_model_input],+ timestep,+ [prompt_embeds[0], negative_prompt_embeds[0]] ,+ control_context_list=[control_latent_input, control_latent_input] if control_latent_input is not None else None,+ control_context_scale=control_context_scale,+ callback=callback,+ pipeline=self,+ **kwargs,+ )++ if model_out_list is None:+ return None++ pos, neg = model_out_list+ model_out_list = None+ pos, neg = pos.float(), neg.float()++ noise_pred = pos + current_guidance_scale * (pos - neg)++ if self._cfg_normalization and float(self._cfg_normalization) > 0.0:+ ori_pos_norm = torch.linalg.vector_norm(pos)+ new_pos_norm = torch.linalg.vector_norm(noise_pred)+ max_new_norm = ori_pos_norm * float(self._cfg_normalization)+ if new_pos_norm > max_new_norm:+ noise_pred = noise_pred * (max_new_norm / new_pos_norm)+ pos = neg = None+ else:+ model_out_list = self.transformer(+ [latent_model_input],+ timestep,+ [prompt_embeds[0]],+ control_context_list=[control_latent_input] if control_latent_input is not None else None,+ control_context_scale=control_context_scale,+ callback=callback,+ pipeline=self,+ **kwargs,+ )++ if model_out_list is None:+ return None+ noise_pred = model_out_list[0]+ model_out_list = None++ noise_pred = noise_pred.squeeze(2)+ noise_pred = -noise_pred++ latents = self.scheduler.step(noise_pred.to(torch.float32), t, latents, return_dict=False)[0]+ assert latents.dtype == torch.float32++ if self._interrupt:+ break+ if callback is not None:+ latents_preview = latents.unsqueeze(2)+ if len(latents_preview) > 1:+ latents_preview = latents_preview.transpose(0, 2)+ callback(i, latents_preview[0], False)+ latents_preview = Noneif self._interrupt:diff --git a/models/z_image/unified_sampler.py b/models/z_image/unified_sampler.pynew file mode 100644index 0000000..11807bd--- /dev/null+++ b/models/z_image/unified_sampler.py@@ -0,0 +1,61 @@+import torch+from torch import nn+from typing import Callable, Union+++class Linear:+ def alpha_in(self, t):+ return t++ def gamma_in(self, t):+ return 1 - t++ def alpha_to(self, t):+ return 1++ def gamma_to(self, t):+ return -1+++class UnifiedSampler(torch.nn.Module):+ """+ UCGM-S: https://arxiv.org/abs/2505.07447+ Credit to https://github.com/LINs-lab/UCGM/blob/main/methodes/unigen.py+ """++ def __init__(self):+ super().__init__()++ transport = Linear()+ self.alpha_in, self.gamma_in = transport.alpha_in, transport.gamma_in+ self.alpha_to, self.gamma_to = transport.alpha_to, transport.gamma_to++ if self.gamma_in(torch.tensor(0)).abs().item() < 0.005:+ self.integ_st = 0 # Start point if integral from 0 to 1+ self.alpha_in, self.gamma_in = self.gamma_in, self.alpha_in+ self.alpha_to, self.gamma_to = self.gamma_to, self.alpha_to+ elif self.alpha_in(torch.tensor(0)).abs().item() < 0.005:+ self.integ_st = 1 # Start point if integral from 1 to 0+ else:+ raise ValueError("Invalid Alpha and Gamma functions")++ def forward(+ self,+ model: Union[nn.Module, Callable],+ x_t: torch.Tensor,+ t: torch.Tensor,+ tt: Union[torch.Tensor, None] = None,+ **model_kwargs,+ ):+ tt = tt.flatten()+ dent = self.alpha_in(t) * self.gamma_to(t) - self.gamma_in(t) * self.alpha_to(t)+ q = torch.ones(x_t.size(0), device=x_t.device) * (t).flatten()+ q = q if self.integ_st == 1 else 1 - q+ F_t = (-1) ** (1 - self.integ_st) * model(x_t, t=q, tt=tt, **model_kwargs)+ t = torch.abs(t)+ z_hat = (x_t * self.gamma_to(t) - F_t * self.gamma_in(t)) / dent+ x_hat = (F_t * self.alpha_in(t) - x_t * self.alpha_to(t)) / dent+ return x_hat, z_hat, F_t, dent++ def kumaraswamy_transform(self, t, a, b, c):+ return (1 - (1 - t**a) ** b) ** cdiff --git a/models/z_image/z_image_main.py b/models/z_image/z_image_main.pyindex cc71fce..9df1b65 100644--- a/models/z_image/z_image_main.py+++ b/models/z_image/z_image_main.py@@ -95,8 +95,7 @@ class model_factory:is_control=False,**kwargs,):--+ model_def = model_def or {}source = model_def.get("source", None)module_source = model_def.get("module_source", None)@@ -108,6 +107,7 @@ class model_factory:self.base_model_type = base_model_typeself.is_control = is_control+ self.model_def = model_defdefault_transformer_config = os.path.join(os.path.dirname(os.path.abspath(__file__)), "configs", f"{base_model_type}.json")@@ -196,6 +196,7 @@ class model_factory:input_prompt: str = "",n_prompt: str | None = None,sampling_steps: int = 20,+ sample_solver: str = "default",width: int = 1024,height: int = 1024,guide_scale: float = 0.0,@@ -232,12 +233,19 @@ class model_factory:self.vae.tile_latent_min_height = tile_sizeself.vae.tile_latent_min_width = tile_size+ unified_solver = self.model_def.get("unified_solver", False)+ if unified_solver:+ sample_solver = "unified"+ elif not sample_solver:+ sample_solver = "default"+guide_scale = 0images = self.pipeline(prompt=input_prompt,negative_prompt=n_prompt,num_inference_steps=sampling_steps,+ sample_solver=sample_solver,guidance_scale=guide_scale,num_images_per_prompt=batch_size,generator=generator,diff --git a/models/z_image/z_image_transformer2d.py b/models/z_image/z_image_transformer2d.pyindex 300b7ff..6738ca0 100644--- a/models/z_image/z_image_transformer2d.py+++ b/models/z_image/z_image_transformer2d.py@@ -969,6 +969,7 @@ class ZImageTransformer2DModel(nn.Module):f_patch_size=1,control_context_list=None,control_context_scale=1.0,+ target_timestep=None,callback=None,pipeline=None,NAG =None,@@ -981,8 +982,15 @@ class ZImageTransformer2DModel(nn.Module):assert len(cap_feats_list) == num_noise_samples, "cap_feats_list must match x_list length"device = x_list[0].device- t = t * self.t_scale- t = self.t_embedder(t)+ t_high = t.to(dtype=torch.float64)+ t_emb = self.t_embedder(t_high.abs() * self.t_scale)+ if target_timestep is not None:+ target_t_high = target_timestep.to(dtype=torch.float64)+ delta_t = t_high - target_t_high+ delta_t_abs = delta_t.abs()+ t_emb_2 = self.t_embedder((target_t_high - t_high) * self.t_scale)+ t_emb = t_emb + t_emb_2 * delta_t_abs.unsqueeze(1)+ t = t_emb# Patchify and embed each (x, cap_feats) pairx_embedder = self.all_x_embedder[f"{patch_size}-{f_patch_size}"]diff --git a/shared/qtypes/nunchaku_fp4.py b/shared/qtypes/nunchaku_fp4.pyindex 268380c..256b60b 100644--- a/shared/qtypes/nunchaku_fp4.py+++ b/shared/qtypes/nunchaku_fp4.py@@ -400,8 +400,10 @@ def _unpack_nunchaku_fp4_weight(qweight, out_features, in_features):k_tiles = in_features // mem_kpacked_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 = torch.stack(+ [(packed_i32 >> shift) & 0xF for shift in (0, 4, 8, 12, 16, 20, 24, 28)],+ dim=-1,+ )vals = vals.permute(0, 3, 6, 4, 8, 1, 2, 7, 5, 9).contiguous()vals = vals.view(out_features, in_features).to(torch.int16)return vals@@ -428,9 +430,7 @@ def _unpack_int4_from_int32(qweight, 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+ vals = torch.stack([(q >> shift) & 0xF for shift in range(0, 32, 4)], dim=-1)return vals.reshape(out_features, in_features)@@ -660,6 +660,8 @@ class NunchakuSVDQWeightTensor(NunchakuBaseWeightTensor):return out.reshape(*input.shape[:-1], out_features)def _linear_cuda(self, input, bias=None):+ if torch.compiler.is_compiling():+ return self._linear_fallback(input, bias=bias)ops = _load_nunchaku_ops()if not ops:return self._linear_fallback(input, bias=bias)@@ -697,7 +699,14 @@ class NunchakuSVDQWeightTensor(NunchakuBaseWeightTensor):out = out[: x.shape[0]]return out.reshape(*input.shape[:-1], self.shape[0])+ @torch.compiler.disable()def linear(self, input, bias=None):+ if torch.is_tensor(input):+ from torch._subclasses.fake_tensor import is_fake++ if is_fake(input):+ out_shape = (*input.shape[:-1], self.shape[0])+ return torch.empty(out_shape, device=input.device, dtype=input.dtype)if torch.is_tensor(input) and input.device.type == "cuda":return self._linear_cuda(input, bias=bias)return self._linear_fallback(input, bias=bias)@@ -974,6 +983,8 @@ class NunchakuAWQWeightTensor(NunchakuBaseWeightTensor):return out.reshape(*input.shape[:-1], weight.shape[0])def _linear_cuda(self, input, bias=None):+ if torch.compiler.is_compiling():+ return self._linear_fallback(input, bias=bias)ops = _load_nunchaku_ops()if not ops:return self._linear_fallback(input, bias=bias)@@ -994,7 +1005,14 @@ class NunchakuAWQWeightTensor(NunchakuBaseWeightTensor):out.add_(bias.view(view_shape))return out.reshape(*input.shape[:-1], out.shape[-1])+ @torch.compiler.disable()def linear(self, input, bias=None):+ if torch.is_tensor(input):+ from torch._subclasses.fake_tensor import is_fake++ if is_fake(input):+ out_shape = (*input.shape[:-1], self.shape[0])+ return torch.empty(out_shape, device=input.device, dtype=input.dtype)if torch.is_tensor(input) and input.device.type == "cuda":return self._linear_cuda(input, bias=bias)return self._linear_fallback(input, bias=bias)diff --git a/shared/qtypes/nunchaku_int4.py b/shared/qtypes/nunchaku_int4.pyindex 9925e54..241772b 100644--- a/shared/qtypes/nunchaku_int4.py+++ b/shared/qtypes/nunchaku_int4.py@@ -317,8 +317,10 @@ def _unpack_nunchaku_w4a4_weight(qweight, out_features, in_features):k_tiles = in_features // mem_kpacked_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 = torch.stack(+ [(packed_i32 >> shift) & 0xF for shift in (0, 4, 8, 12, 16, 20, 24, 28)],+ dim=-1,+ )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@@ -346,9 +348,7 @@ def _unpack_int4_from_int32(qweight, 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+ vals = torch.stack([(q >> shift) & 0xF for shift in range(0, 32, 4)], dim=-1)return vals.reshape(out_features, in_features)@@ -587,6 +587,7 @@ class NunchakuSVDQWeightTensor(NunchakuBaseWeightTensor):out = out[: x.shape[0]]return out.reshape(*input.shape[:-1], self.shape[0])+ @torch.compiler.disable()def linear(self, input, bias=None):if torch.is_tensor(input) and input.device.type == "cuda":return self._linear_cuda(input, bias=bias)@@ -862,6 +863,7 @@ class NunchakuAWQWeightTensor(NunchakuBaseWeightTensor):out.add_(bias.view(view_shape))return out.reshape(*input.shape[:-1], out.shape[-1])+ @torch.compiler.disable()def linear(self, input, bias=None):if torch.is_tensor(input) and input.device.type == "cuda":return self._linear_cuda(input, bias=bias)