Python
added suppport for Ovi
deepbeepmeep83ff93fe78f8
diff --git a/README.md b/README.mdindex 6c8473c..6a1153b 100644--- a/README.md+++ b/README.md@@ -36,6 +36,12 @@ WanGP supports the Wan (and derived models), Hunyuan Video and LTV Video models-----## 🔥 Latest Updates :+### October 26 2025: WanGP v9.20, Why isn't all my VRAM used ?++*WanGP exclusive*++**Wan 2.2 Ovi 10 GB** for all the GPU Poors of the World: *only 6 GB of VRAM to generate 121 frames at 720p*. With 16 GB of VRAM, you may even be able to load all the model in VRAM with *Memory Profile 3*+### October 24 2025: WanGP v9.10, What else will you ever need after this one ?With WanGP v9 you will have enough features to go to a desert island with no internet connection and comes back with a full Hollywood movie.diff --git a/models/wan/ovi/modules/fusion.py b/models/wan/ovi/modules/fusion.pyindex 95f593b..561ee80 100644--- a/models/wan/ovi/modules/fusion.py+++ b/models/wan/ovi/modules/fusion.py@@ -371,6 +371,5 @@ class FusionModel(nn.Module):mod.weight.div_(10.0)- def set_rope_params(self):- self.video_model.set_rope_params()- self.audio_model.set_rope_params()+ def custom_compile(self, compile_kwargs):+ torch.compile(self.single_fusion_block_forward, **compile_kwargs)diff --git a/models/wan/ovi/modules/model.py b/models/wan/ovi/modules/model.pyindex 90427d8..264259d 100644--- a/models/wan/ovi/modules/model.py+++ b/models/wan/ovi/modules/model.py@@ -42,44 +42,57 @@ def rope_params(max_seq_len, dim, theta=10000, freqs_scaling=1.0):freqs = torch.polar(torch.ones_like(freqs), freqs)return freqs-# def rope_params(max_seq_len, dim, theta=10000, freqs_scaling=1.0, use_real = True):-# freqs = 1.0 / (-# theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)-# ) # [D/2]-# # assert interpolation_factor == 1.0, f"interpolation_factor: {interpolation_factor}"-# freqs = torch.outer(pos * interpolation_factor, freqs) # [S, D/2]-# if use_real:-# freqs_cos = freqs.cos().repeat_interleave(2, dim=1) # [S, D]-# freqs_sin = freqs.sin().repeat_interleave(2, dim=1) # [S, D]-# return freqs_cos, freqs_sin-# else:-# freqs_cis = torch.polar( torch.ones_like(freqs), freqs) # complex64 # [S, D/2]-# return freqs_cis+[email protected]('cuda', enabled=False)+def rope_params_audio_real(max_seq_len, head_dim, rotary_dim, theta=10000, freqs_scaling=1.0):+ assert rotary_dim % 2 == 0+ assert rotary_dim <= head_dim+ pos = torch.arange(max_seq_len, dtype=torch.float32)+ base = torch.arange(0, rotary_dim, 2, dtype=torch.float32) / rotary_dim+ inv_freq = freqs_scaling * torch.pow(theta, -base)+ angles = torch.outer(pos, inv_freq)+ cos = angles.cos().repeat_interleave(2, dim=1)+ sin = angles.sin().repeat_interleave(2, dim=1)+ if rotary_dim < head_dim:+ pad = head_dim - rotary_dim+ cos = torch.cat([cos, cos.new_ones(max_seq_len, pad)], dim=1)+ sin = torch.cat([sin, sin.new_zeros(max_seq_len, pad)], dim=1)+ return cos, sin+@amp.autocast('cuda', enabled=False)def rope_apply_1d(x, grid_sizes, freqs):- n, c = x.size(2), x.size(3) // 2 ## b l h d- c_rope = freqs.shape[1] # number of complex dims to rotate- assert c_rope <= c, "RoPE dimensions cannot exceed half of hidden size"-- # loop over samplesoutput = []- for i, (l, ) in enumerate(grid_sizes.tolist()):+ for i, (l,) in enumerate(grid_sizes.tolist()):seq_len = l- # precompute multipliers- x_i = torch.view_as_complex(x[i, :seq_len].to(torch.float64).reshape(- seq_len, n, -1, 2)) # [l n d//2]- x_i_rope = x_i[:, :, :c_rope] * freqs[:seq_len, None, :] # [L, N, c_rope]- x_i_passthrough = x_i[:, :, c_rope:] # untouched dims- x_i = torch.cat([x_i_rope, x_i_passthrough], dim=2)-- # apply rotary embedding- x_i = torch.view_as_real(x_i).flatten(2)- x_i = torch.cat([x_i, x[i, seq_len:]])-- # append to collection- output.append(x_i)- return torch.stack(output).bfloat16()+ x_prefix = x[i, :seq_len]+ if isinstance(freqs, tuple):+ from ...modules.posemb_layers import apply_rotary_emb_single+ cos_table, sin_table = freqs+ cos_i = cos_table[:seq_len]+ sin_i = sin_table[:seq_len]+ rotated = apply_rotary_emb_single(+ [x_prefix.unsqueeze(0)],+ (cos_i, sin_i),+ head_first=False,+ ).squeeze(0)+ else:+ n, c = x.size(2), x.size(3) // 2+ c_rope = freqs.shape[1]+ assert c_rope <= c, "RoPE dimensions cannot exceed half of hidden size"+ x_i = torch.view_as_complex(+ x_prefix.to(torch.float64).reshape(seq_len, n, -1, 2)+ )+ x_i_rope = x_i[:, :, :c_rope] * freqs[:seq_len, None, :]+ x_i_passthrough = x_i[:, :, c_rope:]+ rotated = torch.view_as_real(+ torch.cat([x_i_rope, x_i_passthrough], dim=2)+ ).flatten(2)+ rotated = rotated.to(x.dtype)+ tail = x[i, seq_len:]+ x_i_full = torch.cat([rotated, tail], dim=0)+ output.append(x_i_full.to(x.dtype))+ return torch.stack(output)@amp.autocast('cuda', enabled=False)def rope_apply_3d(x, grid_sizes, freqs):@@ -113,17 +126,17 @@ def rope_apply_3d(x, grid_sizes, freqs):@amp.autocast('cuda', enabled=False)def rope_apply(x, grid_sizes, freqs):+ x_ndim = grid_sizes.shape[-1]if isinstance(freqs, tuple):+ if x_ndim == 1:+ return rope_apply_1d(x, grid_sizes, freqs)from ...modules.posemb_layers import apply_rotary_emb_singleqklist = [x]del xreturn apply_rotary_emb_single(qklist, freqs, head_first=False)- else:- x_ndim = grid_sizes.shape[-1]- if x_ndim == 3:- return rope_apply_3d(x, grid_sizes, freqs)- else:- return rope_apply_1d(x, grid_sizes, freqs)+ if x_ndim == 3:+ return rope_apply_3d(x, grid_sizes, freqs)+ return rope_apply_1d(x, grid_sizes, freqs)@@ -255,7 +268,7 @@ class WanSelfAttention(nn.Module):x(Tensor): Shape [B, L, C]seq_lens(Tensor): Shape [B]grid_sizes(Tensor): Shape [B, 3], the second dimension contains (F, H, W)- freqs(Tensor): Rope freqs, shape [1024, C / num_heads / 2]+ freqs(Union[Tensor, Tuple[Tensor, Tensor]]): Rotary parameters"""q, k, v = self.qkv_fn(x)q=rope_apply(q, grid_sizes, freqs)@@ -603,7 +616,8 @@ class WanModel(ModelMixin, ConfigMixin):num_heads = self.num_headsassert (dim % num_heads) == 0 and (dim // num_heads) % 2 == 0d = dim // num_heads- return rope_params(1024, d - 4 * (d // 6), freqs_scaling=self.temporal_rope_scaling_factor)+ rotary_dim = d - 4 * (d // 6)+ return rope_params_audio_real(1024, d, rotary_dim, freqs_scaling=self.temporal_rope_scaling_factor)def set_rope_params(self):# buffers (don't use register_buffer otherwise dtype will be changed in to())@@ -613,9 +627,8 @@ class WanModel(ModelMixin, ConfigMixin):d = dim // num_headsif self.is_audio_type:- ## to be determined- # self.freqs = rope_params(1024, d, freqs_scaling=temporal_rope_scaling_factor)- self.freqs = rope_params(1024, d - 4 * (d // 6), freqs_scaling=self.temporal_rope_scaling_factor)+ rotary_dim = d - 4 * (d // 6)+ self.freqs = rope_params_audio_real(1024, d, rotary_dim, freqs_scaling=self.temporal_rope_scaling_factor)else:self.freqs = torch.cat([rope_params(1024, d - 4 * (d // 6)),diff --git a/models/wan/ovi_fusion_engine.py b/models/wan/ovi_fusion_engine.pyindex b3fddf2..def48d6 100644--- a/models/wan/ovi_fusion_engine.py+++ b/models/wan/ovi_fusion_engine.py@@ -221,11 +221,7 @@ class OviFusionEngine:audio_freqs = self.model.audio_model.get_audio_rope_params()video_noise = torch.randn((self.video_latent_channel, video_latent_length, video_latent_h, video_latent_w), device=self.device, dtype=self.target_dtype, generator=torch.Generator(device=self.device).manual_seed(seed)) # c, f, h, waudio_noise = torch.randn((audio_latent_length, self.audio_latent_channel), device=self.device, dtype=self.target_dtype, generator=torch.Generator(device=self.device).manual_seed(seed)) # 1, l c -> l, c- # self.model.audio_model.freqs= self.model.audio_model.freqs.to("cuda")- # self.model.video_model.freqs= self.model.video_model.freqs.to("cuda")def ret():- # self.model.audio_model.freqs= self.model.audio_model.freqs.to("cpu")- # self.model.video_model.freqs= self.model.video_model.freqs.to("cpu")return None# Calculate sequence lengths from actual latents@@ -366,3 +362,7 @@ class OviFusionEngine:raise NotImplementedError("Unsupported solver.")return sample_scheduler, timesteps++ def custom_compile(self, **compile_kwargs):+ self.model.custom_compile(compile_kwargs)+diff --git a/models/wan/ovi_handler.py b/models/wan/ovi_handler.pyindex 4d3c857..69aa883 100644--- a/models/wan/ovi_handler.py+++ b/models/wan/ovi_handler.py@@ -55,6 +55,7 @@ class family_handler:"sliding_window": True,"sliding_window_size_locked": True,"sliding_window_defaults" : { "overlap_min" : 1, "overlap_max" : 1, "overlap_step": 0, "overlap_default": 1},+ "compile": ["transformer", "transformer2"]}cfg.update(model_def)return cfgdiff --git a/shared/asyncio_utils.py b/shared/asyncio_utils.pynew file mode 100644index 0000000..a76db5e--- /dev/null+++ b/shared/asyncio_utils.py@@ -0,0 +1,25 @@+import os+++def silence_proactor_connection_reset() -> None:+ if os.name != "nt":+ return++ from asyncio import proactor_events as _proactor++ transport_cls = _proactor._ProactorBasePipeTransport+ if getattr(transport_cls, "_wan2gp_patch", False):+ return++ original = transport_cls._call_connection_lost++ def _call_connection_lost(self, exc):+ if isinstance(exc, ConnectionResetError):+ exc = None+ try:+ return original(self, exc)+ except ConnectionResetError:+ return None++ transport_cls._call_connection_lost = _call_connection_lost+ transport_cls._wan2gp_patch = Truediff --git a/wgp.py b/wgp.pyindex 72add81..1a6640a 100644--- a/wgp.py+++ b/wgp.py@@ -8,14 +8,10 @@ p = os.path.dirname(os.path.abspath(__file__))if p not in sys.path:sys.path.insert(0, p)import asyncio-if os.name == "nt":+if os.name == "nt":asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())- import asyncio.proactor_events as _proactor- _orig_call_lost = _proactor._ProactorBasePipeTransport._call_connection_lost- def _quiet_call_lost(self, exc):- if isinstance(exc, ConnectionResetError): exc = None- return _orig_call_lost(self, exc)- _proactor._ProactorBasePipeTransport._call_connection_lost = _quiet_call_lost+from shared.asyncio_utils import silence_proactor_connection_reset+silence_proactor_connection_reset()import timeimport threadingimport argparse@@ -82,7 +78,7 @@ global_queue_ref = []AUTOSAVE_FILENAME = "queue.zip"PROMPT_VARS_MAX = 10target_mmgp_version = "3.6.7"-WanGP_version = "9.10"+WanGP_version = "9.20"settings_version = 2.39max_source_video_frames = 3000prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer = None, None, None, None@@ -3278,8 +3274,11 @@ def load_models(model_type, override_profile = -1):if "transformer" in pipe:loras_transformer += ["transformer"]if "transformer2" in pipe:- loras_transformer += ["transformer2"]- offloadobj = offload.profile(pipe, profile_no= profile, compile = compile, quantizeTransformer = False, loras = loras_transformer, perc_reserved_mem_max = perc_reserved_mem_max , vram_safety_coefficient = vram_safety_coefficient , convertWeightsFloatTo = transformer_dtype, **kwargs)+ loras_transformer += ["transformer2"]+ if len(compile) > 0 and hasattr(wan_model, "custom_compile"):+ wan_model.custom_compile(backend= "inductor", mode ="default")+ compile_modules = model_def.get("compile", compile) if len(compile) > 0 else ""+ offloadobj = offload.profile(pipe, profile_no= profile, compile = compile_modules, quantizeTransformer = False, loras = loras_transformer, perc_reserved_mem_max = perc_reserved_mem_max , vram_safety_coefficient = vram_safety_coefficient , convertWeightsFloatTo = transformer_dtype, **kwargs)if len(args.gpu) > 0:torch.set_default_device(args.gpu)transformer_type = model_type@@ -8292,7 +8291,8 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonlabel= video_prompt_type_video_mask_label , scale = 1, visible= "V" in video_prompt_type_value and not "U" in video_prompt_type_value and mask_preprocessing.get("visible", True),show_label= True,)-+ any_control_video = True+ any_control_image = image_outputs# Image Refs Selectionif image_ref_choices is None: