Python
added Chrono Edit support
deepbeepmeepd1ecd5fdc92e
diff --git a/README.md b/README.mdindex 750a152..4bc121e 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 :+### November 1 2025: WanGP v9.3, How many bananas is 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.++**LyCoris** support: preliminary basic Lycoris support for this Lora format. At least Qwen Multi Camera should work (https://huggingface.co/dx8152/Qwen-Edit-2509-Multiple-angles). If you have a Lycoris that does not work and it may be interesting please mention it in the Request Channel+### October 29 2025: WanGP v9.21, Why isn't all my VRAM used ?diff --git a/defaults/chrono_edit.json b/defaults/chrono_edit.jsonnew file mode 100644index 0000000..a3f5267--- /dev/null+++ b/defaults/chrono_edit.json@@ -0,0 +1,13 @@+{+ "model": {+ "name": "Wan2.1 Chrono Edit 14B",+ "architecture": "chrono_edit",+ "description": "This model in an Image Editor that will follow your instructions. It generates internally a video to produce the desired effect on the original image (the result being the End Image). It expects a very specific prompt format. It is why you must absolutely use the Prompt Enhancer that has been tuned for this model.",+ "URLs": [+ "https://huggingface.co/DeepBeepMeep/Wan2.1/resolve/main/wan2.1_chrono_edit_14B_mbf16.safetensors",+ "https://huggingface.co/DeepBeepMeep/Wan2.1/resolve/main/wan2.1_chrono_edit_14B_quanto_mbf16_int8.safetensors",+ "https://huggingface.co/DeepBeepMeep/Wan2.1/resolve/main/wan2.1_chrono_edit_14B_quanto_mfp16_int8.safetensors"+ ]+ },+ "prompt": "Rotate the pose of the woman so she that is facing the right"+}\ No newline at end of filediff --git a/defaults/chrono_edit_distill.json b/defaults/chrono_edit_distill.jsonnew file mode 100644index 0000000..841b1d6--- /dev/null+++ b/defaults/chrono_edit_distill.json@@ -0,0 +1,16 @@+{+ "model": {+ "name": "Wan2.1 Chrono Edit Distill 14B",+ "architecture": "chrono_edit",+ "description": "This model in an Image Editor that will follow your instructions. It generates internally a video to produce the desired effect on the original image (the result being the End Image). It expects a very specific prompt format. It is why you must absolutely use the Prompt Enhancer that has been tuned for this model. This version is accelerated using the Chrono Distill",+ "URLs": "chrono_edit",+ "profiles_dir": [""],+ "loras": ["https://huggingface.co/DeepBeepMeep/Wan2.1/resolve/main/loras_accelerators/chronoedit_distill_lora.safetensors"],+ "loras_multipliers": [1]+ },+ "prompt": "Rotate the pose of the woman so she that is facing the right",+ "num_inference_steps": 8,+ "flow_shift": 2,+ "guidance_phases": 1,+ "guidance_scale": 1+}\ No newline at end of filediff --git a/models/hyvideo/hunyuan_handler.py b/models/hyvideo/hunyuan_handler.pyindex 00dd21b..28c8531 100644--- a/models/hyvideo/hunyuan_handler.py+++ b/models/hyvideo/hunyuan_handler.py@@ -43,6 +43,8 @@ class family_handler():extra_model_def["frames_minimum"] = 5extra_model_def["frames_steps"] = 4extra_model_def["sliding_window"] = False+ extra_model_def["flow_shift"] = True+if base_model_type in ["hunyuan", "hunyuan_i2v"]:extra_model_def["embedded_guidance"] = Trueelse:diff --git a/models/ltx_video/utils/prompt_enhance_utils.py b/models/ltx_video/utils/prompt_enhance_utils.pyindex 0d6e521..2a87c7e 100644--- a/models/ltx_video/utils/prompt_enhance_utils.py+++ b/models/ltx_video/utils/prompt_enhance_utils.py@@ -46,13 +46,17 @@ Do not exceed the 150 word limit!Output the enhanced prompt only."""-I2V_CINEMATIC_PROMPT = """You are an expert cinematic director with many award winning movies, When writing prompts based on the user input, focus on detailed, chronological descriptions of actions and scenes.+IT2V_CINEMATIC_PROMPT = """You are an expert cinematic director with many award winning movies.+You have the following information:+1. The user provides a general text input about its scenes expectations+2. The user provides a caption of an image of a subject that relates to the scene+When writing prompts based on the user input, focus on detailed, chronological descriptions of actions and scenes.Include specific movements, appearances, camera angles, and environmental details - all in a single flowing paragraph.Start directly with the action, and keep descriptions literal and precise.Think like a cinematographer describing a shot list.Keep within 150 words.For best results, build your prompts using this structure:-Describe the image first and then add the user input. Image description should be in first priority! Align to the image caption if it contradicts the user text input.+Describe the inital scene first using the image caption of the subject and then describe how the scene evolves by following the user text input. Image description should be in first priority! Align to the image caption if it contradicts the user text input.Start with main action in a single sentenceAdd specific details about movements and gesturesDescribe character/object appearances precisely@@ -65,14 +69,37 @@ Do not exceed the 150 word limit!Output the enhanced prompt only."""-I2I_VISUAL_PROMPT = """You are an expert visual artist and photographer with award-winning compositions. When writing prompts based on the user input, focus on detailed, precise descriptions of visual elements and composition.+I2V_CINEMATIC_PROMPT = """You are an expert cinematic director with many award winning movies.+You have been provided with a caption of an image of a subject that relates to the scene to film.+Focus on detailed, chronological descriptions of actions and scenes.+Include specific movements, appearances, camera angles, and environmental details - all in a single flowing paragraph.+Start directly with the action, and keep descriptions literal and precise.+Think like a cinematographer describing a shot list.+Keep within 150 words.+For best results, build your prompts using this structure:+Describe the inital scene first using the image caption of the subject and then describe how the scene should naturally evolves.+Start with main action in a single sentence+Add specific details about movements and gestures+Describe character/object appearances precisely+Include background and environment details+Specify camera angles and movements+Describe lighting and colors+Note any changes or sudden events+Do not exceed the 150 word limit!+Output the enhanced prompt only.+"""++IT2I_VISUAL_PROMPT = """You are an expert visual artist and photographer with award-winning compositions. When writing prompts based on the user input, focus on detailed, precise descriptions of visual elements and composition.Include specific poses, appearances, framing, and environmental details - all in a single flowing paragraph.+You have the following information:+1. The user provides a general text input about the expected photography+2. The user provides a caption of an image of a subject he wants to be represented in the photographyStart directly with the main subject, and keep descriptions literal and precise.Think like a photographer describing the perfect shot.Do not change the user input intent, just enhance it.Keep within 150 words.For best results, build your prompts using this structure:-Start with main subject and pose in a single sentence+Using the image caption start with main subject and pose in a single sentenceAdd specific details about expressions and positioningDescribe character/object appearances preciselyInclude background and environment details@@ -83,6 +110,25 @@ Do not exceed the 150 word limit!Output the enhanced prompt only."""+I2I_VISUAL_PROMPT = """You are an expert visual artist and photographer with award-winning compositions.+You have been provided with a caption of an image of a subject to be represented in the photography.+Focus on detailed, descriptions of actions that are happening in the photography.+Include specific poses, appearances, framing, and environmental details - all in a single flowing paragraph.+Start directly with the main subject, and keep descriptions literal and precise.+Think like a photographer describing the perfect shot.+Do not change the user input intent, just enhance it.+Keep within 150 words.+For best results, build your prompts using this structure:+Using the image caption start with main subject and pose in a single sentence+Add specific details about expressions and positioning+Describe character/object appearances precisely+Include background and environment details+Specify framing, composition and perspective+Describe lighting, colors, and mood+Note any atmospheric or stylistic elements+Do not exceed the 150 word limit!+Output the enhanced prompt only.+"""def tensor_to_pil(tensor):# Ensure tensor is in range [-1, 1]@@ -111,18 +157,23 @@ def generate_cinematic_prompt(video_prompt= True,text_prompt = False,max_new_tokens: int = 256,+ prompt_enhancer_instructions = None,) -> List[str]:prompts = [prompt] if isinstance(prompt, str) else promptif images is None:+ if prompt_enhancer_instructions is None:+ prompt_enhancer_instructions= T2T_TEXT_PROMPT if text_prompt else (T2V_CINEMATIC_PROMPT if video_prompt else T2I_VISUAL_PROMPT)prompts = _generate_t2v_prompt(prompt_enhancer_model,prompt_enhancer_tokenizer,prompts,max_new_tokens,- T2T_TEXT_PROMPT if text_prompt else (T2V_CINEMATIC_PROMPT if video_prompt else T2I_VISUAL_PROMPT),+ prompt_enhancer_instructions,)else:+ if prompt_enhancer_instructions is None:+ prompt_enhancer_instructions= IT2V_CINEMATIC_PROMPT if video_prompt else IT2I_VISUAL_PROMPTprompts = _generate_i2v_prompt(image_caption_model,@@ -132,7 +183,7 @@ def generate_cinematic_prompt(prompts,images,max_new_tokens,- I2V_CINEMATIC_PROMPT if video_prompt else I2I_VISUAL_PROMPT,+ prompt_enhancer_instructions,)return promptsdiff --git a/models/qwen/transformer_qwenimage.py b/models/qwen/transformer_qwenimage.pyindex 8ec34ed..b9eafba 100644--- a/models/qwen/transformer_qwenimage.py+++ b/models/qwen/transformer_qwenimage.py@@ -493,6 +493,7 @@ class QwenImageTransformer2DModel(nn.Module):new_sd = {}for k,v in sd.items():k = k.replace(".lora.", ".lora_")+ k = k.replace(".default.weight", ".weight")new_sd[k] = vsd = new_sd@@ -525,6 +526,7 @@ class QwenImageTransformer2DModel(nn.Module):new_sd[k] = vsd = new_sdreturn sd+return sddef __init__(diff --git a/models/wan/any2video.py b/models/wan/any2video.pyindex ac5a2eb..8d94f2d 100644--- a/models/wan/any2video.py+++ b/models/wan/any2video.py@@ -163,13 +163,13 @@ class WanAny2V:kwargs= { "modelClass": WanModel,"do_quantize": quantizeTransformer and not save_quantized, "defaultConfigPath": base_config_file , "ignore_unused_weights": ignore_unused_weights, "writable_tensors": False, "default_dtype": dtype, "preprocess_sd": preprocess_sd, "forcedConfigPath": forcedConfigPath, }kwargs_light= { "modelClass": WanModel,"writable_tensors": False, "preprocess_sd": preprocess_sd , "forcedConfigPath" : base_config_file}if module_source is not None:- self.model = offload.fast_load_transformers_model(model_filename[:1] + [module_source], **kwargs)+ self.model = offload.fast_load_transformers_model(model_filename[:1] + [fl.locate_file(module_source)], **kwargs)if module_source2 is not None:- self.model2 = offload.fast_load_transformers_model(model_filename[1:2] + [module_source2], **kwargs)+ self.model2 = offload.fast_load_transformers_model(model_filename[1:2] + [fl.locate_file(module_source2)], **kwargs)if source is not None:- self.model = offload.fast_load_transformers_model(source, **kwargs_light)+ self.model = offload.fast_load_transformers_model(fl.locate_file(source), **kwargs_light)if source2 is not None:- self.model2 = offload.fast_load_transformers_model(source2, **kwargs_light)+ self.model2 = offload.fast_load_transformers_model(fl.locate_file(source2), **kwargs_light)if self.model is not None or self.model2 is not None:from wgp import save_model@@ -508,15 +508,22 @@ class WanAny2V:alpha_class = model_def.get("alpha_class", False)lucy_edit= model_type in ["lucy_edit"]animate= model_type in ["animate"]+ chrono_edit = model_type in ["chrono_edit"]start_step_no = 0ref_images_count = 0trim_frames = 0+ last_latent_output = Falseextended_overlapped_latents = clip_image_start = clip_image_end = image_mask_latents = latent_slice = Noneno_noise_latents_injection = infinitetalktimestep_injection = False++ if chrono_edit:+ frame_num = 29+ last_latent_output = True+lat_frames = int((frame_num - 1) // self.vae_stride[0]) + 1extended_input_dim = 0- ref_images_before = False+ ref_images_before = False# image2videoif model_def.get("i2v_class", False) and not animate:any_end_frame = False@@ -1098,7 +1105,7 @@ class WanAny2V:latents_preview = latentsif ref_images_before and ref_images_count > 0: latents_preview = latents_preview[:, :, ref_images_count: ]if trim_frames > 0: latents_preview= latents_preview[:, :,:-trim_frames]- if image_outputs: latents_preview= latents_preview[:, :,:1]+ if image_outputs: latents_preview= latents_preview[:, :,-1:] if last_latent_output else latents_preview[:, :,:1]if len(latents_preview) > 1: latents_preview = latents_preview.transpose(0,2)callback(i, latents_preview[0], False, denoising_extra =denoising_extra )latents_preview = None@@ -1117,6 +1124,9 @@ class WanAny2V:if chipmunk:self.model.release_chipmunk() # need to add it at every exit when in prod+ if image_outputs :+ x0 = [x[:,-1:] if last_latent_output else x[:,:1] for x in x0 ]+videos = self.vae.decode(x0, VAE_tile_size)any_vae2= self.vae2 is not Noneif any_vae2:diff --git a/models/wan/chono_edit_prompt.py b/models/wan/chono_edit_prompt.pynew file mode 100644index 0000000..6c97aa3--- /dev/null+++ b/models/wan/chono_edit_prompt.py@@ -0,0 +1,42 @@++image_prompt_enhancer_instructions="""You are a professional edit instruction rewriter and prompt engineer. Your task is to generate a precise, concise, and visually achievable chain-of-thought reasoning based on the user-provided instruction and the image to be edited.++You have the following information:+1. The user provides instructions to edit an image+2. The user provides a description of the image to edit++Your task is NOT to output the final answer or the edited image. Instead, you must:+- Generate a "thinking" or chain-of-thought process that explains how you reason about the editing task.+- First identify the task type, then provide reasoning/analysis that leads to how the image should be edited.+- Always describe pose and appearance in detail.+- Match the original visual style or genre (anime, CG art, cinematic, poster). If not explicit, choose a stylistically appropriate one based on the image.+- Incorporate motion and camera direction when relevant (e.g., walking, turning, dolly in/out, pan), implying natural human/character motion and interactions.+- Maintain quoted phrases or titles exactly (e.g., character names, series names). Do not translate or alter the original language of text.++## Task Type Handling Rules:++**1. Standard Editing Tasks (e.g., Add, Delete, Replace, Action Change):**+- For replacement tasks, specify what to replace and key visual features of the new element.+- For text editing tasks, specify text position, color, and layout concisely.+- If the user wants to "extract" something, this means they want to remove the background and only keep the specified object isolated. We should add "while removing the background" to the reasoning.+- Explicitly note what must stay unchanged: appearances (hairstyle, clothing, expression, skin tone/race, age), posture, pose, visual style/genre, spatial layout, and shot composition (e.g., medium shot, close-up, side view).++**2. Character Consistency Editing Tasks (e.g., Scenario Change):**+- For tasks that place an object/character (e.g., human, robot, animal) in a completely new scenario, preserve the object's core identity (appearance, materials, key features) but adapt its pose, interaction, and context to fit naturally in the new environment.+- Reason about how the object should interact with the new scenario (e.g., pose changes, hand positions, orientation, facial direction).+- The background and context should transform completely to match the new scenario while maintaining visual coherence.+- Describe both what stays the same (core appearance) and what must change (pose, interaction, setting) to make the scene look realistic and natural.++The length of outputs should be **around 80 - 100 words** to fully describe the transformation. Always start with "The user wants to ..."++Example Output 1 (Standard Editing Task):+The user wants to make the knight kneel on his right knee while keeping the rest of the pose intact.+The knight should lower his stance so his right leg bends to the ground in a kneeling position, with the left leg bent upright to support balance.+The shield with the NVIDIA logo should still be held up firmly in his left hand, angled forward in a defensive posture, while the right hand continues gripping the weapon.+The armor reflections, proportions, and medieval style should remain consistent, emphasizing a powerful and respectful kneeling stance.++Example Output 2 (Character Consistency Editing Task):+The user wants to change the image by modifying the scene so that the woman is drinking coffee in a cozy coffee shop.+The elegant anime-style woman keeps her same graceful expression, long flowing dark hair adorned with golden ornaments, and detailed traditional outfit with red and gold floral patterns.+She is now seated at a wooden café table, holding a steaming cup of coffee near her lips with one hand, while soft sunlight filters through the window, highlighting her refined features.+The background transforms into a warmly lit café interior with subtle reflections, bookshelves, and gentle ambience, maintaining the delicate, painterly aesthetic."""\ No newline at end of filediff --git a/models/wan/configs/chrono_edit.json b/models/wan/configs/chrono_edit.jsonnew file mode 100644index 0000000..f5a12b2--- /dev/null+++ b/models/wan/configs/chrono_edit.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": 36,+ "model_type": "i2v",+ "num_heads": 40,+ "num_layers": 40,+ "out_dim": 16,+ "text_len": 512+}diff --git a/models/wan/convert_wan.py b/models/wan/convert_wan.pynew file mode 100644index 0000000..9311f5f--- /dev/null+++ b/models/wan/convert_wan.py@@ -0,0 +1,146 @@+"""+wan_convert_universal — Diffusers → Wan (T2V/I2V) canonical naming, single format.++- No model detection or flags.+- Shared keys get the same canonical names used by both T2V and I2V loaders.+- I2V extras are mapped only if present in the source.++API:+ new_sd = convert_state_dict_universal(state_dict, cast_dtype=None)+ convert_files_universal([...safetensors...], "out/model.safetensors", cast_dtype=None)+"""++import os, re+from typing import Dict, List, Optional+import torch+from safetensors.torch import safe_open, save_file++_RE_BLOCK = r"^blocks\.(\d+)\."++def _common_unet(src: str) -> str:+ s = src+ # attn1/attn2 → self_attn/cross_attn+ s = re.sub(rf"{_RE_BLOCK}attn1\.", r"blocks.\1.self_attn.", s)+ s = re.sub(rf"{_RE_BLOCK}attn2\.", r"blocks.\1.cross_attn.", s)+ # to_q/k/v/out.0 → q/k/v/o (any *attn* path)+ s = re.sub(r"(\b[^.\s]*attn[^.\s]*\b.*?\.)to_q\.", r"\1q.", s)+ s = re.sub(r"(\b[^.\s]*attn[^.\s]*\b.*?\.)to_k\.", r"\1k.", s)+ s = re.sub(r"(\b[^.\s]*attn[^.\s]*\b.*?\.)to_v\.", r"\1v.", s)+ s = re.sub(r"(\b[^.\s]*attn[^.\s]*\b.*?\.)to_out\.0\.", r"\1o.", s)+ # ffn.net.0.proj → ffn.0 ; ffn.net.2 → ffn.2+ s = re.sub(rf"{_RE_BLOCK}ffn\.net\.0\.proj\.", r"blocks.\1.ffn.0.", s)+ s = re.sub(rf"{_RE_BLOCK}ffn\.net\.2\.", r"blocks.\1.ffn.2.", s)+ return s++def rename_key_universal(src: str) -> str:+ """+ Canonical Wan naming (works for both T2V and I2V shared keys).+ """+ s = _common_unet(src)++ # Cross-attn image projections (only hit if present in the source)+ s = re.sub(rf"{_RE_BLOCK}cross_attn\.add_k_proj\.", r"blocks.\1.cross_attn.k_img.", s)+ s = re.sub(rf"{_RE_BLOCK}cross_attn\.add_v_proj\.", r"blocks.\1.cross_attn.v_img.", s)+ s = re.sub(rf"{_RE_BLOCK}cross_attn\.norm_added_k\.", r"blocks.\1.cross_attn.norm_k_img.", s)++ # Block-level canonical names+ s = re.sub(rf"{_RE_BLOCK}scale_shift_table$", r"blocks.\1.modulation", s) # shared canonical+ s = re.sub(rf"{_RE_BLOCK}norm2\b", r"blocks.\1.norm3", s) # shared canonical++ # Conditioning MLPs (canonical heads)+ s = re.sub(r"^condition_embedder\.text_embedder\.linear_1\.", r"text_embedding.0.", s)+ s = re.sub(r"^condition_embedder\.text_embedder\.linear_2\.", r"text_embedding.2.", s)++ s = re.sub(r"^condition_embedder\.time_embedder\.linear_1\.", r"time_embedding.0.", s)+ s = re.sub(r"^condition_embedder\.time_embedder\.linear_2\.", r"time_embedding.2.", s)++ # time projection single linear → time_projection.1.*+ s = re.sub(r"^condition_embedder\.time_proj\.", r"time_projection.1.", s)++ # Image conditioner "head" (corrected ordering!)+ s = re.sub(r"^condition_embedder\.image_embedder\.norm1\.", r"img_emb.proj.0.", s) # LN (vector)+ s = re.sub(r"^condition_embedder\.image_embedder\.ff\.net\.0\.proj\.", r"img_emb.proj.1.", s) # Linear (matrix)+ s = re.sub(r"^condition_embedder\.image_embedder\.ff\.net\.2\.", r"img_emb.proj.3.", s) # Linear (matrix)+ s = re.sub(r"^condition_embedder\.image_embedder\.norm2\.", r"img_emb.proj.4.", s) # LN (vector)++ # Output head: canonical head.head.* ; top-level scale_shift_table → head.modulation+ s = re.sub(r"^proj_out\.", r"head.head.", s)+ if s == "scale_shift_table":+ s = "head.modulation"++ # patch_embedding.* remains unchanged+ return s++# ---------- Public helpers (single canonical format) ----------++def convert_state_dict_universal(+ state_dict: Dict[str, torch.Tensor],+ cast_dtype: Optional[str] = None,+) -> Dict[str, torch.Tensor]:+ """+ Map a Diffusers-style state_dict to the canonical Wan naming (T2V/I2V shared).+ """+ dtype = None+ if cast_dtype:+ cd = cast_dtype.lower().strip()+ if cd in ("float16", "fp16", "half"): dtype = torch.float16+ elif cd in ("bfloat16", "bf16"): dtype = torch.bfloat16+ elif cd in ("float32", "fp32"): dtype = torch.float32+ else: raise ValueError(f"Unsupported cast_dtype: {cast_dtype}")++ out: Dict[str, torch.Tensor] = {}+ for k, t in state_dict.items():+ out[rename_key_universal(k)] = t.to(dtype) if dtype is not None else t+ return out++def convert_files_universal(+ input_paths: List[str],+ out_safetensors: str,+ cast_dtype: Optional[str] = None,+) -> None:+ """+ Stream one/many Diffusers .safetensors into a single canonical Wan .safetensors.+ """+ dtype = None+ if cast_dtype:+ cd = cast_dtype.lower().strip()+ if cd in ("float16", "fp16", "half"): dtype = torch.float16+ elif cd in ("bfloat16", "bf16"): dtype = torch.bfloat16+ elif cd in ("float32", "fp32"): dtype = torch.float32+ else: raise ValueError(f"Unsupported cast_dtype: {cast_dtype}")++ os.makedirs(os.path.dirname(out_safetensors) or ".", exist_ok=True)+ out: Dict[str, torch.Tensor] = {}+ for p in input_paths:+ with safe_open(p, framework="pt", device="cpu") as f:+ for k in f.keys():+ t = f.get_tensor(k)+ if dtype is not None: t = t.to(dtype)+ out[rename_key_universal(k)] = t++ save_file(out, out_safetensors, metadata={+ "format": "wan_universal",+ "converted_from": "diffusers",+ "script": "wan_convert_universal",+ "cast_dtype": str(dtype) if dtype is not None else "unchanged",+ })++++def main():+++ from mmgp import safetensors2+ files = [f"c:/temp/chrono/diffusion_pytorch_model-{i:05d}-of-00014.safetensors" for i in range(1, 15)]+ new_sd = {}+ for file in files:+ sd = safetensors2.torch_load_file(file)+ conv_sd = convert_state_dict_universal(sd) #, cast_dtype="bf16"+ sd = None+ new_sd.update(conv_sd)++ safetensors2.torch_write_file(new_sd, "chrono.safetensors")++if __name__ == "__main__":+ main()+diff --git a/models/wan/modules/model.py b/models/wan/modules/model.pyindex 6ad72e8..0aca3d0 100644--- a/models/wan/modules/model.py+++ b/models/wan/modules/model.py@@ -475,8 +475,10 @@ class WanI2VCrossAttention(WanSelfAttention):audio_x = self.processor(q, audio_proj, grid_sizes[0], audio_context_lens)k_img = self.k_img(context_img)self.norm_k_img(k_img)- k_img = k_img.view(b, -1, n, d)- v_img = self.v_img(context_img).view(b, -1, n, d)+ k_img = k_img.view(1, -1, n, d)+ v_img = self.v_img(context_img).view(1, -1, n, d)+ if b > 1:+ k_img, v_img = k_img.expand(b, -1, -1, -1), v_img.expand(b, -1, -1, -1)qkv_list = [q, k_img, v_img]del q, k_img, v_imgimg_x = pay_attention(qkv_list)@@ -901,13 +903,13 @@ class WanModel(ModelMixin, ConfigMixin):return sd- # new_sd = {}- # for k,v in sd.items():- # if k.endswith("modulation.diff"):- # pass- # else:- # new_sd[ k] = v- # sd = new_sd+ new_sd = {}+ for k,v in sd.items():+ if k.endswith("modulation.diff"):+ pass+ else:+ new_sd[ k] = v+ sd = new_sd# if first.startswith("blocks."):# new_sd = {}diff --git a/models/wan/wan_handler.py b/models/wan/wan_handler.pyindex 011fe44..886e2ea 100644--- a/models/wan/wan_handler.py+++ b/models/wan/wan_handler.py@@ -7,7 +7,7 @@ def test_vace(base_model_type):return base_model_type in ["vace_14B", "vace_14B_2_2", "vace_1.3B", "vace_multitalk_14B", "vace_standin_14B", "vace_lynx_14B", "vace_ditto_14B"]def test_class_i2v(base_model_type):- return base_model_type in ["i2v", "i2v_2_2", "fun_inp_1.3B", "fun_inp", "flf2v_720p", "fantasy", "multitalk", "infinitetalk", "i2v_2_2_multitalk", "animate" ]+ return base_model_type in ["i2v", "i2v_2_2", "fun_inp_1.3B", "fun_inp", "flf2v_720p", "fantasy", "multitalk", "infinitetalk", "i2v_2_2_multitalk", "animate", "chrono_edit" ]def test_class_t2v(base_model_type):return base_model_type in ["t2v", "t2v_2_2", "alpha", "lynx"]@@ -38,7 +38,7 @@ class family_handler():def query_supported_types():return ["multitalk", "infinitetalk", "fantasy", "vace_14B", "vace_14B_2_2", "vace_multitalk_14B", "vace_standin_14B", "vace_lynx_14B","t2v_1.3B", "standin", "lynx_lite", "lynx", "t2v", "t2v_2_2", "vace_1.3B", "vace_ditto_14B", "phantom_1.3B", "phantom_14B",- "recam_1.3B", "animate", "alpha", "alpha_lynx",+ "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"]@@ -146,6 +146,8 @@ class family_handler():group = "wan2_2"elif i2v:profiles_dir = "wan_i2v"+ if base_model_type in ["chrono_edit"]:+ profiles_dir = "wan_chrono_edit"elif test_wan_5B(base_model_type):profiles_dir = "wan_2_2_5B"group = "wan2_2"@@ -181,7 +183,8 @@ class family_handler():"sliding_window" : base_model_type in ["multitalk", "infinitetalk", "t2v", "t2v_2_2", "fantasy", "animate", "lynx"] or test_class_i2v(base_model_type) or test_wan_5B(base_model_type) or vace_class, #"ti2v_2_2","multiple_submodels" : multiple_submodels,"guidance_max_phases" : 3,- "skip_layer_guidance" : True,+ "skip_layer_guidance" : True,+ "flow_shift": True,"cfg_zero" : True,"cfg_star" : True,"adaptive_projected_guidance" : True,@@ -420,7 +423,13 @@ class family_handler():"visible" : False,}extra_model_def["video_length_locked"] = 81-+ if base_model_type in ["chrono_edit"]:+ from .chono_edit_prompt import image_prompt_enhancer_instructions+ extra_model_def["image_prompt_enhancer_instructions"] = image_prompt_enhancer_instructions+ extra_model_def["video_prompt_enhancer_instructions"] = image_prompt_enhancer_instructions+ extra_model_def["image_outputs"] = True+ extra_model_def["prompt_enhancer_choices_allowed"] = ["TI"]+if vace_class or base_model_type in ["animate", "t2v", "t2v_2_2", "lynx"] :image_prompt_types_allowed = "TVL"elif base_model_type in ["infinitetalk"]:@@ -673,6 +682,9 @@ class family_handler():"video_prompt_type": "V",})+ if base_model_type in ["chrono_edit"]:+ ui_defaults.update({"image_mode": 1, "prompt_enhancer":"TI"})+if test_oneframe_overlap(base_model_type):ui_defaults["sliding_window_overlap"] = 1ui_defaults["color_correction_strength"]= 0diff --git a/profiles/wan_chrono_edit/Chrono Edit Distill - 8 Steps.json b/profiles/wan_chrono_edit/Chrono Edit Distill - 8 Steps.jsonnew file mode 100644index 0000000..74d4c52--- /dev/null+++ b/profiles/wan_chrono_edit/Chrono Edit Distill - 8 Steps.json@@ -0,0 +1,11 @@+{++ "activated_loras": [+ "https://huggingface.co/DeepBeepMeep/Wan2.1/resolve/main/loras_accelerators/chronoedit_distill_lora.safetensors"+ ],+ "loras_multipliers": "1",+ "num_inference_steps": 8,+ "flow_shift": 2,+ "guidance_phases": 1,+ "guidance_scale": 1+}diff --git a/wgp.py b/wgp.pyindex b0f7e5f..35f61a9 100644--- a/wgp.py+++ b/wgp.py@@ -78,7 +78,7 @@ global_queue_ref = []AUTOSAVE_FILENAME = "queue.zip"PROMPT_VARS_MAX = 10target_mmgp_version = "3.6.7"-WanGP_version = "9.25"+WanGP_version = "9.3"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@@ -3263,7 +3263,8 @@ def load_models(model_type, override_profile = -1):for filename, file_model_type, file_module_type, submodel_no in zip(model_file_list, model_type_list, module_type_list, model_submodel_no_list):if len(filename) == 0: continuedownload_models(filename, file_model_type, file_module_type, submodel_no)- local_model_file_list.append( get_local_model_filename(filename ))+ local_file_name = get_local_model_filename(filename )+ local_model_file_list.append( os.path.basename(filename) if local_file_name is None else local_file_name )if len(local_model_file_list) == 0:download_models("", model_type, "", -1)@@ -3823,10 +3824,10 @@ def select_video(state, current_gallery_tab, input_file_list, file_selected, audvideo_guidance_scale = f"{video_guidance_scale}, {video_guidance2_scale} & {video_guidance3_scale} with Switch at Noise Levels {video_switch_threshold} & {video_switch_threshold2}"if multiple_submodels:video_guidance_scale += f" + Model Switch at {video_switch_threshold if video_model_switch_phase ==1 else video_switch_threshold2}"- if image_outputs or is_audio:- video_flow_shift = None- else:+ if model_def.get("flow_shift", False):video_flow_shift = configs.get("flow_shift", None)+ else:+ video_flow_shift = Nonevideo_video_guide_outpainting = configs.get("video_guide_outpainting", "")video_outpainting = ""@@ -4687,7 +4688,7 @@ class DynamicClass:return self.assign(**dict)-def process_prompt_enhancer(prompt_enhancer, original_prompts, image_start, original_image_refs, is_image, audio_only, seed ):+def process_prompt_enhancer(prompt_enhancer, original_prompts, image_start, original_image_refs, is_image, audio_only, seed, prompt_enhancer_instructions = None ):text_encoder_max_tokens = 256from models.ltx_video.utils.prompt_enhance_utils import generate_cinematic_prompt@@ -4715,6 +4716,7 @@ def process_prompt_enhancer(prompt_enhancer, original_prompts, image_start, orivideo_prompt = not is_image,text_prompt = audio_only,max_new_tokens=text_encoder_max_tokens,+ prompt_enhancer_instructions = prompt_enhancer_instructions,)return prompts@@ -4784,13 +4786,15 @@ def enhance_prompt(state, prompt, prompt_enhancer, multi_images_gen_type, overriseed = inputs["seed"]seed = set_seed(seed)enhanced_prompts = []+ prompt_enhancer_instructions = model_def.get("image_prompt_enhancer_instructions" if is_image else "video_prompt_enhancer_instructions", None)+for i, (one_prompt, one_image) in enumerate(zip(original_prompts, image_start)):start_images = [one_image] if one_image is not None else Nonestatus = f'Please Wait While Enhancing Prompt' if num_prompts==1 else f'Please Wait While Enhancing Prompt #{i+1}'progress((i , num_prompts), desc=status, total= num_prompts)try:- enhanced_prompt = process_prompt_enhancer(prompt_enhancer, [one_prompt], start_images, original_image_refs, is_image, audio_only, seed )+ enhanced_prompt = process_prompt_enhancer(prompt_enhancer, [one_prompt], start_images, original_image_refs, is_image, audio_only, seed, prompt_enhancer_instructions )except Exception as e:enhancer_offloadobj.unload_all()release_GPU_ressources(state, "prompt_enhancer")@@ -6784,7 +6788,7 @@ def prepare_inputs_dict(target, inputs, model_type = None, model_filename = Noneif guidance_max_phases < 3 or guidance_phases < 3:pop += ["guidance3_scale", "switch_threshold2", "model_switch_phase"]- if ltxv or image_outputs:+ if not model_def.get("flow_shift", False):pop += ["flow_shift"]if model_def.get("no_negative_prompt", False) :@@ -8202,8 +8206,9 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonmodel_mode_choices = model_def.get("model_modes", None)model_modes_visibility = [0,1,2]if model_mode_choices is not None: model_modes_visibility= model_mode_choices.get("image_modes", model_modes_visibility)-- with gr.Column(visible= image_mode_value == 0 and len(image_prompt_types_allowed)> 0 or model_mode_choices is not None and image_mode_value in model_modes_visibility ) as image_prompt_column:+ if image_mode_value != 0:+ image_prompt_types_allowed = del_in_sequence(image_prompt_types_allowed, "EVL")+ with gr.Column(visible= image_prompt_types_allowed not in ("", "T") or model_mode_choices is not None and image_mode_value in model_modes_visibility ) as image_prompt_column:# Video Continue / Start Frame / End Frameimage_prompt_type_value= ui_defaults.get("image_prompt_type","")image_prompt_type = gr.Text(value= image_prompt_type_value, visible= False)@@ -8531,16 +8536,18 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nonwizard_variables_var = gr.Text(wizard_variables, visible = False)with gr.Row(visible= server_config.get("enhancer_enabled", 0) > 0 ) as prompt_enhancer_row:on_demand_prompt_enhancer = server_config.get("enhancer_mode", 0) == 1+ prompt_enhancer_choices_allowed = model_def.get("prompt_enhancer_choices_allowed", ["T"] if audio_only else ["T", "I", "TI"])prompt_enhancer_value = ui_defaults.get("prompt_enhancer", "")- if len(prompt_enhancer_value) == 0 and on_demand_prompt_enhancer: prompt_enhancer_value = "T"prompt_enhancer_btn = gr.Button( value ="Enhance Prompt", visible= on_demand_prompt_enhancer, size="lg", elem_classes="btn_centered")- prompt_enhancer_choices= ([] if on_demand_prompt_enhancer else [("Disabled", "")]) + [("Based on Text Prompt Content", "T")]- if not audio_only:- prompt_enhancer_choices += [- ("Based on Images Prompts Content (such as Start Image and Reference Images)", "I"),- ("Based on both Text Prompt and Images Prompts Content", "TI"),- ]-+ prompt_enhancer_choices= ([] if on_demand_prompt_enhancer else [("Disabled", "")])+ if "T" in prompt_enhancer_choices_allowed:+ prompt_enhancer_choices += [("Based on Text Prompt Content", "T")]+ if "I" in prompt_enhancer_choices_allowed:+ prompt_enhancer_choices += [("Based on Images Prompts Content (such as Start Image and Reference Images)", "I")]+ if "TI" in prompt_enhancer_choices_allowed:+ prompt_enhancer_choices += [("Based on both Text Prompt and Images Prompts Content", "TI")]++ if len(prompt_enhancer_value) == 0 and on_demand_prompt_enhancer: prompt_enhancer_value = prompt_enhancer_choices[0][1]prompt_enhancer = gr.Dropdown(choices=prompt_enhancer_choices,value=prompt_enhancer_value,@@ -8639,14 +8646,15 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Nontemperature = gr.Slider( 0.1, 1.5, value=ui_defaults.get("temperature", 0.8), step=0.01, label="Temperature")sample_solver_choices = model_def.get("sample_solvers", None)- with gr.Row(visible = sample_solver_choices is not None or not (image_outputs or audio_only)) as sample_solver_row:+ any_flow_shift = model_def.get("flow_shift", False)+ with gr.Row(visible = sample_solver_choices is not None or any_flow_shift ) as sample_solver_row:if sample_solver_choices is None:sample_solver = gr.Dropdown( value="", choices=[ ("", ""), ], visible= False, label= "Sampler Solver / Scheduler" )else:sample_solver = gr.Dropdown( value=ui_defaults.get("sample_solver", sample_solver_choices[0][1]),choices= sample_solver_choices, visible= True, label= "Sampler Solver / Scheduler")- flow_shift = gr.Slider(1.0, 25.0, value=ui_defaults.get("flow_shift",3), step=0.1, label="Shift Scale", visible = not (image_outputs or audio_only))+ flow_shift = gr.Slider(1.0, 25.0, value=ui_defaults.get("flow_shift",3), step=0.1, label="Shift Scale", visible = any_flow_shift)control_net_weight_alt_name = model_def.get("control_net_weight_alt_name", "")with gr.Row(visible = vace or len(control_net_weight_alt_name) >0 ) as control_net_weights_row:control_net_weight = gr.Slider(0.0, 2.0, value=ui_defaults.get("control_net_weight",1), step=0.1, label="Vace Weight #1", visible=vace)