Spaces:
Sleeping
Sleeping
Upload 9 files
Browse files- README.md +18 -7
- install_w4a8.py +59 -0
- main.py +195 -0
- requirements.txt +7 -6
- w4a8/__init__.py +25 -0
- w4a8/comfy_load_test.py +108 -0
- w4a8/comfy_quant_w4a8.py +42 -0
- w4a8/w4a8_conversion.py +422 -0
- w4a8/w4a8_converter.py +254 -0
README.md
CHANGED
|
@@ -1,12 +1,23 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
app_file:
|
| 9 |
pinned: false
|
| 10 |
---
|
| 11 |
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Quant Converter W4A8 INT8 ConvRot
|
| 3 |
+
emoji: 🔧
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: purple
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 4.44.0
|
| 8 |
+
app_file: main.py
|
| 9 |
pinned: false
|
| 10 |
---
|
| 11 |
|
| 12 |
+
CPU-safe safetensors quantizer. Exposes the original convert_to_quant int8 and convrot w4a4 paths plus a W4A8 (asym_w4a8_int8) add-on that installs itself into the pip-installed convert_to_quant package on container start.
|
| 13 |
+
|
| 14 |
+
Settings:
|
| 15 |
+
- COMFY_ALLOW_VENDORED=1 enables the vendored comfy.quant_ops shipped inside convert_to_quant, which is what you want on CPU-only Spaces.
|
| 16 |
+
- COMFYUI_ROOT can override the comfy location if you also clone full ComfyUI.
|
| 17 |
+
|
| 18 |
+
Supported conversion types:
|
| 19 |
+
- w4a8
|
| 20 |
+
- int8
|
| 21 |
+
- convrot_w4a4
|
| 22 |
+
|
| 23 |
+
Output is a safetensors file ready to drop into ComfyUI's models directory.
|
install_w4a8.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib
|
| 2 |
+
import os
|
| 3 |
+
import shutil
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
ADDON_NAME = "w4a8"
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _find_source():
|
| 10 |
+
here = os.path.dirname(os.path.abspath(__file__))
|
| 11 |
+
candidates = [
|
| 12 |
+
os.path.join(here, ADDON_NAME),
|
| 13 |
+
os.path.join(here, "convert_to_quant", ADDON_NAME),
|
| 14 |
+
]
|
| 15 |
+
for c in candidates:
|
| 16 |
+
if os.path.isdir(c) and os.path.isfile(os.path.join(c, "__init__.py")):
|
| 17 |
+
return c
|
| 18 |
+
return None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _find_target():
|
| 22 |
+
try:
|
| 23 |
+
import convert_to_quant
|
| 24 |
+
except ImportError:
|
| 25 |
+
return None
|
| 26 |
+
pkg_dir = os.path.dirname(os.path.abspath(convert_to_quant.__file__))
|
| 27 |
+
return os.path.join(pkg_dir, ADDON_NAME)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def install(verbose=True):
|
| 31 |
+
src = _find_source()
|
| 32 |
+
if src is None:
|
| 33 |
+
if verbose:
|
| 34 |
+
print("[w4a8-install] source folder not found")
|
| 35 |
+
return False
|
| 36 |
+
dst = _find_target()
|
| 37 |
+
if dst is None:
|
| 38 |
+
if verbose:
|
| 39 |
+
print("[w4a8-install] convert_to_quant is not importable")
|
| 40 |
+
return False
|
| 41 |
+
try:
|
| 42 |
+
if os.path.exists(dst):
|
| 43 |
+
shutil.rmtree(dst)
|
| 44 |
+
shutil.copytree(src, dst)
|
| 45 |
+
except Exception as e:
|
| 46 |
+
if verbose:
|
| 47 |
+
print(f"[w4a8-install] copy failed: {e}")
|
| 48 |
+
return False
|
| 49 |
+
importlib.invalidate_caches()
|
| 50 |
+
for name in list(sys.modules):
|
| 51 |
+
if name == "convert_to_quant.w4a8" or name.startswith("convert_to_quant.w4a8."):
|
| 52 |
+
del sys.modules[name]
|
| 53 |
+
if verbose:
|
| 54 |
+
print(f"[w4a8-install] installed {src} -> {dst}")
|
| 55 |
+
return True
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
if __name__ == "__main__":
|
| 59 |
+
sys.exit(0 if install() else 1)
|
main.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import json
|
| 4 |
+
import tempfile
|
| 5 |
+
import traceback
|
| 6 |
+
import shutil
|
| 7 |
+
|
| 8 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 9 |
+
if HERE not in sys.path:
|
| 10 |
+
sys.path.insert(0, HERE)
|
| 11 |
+
|
| 12 |
+
if "COMFY_ALLOW_VENDORED" not in os.environ:
|
| 13 |
+
os.environ["COMFY_ALLOW_VENDORED"] = "1"
|
| 14 |
+
|
| 15 |
+
os.environ.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "0")
|
| 16 |
+
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
from install_w4a8 import install as _install_w4a8
|
| 20 |
+
_install_w4a8(verbose=True)
|
| 21 |
+
except Exception as _e:
|
| 22 |
+
print("[main] w4a8 install step failed:", _e)
|
| 23 |
+
|
| 24 |
+
import gradio as gr
|
| 25 |
+
import torch
|
| 26 |
+
|
| 27 |
+
CONVERTERS = {}
|
| 28 |
+
WARNINGS = []
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _try_register(name, module_path, func_name):
|
| 32 |
+
try:
|
| 33 |
+
mod = __import__(module_path, fromlist=[func_name])
|
| 34 |
+
except Exception as e:
|
| 35 |
+
WARNINGS.append(f"{name}: import failed ({type(e).__name__}: {e})")
|
| 36 |
+
return
|
| 37 |
+
fn = getattr(mod, func_name, None)
|
| 38 |
+
if fn is None:
|
| 39 |
+
WARNINGS.append(f"{name}: {module_path}.{func_name} missing")
|
| 40 |
+
return
|
| 41 |
+
CONVERTERS[name] = (module_path, func_name, fn)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _discover():
|
| 45 |
+
try:
|
| 46 |
+
from convert_to_quant.w4a8 import convert_to_w4a8, w4a8_available
|
| 47 |
+
if w4a8_available():
|
| 48 |
+
CONVERTERS["w4a8"] = ("convert_to_quant.w4a8", "convert_to_w4a8", convert_to_w4a8)
|
| 49 |
+
else:
|
| 50 |
+
from convert_to_quant.w4a8 import w4a8_last_error
|
| 51 |
+
WARNINGS.append(f"w4a8: unavailable ({w4a8_last_error()})")
|
| 52 |
+
except Exception as e:
|
| 53 |
+
WARNINGS.append(f"w4a8: import failed ({type(e).__name__}: {e})")
|
| 54 |
+
|
| 55 |
+
_try_register("int8", "convert_to_quant.convert_int8", "convert_to_int8")
|
| 56 |
+
_try_register("int8", "convert_to_quant.convert_to_int8", "convert_to_int8")
|
| 57 |
+
|
| 58 |
+
for cand_mod in (
|
| 59 |
+
"convert_to_quant.convert_convrot_w4a4",
|
| 60 |
+
"convert_to_quant.convert_w4a4",
|
| 61 |
+
"convert_to_quant.convert_convrot",
|
| 62 |
+
):
|
| 63 |
+
_try_register("convrot_w4a4", cand_mod, "convert_to_w4a4")
|
| 64 |
+
if "convrot_w4a4" in CONVERTERS:
|
| 65 |
+
break
|
| 66 |
+
|
| 67 |
+
_try_register("fp8", "convert_to_quant.convert_fp8", "convert_to_fp8")
|
| 68 |
+
_try_register("fp8", "convert_to_quant.convert_to_fp8", "convert_to_fp8")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
_discover()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _resolve_input_file(uploaded_file, hf_repo, hf_filename, hf_token):
|
| 75 |
+
if uploaded_file:
|
| 76 |
+
return uploaded_file, None
|
| 77 |
+
if hf_repo and hf_filename:
|
| 78 |
+
from huggingface_hub import hf_hub_download
|
| 79 |
+
path = hf_hub_download(
|
| 80 |
+
repo_id=hf_repo,
|
| 81 |
+
filename=hf_filename,
|
| 82 |
+
token=hf_token or None,
|
| 83 |
+
resume_download=True,
|
| 84 |
+
)
|
| 85 |
+
return path, None
|
| 86 |
+
raise ValueError("Provide either an uploaded file or HF repo + filename")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _call_converter(kind, entry, src_path, dst_path, **kw):
|
| 90 |
+
_, _, fn = entry
|
| 91 |
+
try:
|
| 92 |
+
fn(input_file=src_path, output_file=dst_path, **kw)
|
| 93 |
+
return
|
| 94 |
+
except TypeError:
|
| 95 |
+
pass
|
| 96 |
+
fn(src_path, dst_path, **kw)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def convert(
|
| 100 |
+
uploaded_file,
|
| 101 |
+
hf_repo,
|
| 102 |
+
hf_filename,
|
| 103 |
+
hf_token,
|
| 104 |
+
conversion_type,
|
| 105 |
+
progress=gr.Progress(),
|
| 106 |
+
):
|
| 107 |
+
if conversion_type not in CONVERTERS:
|
| 108 |
+
return None, f"Conversion type '{conversion_type}' unavailable. Available: {list(CONVERTERS)}"
|
| 109 |
+
|
| 110 |
+
workdir = tempfile.mkdtemp(prefix="qc_")
|
| 111 |
+
try:
|
| 112 |
+
progress(0.02, desc="Resolving input")
|
| 113 |
+
src_path, _ = _resolve_input_file(uploaded_file, hf_repo, hf_filename, hf_token)
|
| 114 |
+
|
| 115 |
+
base = os.path.splitext(os.path.basename(src_path))[0]
|
| 116 |
+
dst_path = os.path.join(workdir, f"{base}_{conversion_type}.safetensors")
|
| 117 |
+
|
| 118 |
+
entry = CONVERTERS[conversion_type]
|
| 119 |
+
|
| 120 |
+
def cb(i, total, key):
|
| 121 |
+
try:
|
| 122 |
+
progress(0.05 + 0.9 * (i / max(total, 1)), desc=f"{conversion_type}: {i}/{total} {key}")
|
| 123 |
+
except Exception:
|
| 124 |
+
pass
|
| 125 |
+
|
| 126 |
+
progress(0.05, desc=f"Running {conversion_type}")
|
| 127 |
+
|
| 128 |
+
kwargs = {}
|
| 129 |
+
try:
|
| 130 |
+
import inspect
|
| 131 |
+
sig = inspect.signature(entry[2])
|
| 132 |
+
if "progress_cb" in sig.parameters:
|
| 133 |
+
kwargs["progress_cb"] = cb
|
| 134 |
+
if "device" in sig.parameters:
|
| 135 |
+
kwargs["device"] = "cuda" if torch.cuda.is_available() else "cpu"
|
| 136 |
+
if "low_memory" in sig.parameters:
|
| 137 |
+
kwargs["low_memory"] = True
|
| 138 |
+
except Exception:
|
| 139 |
+
pass
|
| 140 |
+
|
| 141 |
+
_call_converter(conversion_type, entry, src_path, dst_path, **kwargs)
|
| 142 |
+
|
| 143 |
+
if not os.path.exists(dst_path):
|
| 144 |
+
return None, f"Converter did not produce {dst_path}"
|
| 145 |
+
|
| 146 |
+
progress(0.98, desc="Finalizing")
|
| 147 |
+
final_dir = tempfile.mkdtemp(prefix="qc_out_")
|
| 148 |
+
final_path = os.path.join(final_dir, os.path.basename(dst_path))
|
| 149 |
+
shutil.move(dst_path, final_path)
|
| 150 |
+
|
| 151 |
+
size_mb = os.path.getsize(final_path) / (1024 * 1024)
|
| 152 |
+
status = f"OK {conversion_type}: {os.path.basename(final_path)} ({size_mb:.1f} MB)"
|
| 153 |
+
if WARNINGS:
|
| 154 |
+
status += "\n" + "\n".join(WARNINGS)
|
| 155 |
+
return final_path, status
|
| 156 |
+
except Exception as e:
|
| 157 |
+
traceback.print_exc()
|
| 158 |
+
return None, f"FAILED: {type(e).__name__}: {e}"
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
with gr.Blocks(title="Quant Converter") as demo:
|
| 162 |
+
gr.Markdown("# Quant Converter")
|
| 163 |
+
gr.Markdown(
|
| 164 |
+
"CPU-safe safetensors quantizer. Available types: "
|
| 165 |
+
+ (", ".join(sorted(CONVERTERS)) if CONVERTERS else "none detected")
|
| 166 |
+
)
|
| 167 |
+
if WARNINGS:
|
| 168 |
+
gr.Markdown("Warnings:\n- " + "\n- ".join(WARNINGS))
|
| 169 |
+
|
| 170 |
+
with gr.Row():
|
| 171 |
+
with gr.Column():
|
| 172 |
+
uploaded_file = gr.File(label="Upload safetensors", file_types=[".safetensors"])
|
| 173 |
+
hf_repo = gr.Textbox(label="Or HF repo id", placeholder="user/model")
|
| 174 |
+
hf_filename = gr.Textbox(label="HF filename", placeholder="model.safetensors")
|
| 175 |
+
hf_token = gr.Textbox(label="HF token (optional)", type="password")
|
| 176 |
+
conversion_type = gr.Dropdown(
|
| 177 |
+
choices=sorted(CONVERTERS.keys()),
|
| 178 |
+
value=("w4a8" if "w4a8" in CONVERTERS else (sorted(CONVERTERS.keys())[0] if CONVERTERS else None)),
|
| 179 |
+
label="Conversion type",
|
| 180 |
+
)
|
| 181 |
+
run_btn = gr.Button("Convert", variant="primary")
|
| 182 |
+
with gr.Column():
|
| 183 |
+
out_file = gr.File(label="Output")
|
| 184 |
+
status = gr.Textbox(label="Status", lines=8)
|
| 185 |
+
|
| 186 |
+
run_btn.click(
|
| 187 |
+
fn=convert,
|
| 188 |
+
inputs=[uploaded_file, hf_repo, hf_filename, hf_token, conversion_type],
|
| 189 |
+
outputs=[out_file, status],
|
| 190 |
+
show_progress=True,
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
if __name__ == "__main__":
|
| 195 |
+
demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))
|
requirements.txt
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
-
gradio
|
| 2 |
-
huggingface_hub
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
|
|
|
|
|
| 1 |
+
gradio>=4.44.0
|
| 2 |
+
huggingface_hub>=0.25.0
|
| 3 |
+
safetensors>=0.4.5
|
| 4 |
+
torch>=2.1.0
|
| 5 |
+
numpy
|
| 6 |
+
convert_to_quant
|
| 7 |
+
comfy_kitchen
|
w4a8/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .w4a8_converter import (
|
| 2 |
+
W4A8_FORMAT,
|
| 3 |
+
W4A8_LAYOUT,
|
| 4 |
+
W4A8_GROUP_SIZE,
|
| 5 |
+
W4A8_CONVROT_GROUP_SIZE,
|
| 6 |
+
W4A8Converter,
|
| 7 |
+
quantize_w4a8_tensor,
|
| 8 |
+
w4a8_available,
|
| 9 |
+
w4a8_last_error,
|
| 10 |
+
w4a8_diagnose,
|
| 11 |
+
)
|
| 12 |
+
from .w4a8_conversion import convert_to_w4a8
|
| 13 |
+
|
| 14 |
+
__all__ = [
|
| 15 |
+
"W4A8_FORMAT",
|
| 16 |
+
"W4A8_LAYOUT",
|
| 17 |
+
"W4A8_GROUP_SIZE",
|
| 18 |
+
"W4A8_CONVROT_GROUP_SIZE",
|
| 19 |
+
"W4A8Converter",
|
| 20 |
+
"quantize_w4a8_tensor",
|
| 21 |
+
"w4a8_available",
|
| 22 |
+
"w4a8_last_error",
|
| 23 |
+
"w4a8_diagnose",
|
| 24 |
+
"convert_to_w4a8",
|
| 25 |
+
]
|
w4a8/comfy_load_test.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from safetensors.torch import load_file
|
| 3 |
+
|
| 4 |
+
from .comfy_quant_w4a8 import W4A8_FORMAT, decode_w4a8_comfy_quant
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def _reconstruct_layer(packed, s_rel, s_channel, codebook, correction, cfg):
|
| 8 |
+
from comfy.quant_ops import QuantizedTensor, AsymW4A8Int8Layout
|
| 9 |
+
|
| 10 |
+
out_features = int(packed.shape[0])
|
| 11 |
+
in_features = int(packed.shape[1]) * 2
|
| 12 |
+
|
| 13 |
+
group_size = int(cfg.get("group_size", 16))
|
| 14 |
+
convrot_group_size = int(cfg.get("convrot_groupsize", 256))
|
| 15 |
+
|
| 16 |
+
params = AsymW4A8Int8Layout.Params(
|
| 17 |
+
scale=s_rel,
|
| 18 |
+
s_channel=s_channel,
|
| 19 |
+
correction=correction,
|
| 20 |
+
codebook=codebook,
|
| 21 |
+
orig_dtype=torch.bfloat16,
|
| 22 |
+
orig_shape=(out_features, in_features),
|
| 23 |
+
group_size=group_size,
|
| 24 |
+
convrot_groupsize=convrot_group_size,
|
| 25 |
+
)
|
| 26 |
+
return QuantizedTensor(packed, "AsymW4A8Int8Layout", params)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def verify_w4a8_load(model_path: str, verbose: bool = True) -> bool:
|
| 30 |
+
try:
|
| 31 |
+
from comfy.quant_ops import QuantizedTensor, AsymW4A8Int8Layout
|
| 32 |
+
except Exception as e:
|
| 33 |
+
print(f"test_load: cannot import comfy.quant_ops ({e})")
|
| 34 |
+
return False
|
| 35 |
+
|
| 36 |
+
print(f"test_load: loading {model_path}")
|
| 37 |
+
tensors = load_file(model_path)
|
| 38 |
+
|
| 39 |
+
w4a8_bases = []
|
| 40 |
+
for k, v in tensors.items():
|
| 41 |
+
if k.endswith(".comfy_quant"):
|
| 42 |
+
try:
|
| 43 |
+
cfg = decode_w4a8_comfy_quant(v)
|
| 44 |
+
except Exception:
|
| 45 |
+
continue
|
| 46 |
+
if cfg.get("format") == W4A8_FORMAT:
|
| 47 |
+
w4a8_bases.append((k[: -len(".comfy_quant")], cfg))
|
| 48 |
+
|
| 49 |
+
print(f"test_load: found {len(w4a8_bases)} W4A8 layers")
|
| 50 |
+
if not w4a8_bases:
|
| 51 |
+
print("test_load: no W4A8 layers found in file")
|
| 52 |
+
return False
|
| 53 |
+
|
| 54 |
+
required = ("weight", "weight_s_rel", "weight_s_channel")
|
| 55 |
+
all_ok = True
|
| 56 |
+
|
| 57 |
+
for base, cfg in sorted(w4a8_bases):
|
| 58 |
+
missing = [r for r in required if f"{base}.{r}" not in tensors]
|
| 59 |
+
if missing:
|
| 60 |
+
print(f" FAIL {base}: missing {missing}")
|
| 61 |
+
all_ok = False
|
| 62 |
+
continue
|
| 63 |
+
|
| 64 |
+
packed = tensors[f"{base}.weight"]
|
| 65 |
+
s_rel = tensors[f"{base}.weight_s_rel"]
|
| 66 |
+
s_channel = tensors[f"{base}.weight_s_channel"]
|
| 67 |
+
codebook = tensors.get(f"{base}.weight_codebook")
|
| 68 |
+
correction = tensors.get(f"{base}.weight_correction")
|
| 69 |
+
|
| 70 |
+
try:
|
| 71 |
+
qt = _reconstruct_layer(
|
| 72 |
+
packed, s_rel, s_channel, codebook, correction, cfg
|
| 73 |
+
)
|
| 74 |
+
except Exception as e:
|
| 75 |
+
print(f" FAIL {base}: reconstruction failed ({type(e).__name__}: {e})")
|
| 76 |
+
all_ok = False
|
| 77 |
+
continue
|
| 78 |
+
|
| 79 |
+
try:
|
| 80 |
+
dq = qt.dequantize()
|
| 81 |
+
except Exception as e:
|
| 82 |
+
print(f" FAIL {base}: dequantize failed ({type(e).__name__}: {e})")
|
| 83 |
+
all_ok = False
|
| 84 |
+
continue
|
| 85 |
+
|
| 86 |
+
out_features = int(packed.shape[0])
|
| 87 |
+
in_features = int(packed.shape[1]) * 2
|
| 88 |
+
expected_shape = (out_features, in_features)
|
| 89 |
+
if tuple(dq.shape) != expected_shape:
|
| 90 |
+
print(
|
| 91 |
+
f" FAIL {base}: dequantized shape {tuple(dq.shape)} "
|
| 92 |
+
f"!= {expected_shape}"
|
| 93 |
+
)
|
| 94 |
+
all_ok = False
|
| 95 |
+
continue
|
| 96 |
+
|
| 97 |
+
if not torch.isfinite(dq).all():
|
| 98 |
+
print(f" FAIL {base}: dequantized tensor has non-finite values")
|
| 99 |
+
all_ok = False
|
| 100 |
+
continue
|
| 101 |
+
|
| 102 |
+
if verbose:
|
| 103 |
+
print(
|
| 104 |
+
f" OK {base}: {out_features}x{in_features} "
|
| 105 |
+
f"gs={cfg.get('group_size')} cgs={cfg.get('convrot_groupsize')}"
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
return all_ok
|
w4a8/comfy_quant_w4a8.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
W4A8_FORMAT = "asym_w4a8_int8"
|
| 7 |
+
W4A8_LAYOUT = "AsymW4A8Int8Layout"
|
| 8 |
+
W4A8_GROUP_SIZE = 16
|
| 9 |
+
W4A8_CONVROT_GROUP_SIZE = 256
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _dict_to_tensor(data: dict) -> torch.Tensor:
|
| 13 |
+
json_str = json.dumps(data)
|
| 14 |
+
byte_data = json_str.encode("utf-8")
|
| 15 |
+
return torch.tensor(list(byte_data), dtype=torch.uint8)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _tensor_to_dict(tensor: torch.Tensor) -> dict:
|
| 19 |
+
byte_data = bytes(tensor.tolist())
|
| 20 |
+
return json.loads(byte_data.decode("utf-8"))
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def create_w4a8_comfy_quant_tensor(
|
| 24 |
+
group_size: int = W4A8_GROUP_SIZE,
|
| 25 |
+
convrot_groupsize: int = W4A8_CONVROT_GROUP_SIZE,
|
| 26 |
+
orig_dtype: Optional[str] = None,
|
| 27 |
+
full_precision_matrix_mult: Optional[bool] = None,
|
| 28 |
+
) -> torch.Tensor:
|
| 29 |
+
config = {
|
| 30 |
+
"format": W4A8_FORMAT,
|
| 31 |
+
"group_size": int(group_size),
|
| 32 |
+
"convrot_groupsize": int(convrot_groupsize),
|
| 33 |
+
}
|
| 34 |
+
if orig_dtype is not None:
|
| 35 |
+
config["orig_dtype"] = str(orig_dtype)
|
| 36 |
+
if full_precision_matrix_mult is True:
|
| 37 |
+
config["full_precision_matrix_mult"] = True
|
| 38 |
+
return _dict_to_tensor(config)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def decode_w4a8_comfy_quant(tensor: torch.Tensor) -> dict:
|
| 42 |
+
return _tensor_to_dict(tensor)
|
w4a8/w4a8_conversion.py
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gc
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
import struct
|
| 6 |
+
from typing import Any, Dict, Optional
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
from ..constants import AVOID_KEY_NAMES, resolve_model_filter_patterns
|
| 11 |
+
from ..utils.logging import info, warning
|
| 12 |
+
from ..utils.memory_efficient_loader import UnifiedSafetensorsLoader
|
| 13 |
+
from .comfy_quant_w4a8 import (
|
| 14 |
+
W4A8_CONVROT_GROUP_SIZE,
|
| 15 |
+
W4A8_FORMAT,
|
| 16 |
+
W4A8_GROUP_SIZE,
|
| 17 |
+
create_w4a8_comfy_quant_tensor,
|
| 18 |
+
)
|
| 19 |
+
from .w4a8_converter import W4A8Converter, w4a8_available
|
| 20 |
+
|
| 21 |
+
_FP8_DTYPES = tuple(
|
| 22 |
+
d for d in (
|
| 23 |
+
getattr(torch, "float8_e4m3fn", None),
|
| 24 |
+
getattr(torch, "float8_e5m2", None),
|
| 25 |
+
) if d is not None
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
_SAFETENSORS_DTYPE_MAP = {
|
| 29 |
+
torch.float64: "F64",
|
| 30 |
+
torch.float32: "F32",
|
| 31 |
+
torch.float16: "F16",
|
| 32 |
+
torch.bfloat16: "BF16",
|
| 33 |
+
torch.int64: "I64",
|
| 34 |
+
torch.int32: "I32",
|
| 35 |
+
torch.int16: "I16",
|
| 36 |
+
torch.int8: "I8",
|
| 37 |
+
torch.uint8: "U8",
|
| 38 |
+
torch.bool: "BOOL",
|
| 39 |
+
}
|
| 40 |
+
if hasattr(torch, "float8_e5m2"):
|
| 41 |
+
_SAFETENSORS_DTYPE_MAP[torch.float8_e5m2] = "F8_E5M2"
|
| 42 |
+
if hasattr(torch, "float8_e4m3fn"):
|
| 43 |
+
_SAFETENSORS_DTYPE_MAP[torch.float8_e4m3fn] = "F8_E4M3"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class StreamingSafetensorsWriter:
|
| 47 |
+
_ALIGN = 8
|
| 48 |
+
_COPY_CHUNK = 8 * 1024 * 1024
|
| 49 |
+
|
| 50 |
+
def __init__(self, output_path: str, metadata: Optional[Dict[str, Any]] = None):
|
| 51 |
+
self.output_path = output_path
|
| 52 |
+
self.temp_path = output_path + ".tmp_payload"
|
| 53 |
+
self.metadata: Dict[str, str] = {
|
| 54 |
+
str(k): str(v) for k, v in (metadata or {}).items()
|
| 55 |
+
}
|
| 56 |
+
self._temp = open(self.temp_path, "wb")
|
| 57 |
+
self._entries: list = []
|
| 58 |
+
self._seen: set = set()
|
| 59 |
+
self._offset = 0
|
| 60 |
+
self._finalized = False
|
| 61 |
+
|
| 62 |
+
def add(self, key: str, tensor: Optional[torch.Tensor]) -> None:
|
| 63 |
+
if self._finalized:
|
| 64 |
+
raise RuntimeError("StreamingSafetensorsWriter already finalized")
|
| 65 |
+
if tensor is None:
|
| 66 |
+
return
|
| 67 |
+
if key in self._seen:
|
| 68 |
+
raise ValueError(f"Duplicate output key: {key}")
|
| 69 |
+
self._seen.add(key)
|
| 70 |
+
|
| 71 |
+
t = tensor.detach().cpu()
|
| 72 |
+
dtype_str = _SAFETENSORS_DTYPE_MAP.get(t.dtype)
|
| 73 |
+
if dtype_str is None:
|
| 74 |
+
raise TypeError(
|
| 75 |
+
f"Cannot serialize tensor {key!r} with dtype {t.dtype}"
|
| 76 |
+
)
|
| 77 |
+
shape = list(t.shape)
|
| 78 |
+
|
| 79 |
+
if t.numel() == 0:
|
| 80 |
+
self._entries.append((key, dtype_str, shape, 0, 0))
|
| 81 |
+
return
|
| 82 |
+
|
| 83 |
+
if t.dim() == 0:
|
| 84 |
+
t = t.unsqueeze(0)
|
| 85 |
+
raw = t.contiguous().view(torch.uint8)
|
| 86 |
+
size = int(raw.numel())
|
| 87 |
+
raw.numpy().tofile(self._temp)
|
| 88 |
+
self._entries.append((key, dtype_str, shape, self._offset, size))
|
| 89 |
+
self._offset += size
|
| 90 |
+
|
| 91 |
+
def finalize(self) -> None:
|
| 92 |
+
if self._finalized:
|
| 93 |
+
return
|
| 94 |
+
self._temp.flush()
|
| 95 |
+
self._temp.close()
|
| 96 |
+
|
| 97 |
+
header: Dict[str, Any] = {}
|
| 98 |
+
if self.metadata:
|
| 99 |
+
header["__metadata__"] = self.metadata
|
| 100 |
+
for key, dtype_str, shape, offset, size in self._entries:
|
| 101 |
+
header[key] = {
|
| 102 |
+
"dtype": dtype_str,
|
| 103 |
+
"shape": shape,
|
| 104 |
+
"data_offsets": [offset, offset + size],
|
| 105 |
+
}
|
| 106 |
+
hjson = json.dumps(header, separators=(",", ":")).encode("utf-8")
|
| 107 |
+
pad = (-(len(hjson) + 8)) % self._ALIGN
|
| 108 |
+
hjson += b" " * pad
|
| 109 |
+
|
| 110 |
+
with open(self.output_path, "wb") as out:
|
| 111 |
+
out.write(struct.pack("<Q", len(hjson)))
|
| 112 |
+
out.write(hjson)
|
| 113 |
+
with open(self.temp_path, "rb") as tmp:
|
| 114 |
+
while True:
|
| 115 |
+
chunk = tmp.read(self._COPY_CHUNK)
|
| 116 |
+
if not chunk:
|
| 117 |
+
break
|
| 118 |
+
out.write(chunk)
|
| 119 |
+
|
| 120 |
+
try:
|
| 121 |
+
os.remove(self.temp_path)
|
| 122 |
+
except OSError:
|
| 123 |
+
pass
|
| 124 |
+
self._finalized = True
|
| 125 |
+
|
| 126 |
+
def abort(self) -> None:
|
| 127 |
+
try:
|
| 128 |
+
self._temp.close()
|
| 129 |
+
except Exception:
|
| 130 |
+
pass
|
| 131 |
+
try:
|
| 132 |
+
if os.path.exists(self.temp_path):
|
| 133 |
+
os.remove(self.temp_path)
|
| 134 |
+
except OSError:
|
| 135 |
+
pass
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _lookup_scale(all_keys, loader, base_key: str):
|
| 139 |
+
for suffix in (".weight_scale", ".scale_weight", ".scale"):
|
| 140 |
+
candidate = base_key + suffix
|
| 141 |
+
if candidate in all_keys:
|
| 142 |
+
return loader.get_tensor(candidate)
|
| 143 |
+
return None
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _dequantize_fp8(weight: torch.Tensor, scale: Optional[torch.Tensor]) -> torch.Tensor:
|
| 147 |
+
if weight.dtype not in _FP8_DTYPES:
|
| 148 |
+
return weight
|
| 149 |
+
|
| 150 |
+
if scale is None:
|
| 151 |
+
return weight.to(torch.bfloat16)
|
| 152 |
+
|
| 153 |
+
s = scale.to(torch.float32)
|
| 154 |
+
|
| 155 |
+
if s.numel() == 1:
|
| 156 |
+
return (weight.to(torch.float32) * s).to(torch.bfloat16)
|
| 157 |
+
|
| 158 |
+
if s.ndim == 1 and s.shape[0] == weight.shape[0]:
|
| 159 |
+
return (weight.to(torch.float32) * s.view(-1, 1)).to(torch.bfloat16)
|
| 160 |
+
if s.ndim == 2 and s.shape == (weight.shape[0], 1):
|
| 161 |
+
return (weight.to(torch.float32) * s).to(torch.bfloat16)
|
| 162 |
+
|
| 163 |
+
if s.ndim == 2 and weight.ndim == 2:
|
| 164 |
+
M, N = weight.shape
|
| 165 |
+
if M % s.shape[0] == 0 and N % s.shape[1] == 0:
|
| 166 |
+
bs_M = M // s.shape[0]
|
| 167 |
+
bs_N = N // s.shape[1]
|
| 168 |
+
wf = weight.to(torch.float32).reshape(s.shape[0], bs_M, s.shape[1], bs_N)
|
| 169 |
+
wf = wf.permute(0, 2, 1, 3) * s.unsqueeze(-1).unsqueeze(-1)
|
| 170 |
+
return wf.permute(0, 2, 1, 3).reshape(M, N).to(torch.bfloat16)
|
| 171 |
+
|
| 172 |
+
return (weight.to(torch.float32) * s).to(torch.bfloat16)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def convert_to_w4a8(
|
| 176 |
+
input_file: str,
|
| 177 |
+
output_file: str,
|
| 178 |
+
device: Optional[str] = None,
|
| 179 |
+
group_size: int = W4A8_GROUP_SIZE,
|
| 180 |
+
convrot_group_size: int = W4A8_CONVROT_GROUP_SIZE,
|
| 181 |
+
seed: int = 0,
|
| 182 |
+
calib_samples: int = 64,
|
| 183 |
+
bias_correction: bool = True,
|
| 184 |
+
filter_flags: Optional[Dict[str, bool]] = None,
|
| 185 |
+
exclude_layers: Optional[str] = None,
|
| 186 |
+
low_memory: bool = False,
|
| 187 |
+
save_quant_metadata: bool = True,
|
| 188 |
+
progress_cb=None,
|
| 189 |
+
) -> None:
|
| 190 |
+
if not w4a8_available():
|
| 191 |
+
raise RuntimeError(
|
| 192 |
+
"W4A8 is unavailable in this environment."
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
if device is None:
|
| 196 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 197 |
+
info(f"W4A8 conversion: {input_file} -> {output_file}")
|
| 198 |
+
info(
|
| 199 |
+
f" device={device} group_size={group_size} "
|
| 200 |
+
f"convrot_groupsize={convrot_group_size} seed={seed}"
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
converter = W4A8Converter(
|
| 204 |
+
group_size=group_size,
|
| 205 |
+
convrot_group_size=convrot_group_size,
|
| 206 |
+
stochastic_rounding=int(seed),
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
loader = UnifiedSafetensorsLoader(input_file, low_memory=True)
|
| 210 |
+
all_keys = loader.keys()
|
| 211 |
+
all_keys_set = set(all_keys)
|
| 212 |
+
original_metadata = loader.metadata() or {}
|
| 213 |
+
|
| 214 |
+
active_filters = filter_flags or {}
|
| 215 |
+
exclude_patterns = list(AVOID_KEY_NAMES)
|
| 216 |
+
for patterns in resolve_model_filter_patterns(active_filters, all_keys).values():
|
| 217 |
+
exclude_patterns.extend(patterns)
|
| 218 |
+
|
| 219 |
+
exclude_regex = None
|
| 220 |
+
if exclude_layers:
|
| 221 |
+
try:
|
| 222 |
+
exclude_regex = re.compile(exclude_layers)
|
| 223 |
+
info(f" --exclude-layers regex: {exclude_layers}")
|
| 224 |
+
except re.error as e:
|
| 225 |
+
loader.close()
|
| 226 |
+
raise ValueError(f"Invalid --exclude-layers regex: {e}") from e
|
| 227 |
+
|
| 228 |
+
weight_keys = sorted(
|
| 229 |
+
k for k in all_keys
|
| 230 |
+
if k.endswith(".weight") and loader.get_ndim(k) == 2
|
| 231 |
+
)
|
| 232 |
+
total = len(weight_keys)
|
| 233 |
+
|
| 234 |
+
calib_gen = torch.Generator(device="cpu")
|
| 235 |
+
calib_gen.manual_seed(seed)
|
| 236 |
+
calib_cache: Dict[int, torch.Tensor] = {}
|
| 237 |
+
|
| 238 |
+
quant_metadata_layers: Optional[Dict[str, dict]] = (
|
| 239 |
+
{} if save_quant_metadata else None
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
tmp_output = output_file + ".tmp.safetensors"
|
| 243 |
+
if os.path.exists(tmp_output):
|
| 244 |
+
os.remove(tmp_output)
|
| 245 |
+
|
| 246 |
+
os.makedirs(os.path.dirname(output_file) or ".", exist_ok=True)
|
| 247 |
+
|
| 248 |
+
writer = StreamingSafetensorsWriter(tmp_output, metadata=original_metadata)
|
| 249 |
+
|
| 250 |
+
quantized_count = 0
|
| 251 |
+
skipped_shape_count = 0
|
| 252 |
+
skipped_filter_count = 0
|
| 253 |
+
failed_count = 0
|
| 254 |
+
fp8_dequantized_count = 0
|
| 255 |
+
|
| 256 |
+
try:
|
| 257 |
+
for i, key in enumerate(weight_keys):
|
| 258 |
+
if progress_cb is not None:
|
| 259 |
+
try:
|
| 260 |
+
progress_cb(i, total, key)
|
| 261 |
+
except Exception:
|
| 262 |
+
pass
|
| 263 |
+
tensor_raw = loader.get_tensor(key)
|
| 264 |
+
base_key = key.rsplit(".weight", 1)[0]
|
| 265 |
+
|
| 266 |
+
if tensor_raw.dim() != 2:
|
| 267 |
+
writer.add(key, tensor_raw)
|
| 268 |
+
continue
|
| 269 |
+
|
| 270 |
+
reason = ""
|
| 271 |
+
if any(p in key for p in exclude_patterns):
|
| 272 |
+
reason = "exclusion pattern"
|
| 273 |
+
if not reason and exclude_regex and exclude_regex.search(key):
|
| 274 |
+
reason = "--exclude-layers regex"
|
| 275 |
+
|
| 276 |
+
if reason:
|
| 277 |
+
info(f"({i + 1}/{total}) skip {key}: {reason}")
|
| 278 |
+
writer.add(key, tensor_raw)
|
| 279 |
+
skipped_filter_count += 1
|
| 280 |
+
del tensor_raw
|
| 281 |
+
gc.collect()
|
| 282 |
+
continue
|
| 283 |
+
|
| 284 |
+
was_fp8 = tensor_raw.dtype in _FP8_DTYPES
|
| 285 |
+
if was_fp8:
|
| 286 |
+
scale = _lookup_scale(all_keys_set, loader, base_key)
|
| 287 |
+
if scale is None:
|
| 288 |
+
warning(
|
| 289 |
+
f" {key}: FP8 weight has no matching scale tensor; "
|
| 290 |
+
f"dequantizing without scale."
|
| 291 |
+
)
|
| 292 |
+
tensor = _dequantize_fp8(tensor_raw, scale)
|
| 293 |
+
fp8_dequantized_count += 1
|
| 294 |
+
else:
|
| 295 |
+
tensor = tensor_raw
|
| 296 |
+
|
| 297 |
+
if not converter.is_compatible(tensor):
|
| 298 |
+
info(
|
| 299 |
+
f"({i + 1}/{total}) skip {key}: incompatible shape "
|
| 300 |
+
f"{tuple(tensor.shape)}"
|
| 301 |
+
)
|
| 302 |
+
writer.add(key, tensor_raw)
|
| 303 |
+
skipped_shape_count += 1
|
| 304 |
+
del tensor_raw, tensor
|
| 305 |
+
gc.collect()
|
| 306 |
+
continue
|
| 307 |
+
|
| 308 |
+
info(
|
| 309 |
+
f"({i + 1}/{total}) W4A8 {key} {tuple(tensor.shape)}"
|
| 310 |
+
+ (" [fp8->bf16]" if was_fp8 else "")
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
try:
|
| 314 |
+
qdata, s_rel, s_channel, codebook, correction, dequant_w = (
|
| 315 |
+
converter.convert(tensor, key=key)
|
| 316 |
+
)
|
| 317 |
+
except Exception as e:
|
| 318 |
+
warning(f" W4A8 quantization failed for {key}: {e}")
|
| 319 |
+
writer.add(key, tensor_raw)
|
| 320 |
+
failed_count += 1
|
| 321 |
+
del tensor_raw, tensor
|
| 322 |
+
gc.collect()
|
| 323 |
+
continue
|
| 324 |
+
|
| 325 |
+
writer.add(key, qdata)
|
| 326 |
+
writer.add(f"{base_key}.weight_s_rel", s_rel)
|
| 327 |
+
writer.add(f"{base_key}.weight_s_channel", s_channel)
|
| 328 |
+
if isinstance(codebook, torch.Tensor):
|
| 329 |
+
writer.add(f"{base_key}.weight_codebook", codebook)
|
| 330 |
+
if isinstance(correction, torch.Tensor):
|
| 331 |
+
writer.add(f"{base_key}.weight_correction", correction)
|
| 332 |
+
|
| 333 |
+
orig_dtype_str = "torch.bfloat16"
|
| 334 |
+
writer.add(
|
| 335 |
+
f"{base_key}.comfy_quant",
|
| 336 |
+
create_w4a8_comfy_quant_tensor(
|
| 337 |
+
group_size=group_size,
|
| 338 |
+
convrot_groupsize=convrot_group_size,
|
| 339 |
+
orig_dtype=orig_dtype_str,
|
| 340 |
+
),
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
if quant_metadata_layers is not None:
|
| 344 |
+
quant_metadata_layers[base_key] = {
|
| 345 |
+
"format": W4A8_FORMAT,
|
| 346 |
+
"group_size": int(group_size),
|
| 347 |
+
"convrot_groupsize": int(convrot_group_size),
|
| 348 |
+
"orig_dtype": orig_dtype_str,
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
bias_key = f"{base_key}.bias"
|
| 352 |
+
if bias_correction and bias_key in all_keys_set:
|
| 353 |
+
try:
|
| 354 |
+
in_features = int(tensor.shape[1])
|
| 355 |
+
if in_features not in calib_cache:
|
| 356 |
+
calib_cache[in_features] = torch.randn(
|
| 357 |
+
calib_samples,
|
| 358 |
+
in_features,
|
| 359 |
+
dtype=torch.float32,
|
| 360 |
+
generator=calib_gen,
|
| 361 |
+
)
|
| 362 |
+
X = calib_cache[in_features]
|
| 363 |
+
original_bias = loader.get_tensor(bias_key)
|
| 364 |
+
with torch.no_grad():
|
| 365 |
+
W_orig = tensor.to(dtype=torch.float32)
|
| 366 |
+
W_deq = dequant_w.to(dtype=torch.float32)
|
| 367 |
+
b_orig = original_bias.to(dtype=torch.float32)
|
| 368 |
+
weight_error = W_orig - W_deq
|
| 369 |
+
output_error = X @ weight_error.T
|
| 370 |
+
bias_corr = output_error.mean(dim=0)
|
| 371 |
+
new_bias = b_orig - bias_corr
|
| 372 |
+
writer.add(bias_key, new_bias.to(dtype=original_bias.dtype))
|
| 373 |
+
except Exception as e:
|
| 374 |
+
warning(f" bias correction failed for {bias_key}: {e}")
|
| 375 |
+
|
| 376 |
+
quantized_count += 1
|
| 377 |
+
del tensor, tensor_raw, dequant_w, qdata, s_rel, s_channel
|
| 378 |
+
gc.collect()
|
| 379 |
+
if torch.cuda.is_available():
|
| 380 |
+
torch.cuda.empty_cache()
|
| 381 |
+
|
| 382 |
+
for key in all_keys:
|
| 383 |
+
if key not in writer._seen:
|
| 384 |
+
writer.add(key, loader.get_tensor(key))
|
| 385 |
+
except BaseException:
|
| 386 |
+
writer.abort()
|
| 387 |
+
loader.close()
|
| 388 |
+
if os.path.exists(tmp_output):
|
| 389 |
+
try:
|
| 390 |
+
os.remove(tmp_output)
|
| 391 |
+
except OSError:
|
| 392 |
+
pass
|
| 393 |
+
raise
|
| 394 |
+
finally:
|
| 395 |
+
try:
|
| 396 |
+
loader.close()
|
| 397 |
+
except Exception:
|
| 398 |
+
pass
|
| 399 |
+
|
| 400 |
+
if save_quant_metadata and quant_metadata_layers:
|
| 401 |
+
writer.metadata["_quantization_metadata"] = json.dumps(
|
| 402 |
+
{"format_version": "1.0", "layers": quant_metadata_layers}
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
info(
|
| 406 |
+
f" summary: {quantized_count} W4A8 layers "
|
| 407 |
+
f"({fp8_dequantized_count} were FP8 and got dequantized), "
|
| 408 |
+
f"{skipped_shape_count} skipped (shape), "
|
| 409 |
+
f"{skipped_filter_count} skipped (filter), "
|
| 410 |
+
f"{failed_count} failed, "
|
| 411 |
+
f"{len(writer._entries)} tensors total"
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
if quantized_count == 0:
|
| 415 |
+
writer.abort()
|
| 416 |
+
raise RuntimeError(
|
| 417 |
+
"W4A8 conversion produced zero quantized layers."
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
writer.finalize()
|
| 421 |
+
os.replace(tmp_output, output_file)
|
| 422 |
+
info("W4A8 conversion complete")
|
w4a8/w4a8_converter.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import Optional, Tuple
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
W4A8_FORMAT = "asym_w4a8_int8"
|
| 7 |
+
W4A8_LAYOUT = "AsymW4A8Int8Layout"
|
| 8 |
+
W4A8_GROUP_SIZE = 16
|
| 9 |
+
W4A8_CONVROT_GROUP_SIZE = 256
|
| 10 |
+
|
| 11 |
+
_LAST_ERROR: Optional[str] = None
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _allow_vendored() -> bool:
|
| 15 |
+
return os.environ.get("COMFY_ALLOW_VENDORED", "") == "1"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _candidate_comfy_roots():
|
| 19 |
+
candidates = []
|
| 20 |
+
env_root = os.environ.get("COMFYUI_ROOT")
|
| 21 |
+
if env_root:
|
| 22 |
+
candidates.append(os.path.abspath(env_root))
|
| 23 |
+
cwd = os.path.abspath(os.getcwd())
|
| 24 |
+
candidates.append(cwd)
|
| 25 |
+
candidates.append(os.path.dirname(cwd))
|
| 26 |
+
return candidates
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _find_real_comfy_root():
|
| 30 |
+
for root in _candidate_comfy_roots():
|
| 31 |
+
if os.path.isfile(os.path.join(root, "comfy", "quant_ops.py")):
|
| 32 |
+
return root
|
| 33 |
+
return None
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _ensure_real_comfy_on_path():
|
| 37 |
+
import sys
|
| 38 |
+
|
| 39 |
+
if _allow_vendored():
|
| 40 |
+
return
|
| 41 |
+
real_root = _find_real_comfy_root()
|
| 42 |
+
if real_root is None:
|
| 43 |
+
return
|
| 44 |
+
vendored_dir = os.path.dirname(os.path.abspath(__file__))
|
| 45 |
+
vendored_dir = os.path.dirname(vendored_dir)
|
| 46 |
+
new_path = []
|
| 47 |
+
for p in sys.path:
|
| 48 |
+
try:
|
| 49 |
+
ap = os.path.abspath(p) if p else os.path.abspath(".")
|
| 50 |
+
except Exception:
|
| 51 |
+
ap = p
|
| 52 |
+
if ap == vendored_dir:
|
| 53 |
+
continue
|
| 54 |
+
if ap == real_root:
|
| 55 |
+
continue
|
| 56 |
+
new_path.append(p)
|
| 57 |
+
sys.path[:] = new_path
|
| 58 |
+
sys.path.insert(0, real_root)
|
| 59 |
+
for name in list(sys.modules):
|
| 60 |
+
if name == "comfy" or name.startswith("comfy."):
|
| 61 |
+
mod = sys.modules.get(name)
|
| 62 |
+
mod_file = getattr(mod, "__file__", "") or ""
|
| 63 |
+
normalized = mod_file.replace("\\", "/")
|
| 64 |
+
if "convert_to_quant/comfy" in normalized:
|
| 65 |
+
del sys.modules[name]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
_ensure_real_comfy_on_path()
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _load_comfy_w4a8():
|
| 72 |
+
import importlib
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
comfy_quant_ops = importlib.import_module("comfy.quant_ops")
|
| 76 |
+
except Exception as e:
|
| 77 |
+
raise RuntimeError(
|
| 78 |
+
f"comfy.quant_ops module is not importable "
|
| 79 |
+
f"({type(e).__name__}: {e})."
|
| 80 |
+
) from e
|
| 81 |
+
|
| 82 |
+
module_file = (getattr(comfy_quant_ops, "__file__", "") or "").replace("\\", "/")
|
| 83 |
+
if "convert_to_quant/comfy" in module_file and not _allow_vendored():
|
| 84 |
+
raise RuntimeError(
|
| 85 |
+
f"comfy.quant_ops resolved to the vendored copy at {module_file!r}. "
|
| 86 |
+
f"Set COMFY_ALLOW_VENDORED=1 to allow it."
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
QuantizedTensor = getattr(comfy_quant_ops, "QuantizedTensor", None)
|
| 90 |
+
if QuantizedTensor is None:
|
| 91 |
+
public = sorted(n for n in dir(comfy_quant_ops) if not n.startswith("_"))
|
| 92 |
+
raise RuntimeError(
|
| 93 |
+
f"comfy.quant_ops has no QuantizedTensor attribute. "
|
| 94 |
+
f"Public names seen: {public[:40]}"
|
| 95 |
+
)
|
| 96 |
+
if not hasattr(QuantizedTensor, "from_float"):
|
| 97 |
+
raise RuntimeError("QuantizedTensor.from_float is missing")
|
| 98 |
+
|
| 99 |
+
AsymW4A8Int8Layout = getattr(comfy_quant_ops, "AsymW4A8Int8Layout", None)
|
| 100 |
+
if AsymW4A8Int8Layout is None:
|
| 101 |
+
public = sorted(n for n in dir(comfy_quant_ops) if not n.startswith("_"))
|
| 102 |
+
raise RuntimeError(
|
| 103 |
+
f"comfy.quant_ops has no AsymW4A8Int8Layout attribute. "
|
| 104 |
+
f"Public names seen: {public[:40]}"
|
| 105 |
+
)
|
| 106 |
+
if not hasattr(AsymW4A8Int8Layout, "Params"):
|
| 107 |
+
raise RuntimeError("AsymW4A8Int8Layout.Params is missing")
|
| 108 |
+
|
| 109 |
+
return QuantizedTensor, AsymW4A8Int8Layout
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def w4a8_available() -> bool:
|
| 113 |
+
global _LAST_ERROR
|
| 114 |
+
try:
|
| 115 |
+
_load_comfy_w4a8()
|
| 116 |
+
_LAST_ERROR = None
|
| 117 |
+
return True
|
| 118 |
+
except Exception as e:
|
| 119 |
+
_LAST_ERROR = f"{type(e).__name__}: {e}"
|
| 120 |
+
return False
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def w4a8_last_error() -> Optional[str]:
|
| 124 |
+
return _LAST_ERROR
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def w4a8_diagnose() -> dict:
|
| 128 |
+
import sys
|
| 129 |
+
|
| 130 |
+
info = {
|
| 131 |
+
"sys.executable": sys.executable,
|
| 132 |
+
"cwd": os.getcwd(),
|
| 133 |
+
"COMFYUI_ROOT": os.environ.get("COMFYUI_ROOT"),
|
| 134 |
+
"COMFY_ALLOW_VENDORED": os.environ.get("COMFY_ALLOW_VENDORED"),
|
| 135 |
+
"real_comfy_root": _find_real_comfy_root(),
|
| 136 |
+
"sys.path_head": list(sys.path[:6]),
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
try:
|
| 140 |
+
import comfy
|
| 141 |
+
info["comfy.__file__"] = getattr(comfy, "__file__", None)
|
| 142 |
+
except Exception as e:
|
| 143 |
+
info["comfy_error"] = f"{type(e).__name__}: {e}"
|
| 144 |
+
|
| 145 |
+
try:
|
| 146 |
+
import comfy.quant_ops as q
|
| 147 |
+
info["comfy.quant_ops.__file__"] = getattr(q, "__file__", None)
|
| 148 |
+
public = sorted(n for n in dir(q) if not n.startswith("_"))
|
| 149 |
+
info["comfy.quant_ops.public_names"] = public
|
| 150 |
+
info["has_QuantizedTensor"] = "QuantizedTensor" in public
|
| 151 |
+
info["has_AsymW4A8Int8Layout"] = "AsymW4A8Int8Layout" in public
|
| 152 |
+
qt = getattr(q, "QuantizedTensor", None)
|
| 153 |
+
info["QuantizedTensor_from_float"] = (
|
| 154 |
+
hasattr(qt, "from_float") if qt is not None else None
|
| 155 |
+
)
|
| 156 |
+
layout = getattr(q, "AsymW4A8Int8Layout", None)
|
| 157 |
+
info["AsymW4A8Int8Layout_Params"] = (
|
| 158 |
+
hasattr(layout, "Params") if layout is not None else None
|
| 159 |
+
)
|
| 160 |
+
except Exception as e:
|
| 161 |
+
info["comfy_quant_ops_error"] = f"{type(e).__name__}: {e}"
|
| 162 |
+
|
| 163 |
+
info["w4a8_available"] = w4a8_available()
|
| 164 |
+
info["last_error"] = _LAST_ERROR
|
| 165 |
+
return info
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class W4A8Converter:
|
| 169 |
+
def __init__(
|
| 170 |
+
self,
|
| 171 |
+
group_size: int = W4A8_GROUP_SIZE,
|
| 172 |
+
convrot_group_size: int = W4A8_CONVROT_GROUP_SIZE,
|
| 173 |
+
stochastic_rounding: int = 0,
|
| 174 |
+
):
|
| 175 |
+
self.group_size = int(group_size)
|
| 176 |
+
self.convrot_group_size = int(convrot_group_size)
|
| 177 |
+
self.stochastic_rounding = int(stochastic_rounding)
|
| 178 |
+
self._QuantizedTensor, self._AsymLayout = _load_comfy_w4a8()
|
| 179 |
+
|
| 180 |
+
def is_compatible(self, weight: torch.Tensor) -> bool:
|
| 181 |
+
if weight.ndim != 2:
|
| 182 |
+
return False
|
| 183 |
+
if weight.shape[1] % self.convrot_group_size != 0:
|
| 184 |
+
return False
|
| 185 |
+
return True
|
| 186 |
+
|
| 187 |
+
def convert(
|
| 188 |
+
self,
|
| 189 |
+
weight: torch.Tensor,
|
| 190 |
+
key: Optional[str] = None,
|
| 191 |
+
**_,
|
| 192 |
+
) -> Tuple[
|
| 193 |
+
torch.Tensor,
|
| 194 |
+
torch.Tensor,
|
| 195 |
+
torch.Tensor,
|
| 196 |
+
Optional[torch.Tensor],
|
| 197 |
+
Optional[torch.Tensor],
|
| 198 |
+
torch.Tensor,
|
| 199 |
+
]:
|
| 200 |
+
if weight.ndim != 2:
|
| 201 |
+
raise ValueError(
|
| 202 |
+
f"W4A8 requires a 2D weight, got shape {tuple(weight.shape)}"
|
| 203 |
+
)
|
| 204 |
+
if weight.shape[1] % self.convrot_group_size != 0:
|
| 205 |
+
raise ValueError(
|
| 206 |
+
f"W4A8 requires in_features % {self.convrot_group_size} == 0, "
|
| 207 |
+
f"got {weight.shape[1]} for key={key!r}"
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
compute_device = weight.device
|
| 211 |
+
if compute_device.type == "cpu" and torch.cuda.is_available():
|
| 212 |
+
compute_device = torch.device("cuda")
|
| 213 |
+
|
| 214 |
+
w = weight.to(device=compute_device)
|
| 215 |
+
|
| 216 |
+
q_weight = self._QuantizedTensor.from_float(
|
| 217 |
+
w,
|
| 218 |
+
W4A8_LAYOUT,
|
| 219 |
+
group_size=self.group_size,
|
| 220 |
+
convrot_groupsize=self.convrot_group_size,
|
| 221 |
+
stochastic_rounding=self.stochastic_rounding,
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
params = q_weight._params
|
| 225 |
+
qdata = q_weight._qdata.detach().cpu()
|
| 226 |
+
s_rel = params.scale.detach().cpu()
|
| 227 |
+
s_channel = params.s_channel.detach().cpu()
|
| 228 |
+
codebook = (
|
| 229 |
+
params.codebook.detach().cpu()
|
| 230 |
+
if isinstance(getattr(params, "codebook", None), torch.Tensor)
|
| 231 |
+
else None
|
| 232 |
+
)
|
| 233 |
+
correction = (
|
| 234 |
+
params.correction.detach().cpu()
|
| 235 |
+
if isinstance(getattr(params, "correction", None), torch.Tensor)
|
| 236 |
+
else None
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
dequant = q_weight.dequantize().detach().cpu()
|
| 240 |
+
|
| 241 |
+
return qdata, s_rel, s_channel, codebook, correction, dequant
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def quantize_w4a8_tensor(
|
| 245 |
+
weight: torch.Tensor,
|
| 246 |
+
group_size: int = W4A8_GROUP_SIZE,
|
| 247 |
+
convrot_group_size: int = W4A8_CONVROT_GROUP_SIZE,
|
| 248 |
+
stochastic_rounding: int = 0,
|
| 249 |
+
):
|
| 250 |
+
return W4A8Converter(
|
| 251 |
+
group_size=group_size,
|
| 252 |
+
convrot_group_size=convrot_group_size,
|
| 253 |
+
stochastic_rounding=stochastic_rounding,
|
| 254 |
+
).convert(weight)
|