#!/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 """ 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()