multimodalart HF Staff commited on
Commit
5158fc3
·
verified ·
1 Parent(s): 9762ac2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +158 -229
app.py CHANGED
@@ -1,13 +1,14 @@
1
  import torch
2
  from diffusers import AutoencoderKLWan, WanPipeline, UniPCMultistepScheduler
3
  from diffusers.utils import export_to_video
4
- from diffusers.loaders.lora_conversion_utils import _convert_non_diffusers_lora_to_diffusers # Keep this if it's the base
5
  import gradio as gr
6
  import tempfile
7
  import os
8
  import spaces
9
  from huggingface_hub import hf_hub_download
10
  import logging # For better logging
 
11
 
12
  # --- Global Model Loading & LoRA Handling ---
13
  MODEL_ID = "Wan-AI/Wan2.1-T2V-14B-Diffusers"
@@ -18,245 +19,175 @@ LORA_FILENAME = "Wan21_CausVid_14B_T2V_lora_rank32.safetensors"
18
  logging.basicConfig(level=logging.INFO)
19
  logger = logging.getLogger(__name__)
20
 
21
- # This dictionary will store the manual patches extracted by the converter
22
- MANUAL_PATCHES_STORE = {}
23
 
24
  def _custom_convert_non_diffusers_wan_lora_to_diffusers(state_dict):
25
  global MANUAL_PATCHES_STORE
26
- MANUAL_PATCHES_STORE = {} # Clear previous patches
27
- peft_state_dict = {}
28
  unhandled_keys = []
29
 
30
- original_keys = list(state_dict.keys())
31
 
32
- processed_state_dict = {}
 
 
 
 
 
 
33
  for k, v in state_dict.items():
 
34
  if k.startswith("diffusion_model."):
35
- processed_state_dict[k[len("diffusion_model."):]] = v
36
  elif k.startswith("difusion_model."): # Handle potential typo
37
- processed_state_dict[k[len("difusion_model."):]] = v
 
38
  else:
