File size: 5,625 Bytes
8d37e4c
 
3ade60b
8d37e4c
 
3ade60b
8d37e4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ade60b
 
8d37e4c
 
 
 
 
 
 
 
 
 
3ade60b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d37e4c
 
 
 
3ade60b
8d37e4c
 
 
 
 
 
 
 
3ade60b
8d37e4c
 
 
 
 
 
 
3ade60b
8d37e4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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!")