Python
added lanpaint, unlocked longcat add fast scaled fp8
DeepBeepMeepa2b1ba826e4b
diff --git a/defaults/longcat_avatar.json b/defaults/longcat_avatar.jsonindex ec4dbb8..e2b3444 100644--- a/defaults/longcat_avatar.json+++ b/defaults/longcat_avatar.json@@ -10,7 +10,6 @@],"reference_image_enabled": true,"ref_img_index": 10,- "visible": false,"mask_frame_range": 3},"num_inference_steps": 50diff --git a/defaults/longcat_avatar_multi.json b/defaults/longcat_avatar_multi.jsonindex 56617ea..b0e98c8 100644--- a/defaults/longcat_avatar_multi.json+++ b/defaults/longcat_avatar_multi.json@@ -10,7 +10,6 @@],"reference_image_enabled": true,"ref_img_index": 10,- "visible": false,"mask_frame_range": 3},"num_inference_steps": 50diff --git a/defaults/longcat_video.json b/defaults/longcat_video.jsonindex 619b78f..b16f495 100644--- a/defaults/longcat_video.json+++ b/defaults/longcat_video.json@@ -3,7 +3,6 @@"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.",- "visible": false,"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"diff --git a/models/longcat/longcat_main.py b/models/longcat/longcat_main.pyindex 1fd10bc..c1f1240 100644--- a/models/longcat/longcat_main.py+++ b/models/longcat/longcat_main.py@@ -508,7 +508,7 @@ class LongCatModel:sample_solver = kwargs.get("sample_solver", self.model_def.get("sample_solver", "auto"))if sample_solver in (None, ""):- sample_solver = "auto"+ sample_solver = "default"prompt_embeds, prompt_mask, neg_embeds, neg_mask = self._encode_prompt(input_prompt,@@ -575,7 +575,7 @@ class LongCatModel:use_distill = sample_solver == "distill"enhance_hf = sample_solver == "enhance_hf"if sample_solver == "auto":- enhance_hf = cond_video is not None and num_cond_frames > 0+ enhance_hf = cond_video is not None and num_cond_frames > 1if use_distill and enhance_hf:raise ValueError("distill and enhance_hf schedules cannot both be enabled.")@@ -604,21 +604,86 @@ class LongCatModel:ref_latent = self.normalize_latents(ref_latent).to(torch.float32)num_ref_latents = 1+ overlapped_latents = kwargs.get("overlapped_latents")+ if torch.is_tensor(overlapped_latents):+ if overlapped_latents.dim() == 4:+ overlapped_latents = overlapped_latents.unsqueeze(0)+ if overlapped_latents.dim() != 5:+ overlapped_latents = None+ else:+ overlapped_latents = None+cond_image_frames = 1 if image_cond is not None else num_cond_frames- latents, num_cond_latents = self._prepare_latents(- batch_size=batch_size,- num_channels_latents=self.transformer.config.in_channels,- height=height,- width=width,- num_frames=frame_num,- dtype=torch.float32,- device=self.device,- generator=generator,- latents=None,- image=image_cond,- video=None if image_cond is not None else cond_video,- num_cond_frames=cond_image_frames,+ expected_num_cond_latents = (+ 1 + (cond_image_frames - 1) // self.vae_scale_factor_temporal if cond_image_frames > 0 else 0)+ use_overlap_latents = (+ overlapped_latents is not None and expected_num_cond_latents > 0 and image_cond is None+ )+ if use_overlap_latents:+ lat_h = int(height) // self.vae_scale_factor_spatial+ lat_w = int(width) // self.vae_scale_factor_spatial+ if (+ overlapped_latents.shape[1] != self.transformer.config.in_channels+ or overlapped_latents.shape[3] != lat_h+ or overlapped_latents.shape[4] != lat_w+ ):+ use_overlap_latents = False++ if use_overlap_latents:+ num_latent_frames = (frame_num - 1) // self.vae_scale_factor_temporal + 1+ shape = (+ batch_size,+ self.transformer.config.in_channels,+ num_latent_frames,+ lat_h,+ lat_w,+ )+ latents = torch.randn(shape, generator=generator, device=self.device, dtype=torch.float32)++ overlap_latents = overlapped_latents.to(device=self.device, dtype=torch.float32)+ if overlap_latents.shape[0] == 1 and batch_size > 1:+ overlap_latents = overlap_latents.repeat(batch_size, 1, 1, 1, 1)+ if overlap_latents.shape[2] > expected_num_cond_latents:+ overlap_latents = overlap_latents[:, :, -expected_num_cond_latents:]++ cond_latents = None+ if cond_video is not None and overlap_latents.shape[2] < expected_num_cond_latents:+ cond_latents_list = []+ for i in range(batch_size):+ encoded_input = cond_video[i][:, -cond_image_frames:].unsqueeze(0)+ latent = retrieve_latents(+ self.vae.encode(encoded_input),+ generator,+ sample_mode="argmax",+ )+ cond_latents_list.append(latent)+ cond_latents = torch.cat(cond_latents_list, dim=0).to(torch.float32)+ cond_latents = self.normalize_latents(cond_latents)+ overlap_len = min(overlap_latents.shape[2], cond_latents.shape[2])+ if overlap_len > 0:+ cond_latents[:, :, -overlap_len:] = overlap_latents[:, :, -overlap_len:]+ else:+ cond_latents = overlap_latents++ num_cond_latents = min(cond_latents.shape[2], num_latent_frames) if cond_latents is not None else 0+ if num_cond_latents > 0:+ latents[:, :, :num_cond_latents] = cond_latents[:, :, -num_cond_latents:]+ else:+ latents, num_cond_latents = self._prepare_latents(+ batch_size=batch_size,+ num_channels_latents=self.transformer.config.in_channels,+ height=height,+ width=width,+ num_frames=frame_num,+ dtype=torch.float32,+ device=self.device,+ generator=generator,+ latents=None,+ image=image_cond,+ video=None if image_cond is not None else cond_video,+ num_cond_frames=cond_image_frames,+ )if reference_image_enabled and ref_latent is None and self.is_avatar and num_cond_latents > 1:ref_latent = latents[:, :, :1].clone()num_ref_latents = 1@@ -631,9 +696,9 @@ class LongCatModel:self.scheduler.set_timesteps(sampling_steps, sigmas=sigmas, device=self.device)timesteps = self.scheduler.timestepsif enhance_hf:- tail_uniform_start = 500+ num_tail_uniform_steps = max(3, min(15, int(len(timesteps) * 0.2)))+ tail_uniform_start = float(timesteps.max()) * 0.5tail_uniform_end = 0- num_tail_uniform_steps = 10timesteps_uniform_tail = list(np.linspace(tail_uniform_start,@@ -647,7 +712,9 @@ class LongCatModel:torch.tensor(t, device=self.device, dtype=torch.float32).unsqueeze(0)for t in timesteps_uniform_tail]- filtered_timesteps = [timestep.unsqueeze(0) for timestep in timesteps if timestep > tail_uniform_start]+ filtered_timesteps = [+ timestep.unsqueeze(0).to(self.device) for timestep in timesteps if timestep > tail_uniform_start+ ]timesteps = torch.cat(filtered_timesteps + timesteps_uniform_tail)self.scheduler.timesteps = timestepsself.scheduler.sigmas = torch.cat(@@ -694,6 +761,8 @@ class LongCatModel:"mask_frame_range": mask_frame_range,}+ callback(-1, None, True, override_num_inference_steps = len(timesteps))+with tqdm(total=len(timesteps), desc="Denoising") as progress_bar:for i, t in enumerate(timesteps):if self._interrupt:diff --git a/models/longcat/modules/attention.py b/models/longcat/modules/attention.pyindex 54639c0..20c6c47 100644--- a/models/longcat/modules/attention.py+++ b/models/longcat/modules/attention.py@@ -3,7 +3,7 @@ from typing import List, Optionalimport torchimport torch.nn as nn-from shared.attention import pay_attention, pay_sparse_attention+from shared.attention import pay_attention #, pay_sparse_attentionfrom .rope_3d import RotaryPositionalEmbeddingfrom .blocks import RMSNorm_FP32diff --git a/models/longcat/modules/avatar/attention.py b/models/longcat/modules/avatar/attention.pyindex 1787088..6847f05 100644--- a/models/longcat/modules/avatar/attention.py+++ b/models/longcat/modules/avatar/attention.py@@ -5,7 +5,7 @@ import torch.nn as nnfrom einops import rearrange-from shared.attention import pay_attention, pay_sparse_attention+from shared.attention import pay_attention #, pay_sparse_attentionfrom .rope_3d import RotaryPositionalEmbeddingfrom ..blocks import RMSNorm_FP32from ...audio_process.torch_utils import get_attn_map_with_targetdiff --git a/models/qwen/pipeline_qwenimage.py b/models/qwen/pipeline_qwenimage.pyindex f2ef8b3..8a20050 100644--- a/models/qwen/pipeline_qwenimage.py+++ b/models/qwen/pipeline_qwenimage.py@@ -585,7 +585,7 @@ class QwenImagePipeline(): #DiffusionPipelinepipeline=None,loras_slists=None,joint_pass= True,- lora_inpaint = False,+ model_mode = 0,outpainting_dims = None,qwen_edit_plus = False,VAE_tile_size = 0,@@ -658,6 +658,9 @@ class QwenImagePipeline(): #DiffusionPipelinereturning a tuple, the first element is a list with the generated images."""+ lora_inpaint = image_mask is not None and model_mode == 1+ lanpaint_enabled = image_mask is not None and model_mode == 2+kwargs = {'pipeline': pipeline, 'callback': callback}if callback != None:callback(-1, None, True)@@ -855,7 +858,10 @@ class QwenImagePipeline(): #DiffusionPipelinelanpaint_proc = original_image_latents = Noneif image_mask_latents is not None:original_image_latents = image_latents[:, :latents.shape[1]].clone()-+ if lanpaint_enabled:+ from shared.inpainting.lanpaint import LanPaint+ lanpaint_proc = LanPaint()+ denoising_strength = 1.randn = torch.randn_like(original_image_latents)if denoising_strength < 1.:first_step = int(len(timesteps) * (1. - denoising_strength))@@ -867,8 +873,6 @@ class QwenImagePipeline(): #DiffusionPipelinetimesteps = timesteps[first_step:]self.scheduler.timesteps = timestepsself.scheduler.sigmas= self.scheduler.sigmas[first_step:]- # from shared.inpainting.lanpaint import LanPaint- # lanpaint_proc = LanPaint()# 6. Denoising loopself.scheduler.set_begin_index(0)updated_num_steps= len(timesteps)@@ -958,7 +962,7 @@ class QwenImagePipeline(): #DiffusionPipelinereturn noise_pred- if lanpaint_proc is not None and i<=3:+ if lanpaint_proc is not None and i<=updated_num_steps-1:latents = lanpaint_proc(denoise, cfg_predictions, true_cfg_scale, 1., latents, original_image_latents, randn, t/1000, image_mask_latents, height=height , width= width, vae_scale_factor= 8)if latents is None: return Nonediff --git a/models/qwen/qwen_handler.py b/models/qwen/qwen_handler.pyindex 2d62f8f..16419ce 100644--- a/models/qwen/qwen_handler.py+++ b/models/qwen/qwen_handler.py@@ -55,6 +55,7 @@ class family_handler():"choices": [("Lora Inpainting: Inpainted area completely unrelated to masked content", 1),("Masked Denoising : Inpainted area may reuse some content that has been masked", 0),+ ("LanPaint : High Quality Inpainting but up x5 slower", 2),],"default": 1,"label" : "Inpainting Method",@@ -195,10 +196,10 @@ class family_handler():from wgp import get_outpainting_dimsoutpainting_dims = get_outpainting_dims(video_guide_outpainting)- if denoising_strength < 1 and model_mode == 1:- gr.Info("Denoising Strength will be ignored while using Lora Inpainting")- if outpainting_dims is not None and model_mode == 0 :- return "Outpainting is not supported with Masked Denoising"+ if denoising_strength < 1 and model_mode != 0:+ gr.Info("Denoising Strength will be ignored if Masked Denoising is not used")+ if outpainting_dims is not None and model_mode != 1 :+ return "Outpainting is supported only with Lora Inpainting"if base_model_type in ["qwen_image_layered_20B"]:if inputs.get("image_guide") is None:return "Qwen Image Layered requires a Control Image."diff --git a/models/qwen/qwen_main.py b/models/qwen/qwen_main.pyindex 8041fc9..da6f8ae 100644--- a/models/qwen/qwen_main.py+++ b/models/qwen/qwen_main.py@@ -279,7 +279,7 @@ class model_factory():denoising_strength=denoising_strength,masking_strength=masking_strength,generator=torch.Generator(device="cuda").manual_seed(seed),- lora_inpaint = image_mask is not None and model_mode == 1,+ model_mode = model_mode,outpainting_dims = outpainting_dims,qwen_edit_plus = qwen_edit_plus,VAE_tile_size = tile_size,diff --git a/shared/inpainting/lanpaint.py b/shared/inpainting/lanpaint.pyindex 3165e7b..b5f9b05 100644--- a/shared/inpainting/lanpaint.py+++ b/shared/inpainting/lanpaint.py@@ -58,6 +58,7 @@ class LanPaint():if n_steps is None:n_steps = self.n_stepsout = self.LanPaint(denoise, cfg_predictions, true_cfg_scale, cfg_BIG, x, sigma, latent_mask, n_steps, self.IS_FLUX, self.IS_FLOW)+ if out is None: return Noneout = _pack_latents(out)return outdef LanPaint(self, denoise, cfg_predictions, true_cfg_scale, cfg_BIG, x, sigma, latent_mask, n_steps, IS_FLUX, IS_FLOW):@@ -65,16 +66,27 @@ class LanPaint():cfg_BIG = 1.0def double_denoise(latents, t):+ latents_unpacked = latentslatents = _pack_latents(latents)noise_pred, neg_noise_pred = denoise(latents, true_cfg_scale)- if noise_pred == None: return None, None+ if noise_pred is None:+ return None, Nonepredict_std = cfg_predictions(noise_pred, neg_noise_pred, true_cfg_scale, t)+ if predict_std is None:+ return None, Nonepredict_std = _unpack_latents(predict_std, self.height, self.width, self.vae_scale_factor)if true_cfg_scale == cfg_BIG:predict_big = predict_stdelse:predict_big = cfg_predictions(noise_pred, neg_noise_pred, cfg_BIG, t)+ if predict_big is None:+ return None, Nonepredict_big = _unpack_latents(predict_big, self.height, self.width, self.vae_scale_factor)+ if self.IS_FLUX or self.IS_FLOW:+ # Flow/Flux models predict velocity; convert to x0 for LanPaint scoring.+ t_broadcast = self.add_none_dims(t)+ predict_std = latents_unpacked - t_broadcast * predict_std+ predict_big = latents_unpacked - t_broadcast * predict_bigreturn predict_std, predict_bigif len(sigma.shape) == 0:@@ -113,6 +125,7 @@ class LanPaint():score_func = partial( self.score_model, y = self.latent_image, mask = latent_mask, abt = self.add_none_dims(abt), sigma = self.add_none_dims(VE_Sigma), tflow = self.add_none_dims(Flow_t), denoise_func = double_denoise )if score_func is None: return Nonex_t, args = self.langevin_dynamics(x_t, score_func , latent_mask, step_size , current_times, sigma_x = self.add_none_dims(self.sigma_x(abt)), sigma_y = self.add_none_dims(self.sigma_y(abt)), args = args)+ if x_t is None: return Noneif IS_FLUX or IS_FLOW:x = x_t / ( self.add_none_dims(abt)**0.5 + (1-self.add_none_dims(abt))**0.5 )else:@@ -168,6 +181,7 @@ class LanPaint():def Coef_C(x_t):x0 = self.x0_evalutation(x_t, score, sigma, args)+ if x0 is None: return NoneC = (abt**0.5 * x0 - x_t )/ (1-abt) + A * x_treturn Cdef advance_time(x_t, v, dt, Gamma, A, C, D):@@ -182,6 +196,8 @@ class LanPaint():#v = torch.zeros_like(x_t)v = NoneC = Coef_C(x_t)+ if C is None:+ return None, None#print(torch.squeeze(dtx), torch.squeeze(dty))x_t, v = advance_time(x_t, v, dt, Gamma, A, C, D)else:@@ -190,6 +206,8 @@ class LanPaint():x_t, v = advance_time(x_t, v, dt/2, Gamma, A, C, D)C_new = Coef_C(x_t)+ if C_new is None:+ return None, Nonev = v + Gamma**0.5 * ( C_new - C) *dtx_t, v = advance_time(x_t, v, dt/2, Gamma, A, C, D)@@ -236,5 +254,8 @@ class LanPaint():def x0_evalutation(self, x_t, score, sigma, args):- x0 = x_t + score(x_t)- return x0\ No newline at end of file+ score = score(x_t)+ if score is None:+ return None+ x0 = x_t + score+ return x0diff --git a/shared/qtypes/scaled_fp8.py b/shared/qtypes/scaled_fp8.pynew file mode 100644index 0000000..fada1dd--- /dev/null+++ b/shared/qtypes/scaled_fp8.py@@ -0,0 +1,560 @@+import ast+import os++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+++HANDLER_NAME = "fp8"++_SCALED_FP8_E4M3_QTYPE_NAME = "scaled_float8_e4m3fn"+_SCALED_FP8_E5M2_QTYPE_NAME = "scaled_float8_e5m2"+++def _register_fp8_qtype(name, dtype):+ if name not in _quanto_qtypes:+ _quanto_qtypes[name] = _quanto_qtype(+ name,+ is_floating_point=True,+ bits=8,+ dtype=dtype,+ qmin=float(torch.finfo(dtype).min),+ qmax=float(torch.finfo(dtype).max),+ )+ return _quanto_qtypes[name]+++_SCALED_FP8_QTYPE_E4M3 = _register_fp8_qtype(_SCALED_FP8_E4M3_QTYPE_NAME, torch.float8_e4m3fn)+_SCALED_FP8_QTYPE_E5M2 = _register_fp8_qtype(_SCALED_FP8_E5M2_QTYPE_NAME, torch.float8_e5m2)++_SCALED_FP8_QTYPE_BY_DTYPE = {+ torch.float8_e4m3fn: _SCALED_FP8_QTYPE_E4M3,+ torch.float8_e5m2: _SCALED_FP8_QTYPE_E5M2,+}+_SCALED_FP8_QTYPES = set(_SCALED_FP8_QTYPE_BY_DTYPE.values())++_FP8_RANGE = {+ torch.float8_e4m3fn: (float(torch.finfo(torch.float8_e4m3fn).min), float(torch.finfo(torch.float8_e4m3fn).max)),+ torch.float8_e5m2: (float(torch.finfo(torch.float8_e5m2).min), float(torch.finfo(torch.float8_e5m2).max)),+}++_FP8_MM_SUPPORT = {+ torch.float8_e4m3fn: False,+ torch.float8_e5m2: False,+}+_FP8_MM_PROBED = False++def _is_float8_dtype(dtype):+ return dtype in _SCALED_FP8_QTYPE_BY_DTYPE+++def _get_fp8_qtype(dtype):+ return _SCALED_FP8_QTYPE_BY_DTYPE.get(dtype, None)+++def _scaled_mm_available(dtype):+ if os.environ.get("WAN2GP_FORCE_FP8_FALLBACK", "").strip().lower() in ("1", "true", "yes", "on"):+ return False+ return bool(_FP8_MM_SUPPORT.get(dtype, False))+++def _reshape_scale(scale, weight):+ if scale.ndim == 0 or scale.numel() == 1:+ return scale+ if scale.ndim == 1 and scale.shape[0] == weight.shape[0]:+ return scale.view(weight.shape[0], *([1] * (weight.ndim - 1)))+ if scale.ndim == 2 and scale.shape[0] == weight.shape[0] and scale.shape[1] == 1:+ return scale.view(weight.shape[0], *([1] * (weight.ndim - 1)))+ return scale+++def _normalize_scaled_mm_scale(scale):+ if not torch.is_tensor(scale):+ return None+ if scale.numel() != 1:+ return None+ if scale.ndim == 0:+ return scale+ return scale.reshape(())+++def _quantize_activation(x, fp8_dtype):+ minv, maxv = _FP8_RANGE[fp8_dtype]+ absmax = x.abs().max().float()+ scale = absmax / maxv+ scale = torch.where(absmax > 0, scale, torch.ones_like(scale))+ scale_f16 = scale.to(dtype=x.dtype)+ q = (x / scale_f16).clamp(minv, maxv).to(fp8_dtype)+ return q, scale.reshape(()).to(torch.float32)+++def _scaled_mm_static_ok(weight, scale):+ if weight is None or scale is None:+ return False+ if not _is_float8_dtype(weight.dtype):+ return False+ if weight.ndim != 2:+ return False+ if not weight.is_contiguous():+ return False+ if weight.shape[0] % 16 != 0 or weight.shape[1] % 16 != 0:+ return False+ if scale.numel() != 1:+ return False+ return True+++++def _init_scaled_mm_support():+ global _FP8_MM_PROBED+ if _FP8_MM_PROBED:+ return+ _FP8_MM_PROBED = True+ if not torch.cuda.is_available():+ return+ support = {torch.float8_e4m3fn: False, torch.float8_e5m2: False}+ try:+ device = torch.device("cuda", torch.cuda.current_device())+ with torch.cuda.device(device):+ a = torch.randn(1, 16, device=device, dtype=torch.float16)+ b = torch.randn(16, 16, device=device, dtype=torch.float16)+ scale = torch.ones((), device=device, dtype=torch.float32)+ for fp8_dtype in support:+ try:+ a_fp8 = a.to(fp8_dtype)+ b_fp8 = b.to(fp8_dtype)+ torch._scaled_mm(a_fp8, b_fp8.t(), scale, scale, out_dtype=torch.float16)+ support[fp8_dtype] = True+ except Exception:+ support[fp8_dtype] = False+ except Exception:+ support = {torch.float8_e4m3fn: False, torch.float8_e5m2: False}+ _FP8_MM_SUPPORT.update(support)+++def _scaled_fp8_qfallback(callable, *args, **kwargs):+ args, kwargs = pytree.tree_map_only(ScaledFP8WeightTensor, lambda x: x.dequantize(), (args, kwargs or {}))+ return callable(*args, **kwargs)+++class ScaledFP8WeightTensor(QTensor):+ @staticmethod+ def create(weight, scale, size, stride, dtype, device=None, requires_grad=False):+ if scale is None:+ scale = torch.ones((), device=weight.device, dtype=torch.float32)+ qtype = _get_fp8_qtype(weight.dtype)+ if qtype is None:+ raise TypeError(f"Scaled FP8 weight requires float8 dtype, got {weight.dtype}.")+ return ScaledFP8WeightTensor(+ qtype=qtype,+ axis=0,+ size=size,+ stride=stride,+ weight=weight,+ scale=scale,+ dtype=dtype,+ requires_grad=requires_grad,+ )++ @staticmethod+ def __new__(cls, qtype, axis, size, stride, weight, scale, dtype, requires_grad=False):+ return torch.Tensor._make_wrapper_subclass(+ cls,+ size,+ strides=stride,+ dtype=dtype,+ device=weight.device,+ requires_grad=requires_grad,+ )++ def __init__(self, qtype, axis, size, stride, weight, scale, dtype, requires_grad=False):+ super().__init__(qtype, axis)+ self._data = weight+ self._scale = scale+ self._scaled_mm_static_ok = _scaled_mm_static_ok(self._data, self._scale)+ self._set_linear_impl()++ def _set_linear_impl(self):+ if self._scaled_mm_static_ok and _scaled_mm_available(self._data.dtype):+ self._linear_impl = ScaledFP8WeightTensor._linear_scaled+ else:+ self._linear_impl = ScaledFP8WeightTensor._linear_fallback++ def linear(self, input, bias=None):+ impl = getattr(self, "_linear_impl", None)+ if impl is None:+ self._set_linear_impl()+ impl = self._linear_impl+ return impl(self, input, bias)++ def dequantize(self, dtype=None, device=None):+ if dtype is None:+ dtype = self.dtype+ if device is None:+ device = self.device+ data = self._data if self._data.device == device else self._data.to(device)+ scale = self._scale if self._scale.device == device else self._scale.to(device)+ out = data.to(dtype)+ if scale.numel() == 1:+ return out * scale.to(dtype)+ return out * _reshape_scale(scale.to(dtype), out)++ def _linear_fallback(self, input, bias=None):+ qweight= self+ target_type = qweight.dtype+ weights, output_scales = qweight._data, qweight._scale+ input = input.to(target_type)+ output_scales = output_scales.to(target_type)+ in_features = input.shape[-1]+ out_features = weights.shape[0]+ output_shape = input.shape[:-1] + (out_features,)+ weights = weights.to(target_type)+ weights *= output_scales+ out = torch.matmul(input.reshape(-1, in_features), weights.t())+ out = out.reshape(output_shape)+ if bias is not None:+ out += bias+ return out++ def _linear_scaled(self, input, bias=None):+ if not torch.is_tensor(input):+ return torch.nn.functional.linear(input, self.dequantize(), bias)+ if (+ not input.is_floating_point()+ or input.dtype not in (torch.float16, torch.bfloat16, torch.float32)+ or input.ndim < 2+ or input.device.type != "cuda"+ or input.device != self._data.device+ or input.shape[-1] != self._data.shape[1]+ ):+ return torch.nn.functional.linear(input, self.dequantize(dtype=input.dtype, device=input.device), bias)++ scale_b = _normalize_scaled_mm_scale(self._scale)+ if scale_b is None:+ return torch.nn.functional.linear(input, self.dequantize(dtype=input.dtype, device=input.device), bias)++ x2d = input.reshape(-1, input.shape[-1])+ if not x2d.is_contiguous():+ x2d = x2d.contiguous()++ if x2d.shape[1] % 16 != 0 or self._data.shape[0] % 16 != 0:+ return torch.nn.functional.linear(input, self.dequantize(dtype=input.dtype, device=input.device), bias)++ fp8_dtype = self._data.dtype+ x_fp8, scale_a = _quantize_activation(x2d, fp8_dtype)+ scale_a = _normalize_scaled_mm_scale(scale_a)+ if scale_a is None:+ return torch.nn.functional.linear(input, self.dequantize(dtype=input.dtype, device=input.device), bias)+ scale_b = scale_b.to(device=x_fp8.device, dtype=torch.float32)++ bias_arg = bias+ if bias_arg is not None:+ if bias_arg.device != x_fp8.device:+ bias_arg = bias_arg.to(x_fp8.device)+ if bias_arg.dtype != input.dtype:+ bias_arg = bias_arg.to(dtype=input.dtype)++ out = torch._scaled_mm(+ x_fp8,+ self._data.t(),+ scale_a,+ scale_b,+ bias=bias_arg,+ out_dtype=input.dtype,+ )++ return out.reshape(*input.shape[:-1], self._data.shape[0])++ def get_quantized_subtensors(self):+ return [("scale", self._scale), ("data", self._data)]++ 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("data", None)+ if data is not None:+ self._data = data+ scale = sub_map.get("scale", None)+ if scale is not None:+ self._scale = scale+ self._scaled_mm_static_ok = _scaled_mm_static_ok(self._data, self._scale)+ self._set_linear_impl()++ def __tensor_flatten__(self):+ inner_tensors = ["_data", "_scale"]+ 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 ScaledFP8WeightTensor(+ qtype=qtype,+ axis=axis,+ size=size,+ stride=stride,+ weight=inner_tensors["_data"],+ scale=inner_tensors["_scale"],+ 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, ScaledFP8WeightTensor):+ return weight.linear(input, bias=bias)+ with torch._C.DisableTorchFunctionSubclass():+ return func(*args, **kwargs)++ @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, ScaledFP8WeightTensor):+ return weight.linear(input, bias=bias)+ if op is torch.ops.aten.detach:+ t = args[0]+ return ScaledFP8WeightTensor.create(+ weight=op(t._data),+ scale=op(t._scale),+ 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 {}))+ return ScaledFP8WeightTensor.create(+ weight=out_data,+ scale=out_scale,+ size=t.size(),+ stride=t.stride(),+ dtype=t.dtype,+ device=device,+ requires_grad=t.requires_grad,+ )+ return _scaled_fp8_qfallback(op, *args, **(kwargs or {}))+++class QLinearScaledFP8(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._scaled_fp8_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._scaled_fp8_default_dtype = dtype++ @property+ def qweight(self):+ if self.weight_qtype in _SCALED_FP8_QTYPES:+ return self.weight+ return super().qweight++ def forward(self, input: torch.Tensor) -> torch.Tensor:+ qweight = self.qweight+ if (+ getattr(qweight, "_scaled_mm_static_ok", False)+ and _scaled_mm_available(qweight._data.dtype)+ and torch.is_tensor(input)+ and input.is_floating_point()+ and input.dtype in (torch.float16, torch.bfloat16, torch.float32)+ and input.ndim >= 2+ and input.device.type == "cuda"+ and input.device == qweight._data.device+ and input.shape[-1] == qweight._data.shape[1]+ ):+ return ScaledFP8WeightTensor._linear_scaled(qweight, input, bias=self.bias)+ return ScaledFP8WeightTensor._linear_fallback(qweight, input, 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 not in _SCALED_FP8_QTYPES:+ 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 + "scale_weight"+ bias_key = prefix + "bias"+ input_scale_key = prefix + "input_scale"+ output_scale_key = prefix + "output_scale"++ weight = state_dict.pop(weight_key, None)+ scale = state_dict.pop(scale_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 is None:+ missing_keys.append(weight_key)++ target_dtype = self._scaled_fp8_default_dtype or self.weight.dtype+ if weight is not None:+ qweight = ScaledFP8WeightTensor.create(+ weight=weight,+ scale=scale,+ size=self.weight.size(),+ stride=self.weight.stride(),+ dtype=target_dtype,+ device=weight.device,+ requires_grad=False,+ )+ self.weight = torch.nn.Parameter(qweight, 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):+ scale_device = weight.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_fp8_specs(state_dict):+ specs = []+ for key, tensor in state_dict.items():+ if not key.endswith(".weight"):+ continue+ if not _is_float8_dtype(tensor.dtype):+ continue+ base = key[:-7]+ specs.append(+ {+ "name": base,+ "weight": tensor,+ }+ )+ return specs+++def detect(state_dict, verboseLevel=1):+ specs = _collect_fp8_specs(state_dict)+ if not specs:+ return {"matched": False, "kind": "none", "details": {}}+ names = [spec["name"] for spec in specs][:8]+ return {"matched": True, "kind": "fp8", "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": {}}+ if "scaled_fp8" in state_dict:+ state_dict.pop("scaled_fp8", None)+ specs = _collect_fp8_specs(state_dict)+ if not specs:+ return {"state_dict": state_dict, "quant_map": {}}+ quant_map = {}+ for spec in specs:+ qtype = _get_fp8_qtype(spec["weight"].dtype)+ if qtype is None:+ continue+ quant_map[spec["name"]] = {"weights": qtype.name, "activations": "none"}+ 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 {}, []+++_init_scaled_mm_support()diff --git a/wgp.py b/wgp.pyindex 2deb37d..fa25688 100644--- a/wgp.py+++ b/wgp.py@@ -19,8 +19,7 @@ import threadingimport argparseimport warningswarnings.filterwarnings('ignore', message='Failed to find.*', module='triton')-from mmgp import offload, safetensors2, profile_type , fp8_quanto_bridge, quant_router-if not os.name == "nt": fp8_quanto_bridge.enable_fp8_marlin_fallback()+from mmgp import offload, safetensors2, profile_type , quant_routertry:import tritonexcept ImportError:@@ -108,10 +107,12 @@ unique_id_lock = threading.Lock()offloadobj = enhancer_offloadobj = wan_model = Nonereload_needed = True_HANDLER_MODULES = [+ "shared.qtypes.scaled_fp8","shared.qtypes.nvfp4","shared.qtypes.nunchaku_int4","shared.qtypes.nunchaku_fp4",]+quant_router.unregister_handler(".fp8_quanto_bridge")for handler in _HANDLER_MODULES:quant_router.register_handler(handler)@@ -626,6 +627,7 @@ def validate_settings(state, model_type, single_prompt, inputs):motion_amplitude = inputs["motion_amplitude"]medium = "Videos" if image_mode == 0 else "Images"+ if image_start is not None and not isinstance(image_start, list): image_start = [image_start]outpainting_dims = get_outpainting_dims(video_guide_outpainting)if server_config.get("fit_canvas", 0) == 2 and outpainting_dims is not None and any_letters(video_prompt_type, "VKF"):@@ -818,7 +820,6 @@ def validate_settings(state, model_type, single_prompt, inputs):-if "S" in image_prompt_type:if model_def.get("black_frame", False) and len(image_start or [])==0:if "E" in image_prompt_type and len(image_end or []):@@ -1195,8 +1196,8 @@ def _load_task_attachments(params, media_base_path, cache_dir=None, log_prefix="# Update params, preserving list/single structureif loaded_items:- has_pil_item = any(isinstance(item, Image.Image) for item in loaded_items)- if is_originally_list or has_pil_item:+ # has_pil_item = any(isinstance(item, Image.Image) for item in loaded_items)+ if is_originally_list: # or has_pil_itemparams[key] = loaded_itemselse:params[key] = loaded_items[0]@@ -5534,7 +5535,7 @@ def generate_video(gen["window_no"] = window_noreturn_latent_slice = Noneif reuse_frames > 0:- return_latent_slice = slice(- min(1, (reuse_frames + discard_last_frames ) // latent_size) , None if discard_last_frames == 0 else -(discard_last_frames // latent_size) )+ return_latent_slice = slice(- max(1, (reuse_frames + discard_last_frames ) // latent_size) , None if discard_last_frames == 0 else -(discard_last_frames // latent_size) )refresh_preview = {"image_guide" : image_guide, "image_mask" : image_mask} if image_mode >= 1 else {}image_start_tensor = image_end_tensor = None