File size: 2,153 Bytes
baa0a0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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())