39
- unhandled_keys.append(k) # Will be logged later if not handled by diff/diff_b
40
-
41
- block_indices = set()
42
- for k_proc in processed_state_dict:
43
- if k_proc.startswith("blocks."):
44
- try:
45
- block_idx_str = k_proc.split("blocks.")[1].split(".")[0]
46
- if block_idx_str.isdigit():
47
- block_indices.add(int(block_idx_str))
48
- except IndexError:
49
- pass # Will be handled as a non-block key or logged
50
- num_blocks = 0
51
- if block_indices:
52
- num_blocks = max(block_indices) + 1
53
-
54
- is_i2v_lora = any("k_img" in k for k in processed_state_dict) and \
55
- any("v_img" in k for k in processed_state_dict)
56
-
57
- handled_original_keys = set()
58
-
59
- # --- Handle Block-level LoRAs & Diffs ---
60
- for i in range(num_blocks):
61
- # Self-attention (maps to attn1 in WanTransformerBlock)
62
- for o_lora, c_diffusers in zip(["q", "k", "v", "o"], ["to_q", "to_k", "to_v", "to_out.0"]):
63
- lora_down_key_proc = f"blocks.{i}.self_attn.{o_lora}.lora_down.weight"
64
- lora_up_key_proc = f"blocks.{i}.self_attn.{o_lora}.lora_up.weight"
65
- diff_b_key_proc = f"blocks.{i}.self_attn.{o_lora}.diff_b"
66
- diff_w_key_proc = f"blocks.{i}.self_attn.{o_lora}.diff" # Assuming .diff for weight
67
-
68
- if lora_down_key_proc in processed_state_dict and lora_up_key_proc in processed_state_dict:
69
- peft_state_dict[f"transformer.blocks.{i}.attn1.{c_diffusers}.lora_A.weight"] = processed_state_dict[lora_down_key_proc]
70
- peft_state_dict[f"transformer.blocks.{i}.attn1.{c_diffusers}.lora_B.weight"] = processed_state_dict[lora_up_key_proc]
71
- handled_original_keys.add(f"diffusion_model.{lora_down_key_proc}")
72
- handled_original_keys.add(f"diffusion_model.{lora_up_key_proc}")
73
- if diff_b_key_proc in processed_state_dict:
74
- target_bias_key = f"transformer.blocks.{i}.attn1.{c_diffusers}.bias"
75
- MANUAL_PATCHES_STORE[target_bias_key] = ("diff_b", processed_state_dict[diff_b_key_proc])
76
- handled_original_keys.add(f"diffusion_model.{diff_b_key_proc}")
77
- if diff_w_key_proc in processed_state_dict:
78
- target_weight_key = f"transformer.blocks.{i}.attn1.{c_diffusers}.weight"
79
- MANUAL_PATCHES_STORE[target_weight_key] = ("diff", processed_state_dict[diff_w_key_proc])
80
- handled_original_keys.add(f"diffusion_model.{diff_w_key_proc}")
81
-
82
- # Cross-attention (maps to attn2 in WanTransformerBlock)
83
- for o_lora, c_diffusers in zip(["q", "k", "v", "o"], ["to_q", "to_k", "to_v", "to_out.0"]):
84
- lora_down_key_proc = f"blocks.{i}.cross_attn.{o_lora}.lora_down.weight"
85
- lora_up_key_proc = f"blocks.{i}.cross_attn.{o_lora}.lora_up.weight"
86
- diff_b_key_proc = f"blocks.{i}.cross_attn.{o_lora}.diff_b"
87
- diff_w_key_proc = f"blocks.{i}.cross_attn.{o_lora}.diff"
88
- norm_q_diff_key_proc = f"blocks.{i}.cross_attn.norm_q.diff" # specific norm diff
89
- norm_k_diff_key_proc = f"blocks.{i}.cross_attn.norm_k.diff" # specific norm diff
90
-
91
- if lora_down_key_proc in processed_state_dict and lora_up_key_proc in processed_state_dict:
92
- peft_state_dict[f"transformer.blocks.{i}.attn2.{c_diffusers}.lora_A.weight"] = processed_state_dict[lora_down_key_proc]
93
- peft_state_dict[f"transformer.blocks.{i}.attn2.{c_diffusers}.lora_B.weight"] = processed_state_dict[lora_up_key_proc]
94
- handled_original_keys.add(f"diffusion_model.{lora_down_key_proc}")
95
- handled_original_keys.add(f"diffusion_model.{lora_up_key_proc}")
96
- if diff_b_key_proc in processed_state_dict:
97
- target_bias_key = f"transformer.blocks.{i}.attn2.{c_diffusers}.bias"
98
- MANUAL_PATCHES_STORE[target_bias_key] = ("diff_b", processed_state_dict[diff_b_key_proc])
99
- handled_original_keys.add(f"diffusion_model.{diff_b_key_proc}")
100
- if diff_w_key_proc in processed_state_dict:
101
- target_weight_key = f"transformer.blocks.{i}.attn2.{c_diffusers}.weight"
102
- MANUAL_PATCHES_STORE[target_weight_key] = ("diff", processed_state_dict[diff_w_key_proc])
103
- handled_original_keys.add(f"diffusion_model.{diff_w_key_proc}")
104
-
105
- if norm_q_diff_key_proc in processed_state_dict: # Assuming norm_q on q_proj
106
- MANUAL_PATCHES_STORE[f"transformer.blocks.{i}.attn2.norm_q.weight"] = ("diff", processed_state_dict[norm_q_diff_key_proc])
107
- handled_original_keys.add(f"diffusion_model.{norm_q_diff_key_proc}")
108
- if norm_k_diff_key_proc in processed_state_dict: # Assuming norm_k on k_proj
109
- MANUAL_PATCHES_STORE[f"transformer.blocks.{i}.attn2.norm_k.weight"] = ("diff", processed_state_dict[norm_k_diff_key_proc])
110
- handled_original_keys.add(f"diffusion_model.{norm_k_diff_key_proc}")
111
-
112
-
113
- if is_i2v_lora:
114
- for o_lora, c_diffusers in zip(["k_img", "v_img"], ["add_k_proj", "add_v_proj"]):
115
- lora_down_key_proc = f"blocks.{i}.cross_attn.{o_lora}.lora_down.weight"
116
- lora_up_key_proc = f"blocks.{i}.cross_attn.{o_lora}.lora_up.weight"
117
- diff_b_key_proc = f"blocks.{i}.cross_attn.{o_lora}.diff_b"
118
- diff_w_key_proc = f"blocks.{i}.cross_attn.{o_lora}.diff"
119
-
120
- if lora_down_key_proc in processed_state_dict and lora_up_key_proc in processed_state_dict:
121
- peft_state_dict[f"transformer.blocks.{i}.attn2.{c_diffusers}.lora_A.weight"] = processed_state_dict[lora_down_key_proc]
122
- peft_state_dict[f"transformer.blocks.{i}.attn2.{c_diffusers}.lora_B.weight"] = processed_state_dict[lora_up_key_proc]
123
- handled_original_keys.add(f"diffusion_model.{lora_down_key_proc}")
124
- handled_original_keys.add(f"diffusion_model.{lora_up_key_proc}")
125
- if diff_b_key_proc in processed_state_dict:
126
- target_bias_key = f"transformer.blocks.{i}.attn2.{c_diffusers}.bias"
127
- MANUAL_PATCHES_STORE[target_bias_key] = ("diff_b", processed_state_dict[diff_b_key_proc])
128
- handled_original_keys.add(f"diffusion_model.{diff_b_key_proc}")
129
- if diff_w_key_proc in processed_state_dict:
130
- target_weight_key = f"transformer.blocks.{i}.attn2.{c_diffusers}.weight"
131
- MANUAL_PATCHES_STORE[target_weight_key] = ("diff", processed_state_dict[diff_w_key_proc])
132
- handled_original_keys.add(f"diffusion_model.{diff_w_key_proc}")
133
-
134
- # FFN
135
- for o_lora_suffix, c_diffusers_path in zip([".0", ".2"], ["net.0.proj", "net.2"]):
136
- lora_down_key_proc = f"blocks.{i}.ffn{o_lora_suffix}.lora_down.weight"
137
- lora_up_key_proc = f"blocks.{i}.ffn{o_lora_suffix}.lora_up.weight"
138
- diff_b_key_proc = f"blocks.{i}.ffn{o_lora_suffix}.diff_b"
139
- diff_w_key_proc = f"blocks.{i}.ffn{o_lora_suffix}.diff" # Assuming .diff for weight
140
-
141
- if lora_down_key_proc in processed_state_dict and lora_up_key_proc in processed_state_dict:
142
- peft_state_dict[f"transformer.blocks.{i}.ffn.{c_diffusers_path}.lora_A.weight"] = processed_state_dict[lora_down_key_proc]
143
- peft_state_dict[f"transformer.blocks.{i}.ffn.{c_diffusers_path}.lora_B.weight"] = processed_state_dict[lora_up_key_proc]
144
- handled_original_keys.add(f"diffusion_model.{lora_down_key_proc}")
145
- handled_original_keys.add(f"diffusion_model.{lora_up_key_proc}")
146
- if diff_b_key_proc in processed_state_dict:
147
- target_bias_key = f"transformer.blocks.{i}.ffn.{c_diffusers_path}.bias"
148
- MANUAL_PATCHES_STORE[target_bias_key] = ("diff_b", processed_state_dict[diff_b_key_proc])
149
- handled_original_keys.add(f"diffusion_model.{diff_b_key_proc}")
150
- if diff_w_key_proc in processed_state_dict:
151
- target_weight_key = f"transformer.blocks.{i}.ffn.{c_diffusers_path}.weight"
152
- MANUAL_PATCHES_STORE[target_weight_key] = ("diff", processed_state_dict[diff_w_key_proc])
153
- handled_original_keys.add(f"diffusion_model.{diff_w_key_proc}")
154
-
155
- # Block norm3 diffs (assuming norm3 applies to the output of the FFN in the original Wan block structure)
156
- norm3_diff_key_proc = f"blocks.{i}.norm3.diff"
157
- norm3_diff_b_key_proc = f"blocks.{i}.norm3.diff_b"
158
- if norm3_diff_key_proc in processed_state_dict:
159
- MANUAL_PATCHES_STORE[f"transformer.blocks.{i}.norm3.weight"] = ("diff", processed_state_dict[norm3_diff_key_proc]) # Norms usually have .weight
160
- handled_original_keys.add(f"diffusion_model.{norm3_diff_key_proc}")
161
- if norm3_diff_b_key_proc in processed_state_dict:
162
- MANUAL_PATCHES_STORE[f"transformer.blocks.{i}.norm3.bias"] = ("diff_b", processed_state_dict[norm3_diff_b_key_proc]) # And .bias
163
- handled_original_keys.add(f"diffusion_model.{norm3_diff_b_key_proc}")
164
-
165
-
166
- # --- Handle Top-level LoRAs & Diffs ---
167
- top_level_mappings = [
168
- # (lora_base_path_proc, diffusers_base_path, lora_suffixes, diffusers_suffixes)
169
- ("text_embedding", "transformer.condition_embedder.text_embedder", ["0", "2"], ["linear_1", "linear_2"]),
170
- ("time_embedding", "transformer.condition_embedder.time_embedder", ["0", "2"], ["linear_1", "linear_2"]),
171
- ("time_projection", "transformer.condition_embedder.time_proj", ["1"], [""]), # Wan has .1, Diffusers has no suffix
172
- ("head", "transformer.proj_out", ["head"], [""]), # Wan has .head, Diffusers has no suffix
173
- ]
174
-
175
- for lora_base_proc, diffusers_base, lora_suffixes, diffusers_suffixes in top_level_mappings:
176
- for l_suffix, d_suffix in zip(lora_suffixes, diffusers_suffixes):
177
- actual_lora_path_proc = f"{lora_base_proc}.{l_suffix}" if l_suffix else lora_base_proc
178
- actual_diffusers_path = f"{diffusers_base}.{d_suffix}" if d_suffix else diffusers_base
179
-
180
- lora_down_key_proc = f"{actual_lora_path_proc}.lora_down.weight"
181
- lora_up_key_proc = f"{actual_lora_path_proc}.lora_up.weight"
182
- diff_b_key_proc = f"{actual_lora_path_proc}.diff_b"
183
- diff_w_key_proc = f"{actual_lora_path_proc}.diff"
184
-
185
- if lora_down_key_proc in processed_state_dict and lora_up_key_proc in processed_state_dict:
186
- peft_state_dict[f"{actual_diffusers_path}.lora_A.weight"] = processed_state_dict[lora_down_key_proc]
187
- peft_state_dict[f"{actual_diffusers_path}.lora_B.weight"] = processed_state_dict[lora_up_key_proc]
188
- handled_original_keys.add(f"diffusion_model.{lora_down_key_proc}")
189
- handled_original_keys.add(f"diffusion_model.{lora_up_key_proc}")
190
- if diff_b_key_proc in processed_state_dict:
191
- MANUAL_PATCHES_STORE[f"{actual_diffusers_path}.bias"] = ("diff_b", processed_state_dict[diff_b_key_proc])
192
- handled_original_keys.add(f"diffusion_model.{diff_b_key_proc}")
193
- if diff_w_key_proc in processed_state_dict:
194
- MANUAL_PATCHES_STORE[f"{actual_diffusers_path}.weight"] = ("diff", processed_state_dict[diff_w_key_proc])
195
- handled_original_keys.add(f"diffusion_model.{diff_w_key_proc}")
196
-
197
- # Patch Embedding
198
- patch_emb_diff_b_key = "patch_embedding.diff_b"
199
- if patch_emb_diff_b_key in processed_state_dict:
200
- MANUAL_PATCHES_STORE["transformer.patch_embedding.bias"] = ("diff_b", processed_state_dict[patch_emb_diff_b_key])
201
- handled_original_keys.add(f"diffusion_model.{patch_emb_diff_b_key}")
202
- # Assuming .diff might exist for patch_embedding.weight, though not explicitly in your example list
203
- patch_emb_diff_w_key = "patch_embedding.diff"
204
- if patch_emb_diff_w_key in processed_state_dict:
205
- MANUAL_PATCHES_STORE["transformer.patch_embedding.weight"] = ("diff", processed_state_dict[patch_emb_diff_w_key])
206
- handled_original_keys.add(f"diffusion_model.{patch_emb_diff_w_key}")
207
-
208
-
209
- # Log unhandled keys
210
- final_unhandled_keys = []
211
- for k_orig in original_keys:
212
- # Reconstruct the processed key to check if it was actually handled by diff/diff_b or lora A/B logic
213
- k_proc = None
214
- if k_orig.startswith("diffusion_model."):
215
- k_proc = k_orig[len("diffusion_model."):]
216
- elif k_orig.startswith("difusion_model."):
217
- k_proc = k_orig[len("difusion_model."):]
218
-
219
- if k_orig not in handled_original_keys and (k_proc is None or not any(k_proc.endswith(s) for s in [".lora_down.weight", ".lora_up.weight", ".diff", ".diff_b", ".alpha"])):
220
- final_unhandled_keys.append(k_orig)
221
-
222
- if final_unhandled_keys:
223
- logger.warning(
224
- f"The following keys from the Wan 2.1 LoRA checkpoint were not converted to PEFT LoRA A/B format "
225
- f"nor identified as manual diff patches: {final_unhandled_keys}."
226
- )
227
-
228
- if not peft_state_dict and not MANUAL_PATCHES_STORE:
229
- logger.warning("No valid LoRA A/B weights or manual diff patches found after conversion.")
230
-
231
- return peft_state_dict
232
-
233
- def apply_manual_diff_patches(pipe_model_component, patches_store, strength_model=1.0):
234
- if not patches_store:
235
- logger.info("No manual diff patches to apply.")
236
  return
