File size: 5,208 Bytes
a05265f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | #!/usr/bin/env python3
"""Apply or revert the FLUX.3 Klein MXFP8 contiguous-input fix to ComfyUI.
Standard-library only. Does not edit model checkpoints or install packages.
"""
import argparse
import ast
import os
from pathlib import Path
import sys
import tempfile
OLD = "ck.quantize_mxfp8(tensor, pad_32x=needs_padding)"
NEW = "ck.quantize_mxfp8(tensor.contiguous(), pad_32x=needs_padding)"
def locate_comfyui(value: str) -> Path:
value = value.strip().strip('"').strip("'")
if not value:
raise ValueError("No ComfyUI folder provided.")
folder = Path(value).expanduser().resolve()
if folder.is_file() and folder.name.lower() == "quant_ops.py":
target = folder
elif (folder / "comfy" / "quant_ops.py").is_file():
target = folder / "comfy" / "quant_ops.py"
else:
raise FileNotFoundError(
f"Cannot find 'comfy/quant_ops.py' under: {folder}\n"
"Enter the ComfyUI source folder (not the models folder)."
)
return target
def atomic_write(path: Path, raw: bytes) -> None:
"""Write to sibling temp file; replace the destination only after success."""
name = None
try:
with tempfile.NamedTemporaryFile(
mode="wb", prefix=path.name + ".tmp.", dir=path.parent,
delete=False
) as output:
name = output.name
output.write(raw)
output.flush()
os.fsync(output.fileno())
os.replace(name, path)
finally:
if name and os.path.exists(name):
os.unlink(name)
def run(target: Path, *, check: bool = False, restore: bool = False) -> int:
backup = target.with_name(target.name + ".mxfp8_backup")
raw = target.read_bytes()
# ComfyUI source should be valid UTF-8; keeping the original newline style.
source = raw.decode("utf-8")
old_count = source.count(OLD)
new_count = source.count(NEW)
print(f"ComfyUI file: {target}")
print(f"Backup file: {backup}")
if check:
if old_count == 1 and new_count == 0:
print("STATUS: Unpatched, expected kernel call found.")
return 0
if old_count == 0 and new_count == 1:
print("STATUS: Patch already applied.")
return 0
print("STATUS: Unsupported or ambiguous source layout; no changes made.")
return 1
if restore:
if not backup.is_file():
print("ERROR: No backup found; refusing to guess original contents.")
return 1
original = backup.read_bytes()
original_source = original.decode("utf-8")
if original_source.count(OLD) != 1 or original_source.count(NEW):
print("ERROR: Backup does not contain the expected unpatched code.")
return 1
if old_count != 0 or new_count != 1:
print("ERROR: Current file is not in the expected patched state.")
return 1
if source.replace(NEW, OLD) != original_source:
print("ERROR: File changed since patching; refusing to erase other edits.")
return 1
atomic_write(target, original)
print("RESTORED original quant_ops.py; restart ComfyUI.")
return 0
if old_count == 0 and new_count == 1:
print("ALREADY PATCHED. No changes needed.")
return 0
if old_count != 1 or new_count:
print("ERROR: Cannot safely identify the MXFP8 call; no changes made.")
print(f"Original call occurrences: {old_count}; patched: {new_count}.")
return 1
patched = source.replace(OLD, NEW, 1)
# Ensure we have not introduced a syntax error.
ast.parse(patched, filename=str(target))
if backup.exists():
if backup.read_bytes() != raw:
print("ERROR: An older backup already exists with different content.")
print("Refusing to replace it or patch a different ComfyUI revision.")
return 1
else:
with backup.open("xb") as output:
output.write(raw)
output.flush()
os.fsync(output.fileno())
atomic_write(target, patched.encode("utf-8"))
print("PATCH APPLIED: MXFP8 activation input is now contiguous.")
print("No weights or model files were changed. Restart ComfyUI.")
return 0
def main() -> int:
parser = argparse.ArgumentParser(
description="Patch ComfyUI MXFP8 activation contiguity, with backup and rollback."
)
parser.add_argument(
"--comfyui", help="ComfyUI root folder (prompts for it if omitted)"
)
operation = parser.add_mutually_exclusive_group()
operation.add_argument("--check", action="store_true", help="Read-only status check")
operation.add_argument("--restore", action="store_true", help="Restore original backup")
args = parser.parse_args()
try:
location = args.comfyui or input("Enter your ComfyUI folder path: ")
target = locate_comfyui(location)
return run(target, check=args.check, restore=args.restore)
except (OSError, UnicodeError, SyntaxError, ValueError, EOFError) as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())
|