P-Q-Image-2.1-DWD / scripts /export_weights.py
johnrachwanpruna's picture
Release P-Q-Image-2.1-Turbo-DWD
baa0a0e verified
Raw History Blame Contribute Delete
2.15 kB
#!/usr/bin/env python
"""Re-write a DWD tail file in the release layout: unused tensors dropped, Linear weights bf16 (or fp32 with
--fp32), the attention RMSNorm weights fp32, metadata the pipeline checks on load. Verifies the result against the
source and prints its sha256.
python scripts/export_weights.py --src tail_fp32.safetensors --out dwd_tail.safetensors
"""
import argparse
import hashlib
import json
import os
import sys
import torch
try:
from pq_image_dwd.weights import export_tail, load_tail_file
except ImportError: # running from a source checkout without installing the package
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src"))
from pq_image_dwd.weights import export_tail, load_tail_file
def sha256(path: str) -> str:
h = hashlib.sha256()
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(1 << 24), b""):
h.update(chunk)
return h.hexdigest()
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--src", required=True, help="tail file to convert")
ap.add_argument("--out", required=True, help="output .safetensors")
ap.add_argument("--fp32", action="store_true", help="keep the Linear weights in fp32")
a = ap.parse_args(argv)
dtype = torch.float32 if a.fp32 else torch.bfloat16
meta = export_tail(a.src, a.out, dtype=dtype)
src, _ = load_tail_file(a.src)
out, _ = load_tail_file(a.out)
if set(src) != set(out):
raise SystemExit("tensor names differ between source and output")
for k, v in src.items():
want = v.float() if k.endswith(("norm_q.weight", "norm_k.weight")) else v.to(dtype)
if not torch.equal(out[k], want):
raise SystemExit(f"tensor {k} differs from the source")
info = {"path": os.path.basename(a.out), "sha256": sha256(a.out), "bytes": os.path.getsize(a.out),
"n_tensors": len(out), "n_params": int(sum(v.numel() for v in out.values())), "metadata": meta}
print(json.dumps(info, indent=1))
return 0
if __name__ == "__main__":
sys.exit(main())