Wan2GP / SageFix2.py
luxxandfuxx's picture
Upload 2 files
a09c99c verified
Raw History Blame Contribute Delete
5.34 kB
from pathlib import Path
import shutil
import re
path = Path("models/minimax_h3/pipeline.py")
backup = Path("models/minimax_h3/pipeline.py.sagefix_backup")
PATCH_MARKER = "# SAGEFIX: Qwen3-VL must use SDPA"
if not path.exists():
raise FileNotFoundError(
f"Couldn't find:\n {path.resolve()}\n\n"
"Run this script from the Wan2GP root directory."
)
text = path.read_text(encoding="utf-8")
# ------------------------------------------------------------
# Already patched?
# ------------------------------------------------------------
if PATCH_MARKER in text:
print("βœ… MiniMax H3 Sage/Qwen fix is already installed.")
raise SystemExit(0)
# ------------------------------------------------------------
# Locate _encode_prompt() structurally
# ------------------------------------------------------------
start = text.find(" def _encode_prompt(self, prompt, presentation):")
if start == -1:
raise RuntimeError(
"❌ Could not locate _encode_prompt() in pipeline.py.\n"
"Nothing was modified."
)
# Find the next method in the class
end_match = re.search(r"\n def \w+\(", text[start + 5:])
if end_match:
end = start + 5 + end_match.start()
else:
end = len(text)
old_function = text[start:end]
print("Found current _encode_prompt():")
print("------------------------------------------------------------")
print(old_function)
print("------------------------------------------------------------")
# ------------------------------------------------------------
# Sanity checks
# ------------------------------------------------------------
required_bits = [
"if self.fixed_prompt is not None:",
"def encode_fn(prompts):",
"self.text_encoder.encode(",
"self.text_encoder_cache.encode(",
]
missing = [x for x in required_bits if x not in old_function]
if missing:
print("❌ The function structure has changed unexpectedly.")
print("Missing expected pieces:")
for item in missing:
print(f" - {item}")
raise RuntimeError(
"SageFix aborted safely. Nothing was modified."
)
# ------------------------------------------------------------
# Build replacement function
# ------------------------------------------------------------
new_function = ''' def _encode_prompt(self, prompt, presentation):
if self.fixed_prompt is not None:
return self.fixed_prompt.prompt_embeds.to(device=self.device, dtype=self.dtype), self.fixed_prompt.text_token_tags
# SAGEFIX: Qwen3-VL must use SDPA
#
# Qwen3-VL's variable-length attention can use head dimensions
# unsupported by SageAttention v1. Temporarily switch to SDPA
# during prompt/reference encoding, then restore the selected
# backend for MiniMax H3 denoising.
previous_attention = offload.shared_state.get("_attention", "sdpa")
offload.shared_state["_attention"] = "sdpa"
try:
def encode_fn(prompts):
return [self.text_encoder.encode(prompts[0], presentation, self.device, self.dtype)]
cache_key = self._prompt_cache_key(prompt, presentation)
return self.text_encoder_cache.encode(
encode_fn,
prompt,
device=self.device,
cache_keys=cache_key
)[0]
finally:
offload.shared_state["_attention"] = previous_attention
'''
# ------------------------------------------------------------
# Backup CURRENT unpatched version
# ------------------------------------------------------------
shutil.copy2(path, backup)
print(f"βœ… Backup created/refreshed:\n {backup}")
# ------------------------------------------------------------
# Apply replacement
# ------------------------------------------------------------
patched_text = text[:start] + new_function + text[end:]
path.write_text(patched_text, encoding="utf-8")
print("βœ… Sage/Qwen compatibility patch applied.")
# ------------------------------------------------------------
# Syntax verification
# ------------------------------------------------------------
try:
compile(
path.read_text(encoding="utf-8"),
str(path),
"exec"
)
except Exception:
print("❌ Syntax check failed. Restoring backup...")
shutil.copy2(backup, path)
print("βœ… Original pipeline.py restored.")
raise
print("βœ… Python syntax check passed.")
# ------------------------------------------------------------
# Show result
# ------------------------------------------------------------
patched = path.read_text(encoding="utf-8")
start2 = patched.find(" def _encode_prompt(self, prompt, presentation):")
end_match2 = re.search(r"\n def \w+\(", patched[start2 + 5:])
if end_match2:
end2 = start2 + 5 + end_match2.start()
else:
end2 = len(patched)
print()
print("--------------- PATCHED FUNCTION ---------------")
print()
print(patched[start2:end2])
print()
print("------------------------------------------------")
print()
print("πŸš€ SageFix complete.")
print("Qwen3-VL encoding β†’ SDPA")
print("MiniMax H3 β†’ selected backend (e.g. Sage)")