PAI-Video-Studio-Video-Diffusion / scripts /quantize_relayvsr_colab.py
AnosVoldigoad1's picture
Add T4/L4/A100 eager fallback for NVFP4 quantization on Colab
3ade60b verified
Raw History Blame Contribute Delete
5.63 kB
#!/usr/bin/env python3
"""Colab GPU quantization pipeline for RelayVSR X2 (W6A8, W4A8, NVFP4) & X4 (NVFP4).
Compatible with Colab T4 (sm_75), L4 (sm_89), A100 (sm_80), and Blackwell (sm_120).
Requires HF_TOKEN in environment. Uploads directly to AnosVoldigoad1/PAI-Video-Studio-Video-Diffusion.
"""
import contextlib
import gc
import hashlib
import json
import os
import re
from pathlib import Path
import comfy_kitchen
import torch
from huggingface_hub import HfApi, hf_hub_download
from safetensors import safe_open
from safetensors.torch import save_file
HF_TOKEN = os.environ.get("HF_TOKEN", "").strip()
if not HF_TOKEN:
raise SystemExit("ERROR: Set HF_TOKEN environment variable first.")
TARGET_REPO = "AnosVoldigoad1/PAI-Video-Studio-Video-Diffusion"
LINEAR_RE = re.compile(r"^blocks\.\d+\..+\.weight$")
WORK = Path("/content/relayvsr_quant_work")
WORK.mkdir(parents=True, exist_ok=True)
api = HfApi(token=HF_TOKEN)
device = "cuda" if torch.cuda.is_available() else "cpu"
cc = torch.cuda.get_device_capability() if torch.cuda.is_available() else (0, 0)
print(f"Device={device} cc={cc} torch={torch.__version__} comfy_kitchen={getattr(comfy_kitchen, '__version__', 'unknown')}")
def file_sha256(path: Path) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 24), b""):
h.update(chunk)
return h.hexdigest()
def _quantize_nvfp4_tensor(w: torch.Tensor, base: str):
from comfy_kitchen.tensor import QuantizedTensor
ctx = comfy_kitchen.use_backend("eager") if (hasattr(comfy_kitchen, "use_backend") and cc[0] < 10) else contextlib.nullcontext()
with ctx:
try:
qt = QuantizedTensor.from_float(w, "TensorCoreNVFP4Layout")
except Exception:
if hasattr(comfy_kitchen, "use_backend"):
with comfy_kitchen.use_backend("eager"):
qt = QuantizedTensor.from_float(w.to(torch.float16 if cc[0] < 8 else torch.bfloat16), "TensorCoreNVFP4Layout")
else:
raise
return qt.state_dict(prefix=f"{base}.")
def quantize_wan(src_path: Path, dst_path: Path, mode: str, src_hash: str) -> None:
out = {}
qmeta_layers = {}
count = 0
work_dtype = torch.bfloat16 if (cc[0] >= 8 or device == "cpu") else torch.float16
with safe_open(str(src_path), "pt", device="cpu") as f:
metadata = dict(f.metadata() or {})
for key in f.keys():
tensor = f.get_tensor(key)
if not (LINEAR_RE.match(key) and tensor.ndim == 2):
out[key] = tensor
continue
base = key[:-len(".weight")]
w = tensor.to(device=device, dtype=work_dtype)
if mode in ("w6a8", "w4a8"):
bits = 6 if mode == "w6a8" else 4
q, s_rel, s_channel, correction, codebook = comfy_kitchen.quantize_w4a8_int8_weight(w, bits=bits)
for name, val in (("q", q), ("s_rel", s_rel), ("s_channel", s_channel), ("correction", correction), ("codebook", codebook)):
if val is not None:
out[f"{base}.w4a8_{name}"] = val.contiguous().cpu()
elif mode == "nvfp4":
sd = _quantize_nvfp4_tensor(w, base)
for k_sd, v_sd in sd.items():
out[k_sd] = v_sd.contiguous().cpu() if isinstance(v_sd, torch.Tensor) else v_sd
conf_bytes = json.dumps({"format": "nvfp4"}).encode("utf-8")
out[f"{base}.comfy_quant"] = torch.tensor(list(conf_bytes), dtype=torch.uint8)
qmeta_layers[base] = {"format": "nvfp4"}
else:
raise ValueError(f"Unsupported mode: {mode}")
del w
count += 1
metadata["relayvsr_quant"] = json.dumps({
"mode": mode,
"comfy_kitchen": getattr(comfy_kitchen, "__version__", "unknown"),
"source_sha256": src_hash,
"quantized_linears": count,
})
if qmeta_layers:
metadata["_quantization_metadata"] = json.dumps({
"format_version": "1.0",
"layers": qmeta_layers,
})
save_file(out, str(dst_path), metadata=metadata)
del out
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
print(f"Saved {dst_path.name} ({dst_path.stat().st_size / (1024**3):.2f} GB, {count} linears)")
def run_variant(src_repo: str, src_file: str, prefix: str, modes: list[str]) -> None:
print(f"\n=== Downloading {src_repo}/{src_file} ===")
local_src = Path(hf_hub_download(repo_id=src_repo, filename=src_file, local_dir=str(WORK / prefix)))
src_hash = file_sha256(local_src)
for mode in modes:
out_name = f"{prefix}_{mode}.safetensors"
out_path = WORK / out_name
print(f"Quantizing {out_name} ...")
quantize_wan(local_src, out_path, mode, src_hash)
print(f"Uploading relayvsr/{out_name} -> {TARGET_REPO} ...")
api.upload_file(
path_or_fileobj=str(out_path),
path_in_repo=f"relayvsr/{out_name}",
repo_id=TARGET_REPO,
repo_type="model",
commit_message=f"Add {out_name} quantized via comfy-kitchen",
)
print(f"UPLOADED: relayvsr/{out_name}")
out_path.unlink(missing_ok=True)
local_src.unlink(missing_ok=True)
if __name__ == "__main__":
run_variant("lightx2v/RelayVSR_X2", "wan_x2.safetensors", "relayvsr_x2", ["w6a8", "w4a8", "nvfp4"])
run_variant("kopper/RelayVSR", "wan.safetensors", "relayvsr_x4", ["nvfp4"])
print("\nALL QUANTIZATIONS & UPLOADS COMPLETED SUCCESSFULLY!")