237
 
238
- logger.info(f"Applying {len(patches_store)} manual diff patches...")
239
- for target_key, (patch_type, diff_tensor) in patches_store.items():
 
 
 
 
 
240
  try:
241
- module_path, param_name = target_key.rsplit('.', 1)
242
- module = pipe_model_component.get_submodule(module_path)
243
- original_param = getattr(module, param_name)
 
 
 
244
 
 
245
  if original_param.shape != diff_tensor.shape:
246
- logger.warning(f"Shape mismatch for {target_key}: model {original_param.shape}, LoRA {diff_tensor.shape}. Skipping patch.")
247
  continue
248
 
249
  with torch.no_grad():
250
- # Ensure diff_tensor is on the same device and dtype as the original parameter
251
- diff_tensor_casted = diff_tensor.to(device=original_param.device, dtype=original_param.dtype)
252
- scaled_diff = diff_tensor_casted * strength_model
253
- original_param.add_(scaled_diff)
254
- # logger.info(f"Applied {patch_type} to {target_key} with strength {strength_model}")
255
  except AttributeError:
256
- logger.warning(f"Could not find parameter {target_key} in the model component. Skipping patch.")
257
  except Exception as e:
258
- logger.error(f"Error applying patch to {target_key}: {e}")
259
- logger.info("Finished applying manual diff patches.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
 
261
  # --- Model Loading ---
262
  logger.info(f"Loading VAE for {MODEL_ID}...")
@@ -271,7 +202,7 @@ pipe = WanPipeline.from_pretrained(
271
  vae=vae,
272
  torch_dtype=torch.bfloat16 # bfloat16 for pipeline
273
  )
274
- flow_shift = 8.0 # 5.0 for 720P, 3.0 for 480P
275
  pipe.scheduler = UniPCMultistepScheduler.from_config(
276
  pipe.scheduler.config, flow_shift=flow_shift
277
  )
@@ -284,14 +215,13 @@ causvid_path = hf_hub_download(repo_id=LORA_REPO_ID, filename=LORA_FILENAME)
284
 
285
  logger.info("Loading LoRA weights with custom converter...")
286
 
287
- # lora_state_dict_raw = WanPipeline.lora_state_dict(causvid_path) # This might already do some conversion
288
-
289
- # Alternative: Load raw state_dict and then convert
290
  from safetensors.torch import load_file as load_safetensors
291
  raw_lora_state_dict = load_safetensors(causvid_path)
292
 
 
293
  peft_state_dict = _custom_convert_non_diffusers_wan_lora_to_diffusers(raw_lora_state_dict)
294
 
 
295
  if peft_state_dict:
296
  pipe.load_lora_weights(
297
  peft_state_dict,
@@ -301,8 +231,8 @@ if peft_state_dict:
301
  else:
302
  logger.warning("No PEFT-compatible LoRA weights found after conversion.")
303
 
304
- lora_strength = 1.0
305
- apply_manual_diff_patches(pipe.transformer, MANUAL_PATCHES_STORE, strength_model=lora_strength)
306
  logger.info("Manual diff_b/diff patches applied.")
307
 
308
 
@@ -334,7 +264,7 @@ def generate_video(prompt, negative_prompt, height, width, num_frames, guidance_
334
 
335
  with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
336
  video_path = tmpfile.name
337
-
338
  export_to_video(output_frames_list, video_path, fps=fps)
339
  logger.info(f"Video successfully generated and saved to {video_path}")
340
  return video_path
@@ -350,7 +280,6 @@ with gr.Blocks() as demo:
350
  Model is loaded into memory when the app starts. This might take a few minutes.
351
  Ensure you have a GPU with sufficient VRAM (e.g., ~24GB+ for these default settings).
352
  """)
353
- # ... (rest of your Gradio UI definition remains the same) ...
354
  with gr.Row():
355
  with gr.Column(scale=2):
356
  prompt_input = gr.Textbox(label="Prompt", value=default_prompt, lines=3)
@@ -363,7 +292,7 @@ with gr.Blocks() as demo:
363
  height_input = gr.Slider(minimum=256, maximum=768, step=64, value=480, label="Height (multiple of 8)")
364
  width_input = gr.Slider(minimum=256, maximum=1024, step=64, value=832, label="Width (multiple of 8)")
365
  with gr.Row():
366
- num_frames_input = gr.Slider(minimum=16, maximum=100, step=1, value=25, label="Number of Frames")
367
  fps_input = gr.Slider(minimum=5, maximum=30, step=1, value=15, label="Output FPS")
368
  steps = gr.Slider(minimum=1.0, maximum=30.0, value=4.0, label="Steps")
369
  guidance_scale_input = gr.Slider(minimum=1.0, maximum=20.0, step=0.5, value=1.0, label="Guidance Scale")
 
1
  import torch
2
  from diffusers import AutoencoderKLWan, WanPipeline, UniPCMultistepScheduler
3
  from diffusers.utils import export_to_video
4
+ from diffusers.loaders.lora_conversion_utils import _convert_non_diffusers_wan_lora_to_diffusers # Keep this if it's the base for standard LoRA parts
5
  import gradio as gr
6
  import tempfile
7
  import os
8
  import spaces
9
  from huggingface_hub import hf_hub_download
10
  import logging # For better logging
11
+ import re # For key manipulation
12
 
13
  # --- Global Model Loading & LoRA Handling ---
14
  MODEL_ID = "Wan-AI/Wan2.1-T2V-14B-Diffusers"
 
19
  logging.basicConfig(level=logging.INFO)
20
  logger = logging.getLogger(__name__)
21
 
22
+ MANUAL_PATCHES_STORE = {"diff": {}, "diff_b": {}}
 
23
 
24
  def _custom_convert_non_diffusers_wan_lora_to_diffusers(state_dict):
25
  global MANUAL_PATCHES_STORE
26
+ MANUAL_PATCHES_STORE = {"diff": {}, "diff_b": {}} # Reset for each conversion
27
+ peft_compatible_state_dict = {}
28
  unhandled_keys = []
29
 
30
+ original_keys_map_to_diffusers = {}
31
 
32
+ # Mapping based on ComfyUI's WanModel structure and PeftAdapterMixin logic
33
+ # This needs to map the original LoRA key naming to Diffusers' expected PEFT keys
34
+ # diffusion_model.blocks.0.self_attn.q.lora_down.weight -> transformer.blocks.0.attn1.to_q.lora_A.weight
35
+ # diffusion_model.blocks.0.ffn.0.lora_down.weight -> transformer.blocks.0.ffn.net.0.proj.lora_A.weight
36
+ # diffusion_model.text_embedding.0.lora_down.weight -> transformer.condition_embedder.text_embedder.linear_1.lora_A.weight (example)
37
+
38
+ # Strip "diffusion_model." and map
39
  for k, v in state_dict.items():
40
+ original_k = k # Keep for logging/debugging
41
  if k.startswith("diffusion_model."):
42
+ k_stripped = k[len("diffusion_model."):]
43
  elif k.startswith("difusion_model."): # Handle potential typo
44
+ k_stripped = k[len("difusion_model."):]
45
+ logger.warning(f"Key '{original_k}' starts with 'difusion_model.' (potential typo), processing as 'diffusion_model.'.")
46
  else:
47
+ unhandled_keys.append(original_k)
48
+ continue
49
+
50
+ # Handle .diff and .diff_b keys by storing them separately
51
+ if k_stripped.endswith(".diff"):
52
+ target_model_key = k_stripped[:-len(".diff")] + ".weight"
53
+ MANUAL_PATCHES_STORE["diff"][target_model_key] = v
54
+ continue
55
+ elif k_stripped.endswith(".diff_b"):
56
+ target_model_key = k_stripped[:-len(".diff_b")] + ".bias"
57
+ MANUAL_PATCHES_STORE["diff_b"][target_model_key] = v
58
+ continue
59
+
60
+ # Handle standard LoRA A/B matrices
61
+ if ".lora_down.weight" in k_stripped:
62
+ diffusers_key_base = k_stripped.replace(".lora_down.weight", "")
63
+ # Apply transformations similar to _convert_non_diffusers_wan_lora_to_diffusers from diffusers
64
+ # but adapt to the PEFT naming convention (lora_A/lora_B)
65
+ # This part needs careful mapping based on WanTransformer3DModel structure
66
+
67
+ # Example mappings (these need to be comprehensive for all layers)
68
+ if diffusers_key_base.startswith("blocks."):
69
+ parts = diffusers_key_base.split(".")
70
+ block_idx = parts[1]
71
+ attn_type = parts[2] # self_attn or cross_attn
72
+ proj_type = parts[3] # q, k, v, o
73
+
74
+ if attn_type == "self_attn":
75
+ diffusers_peft_key = f"transformer.blocks.{block_idx}.attn1.to_{proj_type}.lora_A.weight"
76
+ elif attn_type == "cross_attn":
77
+ # WanTransformer3DModel uses attn2 for cross-attention like features
78
+ diffusers_peft_key = f"transformer.blocks.{block_idx}.attn2.to_{proj_type}.lora_A.weight"
79
+ else: # ffn
80
+ ffn_idx = proj_type # "0" or "2"
81
+ diffusers_peft_key = f"transformer.blocks.{block_idx}.ffn.net.{ffn_idx}.proj.lora_A.weight"
82
+ elif diffusers_key_base.startswith("text_embedding."):
83
+ idx_map = {"0": "linear_1", "2": "linear_2"}
84
+ idx = diffusers_key_base.split(".")[1]
85
+ diffusers_peft_key = f"transformer.condition_embedder.text_embedder.{idx_map[idx]}.lora_A.weight"
86
+ elif diffusers_key_base.startswith("time_embedding."):
87
+ idx_map = {"0": "linear_1", "2": "linear_2"}
88
+ idx = diffusers_key_base.split(".")[1]
89
+ diffusers_peft_key = f"transformer.condition_embedder.time_embedder.{idx_map[idx]}.lora_A.weight"
90
+ elif diffusers_key_base.startswith("time_projection."): # Assuming '1' from your example
91
+ diffusers_peft_key = f"transformer.condition_embedder.time_proj.lora_A.weight"
92
+ elif diffusers_key_base.startswith("patch_embedding"):
93
+ # WanTransformer3DModel has 'patch_embedding' at the top level
94
+ diffusers_peft_key = f"transformer.patch_embedding.lora_A.weight" # This needs to match how PEFT would name it
95
+ elif diffusers_key_base.startswith("head.head"):
96
+ diffusers_peft_key = f"transformer.proj_out.lora_A.weight"
97
+ else:
98
+ unhandled_keys.append(original_k)
99
+ continue
100
+
101
+ peft_compatible_state_dict[diffusers_peft_key] = v
102
+ original_keys_map_to_diffusers[k_stripped] = diffusers_peft_key
103
+
104
+ elif ".lora_up.weight" in k_stripped:
105
+ # Find the corresponding lora_down key to determine the base name
106
+ down_key_stripped = k_stripped.replace(".lora_up.weight", ".lora_down.weight")
107
+ if down_key_stripped in original_keys_map_to_diffusers:
108
+ diffusers_peft_key_A = original_keys_map_to_diffusers[down_key_stripped]
109
+ diffusers_peft_key_B = diffusers_peft_key_A.replace(".lora_A.weight", ".lora_B.weight")
110
+ peft_compatible_state_dict[diffusers_peft_key_B] = v
111
+ else:
112
+ unhandled_keys.append(original_k)
113
+ elif not (k_stripped.endswith(".alpha") or k_stripped.endswith(".dora_scale")): # Alphas are handled by PEFT if lora_A/B present
114
+ unhandled_keys.append(original_k)
115
+
116
+
117
+ if unhandled_keys:
118
+ logger.warning(f"Custom Wan LoRA Converter: Unhandled keys: {unhandled_keys}")
119
+
120
+ return peft_compatible_state_dict
121
+
122
+
123
+ def apply_manual_diff_patches(pipe_model, patches_store, lora_strength=1.0):
124
+ if not hasattr(pipe_model, "transformer"):
125
+ logger.error("Pipeline model does not have a 'transformer' attribute to patch.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  return
127
 
128
+ transformer = pipe_model.transformer
129
+ changed_params_count = 0
130
+
131
+ for key_base, diff_tensor in patches_store.get("diff", {}).items():
132
+ # key_base is like "blocks.0.self_attn.q.weight"
133
+ # We need to prepend "transformer." to match diffusers internal naming
134
+ target_key_full = f"transformer.{key_base}"
135
  try:
136
+ module_path_parts = target_key_full.split('.')
137
+ param_name = module_path_parts[-1]
138
+ module_path = ".".join(module_path_parts[:-1])
139
+ module = transformer
140
+ for part in module_path.split('.')[1:]: # Skip the first 'transformer'
141
+ module = getattr(module, part)
142
 
143
+ original_param = getattr(module, param_name)
144
  if original_param.shape != diff_tensor.shape:
145
+ logger.warning(f"Shape mismatch for diff patch on {target_key_full}: model {original_param.shape}, lora {diff_tensor.shape}. Skipping.")
146
  continue
147
 
148
  with torch.no_grad():
149
+ scaled_diff = (lora_strength * diff_tensor.to(original_param.device, original_param.dtype))
150
+ original_param.data.add_(scaled_diff)
151
+ changed_params_count +=1
 
 
152
  except AttributeError:
153
+ logger.warning(f"Could not find parameter {target_key_full} in transformer to apply diff patch.")
154
  except Exception as e:
155
+ logger.error(f"Error applying diff patch to {target_key_full}: {e}")
156
+
157
+
158
+ for key_base, diff_b_tensor in patches_store.get("diff_b", {}).items():
159
+ # key_base is like "blocks.0.self_attn.q.bias"
160
+ target_key_full = f"transformer.{key_base}"
161
+ try:
162
+ module_path_parts = target_key_full.split('.')
163
+ param_name = module_path_parts[-1]
164
+ module_path = ".".join(module_path_parts[:-1])
165
+ module = transformer
166
+ for part in module_path.split('.')[1:]:
167
+ module = getattr(module, part)
168
+
169
+ original_param = getattr(module, param_name)
170
+ if original_param is None:
171
+ logger.warning(f"Bias parameter {target_key_full} is None in model. Skipping diff_b patch.")
172
+ continue
173
+
174
+ if original_param.shape != diff_b_tensor.shape:
175
+ logger.warning(f"Shape mismatch for diff_b patch on {target_key_full}: model {original_param.shape}, lora {diff_b_tensor.shape}. Skipping.")
176
+ continue
177
+
178
+ with torch.no_grad():
179
+ scaled_diff_b = (lora_strength * diff_b_tensor.to(original_param.device, original_param.dtype))
180
+ original_param.data.add_(scaled_diff_b)
181
+ changed_params_count +=1
182
+ except AttributeError:
183
+ logger.warning(f"Could not find parameter {target_key_full} in transformer to apply diff_b patch.")
184
+ except Exception as e:
185
+ logger.error(f"Error applying diff_b patch to {target_key_full}: {e}")
186
+ if changed_params_count > 0:
187
+ logger.info(f"Applied {changed_params_count} manual diff/diff_b patches.")
188
+ else:
189
+ logger.info("No manual diff/diff_b patches were applied.")
190
+
191
 
192
  # --- Model Loading ---
193
  logger.info(f"Loading VAE for {MODEL_ID}...")
 
202
  vae=vae,
203
  torch_dtype=torch.bfloat16 # bfloat16 for pipeline
204
  )
205
+ flow_shift = 8.0
206
  pipe.scheduler = UniPCMultistepScheduler.from_config(
207
  pipe.scheduler.config, flow_shift=flow_shift
208
  )
 
215
 
216
  logger.info("Loading LoRA weights with custom converter...")
217
 
 
 
 
218
  from safetensors.torch import load_file as load_safetensors
219
  raw_lora_state_dict = load_safetensors(causvid_path)
220
 
221
+ # Now call our custom converter which will populate MANUAL_PATCHES_STORE
222
  peft_state_dict = _custom_convert_non_diffusers_wan_lora_to_diffusers(raw_lora_state_dict)
223
 
224
+ # Load the LoRA A/B matrices using PEFT
225
  if peft_state_dict:
226
  pipe.load_lora_weights(
227
  peft_state_dict,
 
231
  else:
232
  logger.warning("No PEFT-compatible LoRA weights found after conversion.")
233
 
234
+ # Apply manual diff_b and diff patches
235
+ apply_manual_diff_patches(pipe, MANUAL_PATCHES_STORE, lora_strength=1.0) # Assuming default strength 1.0
236
  logger.info("Manual diff_b/diff patches applied.")
237
 
238
 
 
264
 
265
  with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
266
  video_path = tmpfile.name
267
+
268
  export_to_video(output_frames_list, video_path, fps=fps)
269
  logger.info(f"Video successfully generated and saved to {video_path}")
270
  return video_path
 
280
  Model is loaded into memory when the app starts. This might take a few minutes.
281
  Ensure you have a GPU with sufficient VRAM (e.g., ~24GB+ for these default settings).
282
  """)
 
283
  with gr.Row():
284
  with gr.Column(scale=2):
285
  prompt_input = gr.Textbox(label="Prompt", value=default_prompt, lines=3)
 
292
  height_input = gr.Slider(minimum=256, maximum=768, step=64, value=480, label="Height (multiple of 8)")
293
  width_input = gr.Slider(minimum=256, maximum=1024, step=64, value=832, label="Width (multiple of 8)")
294
  with gr.Row():
295
+ num_frames_input = gr.Slider(minimum=16, maximum=100, step=1, value=25, label="Number of Frames")
296
  fps_input = gr.Slider(minimum=5, maximum=30, step=1, value=15, label="Output FPS")
297
  steps = gr.Slider(minimum=1.0, maximum=30.0, value=4.0, label="Steps")
298
  guidance_scale_input = gr.Slider(minimum=1.0, maximum=20.0, step=0.5, value=1.0, label="Guidance Scale")