#!/usr/bin/env python """Cast an fp32 HF checkpoint to bf16, one safetensors shard at a time (low memory). Reads SRC (read-only), writes a bf16 copy to DST. Copies config (torch_dtype patched to bfloat16), tokenizer, generation_config, and the weight index (total_size updated). Originals are never modified. """ import json, os, shutil, sys import torch from safetensors.torch import load_file, save_file SRC, DST = sys.argv[1], sys.argv[2] os.makedirs(DST, exist_ok=True) idx_path = os.path.join(SRC, "model.safetensors.index.json") with open(idx_path) as f: index = json.load(f) shards = sorted(set(index["weight_map"].values())) total = 0 for shard in shards: sd = load_file(os.path.join(SRC, shard)) out = {} for k, v in sd.items(): out[k] = v.to(torch.bfloat16) if v.is_floating_point() else v total += out[k].numel() * out[k].element_size() save_file(out, os.path.join(DST, shard), metadata={"format": "pt"}) print(f" cast {shard}: {len(out)} tensors") del sd, out # index with updated total_size index["metadata"] = index.get("metadata", {}) index["metadata"]["total_size"] = total with open(os.path.join(DST, "model.safetensors.index.json"), "w") as f: json.dump(index, f, indent=2) # config.json with torch_dtype patched with open(os.path.join(SRC, "config.json")) as f: cfg = json.load(f) cfg["torch_dtype"] = "bfloat16" with open(os.path.join(DST, "config.json"), "w") as f: json.dump(cfg, f, indent=2) # copy aux files verbatim for fn in ("generation_config.json", "tokenizer.json", "tokenizer_config.json", "vocab.json", "merges.txt", "special_tokens_map.json", "added_tokens.json", "chat_template.jinja", "tokenizer.model"): s = os.path.join(SRC, fn) if os.path.isfile(s): shutil.copy2(s, os.path.join(DST, fn)) print(f"done: {DST} (~{total/1e9:.1f} GB bf16)")