File size: 1,496 Bytes
9834d1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Put back source tensors whose dtype a ModelOpt export changed (GDN A_log / dt_bias FP32 -> BF16).

Only non-quantized tensors that exist in both checkpoints with equal shape are touched; they are
replaced by the exact source bytes. Usage: restore_fp32_modelopt.py <src_dir> <modelopt_dir>
"""
import glob
import os
import sys

from safetensors import safe_open
from safetensors.torch import save_file


def main() -> None:
    src, q = sys.argv[1:3]
    path = os.path.join(q, "model.safetensors")
    with safe_open(path, "pt") as f:
        meta = f.metadata()
        tensors = {k: f.get_tensor(k) for k in f.keys()}
    # never touch quantized modules (NVFP4 or FP8 weights can share the source shape)
    quant = {k.rsplit(".", 1)[0] for k in tensors if k.endswith((".weight_scale", ".input_scale"))}
    fixed = []
    for sf in glob.glob(os.path.join(src, "model-*.safetensors")):
        with safe_open(sf, "pt") as f:
            for k in f.keys():
                b = tensors.get(k)
                if b is not None and k.rsplit(".", 1)[0] not in quant:
                    a = f.get_tensor(k)
                    if a.shape == b.shape and a.dtype != b.dtype:
                        tensors[k] = a
                        fixed.append(k)
    print("restored", len(fixed), "tensors, e.g.", fixed[:3])
    if fixed:
        tmp = path + ".tmp"
        save_file(tensors, tmp, metadata=meta)
        os.replace(tmp, path)


if __name__ == "__main__":
    main()