Python
add mocha support
DeepBeepMeepe38a21aaa3e6
diff --git a/README.md b/README.mdindex bb60662..12cbb4a 100644--- a/README.md+++ b/README.md@@ -36,6 +36,14 @@ WanGP supports the Wan (and derived models), Hunyuan Video and LTV Video models-----## 🔥 Latest Updates :+### November 9 2025: WanGP v9.41, Free Lunch++**VAE Upsampler** for Wan 2.1/2.2 Text 2 Image and Qwen Image: *spacepxl* has tweaked the VAE Decoder used by *Wan* & *Qwen* so that it can decode and upsample x2 at the same time. The end Result is a Fast High Quality Image Upsampler (much better than Lanczos). Check the *Postprocessing Tab* / *Spatial Upsampling* Dropdown box. Unfortunately this will work only with Image Generation, no support yet for Video Generation. I have also added a VAE Refiner that keeps the existing resolution but slightly improves the details.++**Mocha**: an alternative to *Wan Animate*. Use this model to replace a person in a control video. For best results you will need to provide two reference images for the new the person, the second image should be a face close up. This model seems to be optimized to generate 81 frames. *t2v fusionix 10 steps Lora Accelarator* works well.++*update 9.41*: Added a Sample PlugIn App that shows how to collect and modify settings from a PlugIn\+### November 6 2025: WanGP v9.35, How many bananas are too many bananas ?**Chrono Edit**: a new original way to edit an Image. This one will generate a Video will that performs the full edition work and return the last Image. It can be hit or a miss but when it works it is quite impressive. Please note you must absolutely use the *Prompt Enhancer* on your *Prompt Instruction* because this model expects a very specific format. The Prompt Enhancer for this model has a specific System Prompt to generate the right Chrono Edit Prompt.diff --git a/defaults/mocha.json b/defaults/mocha.jsonnew file mode 100644index 0000000..f8f1628--- /dev/null+++ b/defaults/mocha.json@@ -0,0 +1,14 @@+{+ "model": {+ "name": "Wan2.1 MoCha 14B",+ "architecture": "mocha",+ "description": "MoCha enables single-character replacement using a source video, a first-frame mask, and up to two clean reference images of a person. It is tuned to generate 81 frames. The second reference frame should be a Face Close up.",+ "URLs": ["https://huggingface.co/Kijai/WanVideo_comfy_fp8_scaled/resolve/main/MoCha/Wan2_1_mocha-14B-preview_fp8_e4m3fn_scaled_KJ.safetensors"]+ },+ "prompt": "video",+ "force_fps": "control",+ "guidance_scale": 5,+ "flow_shift": 5,+ "num_inference_steps": 20,+ "video_length": 81+}diff --git a/models/qwen/autoencoder_kl_qwenimage.py b/models/qwen/autoencoder_kl_qwenimage.pyindex d144284..026a2f4 100644--- a/models/qwen/autoencoder_kl_qwenimage.py+++ b/models/qwen/autoencoder_kl_qwenimage.py@@ -571,6 +571,7 @@ class QwenImageDecoder3d(nn.Module):attn_scales=[],temperal_upsample=[False, True, True],dropout=0.0,+ upsampler_factor = 1,non_linearity: str = "silu",):super().__init__()@@ -580,7 +581,7 @@ class QwenImageDecoder3d(nn.Module):self.num_res_blocks = num_res_blocksself.attn_scales = attn_scalesself.temperal_upsample = temperal_upsample-+ self.upsampler_factor = upsampler_factorself.nonlinearity = get_activation(non_linearity)# dimensions@@ -622,7 +623,7 @@ class QwenImageDecoder3d(nn.Module):# output blocksself.norm_out = QwenImageRMS_norm(out_dim, images=False)- self.conv_out = QwenImageCausalConv3d(out_dim, 3, 3, padding=1)+ self.conv_out = QwenImageCausalConv3d(out_dim, 3*int(upsampler_factor*upsampler_factor), 3, padding=1)self.gradient_checkpointing = False@@ -661,6 +662,12 @@ class QwenImageDecoder3d(nn.Module):feat_idx[0] += 1else:x = self.conv_out(x)+++ if self.upsampler_factor > 1:+ x = F.pixel_shuffle(x.movedim(2, 1), upscale_factor=self.upsampler_factor).movedim(1, 2) # pixel shuffle needs [..., C, H, W] format++return x@@ -711,6 +718,7 @@ class AutoencoderKLQwenImage(ModelMixin, ConfigMixin, FromOriginalModelMixin):attn_scales: List[float] = [],temperal_downsample: List[bool] = [False, True, True],dropout: float = 0.0,+ upsampler_factor = 1,latents_mean: List[float] = [-0.7571, -0.7089, -0.9113, 0.1075, -0.1745, 0.9653, -0.1517, 1.5508, 0.4134, -0.0715, 0.5517, -0.3632, -0.1922, -0.9497, 0.2503, -0.2921],latents_std: List[float] = [2.8184, 1.4541, 2.3275, 2.6558, 1.2196, 1.7708, 2.6052, 2.0743, 3.2687, 2.1526, 2.8652, 1.5579, 1.6382, 1.1253, 2.8251, 1.9160],) -> None:@@ -720,7 +728,7 @@ class AutoencoderKLQwenImage(ModelMixin, ConfigMixin, FromOriginalModelMixin):self.z_dim = z_dimself.temperal_downsample = temperal_downsampleself.temperal_upsample = temperal_downsample[::-1]-+ self.upsampler_factor = upsampler_factorself.encoder = QwenImageEncoder3d(base_dim, z_dim * 2, dim_mult, num_res_blocks, attn_scales, self.temperal_downsample, dropout)@@ -728,7 +736,7 @@ class AutoencoderKLQwenImage(ModelMixin, ConfigMixin, FromOriginalModelMixin):self.post_quant_conv = QwenImageCausalConv3d(z_dim, z_dim, 1)self.decoder = QwenImageDecoder3d(- base_dim, z_dim, dim_mult, num_res_blocks, attn_scales, self.temperal_upsample, dropout+ base_dim, z_dim, dim_mult, num_res_blocks, attn_scales, self.temperal_upsample, dropout, upsampler_factor)self.spatial_compression_ratio = 2 ** len(self.temperal_downsample)@@ -1025,16 +1033,18 @@ class AutoencoderKLQwenImage(ModelMixin, ConfigMixin, FromOriginalModelMixin):returned."""_, _, num_frames, height, width = z.shape- sample_height = height * self.spatial_compression_ratio- sample_width = width * self.spatial_compression_ratio+ factor = self.upsampler_factor+ sample_height = height * self.spatial_compression_ratio * factor+ sample_width = width * self.spatial_compression_ratio * factortile_latent_min_height = self.tile_sample_min_height // self.spatial_compression_ratiotile_latent_min_width = self.tile_sample_min_width // self.spatial_compression_ratiotile_latent_stride_height = self.tile_sample_stride_height // self.spatial_compression_ratiotile_latent_stride_width = self.tile_sample_stride_width // self.spatial_compression_ratio-- blend_height = self.tile_sample_min_height - self.tile_sample_stride_height- blend_width = self.tile_sample_min_width - self.tile_sample_stride_width+ tile_sample_min_height, tile_sample_stride_height = self.tile_sample_min_height * factor , self.tile_sample_stride_height * factor+ tile_sample_min_width, tile_sample_stride_width = self.tile_sample_min_width * factor , self.tile_sample_stride_width * factor+ blend_height = tile_sample_min_height - tile_sample_stride_height+ blend_width = tile_sample_min_width - tile_sample_stride_width# Split z into overlapping tiles and decode them separately.# The tiles have an overlap to avoid seams between tiles.@@ -1064,7 +1074,7 @@ class AutoencoderKLQwenImage(ModelMixin, ConfigMixin, FromOriginalModelMixin):tile = self.blend_v(rows[i - 1][j], tile, blend_height)if j > 0:tile = self.blend_h(row[j - 1], tile, blend_width)- result_row.append(tile[:, :, :, : self.tile_sample_stride_height, : self.tile_sample_stride_width])+ result_row.append(tile[:, :, :, : tile_sample_stride_height, : tile_sample_stride_width])result_rows.append(torch.cat(result_row, dim=-1))dec = torch.cat(result_rows, dim=3)[:, :, :, :sample_height, :sample_width]diff --git a/models/qwen/pipeline_qwenimage.py b/models/qwen/pipeline_qwenimage.pyindex d70f094..e33fc86 100644--- a/models/qwen/pipeline_qwenimage.py+++ b/models/qwen/pipeline_qwenimage.py@@ -177,8 +177,8 @@ class QwenImagePipeline(): #DiffusionPipelineself.transformer=transformerself.processor = processor- self.latent_channels = self.vae.config.z_dim if getattr(self, "vae", None) else 16- self.vae_scale_factor = 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8+ self.latent_channels = self.vae.z_dim if getattr(self, "vae", None) else 16+ self.vae_scale_factor = 8 # 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8# QwenImage latents are turned into 2x2 patches and packed. This means the latent width and height has to be divisible# by the patch size. So the vae scale factor is multiplied by the patch size to account for thisself.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)@@ -473,6 +473,7 @@ class QwenImagePipeline(): #DiffusionPipelinedevice,generator,latents=None,+ tile_size=0,):# VAE applies 8x compression on images but we must also account for packing which requires# latent height and width to be divisible by 2.@@ -489,7 +490,10 @@ class QwenImagePipeline(): #DiffusionPipelinefor image in images:image = image.to(device=device, dtype=dtype)if image.shape[1] != self.latent_channels:- image_latents = self._encode_vae_image(image=image, generator=generator)+ if self.use_Wan_VAE:+ image_latents = self.vae.encode(image, tile_size = tile_size)[0].unsqueeze(0)+ else:+ image_latents = self._encode_vae_image(image=image, generator=generator)else:image_latents = imageif batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0:@@ -569,6 +573,7 @@ class QwenImagePipeline(): #DiffusionPipelinelora_inpaint = False,outpainting_dims = None,qwen_edit_plus = False,+ VAE_tile_size = 0,):r"""Function invoked when calling the pipeline for generation.@@ -642,7 +647,7 @@ class QwenImagePipeline(): #DiffusionPipelineif callback != None:callback(-1, None, True)-+ vae_z_dim = self.vae.z_dimheight = height or self.default_sample_size * self.vae_scale_factorwidth = width or self.default_sample_size * self.vae_scale_factor@@ -759,6 +764,7 @@ class QwenImagePipeline(): #DiffusionPipelinedevice,generator,latents,+ tile_size=VAE_tile_size)original_image_latents = None if image_latents is None else image_latents.clone()@@ -944,17 +950,21 @@ class QwenImagePipeline(): #DiffusionPipelineelse:latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)latents = latents.to(self.vae.dtype)- latents_mean = (- torch.tensor(self.vae.config.latents_mean)- .view(1, self.vae.config.z_dim, 1, 1, 1)- .to(latents.device, latents.dtype)- )- latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(- latents.device, latents.dtype- )- latents = latents / latents_std + latents_mean- output_image = self.vae.decode(latents, return_dict=False)[0][:, :, 0]- if image_mask is not None and not lora_inpaint : #not (lora_inpaint and outpainting_dims is not None):+ if self.use_Wan_VAE:+ output_image = torch.cat([image.transpose(0,1) for image in self.vae.decode(latents, tile_size= VAE_tile_size)])+ else:+ latents_mean = (+ torch.tensor(self.vae.config.latents_mean)+ .view(1, vae_z_dim, 1, 1, 1)+ .to(latents.device, latents.dtype)+ )+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, vae_z_dim, 1, 1, 1).to(+ latents.device, latents.dtype+ )+ latents = latents / latents_std + latents_mean+ output_image = self.vae.decode(latents, return_dict=False)[0][:, :, 0]++ if image_mask is not None and not lora_inpaint and self.vae.upsampling_set is None: #not (lora_inpaint and outpainting_dims is not None):output_image = vae_images[0].squeeze(2) * (1 - image_mask_rebuilt) + output_image.to(vae_images[0] ) * image_mask_rebuiltdiff --git a/models/qwen/qwen_handler.py b/models/qwen/qwen_handler.pyindex 66e5392..597de8b 100644--- a/models/qwen/qwen_handler.py+++ b/models/qwen/qwen_handler.py@@ -22,6 +22,8 @@ class family_handler():"profiles_dir": ["qwen"],}+ extra_model_def["vae_upsampler"] = [1,2]+if base_model_type in ["qwen_image_edit_20B", "qwen_image_edit_plus_20B"]:extra_model_def["inpaint_support"] = Trueextra_model_def["image_ref_choices"] = {@@ -74,14 +76,21 @@ class family_handler():@staticmethoddef query_model_files(computeList, base_model_type, model_filename, text_encoder_quantization):text_encoder_filename = get_qwen_text_encoder_filename(text_encoder_quantization)- return {+ download_def = [{"repoId" : "DeepBeepMeep/Qwen_image","sourceFolderList" : ["", "Qwen2.5-VL-7B-Instruct"],"fileList" : [ ["qwen_vae.safetensors", "qwen_vae_config.json"], ["merges.txt", "tokenizer_config.json", "config.json", "vocab.json", "video_preprocessor_config.json", "preprocessor_config.json"] + computeList(text_encoder_filename) ]- }+ }]++ download_def += [{+ "repoId" : "DeepBeepMeep/Wan2.1",+ "sourceFolderList" : ["" ],+ "fileList" : [ ["Wan2.1_VAE_upscale2x_imageonly_real_v1.safetensors"] ]+ }]+ return download_def@staticmethod- def load_model(model_filename, model_type, base_model_type, model_def, quantizeTransformer = False, text_encoder_quantization = None, dtype = torch.bfloat16, VAE_dtype = torch.float32, mixed_precision_transformer = False, save_quantized = False, submodel_no_list = None, override_text_encoder = None):+ def load_model(model_filename, model_type, base_model_type, model_def, quantizeTransformer = False, text_encoder_quantization = None, dtype = torch.bfloat16, VAE_dtype = torch.float32, mixed_precision_transformer = False, save_quantized = False, submodel_no_list = None, override_text_encoder = None, VAE_upsampling = None, **kwargs):from .qwen_main import model_factoryfrom mmgp import offload@@ -96,10 +105,12 @@ class family_handler():dtype = dtype,VAE_dtype = VAE_dtype,mixed_precision_transformer = mixed_precision_transformer,- save_quantized = save_quantized+ save_quantized = save_quantized,+ VAE_upsampling = VAE_upsampling,)- pipe = {"tokenizer" : pipe_processor.tokenizer, "transformer" : pipe_processor.transformer, "text_encoder" : pipe_processor.text_encoder, "vae" : pipe_processor.vae}+ from ..wan.modules.vae import WanVAE+ pipe = {"tokenizer" : pipe_processor.tokenizer, "transformer" : pipe_processor.transformer, "text_encoder" : pipe_processor.text_encoder, "vae" : pipe_processor.vae.model if isinstance(pipe_processor.vae, WanVAE) else pipe_processor.vae }return pipe_processor, pipediff --git a/models/qwen/qwen_main.py b/models/qwen/qwen_main.pyindex e5fcf85..c1c3333 100644--- a/models/qwen/qwen_main.py+++ b/models/qwen/qwen_main.py@@ -46,6 +46,7 @@ class model_factory():dtype = torch.bfloat16,VAE_dtype = torch.float32,mixed_precision_transformer = False,+ VAE_upsampling = None,):@@ -87,10 +88,25 @@ class model_factory():# text_encoder = offload.fast_load_transformers_model(text_encoder_filename, do_quantize=True, writable_tensors= True , modelClass=Qwen2_5_VLForConditionalGeneration, defaultConfigPath="text_encoder_config.json", verboseLevel=2)# text_encoder.to(torch.float16)# offload.save_model(text_encoder, "text_encoder_quanto_fp16.safetensors", do_quantize= True)-- vae = offload.fast_load_transformers_model( fl.locate_file("qwen_vae.safetensors"), writable_tensors= True , modelClass=AutoencoderKLQwenImage, defaultConfigPath= fl.locate_file("qwen_vae_config.json"))-+ use_Wan_VAE = True+ VAE_upsampler_factor = 2 if VAE_upsampling is not None else 1++ if use_Wan_VAE:+ vae_checkpoint = "Wan2.1_VAE_upscale2x_imageonly_real_v1.safetensors" if VAE_upsampler_factor == 2 else "Wan2.1_VAE.safetensors"+ from ..wan.modules.vae import WanVAE+ vae = WanVAE( vae_pth=fl.locate_file(vae_checkpoint), dtype= VAE_dtype, upsampler_factor = VAE_upsampler_factor, device="cpu")+ vae.device = "cuda" #self.device # need to set to cuda so that vae buffers are properly moved (although the rest will stay in the CPU)+ else:+ if VAE_upsampler_factor ==2 :+ from .convert_diffusers_qwen_vae import convert_state_dict+ vae_checkpoint = "Wan2.1_VAE_upscale2x_imageonly_real_v1.safetensors"+ else:+ convert_state_dict = None+ vae_checkpoint = "qwen_vae.safetensors"+ vae = offload.fast_load_transformers_model( fl.locate_file(vae_checkpoint), writable_tensors= True , modelClass=AutoencoderKLQwenImage, defaultConfigPath= fl.locate_file("qwen_vae_config.json"), configKwargs={"upsampler_factor": VAE_upsampler_factor}, preprocess_sd=convert_state_dict)+ vae.upsampling_set = VAE_upsamplingself.pipeline = QwenImagePipeline(vae, text_encoder, tokenizer, transformer, processor)+ self.pipeline.use_Wan_VAE = use_Wan_VAEself.vae=vaeself.text_encoder=text_encoderself.tokenizer=tokenizer@@ -170,12 +186,17 @@ class model_factory():self.scheduler=FlowMatchEulerDiscreteScheduler(**scheduler_config)self.pipeline.scheduler = self.schedulerif VAE_tile_size is not None:+ if isinstance(VAE_tile_size, int):+ tiling_type = VAE_tile_size+ VAE_tile_size = [False, 0] if tiling_type == 0 else [True, 256]self.vae.use_tiling = VAE_tile_size[0]self.vae.tile_latent_min_height = VAE_tile_size[1]self.vae.tile_latent_min_width = VAE_tile_size[1]-+ tile_size = VAE_tile_size[1]+ # tile_size = 256qwen_edit_plus = self.base_model_type in ["qwen_image_edit_plus_20B"]- self.vae.enable_slicing()+ if hasattr(self.vae, "enable_slicing"):+ self.vae.enable_slicing()# width, height = aspect_ratios["16:9"]if n_prompt is None or len(n_prompt) == 0:@@ -216,6 +237,7 @@ class model_factory():lora_inpaint = image_mask is not None and model_mode == 1,outpainting_dims = outpainting_dims,qwen_edit_plus = qwen_edit_plus,+ VAE_tile_size = tile_size,)if image is None: return Nonereturn image.transpose(0, 1)diff --git a/models/wan/any2video.py b/models/wan/any2video.pyindex 44ec2dd..b6f3b95 100644--- a/models/wan/any2video.py+++ b/models/wan/any2video.py@@ -76,7 +76,8 @@ class WanAny2V:save_quantized = False,dtype = torch.bfloat16,VAE_dtype = torch.float32,- mixed_precision_transformer = False+ mixed_precision_transformer = False,+ VAE_upsampling = None,):self.device = torch.device(f"cuda")self.config = config@@ -87,6 +88,7 @@ class WanAny2V:self.model_def = model_defself.model2 = Noneself.transformer_switch = model_def.get("URLs2", None) is not None+ self.is_mocha = model_def.get("mocha_mode", False)self.text_encoder = T5EncoderModel(text_len=config.text_len,dtype=config.t5_dtype,@@ -103,7 +105,7 @@ class WanAny2V:tokenizer_path=fl.locate_folder("xlm-roberta-large"))ignore_unused_weights = model_def.get("ignore_unused_weights", False)-+ vae_upsampler_factor = 1vae_checkpoint2 = Noneif model_def.get("wan_5B_class", False):self.vae_stride = (4, 16, 16)@@ -111,15 +113,19 @@ class WanAny2V:vae = Wan2_2_VAEelse:vae = WanVAE- self.vae_stride = config.vae_stride- if model_def.get("alpha_class", False):+ self.vae_stride = config.vae_stride+ if VAE_upsampling is not None:+ 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"else:vae_checkpoint = "Wan2.1_VAE.safetensors"self.patch_size = config.patch_size- self.vae = vae( vae_pth=fl.locate_file(vae_checkpoint), dtype= VAE_dtype, device="cpu")+ self.vae = vae( vae_pth=fl.locate_file(vae_checkpoint), dtype= VAE_dtype, upsampler_factor = vae_upsampler_factor, device="cpu")+ self.vae.upsampling_set = VAE_upsamplingself.vae.device = self.device # need to set to cuda so that vae buffers are properly moved (although the rest will stay in the CPU)self.vae2 = Noneif vae_checkpoint2 is not None:@@ -324,6 +330,33 @@ class WanAny2V:clear_caches()return ref_buffer[0], (ref_buffer[1] if any_guidance else None)+ def _build_mocha_latents(self, source_video, mask_tensor, ref_images, frame_num, lat_frames, lat_h, lat_w, tile_size):+ video = source_video.to(device=self.device, dtype=self.VAE_dtype)+ source_latents = self.vae.encode([video], tile_size=tile_size)[0].unsqueeze(0).to(self.dtype)+ mask = mask_tensor[:, :1].to(device=self.device, dtype=self.dtype)+ mask_latents = F.interpolate(mask, size=(lat_h, lat_w), mode="nearest").unsqueeze(2).repeat(1, self.vae.model.z_dim, 1, 1, 1)++ ref_latents = [self.vae.encode([convert_image_to_tensor(img).unsqueeze(1).to(device=self.device, dtype=self.VAE_dtype)], tile_size=tile_size)[0].unsqueeze(0).to(self.dtype) for img in ref_images[:2]]+ ref_latents = torch.cat(ref_latents, dim=2)++ mocha_latents = torch.cat([source_latents, mask_latents, ref_latents], dim=2)++ base_len, source_len, mask_len = lat_frames, source_latents.shape[2], mask_latents.shape[2]+ cos_parts, sin_parts = [], []++ def append_freq(start_t, length, h_offset=1, w_offset=1):+ cos, sin = get_nd_rotary_pos_embed( (start_t, h_offset, w_offset), (start_t + length, h_offset + lat_h // 2, w_offset + lat_w // 2))+ cos_parts.append(cos)+ sin_parts.append(sin)++ append_freq(1, base_len)+ append_freq(1, source_len)+ append_freq(1, mask_len)+ append_freq(0, 1)+ if ref_latents.shape[2] > 1: append_freq(0, 1, 1 + lat_h // 2, 1 + lat_w // 2)++ return mocha_latents, (torch.cat(cos_parts, dim=0), torch.cat(sin_parts, dim=0))+def generate(self,input_prompt,input_frames= None,@@ -487,11 +520,12 @@ class WanAny2V:lucy_edit= model_type in ["lucy_edit"]animate= model_type in ["animate"]chrono_edit = model_type in ["chrono_edit"]+ mocha = model_type in ["mocha"]start_step_no = 0ref_images_count = 0trim_frames = 0last_latent_output = False- extended_overlapped_latents = clip_image_start = clip_image_end = image_mask_latents = latent_slice = None+ extended_overlapped_latents = clip_image_start = clip_image_end = image_mask_latents = latent_slice = freqs = Noneno_noise_latents_injection = infinitetalktimestep_injection = False@@ -789,6 +823,12 @@ class WanAny2V:if prefix_frames_count > 0:color_reference_frame = input_frames[0][:, prefix_frames_count -1:prefix_frames_count].clone()lat_h, lat_w = height // self.vae_stride[1], width // self.vae_stride[2]++ # Mocha+ if mocha:+ extended_latents, freqs = self._build_mocha_latents( input_frames, input_masks, input_ref_images[:2], frame_num, lat_frames, lat_h, lat_w, VAE_tile_size )+ extended_input_dim = 2+target_shape = (self.vae.model.z_dim, lat_frames + ref_images_count, lat_h, lat_w)if multitalk:@@ -808,7 +848,9 @@ class WanAny2V:expand_shape = [batch_size] + [-1] * len(target_shape)# Ropes- if extended_input_dim>=2:+ if freqs is not None:+ pass+ elif extended_input_dim>=2:shape = list(target_shape[1:])shape[extended_input_dim-2] *= 2freqs = get_rotary_pos_embed(shape, enable_RIFLEx= False)diff --git a/models/wan/configs/mocha.json b/models/wan/configs/mocha.jsonnew file mode 100644index 0000000..c554e73--- /dev/null+++ b/models/wan/configs/mocha.json@@ -0,0 +1,14 @@+{+ "_class_name": "WanModel",+ "_diffusers_version": "0.30.0",+ "dim": 5120,+ "eps": 1e-06,+ "ffn_dim": 13824,+ "freq_dim": 256,+ "in_dim": 16,+ "model_type": "t2v",+ "num_heads": 40,+ "num_layers": 40,+ "out_dim": 16,+ "text_len": 512+}diff --git a/models/wan/modules/vae.py b/models/wan/modules/vae.pyindex 8290d94..c6e16a2 100644--- a/models/wan/modules/vae.py+++ b/models/wan/modules/vae.py@@ -410,7 +410,9 @@ class Decoder3d(nn.Module):num_res_blocks=2,attn_scales=[],temperal_upsample=[False, True, True],- dropout=0.0):+ dropout=0.0,+ upsampler_factor = 1,+ ):super().__init__()self.dim = dimself.z_dim = z_dim@@ -453,7 +455,7 @@ class Decoder3d(nn.Module):# output blocksself.head = nn.Sequential(RMS_norm(out_dim, images=False), nn.SiLU(),- CausalConv3d(out_dim, 3, 3, padding=1))+ CausalConv3d(out_dim, 3 * int(upsampler_factor*upsampler_factor), 3, padding=1))def forward(self, x, feat_cache=None, feat_idx=[0]):## conv1@@ -529,6 +531,7 @@ class WanVAE_(nn.Module):num_res_blocks=2,attn_scales=[],temperal_downsample=[True, True, False],+ upsampler_factor = 1,dropout=0.0):super().__init__()self.dim = dim@@ -538,6 +541,7 @@ class WanVAE_(nn.Module):self.attn_scales = attn_scalesself.temperal_downsample = temperal_downsampleself.temperal_upsample = temperal_downsample[::-1]+ self.upsampler_factor = upsampler_factor# modulesself.encoder = Encoder3d(dim, z_dim * 2, dim_mult, num_res_blocks,@@ -545,7 +549,7 @@ class WanVAE_(nn.Module):self.conv1 = CausalConv3d(z_dim * 2, z_dim * 2, 1)self.conv2 = CausalConv3d(z_dim, z_dim, 1)self.decoder = Decoder3d(dim, z_dim, dim_mult, num_res_blocks,- attn_scales, self.temperal_upsample, dropout)+ attn_scales, self.temperal_upsample, dropout, upsampler_factor)def forward(self, x):mu, log_var = self.encode(x)@@ -600,8 +604,7 @@ class WanVAE_(nn.Module):# z: [b,c,t,h,w]if scale != None:if isinstance(scale[0], torch.Tensor):- z = z / scale[1].view(1, self.z_dim, 1, 1, 1) + scale[0].view(- 1, self.z_dim, 1, 1, 1)+ z = z / scale[1].view(1, self.z_dim, 1, 1, 1) + scale[0].view(1, self.z_dim, 1, 1, 1)else:z = z / scale[1] + scale[0]iter_ = z.shape[2]@@ -626,6 +629,10 @@ class WanVAE_(nn.Module):feat_idx=self._conv_idx))self.clear_cache()out = torch.cat(out_list, 2)++ if self.upsampler_factor > 1:+ out = F.pixel_shuffle(out.movedim(2, 1), upscale_factor=self.upsampler_factor).movedim(1, 2) # pixel shuffle needs [..., C, H, W] format+return outdef blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:@@ -648,13 +655,13 @@ class WanVAE_(nn.Module):# z: [b,c,t,h,w]if isinstance(scale[0], torch.Tensor):- z = z / scale[1].view(1, self.z_dim, 1, 1, 1) + scale[0].view(- 1, self.z_dim, 1, 1, 1)+ z = z / scale[1].view(1, self.z_dim, 1, 1, 1) + scale[0].view( 1, self.z_dim, 1, 1, 1)else:z = z / scale[1] + scale[0]overlap_size = int(tile_latent_min_size * (1 - tile_overlap_factor)) #8 0.75+ tile_sample_min_size *= self.upsampler_factorblend_extent = int(tile_sample_min_size * tile_overlap_factor) #256 0.25row_limit = tile_sample_min_size - blend_extent@@ -783,9 +790,11 @@ class WanVAE:z_dim=16,vae_pth='cache/vae_step_411000.pth',dtype=torch.float,+ upsampler_factor = 1,device="cuda"):self.dtype = dtypeself.device = device+ self.z_dim = z_dimmean = [-0.7571, -0.7089, -0.9113, 0.1075, -0.1745, 0.9653, -0.1517, 1.5508,@@ -802,6 +811,7 @@ class WanVAE:# init modelself.model = _video_vae(pretrained_path=vae_pth,+ upsampler_factor = upsampler_factor,z_dim=z_dim,).to(dtype).eval() #.requires_grad_(False).to(device)self.model._model_dtype = dtypediff --git a/models/wan/modules/vae2_2.py b/models/wan/modules/vae2_2.pyindex c1a88f5..493ce85 100644--- a/models/wan/modules/vae2_2.py+++ b/models/wan/modules/vae2_2.py@@ -1037,12 +1037,13 @@ class Wan2_2_VAE:dim_mult=[1, 2, 4, 4],temperal_downsample=[False, True, True],dtype=torch.float,+ upsampler_factor=1,device="cuda",):self.dtype = dtypeself.device = device-+ assert upsampler_factor == 1mean = torch.tensor([-0.2289,diff --git a/models/wan/wan_handler.py b/models/wan/wan_handler.pyindex 886e2ea..31f59c6 100644--- a/models/wan/wan_handler.py+++ b/models/wan/wan_handler.py@@ -39,7 +39,7 @@ class family_handler():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",- "i2v", "i2v_2_2", "i2v_2_2_multitalk", "ti2v_2_2", "lucy_edit", "flf2v_720p", "fun_inp_1.3B", "fun_inp"]+ "i2v", "i2v_2_2", "i2v_2_2_multitalk", "ti2v_2_2", "lucy_edit", "flf2v_720p", "fun_inp_1.3B", "fun_inp", "mocha"]@staticmethod@@ -49,7 +49,9 @@ class family_handler():"flf2v_720p" : "i2v","t2v_1.3B" : "t2v","t2v_2_2" : "t2v",- "t2v_2_2" : "alpha",+ "alpha" : "t2v",+ "lynx" : "t2v",+ "standin" : "t2v","vace_standin_14B" : "vace_14B","vace_lynx_14B" : "vace_14B","vace_14B_2_2": "vace_14B",@@ -85,7 +87,7 @@ class family_handler():"magcache_thresh" : 0,"magcache_K" : 2,})- if base_model_type in ["t2v"] and "URLs2" in model_def:+ if base_model_type in ["t2v", "mocha"] and "URLs2" in model_def:def_mag_ratios = [1.00124, 1.00155, 0.99822, 0.99851, 0.99696, 0.99687, 0.99703, 0.99732, 0.9966, 0.99679, 0.99602, 0.99658, 0.99578, 0.99664, 0.99484, 0.9949, 0.99633, 0.996, 0.99659, 0.99683, 0.99534, 0.99549, 0.99584, 0.99577, 0.99681, 0.99694, 0.99563, 0.99554, 0.9944, 0.99473, 0.99594, 0.9964, 0.99466, 0.99461, 0.99453, 0.99481, 0.99389, 0.99365, 0.99391, 0.99406, 0.99354, 0.99361, 0.99283, 0.99278, 0.99268, 0.99263, 0.99057, 0.99091, 0.99125, 0.99126, 0.65523, 0.65252, 0.98808, 0.98852, 0.98765, 0.98736, 0.9851, 0.98535, 0.98311, 0.98339, 0.9805, 0.9806, 0.97776, 0.97771, 0.97278, 0.97286, 0.96731, 0.96728, 0.95857, 0.95855, 0.94385, 0.94385, 0.92118, 0.921, 0.88108, 0.88076, 0.80263, 0.80181]elif base_model_type in ["i2v_2_2"]:def_mag_ratios = [0.99191, 0.99144, 0.99356, 0.99337, 0.99326, 0.99285, 0.99251, 0.99264, 0.99393, 0.99366, 0.9943, 0.9943, 0.99276, 0.99288, 0.99389, 0.99393, 0.99274, 0.99289, 0.99316, 0.9931, 0.99379, 0.99377, 0.99268, 0.99271, 0.99222, 0.99227, 0.99175, 0.9916, 0.91076, 0.91046, 0.98931, 0.98933, 0.99087, 0.99088, 0.98852, 0.98855, 0.98895, 0.98896, 0.98806, 0.98808, 0.9871, 0.98711, 0.98613, 0.98618, 0.98434, 0.98435, 0.983, 0.98307, 0.98185, 0.98187, 0.98131, 0.98131, 0.9783, 0.97835, 0.97619, 0.9762, 0.97264, 0.9727, 0.97088, 0.97098, 0.96568, 0.9658, 0.96045, 0.96055, 0.95322, 0.95335, 0.94579, 0.94594, 0.93297, 0.93311, 0.91699, 0.9172, 0.89174, 0.89202, 0.8541, 0.85446, 0.79823, 0.79902]@@ -158,6 +160,9 @@ class family_handler():else:profiles_dir = "wan"+ if (test_class_t2v(base_model_type) or vace_class or not base_model_type in ["chrono_edit"]) and not base_model_type in ["alpha"]:+ extra_model_def["vae_upsampler"] = [1,2]+extra_model_def["profiles_dir"] = [profiles_dir]extra_model_def["group"] = group@@ -294,6 +299,7 @@ class family_handler():extra_model_def["keep_frames_video_guide_not_supported"] = Trueextra_model_def["extract_guide_from_window_start"] = Trueextra_model_def["forced_guide_mask_inputs"] = True+ extra_model_def["no_background_removal"] = Trueextra_model_def["background_removal_label"]= "Remove Backgrounds behind People (Animate Mode Only)"extra_model_def["background_ref_outpainted"] = Falseextra_model_def["return_image_refs_tensor"] = True@@ -445,6 +451,19 @@ class family_handler():else:image_prompt_types_allowed = ""extra_model_def["image_prompt_types_allowed"] = image_prompt_types_allowed+ if base_model_type in ["mocha"]:+ extra_model_def["guide_custom_choices"] = {+ "choices":[+ ("Transfer Person In Reference Images (Second Image must be a Close Up) in Control Video", "VAI"),+ ],+ "default": "VAI",+ "letters_filter": "VAI",+ "label": "Type of Process",+ "scale": 3,+ "show_label" : False,+ "visible": True,+ }+ extra_model_def["background_removal_color"] = [128, 128, 128]if base_model_type in ["fantasy"] or multitalk:extra_model_def["audio_guidance"] = True@@ -476,21 +495,21 @@ class family_handler():download_def = [{"repoId" : "DeepBeepMeep/Wan2.1","sourceFolderList" : ["xlm-roberta-large", "umt5-xxl", "" ],- "fileList" : [ [ "models_clip_open-clip-xlm-roberta-large-vit-huge-14-bf16.safetensors", "sentencepiece.bpe.model", "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json"], ["special_tokens_map.json", "spiece.model", "tokenizer.json", "tokenizer_config.json"] + computeList(text_encoder_filename) , ["Wan2.1_VAE.safetensors", "fantasy_proj_model.safetensors" ] + computeList(model_filename) ]+ "fileList" : [ [ "models_clip_open-clip-xlm-roberta-large-vit-huge-14-bf16.safetensors", "sentencepiece.bpe.model", "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json"], ["special_tokens_map.json", "spiece.model", "tokenizer.json", "tokenizer_config.json"] + computeList(text_encoder_filename) , ["Wan2.1_VAE.safetensors", "fantasy_proj_model.safetensors", "Wan2.1_VAE_upscale2x_imageonly_real_v1.safetensors"] + computeList(model_filename) ]}]if test_wan_5B(base_model_type):download_def += [ {"repoId" : "DeepBeepMeep/Wan2.2","sourceFolderList" : [""],- "fileList" : [ [ "Wan2.2_VAE.safetensors" ] ]+ "fileList" : [ [ "Wan2.2_VAE.safetensors"] ]}]return download_def@staticmethod- def load_model(model_filename, model_type, base_model_type, model_def, quantizeTransformer = False, text_encoder_quantization = None, dtype = torch.bfloat16, VAE_dtype = torch.float32, mixed_precision_transformer = False, save_quantized= False, submodel_no_list = None, override_text_encoder = None):+ def load_model(model_filename, model_type, base_model_type, model_def, quantizeTransformer = False, text_encoder_quantization = None, dtype = torch.bfloat16, VAE_dtype = torch.float32, mixed_precision_transformer = False, save_quantized= False, submodel_no_list = None, override_text_encoder = None, VAE_upsampling = None, **kwargs):from .configs import WAN_CONFIGSif test_class_i2v(base_model_type):@@ -512,7 +531,8 @@ class family_handler():dtype = dtype,VAE_dtype = VAE_dtype,mixed_precision_transformer = mixed_precision_transformer,- save_quantized = save_quantized+ save_quantized = save_quantized,+ VAE_upsampling = VAE_upsampling,)pipe = {"transformer": wan_model.model, "text_encoder" : wan_model.text_encoder.model, "vae": wan_model.vae.model }@@ -592,6 +612,12 @@ class family_handler():audio_prompt_type += "A"ui_defaults["audio_prompt_type"] = audio_prompt_type+ if settings_version < 2.40:+ if base_model_type in ["animate"]:+ remove_background_images_ref = ui_defaults.get("remove_background_images_ref", None)+ if remove_background_images_ref !=0:+ ui_defaults["remove_background_images_ref"] = 0+@staticmethoddef update_default_settings(base_model_type, model_def, ui_defaults):ui_defaults.update({@@ -676,11 +702,18 @@ class family_handler():"video_prompt_type": "PVBKI","mask_expand": 20,"audio_prompt_type": "R",+ "remove_background_images_ref" : 0,+ "force_fps": "control",})elif base_model_type in ["vace_ditto_14B"]:ui_defaults.update({"video_prompt_type": "V",})+ elif base_model_type in ["mocha"]:+ ui_defaults.update({+ "video_prompt_type": "VAI",+ "force_fps": "control",+ })if base_model_type in ["chrono_edit"]:ui_defaults.update({"image_mode": 1, "prompt_enhancer":"TI"})diff --git a/shared/utils/utils.py b/shared/utils/utils.pyindex 4f47fbd..598c351 100644--- a/shared/utils/utils.py+++ b/shared/utils/utils.py@@ -220,10 +220,10 @@ def convert_image_to_video(image):out.release()return temp_video.name-def resize_lanczos(img, h, w):+def resize_lanczos(img, h, w, method = None):img = (img + 1).float().mul_(127.5)img = Image.fromarray(np.clip(img.movedim(0, -1).cpu().numpy(), 0, 255).astype(np.uint8))- img = img.resize((w,h), resample=Image.Resampling.LANCZOS)+ img = img.resize((w,h), resample=Image.Resampling.LANCZOS if method is None else method)img = torch.from_numpy(np.array(img).astype(np.float32)).movedim(-1, 0)img = img.div(127.5).sub_(1)return img@@ -325,7 +325,7 @@ def calculate_dimensions_and_resize_image(image, canvas_height, canvas_width, fiimage = image.resize((new_width, new_height), resample=Image.Resampling.LANCZOS)return image, new_height, new_width-def resize_and_remove_background(img_list, budget_width, budget_height, rm_background, any_background_ref, fit_into_canvas = 0, block_size= 16, outpainting_dims = None, background_ref_outpainted = True, inpaint_color = 127.5, return_tensor = False, ignore_last_refs = 0 ):+def resize_and_remove_background(img_list, budget_width, budget_height, rm_background, any_background_ref, fit_into_canvas = 0, block_size= 16, outpainting_dims = None, background_ref_outpainted = True, inpaint_color = 127.5, return_tensor = False, ignore_last_refs = 0, background_removal_color = [255, 255, 255] ):if rm_background:session = new_session()@@ -358,7 +358,7 @@ def resize_and_remove_background(img_list, budget_width, budget_height, rm_backgresized_image= img.resize((new_width,new_height), resample=Image.Resampling.LANCZOS)if rm_background and not (any_background_ref and i==0 or any_background_ref == 2) :# resized_image = remove(resized_image, session=session, alpha_matting_erode_size = 1,alpha_matting_background_threshold = 70, alpha_foreground_background_threshold = 100, alpha_matting = True, bgcolor=[255, 255, 255, 0]).convert('RGB')- resized_image = remove(resized_image, session=session, alpha_matting_erode_size = 1, alpha_matting = True, bgcolor=[255, 255, 255, 0]).convert('RGB')+ resized_image = remove(resized_image, session=session, alpha_matting_erode_size = 1, alpha_matting = True, bgcolor=background_removal_color + [0]).convert('RGB')if return_tensor:output_list.append(convert_image_to_tensor(resized_image).unsqueeze(1))else:diff --git a/wgp.py b/wgp.pyindex d004e0a..aa02a11 100644--- a/wgp.py+++ b/wgp.py@@ -78,8 +78,8 @@ global_queue_ref = []AUTOSAVE_FILENAME = "queue.zip"PROMPT_VARS_MAX = 10target_mmgp_version = "3.6.7"-WanGP_version = "9.37"-settings_version = 2.39+WanGP_version = "9.41"+settings_version = 2.40max_source_video_frames = 3000prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer = None, None, None, Noneimage_names_list = ["image_start", "image_end", "image_refs"]@@ -616,12 +616,19 @@ def process_prompt_and_add_tasks(state, current_gallery_tab, model_choice):switch_threshold2 = inputs["switch_threshold2"]multi_prompts_gen_type = inputs["multi_prompts_gen_type"]video_guide_outpainting = inputs["video_guide_outpainting"]+ spatial_upsampling = inputs["spatial_upsampling"]+ medium = "Videos" if image_mode == 0 else "Images"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"):gr.Info("Output Resolution Cropping will be not used for this Generation as it is not compatible with Video Outpainting")+ if "vae" in spatial_upsampling:+ if image_mode not in model_def.get("vae_upsampler", []):+ gr.Info(f"VAE Spatial Upsampling is not available for {medium}")+ return ret()+if len(activated_loras) > 0:error = check_loras_exist(model_type, activated_loras)if len(error) > 0:@@ -3208,7 +3215,7 @@ def setup_prompt_enhancer(pipe, kwargs):-def load_models(model_type, override_profile = -1):+def load_models(model_type, override_profile = -1, **model_kwargs):global transformer_type, loaded_profilebase_model_type = get_base_model_type(model_type)model_def = get_model_def(model_type)@@ -3290,10 +3297,10 @@ def load_models(model_type, override_profile = -1):print(f"Loading Text Encoder '{override_text_encoder}' ...")else:override_text_encoder = None-+ torch.set_default_device('cpu')wan_model, pipe = model_types_handlers[base_model_type].load_model(local_model_file_list, model_type, base_model_type, model_def, quantizeTransformer = quantizeTransformer, text_encoder_quantization = text_encoder_quantization,- dtype = transformer_dtype, VAE_dtype = VAE_dtype, mixed_precision_transformer = mixed_precision_transformer, save_quantized = save_quantized, submodel_no_list = model_submodel_no_list, override_text_encoder = override_text_encoder )+ dtype = transformer_dtype, VAE_dtype = VAE_dtype, mixed_precision_transformer = mixed_precision_transformer, save_quantized = save_quantized, submodel_no_list = model_submodel_no_list, override_text_encoder = override_text_encoder, **model_kwargs )kwargs = {}if "pipe" in pipe:@@ -4435,7 +4442,13 @@ def perform_temporal_upsampling(sample, previous_last_frame, temporal_upsamplingdef perform_spatial_upsampling(sample, spatial_upsampling):from shared.utils.utils import resize_lanczos- if spatial_upsampling == "lanczos1.5":+ if spatial_upsampling == "vae2":+ return sample+ method = None+ if spatial_upsampling == "vae1":+ scale = 0.5+ method = Image.Resampling.BICUBIC+ elif spatial_upsampling == "lanczos1.5":scale = 1.5else:scale = 2@@ -4448,7 +4461,7 @@ def perform_spatial_upsampling(sample, spatial_upsampling):w = int(w)frames_to_upsample = [sample[:, i] for i in range( sample.shape[1]) ]def upsample_frames(frame):- return resize_lanczos(frame, h, w).unsqueeze(1)+ return resize_lanczos(frame, h, w, method).unsqueeze(1)sample = torch.cat(process_images_multithread(upsample_frames, frames_to_upsample, "upsample", wrap_in_list = False, max_workers=get_default_workers(), in_place=True), dim=1)frames_to_upsample = Nonereturn sample@@ -4981,12 +4994,18 @@ def generate_video(if "P" in preload_model_policy and not "U" in preload_model_policy:while wan_model == None:time.sleep(1)-+ vae_upsampling = model_def.get("vae_upsampler", None)+ model_kwargs = {}+ if vae_upsampling is not None:+ new_vae_upsampling = None if image_mode not in vae_upsampling or "vae" not in spatial_upsampling else spatial_upsampling+ old_vae_upsampling = None if reload_needed or wan_model is None or not hasattr(wan_model, "vae") else wan_model.vae.upsampling_set+ reload_needed = reload_needed or old_vae_upsampling != new_vae_upsampling+ if new_vae_upsampling: model_kwargs = {"VAE_upsampling": new_vae_upsampling}if model_type != transformer_type or reload_needed or override_profile>0 and override_profile != loaded_profile or override_profile<0 and default_profile != loaded_profile:wan_model = Nonerelease_model()send_cmd("status", f"Loading model {get_model_name(model_type)}...")- wan_model, offloadobj = load_models(model_type, override_profile)+ wan_model, offloadobj = load_models(model_type, override_profile, **model_kwargs)send_cmd("status", "Model loaded")reload_needed= Falseoverridden_attention = get_overridden_attention(model_type)@@ -5485,7 +5504,8 @@ def generate_video(outpainting_dims =outpainting_dims,background_ref_outpainted = model_def.get("background_ref_outpainted", True),return_tensor= model_def.get("return_image_refs_tensor", False),- ignore_last_refs =model_def.get("no_processing_on_last_images_refs",0))+ ignore_last_refs =model_def.get("no_processing_on_last_images_refs",0),+ background_removal_color = model_def.get("background_removal_color", [255, 255, 255] ))frames_to_inject_parsed = frames_to_inject[ window_start_frame if extract_guide_from_window_start else guide_start_frame: guide_end_frame]if video_guide is not None or len(frames_to_inject_parsed) > 0 or model_def.get("forced_guide_mask_inputs", False):@@ -5768,7 +5788,7 @@ def generate_video(output_new_audio_data = full_generated_audio- if len(temporal_upsampling) > 0 or len(spatial_upsampling) > 0:+ if len(temporal_upsampling) > 0 or len(spatial_upsampling) > 0 and not "vae2" in spatial_upsampling:send_cmd("progress", [0, get_latest_status(state,"Upsampling")])output_fps = fps@@ -8264,7 +8284,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonvideo_source = gr.Video(label= "Video to Continue", height = gallery_height, visible= "V" in image_prompt_type_value, value= ui_defaults.get("video_source", None), elem_id="video_input")image_end_row, image_end, image_end_extra = get_image_gallery(label= get_image_end_label(ui_defaults.get("multi_prompts_gen_type", 0)), value = ui_defaults.get("image_end", None), visible= any_letters(image_prompt_type_value, "SVL") and ("E" in image_prompt_type_value) )if model_mode_choices is None or image_mode_value not in model_modes_visibility:- model_mode = gr.Dropdown(value=None, visible=False)+ model_mode = gr.Dropdown(value=None, label="model mode", visible=False, allow_custom_value= True)else:model_mode_value = get_default_value(model_mode_choices["choices"], ui_defaults.get("model_mode", None), model_mode_choices["default"] )model_mode = gr.Dropdown(choices=model_mode_choices["choices"], value=model_mode_value, label=model_mode_choices["label"], visible=True)@@ -8342,6 +8362,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non)any_control_video = Trueany_control_image = image_outputs+ any_reference_image = any("I" in choice for label, choice in guide_custom_choices["choices"])# Custom dropdown box & checkboxcustom_video_selection = model_def.get("custom_video_selection", None)@@ -8411,7 +8432,6 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonvisible = False,label="Start / Reference Images", scale = 1)- any_reference_image = Falseelse:any_reference_image = Truevideo_prompt_type_image_refs = gr.Dropdown(@@ -8482,7 +8502,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonframes_positions = gr.Text(value=ui_defaults.get("frames_positions","") , visible= "F" in video_prompt_type_value, scale = 2, label= "Positions of Injected Frames (1=first, L=last of a window) no position for other Image Refs)" )image_refs_relative_size = gr.Slider(20, 100, value=ui_defaults.get("image_refs_relative_size", 50), step=1, label="Rescale Internaly Image Ref (% in relation to Output Video) to change Output Composition", visible = model_def.get("any_image_refs_relative_size", False) and image_outputs)- no_background_removal = model_def.get("no_background_removal", False) or image_ref_choices is None+ no_background_removal = model_def.get("no_background_removal", False) #or image_ref_choices is Nonebackground_removal_label = model_def.get("background_removal_label", "Remove Background behind People / Objects")remove_background_images_ref = gr.Dropdown(@@ -8760,7 +8780,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonwith gr.Column():gr.Markdown("<B>Upsampling - postprocessing that may improve fluidity and the size of the video</B>")- def gen_upsampling_dropdowns(temporal_upsampling, spatial_upsampling , film_grain_intensity, film_grain_saturation, element_class= None, max_height= None, image_outputs = False):+ def gen_upsampling_dropdowns(temporal_upsampling, spatial_upsampling , film_grain_intensity, film_grain_saturation, element_class= None, max_height= None, image_outputs = False, any_vae_upsampling = False):temporal_upsampling = gr.Dropdown(choices=[("Disabled", ""),@@ -8774,12 +8794,13 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonelem_classes= element_class# max_height = max_height)+spatial_upsampling = gr.Dropdown(choices=[("Disabled", ""),("Lanczos x1.5", "lanczos1.5"),("Lanczos x2.0", "lanczos2"),- ],+ ] + ([("VAE x1.0 (refined)", "vae1"),("VAE x2.0", "vae2")] if any_vae_upsampling else []) ,value=spatial_upsampling,visible=True,scale = 1,@@ -8793,7 +8814,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonfilm_grain_saturation = gr.Slider(0.0, 1, value=film_grain_saturation, step=0.01, label="Film Grain Saturation")return temporal_upsampling, spatial_upsampling, film_grain_intensity, film_grain_saturation- temporal_upsampling, spatial_upsampling, film_grain_intensity, film_grain_saturation = gen_upsampling_dropdowns(ui_defaults.get("temporal_upsampling", ""), ui_defaults.get("spatial_upsampling", ""), ui_defaults.get("film_grain_intensity", 0), ui_defaults.get("film_grain_saturation", 0.5), image_outputs= image_outputs)+ temporal_upsampling, spatial_upsampling, film_grain_intensity, film_grain_saturation = gen_upsampling_dropdowns(ui_defaults.get("temporal_upsampling", ""), ui_defaults.get("spatial_upsampling", ""), ui_defaults.get("film_grain_intensity", 0), ui_defaults.get("film_grain_saturation", 0.5), image_outputs= image_outputs, any_vae_upsampling= "vae_upsampler"in model_def)with gr.Tab("Audio", visible = not (image_outputs or audio_only)) as audio_tab:any_audio_source = not (image_outputs or audio_only)