"""Put fine-tuned weights back into the released checkpoint's own format. The trainer's tool writes a merged model with the routed experts in 16-bit. The serving engine on this GPU family takes the experts only as released (4-bit NVFP4 and 8-bit MXFP8, declared per tensor in hf_quant_config.json), so that merged folder cannot be served. The fine-tune here changes attention weights only, so the fix is exact: take the released checkpoint and replace just the tensors the fine-tune changed. Everything else, the experts and their quantization included, stays byte for byte as released. python train/graft.py map --stock --identity --out map.json python train/graft.py apply --stock --identity --merged --map map.json --lora --out `map` finds which released tensor is which merged tensor by content: a merge of untrained adapters changes nothing, so equal shape and equal bytes identify a pair. `apply` refuses to go on if the fine-tune changed a tensor that has no released counterpart (an expert, for one): nothing is then written. """ import argparse import glob import hashlib import json import os import shutil import sys import torch from safetensors import safe_open from safetensors.torch import save_file def digest(t): t = t.contiguous() raw = t.view(torch.uint8) if t.dtype == torch.uint8 else t.view(-1).view(torch.int16 if t.element_size() == 2 else torch.int32 if t.element_size() == 4 else torch.int8 if t.element_size() == 1 else torch.int64) return hashlib.sha1(raw.numpy().tobytes()).hexdigest() def tensors(folder, pattern="model*.safetensors"): for f in sorted(glob.glob(os.path.join(folder, pattern))): with safe_open(f, framework="pt") as sf: for k in sf.keys(): yield f, k, sf.get_tensor(k) def cmd_map(a): by = {} n_id = 0 for _f, k, t in tensors(a.identity): n_id += 1 by.setdefault((tuple(t.shape), str(t.dtype), digest(t)), []).append(k) mapping, unmatched, ambiguous = {}, [], 0 used = set() n_stock = 0 for _f, k, t in tensors(a.stock): n_stock += 1 cands = [c for c in by.get((tuple(t.shape), str(t.dtype), digest(t)), []) if c not in used] if not cands: unmatched.append([k, list(t.shape), str(t.dtype)]) continue if len(cands) > 1: ambiguous += 1 tail = k.split(".")[-2:] cands.sort(key=lambda c: (c.split(".")[-2:] != tail, c)) mapping[k] = cands[0] used.add(cands[0]) json.dump({"stock_tensors": n_stock, "identity_tensors": n_id, "matched": len(mapping), "ambiguous_by_content": ambiguous, "unmatched_stock": unmatched, "map": mapping}, open(a.out, "w"), indent=1) kinds = sorted({".".join(k[0].split(".")[-2:]) for k in unmatched}) print(json.dumps({"stock_tensors": n_stock, "identity_tensors": n_id, "matched": len(mapping), "ambiguous_by_content": ambiguous, "unmatched_stock": len(unmatched), "unmatched_kinds": kinds[:20]})) def cmd_apply(a): m = json.load(open(a.map))["map"] back = {v: k for k, v in m.items()} ident = {k: (tuple(t.shape), digest(t)) for _f, k, t in tensors(a.identity)} changed = {} for _f, k, t in tensors(a.merged): if k not in ident: sys.exit(f"REFUSED: the fine-tuned merge has a tensor the untrained merge does not: {k}") if ident[k] != (tuple(t.shape), digest(t)): changed[k] = t no_home = sorted(k for k in changed if k not in back) if no_home and a.lora: # The merge writes the experts dequantized, and two merges need not round them alike. That is no change of # the model if the adapters hold no expert weight: read the adapter file itself to know. import re trained = [] for f in glob.glob(os.path.join(a.lora, "*.safetensors")): with safe_open(f, framework="pt") as sf: trained += list(sf.keys()) if not trained: sys.exit(f"REFUSED: no adapter weights found in {a.lora}. Nothing written.") on_experts = sorted(k for k in trained if ".self_attn." not in k) # every adapter weight must sit on an attention module if on_experts: sys.exit(f"REFUSED: {len(on_experts)} adapter weights are not on attention modules (first: {on_experts[:3]}). Nothing written.") ignored = [k for k in no_home if re.search(r"\.experts\.w(?:13|2)_weight$", k)] no_home = [k for k in no_home if k not in ignored] for k in ignored: changed.pop(k) print(json.dumps({"adapter_tensors": len(trained), "adapter_tensors_on_experts": 0, "expert_tensors_left_as_released": len(ignored)})) if no_home: sys.exit(f"REFUSED: {len(no_home)} changed tensors have no released counterpart (first: {no_home[:5]}). Nothing written.") os.makedirs(a.out, exist_ok=True) files = sorted(glob.glob(os.path.join(a.stock, "model*.safetensors"))) report = {"changed_tensors": len(changed), "changed": {}} for f in files: out, meta = {}, None with safe_open(f, framework="pt") as sf: meta = sf.metadata() for k in sf.keys(): t = sf.get_tensor(k) mk = m.get(k) if mk in changed: new = changed[mk] if tuple(new.shape) != tuple(t.shape) or new.dtype != t.dtype: sys.exit(f"REFUSED: {k}: released {tuple(t.shape)} {t.dtype}, fine-tuned {tuple(new.shape)} {new.dtype}") d = (new.float() - t.float()).abs() report["changed"][k] = {"merged_name": mk, "shape": list(t.shape), "max_abs_change": float(d.max()), "mean_abs_change": float(d.mean())} t = new out[k] = t save_file(out, os.path.join(a.out, os.path.basename(f)), metadata=meta) for f in os.listdir(a.stock): src = os.path.join(a.stock, f) if f.startswith("model") and f.endswith(".safetensors") or f in ("README.md", ".gitattributes") or f.startswith("."): continue dst = os.path.join(a.out, f) if os.path.isdir(src): shutil.copytree(src, dst, dirs_exist_ok=True) else: shutil.copy(src, dst) report["files"] = {f: os.path.getsize(os.path.join(a.out, f)) for f in sorted(os.listdir(a.out)) if os.path.isfile(os.path.join(a.out, f))} json.dump(report, open(os.path.join(a.out, "graft_report.json"), "w"), indent=1) print(json.dumps({"changed_tensors": len(changed), "gb": round(sum(report["files"].values()) / 1e9, 2), "largest_change": max((v["max_abs_change"] for v in report["changed"].values()), default=0.0)})) def main(): ap = argparse.ArgumentParser() sub = ap.add_subparsers(dest="cmd", required=True) p = sub.add_parser("map") p.add_argument("--stock", required=True) p.add_argument("--identity", required=True) p.add_argument("--out", required=True) q = sub.add_parser("apply") for x in ("--stock", "--identity", "--merged", "--map", "--out"): q.add_argument(x, required=True) q.add_argument("--lora", default="", help="the adapter folder: lets the tool confirm that no expert weight was trained") a = ap.parse_args() cmd_map(a) if a.cmd == "map" else cmd_apply(a) if __name__ == "__main__": main()