yasserrmd's picture
WSP 2.0 sparse weight edit: strict-JSON fence repair (32,768 BF16 values, 16 w2 columns)
1a2bb00 verified
Raw History Blame Contribute Delete
2.1 kB
"""Deterministic apply/revert of a WSP sparse patch to a native safetensors checkpoint (no training, no grad).
Usage:
python src/apply_patch.py --base <snapshot_dir> --patch patches/chosen_patch.safetensors --manifest patches/chosen_patch.json --out <out_dir>
python src/apply_patch.py --base <edited_dir> --patch ... --manifest ... --out <restored_dir> --revert
Never writes into --base."""
import argparse, os, shutil, json, hashlib, torch
from safetensors.torch import load_file, save_file
import sys; sys.path.insert(0, os.path.dirname(__file__))
import wsp_patch as WP
def apply_to_state(sd, patch, reverse=False):
n = 0
for name, t in patch["tensors"].items():
flat = sd[name].view(-1)
expect = t["new"] if reverse else t["orig"]
if not torch.equal(flat[t["idx"]].view(torch.int16), expect.view(torch.int16)):
raise ValueError(f"precondition failed for {name}: coordinates are not in the expected {'edited' if reverse else 'original'} state")
flat[t["idx"]] = t["orig"] if reverse else t["new"]; n += t["idx"].numel()
return n
def main():
ap = argparse.ArgumentParser(); ap.add_argument("--base", required=True); ap.add_argument("--patch", required=True)
ap.add_argument("--manifest", required=True); ap.add_argument("--out", required=True); ap.add_argument("--revert", action="store_true")
a = ap.parse_args()
assert os.path.realpath(a.out) != os.path.realpath(a.base), "refusing to overwrite base"
patch = WP.load(a.patch, a.manifest)
os.makedirs(a.out, exist_ok=True)
for fn in os.listdir(a.base):
p = os.path.join(a.base, fn)
if os.path.isfile(p) and not fn.endswith(".safetensors"): shutil.copy(p, os.path.join(a.out, fn))
sd = load_file(os.path.join(a.base, "model.safetensors"))
n = apply_to_state(sd, patch, reverse=a.revert)
save_file({k: v.contiguous() for k, v in sd.items()}, os.path.join(a.out, "model.safetensors"), metadata={"format": "pt"})
print(json.dumps({"written": a.out, "coordinates": n, "revert": a.revert}))
if __name__ == "__main__": main()