Surgery on the weights #
What is new: operations on a model's weights (transplant, revert, ablate, edit rows, subtract a delta) run as Set → Lock → Reflect → Pop:
- Set: the operation is frozen as a record before anything runs.
- Lock: its sources are re-verified and its targets checked; a bad request is refused before a single byte is written.
- Reflect: the alternatives you considered are kept beside it.
- Pop: it is applied to a new child checkpoint, never in place, with the exact inverse stored and a new badge that names its parent.
Why it matters: "we fixed the bad layers" becomes checkable. The child's badge differs from the parent's in exactly the tensors you named, the inverse brings the parent back byte for byte, and the record says what was done, why, and what else was on the table.
Two models: one clean, one to repair #
import numpy as np
from pathlib import Path
from tensorchain.weights import delta as D, safetensors as ST, store as S, surgery as SG
from tensorchain.workspace import Workspace
def bf16(values):
return D.encode(np.asarray(values, dtype=np.float32), "BF16")
def model(d, salt):
d.mkdir(parents=True)
rng = np.random.default_rng(salt)
ST.make(d / "model.safetensors", [
("layers.0.w", "BF16", [8, 4], bf16(rng.normal(size=32))),
("layers.1.w", "BF16", [8, 4], bf16(rng.normal(size=32))),
("norm", "F32", [4], rng.normal(size=4).astype("<f4").tobytes())])
(d / "config.json").write_text('{"h": 4}')
return d
ws = Workspace("ws.sqlite", actor="docs").__enter__()
clean = S.put_checkpoint(ws, model(Path("clean"), 1))
dirty = S.put_checkpoint(ws, model(Path("dirty"), 2))
raw = lambda ck, name: S.recall_tensor(ws, S.checkpoint_info(ws, ck)["tensors"][name])
print("clean", clean[:16], "dirty", dirty[:16])
assert raw(clean, "layers.1.w") != raw(dirty, "layers.1.w")
clean e3a9c73435071956 dirty 5861411d9317a5cd
Transplant one layer, keep the inverse #
Replace layers.1.w in the dirty model with the clean model's, and record that ablating it was the road not taken.
sg = SG.Surgery(ws)
r = sg.run({"op": "transplant", "base": dirty, "from": clean, "tensors": ["layers.1.w"], "reason": "the bad layer",
"alternatives": [{"op": "ablate", "tensor": "layers.1.w", "rows": [0, 8]}]})
print("changed:", r["changed"], "exact:", r["exact"], "badge parents:", [p[:16] for p in r["badge"]["parents"]])
assert raw(r["child"], "layers.1.w") == raw(clean, "layers.1.w") # the transplanted layer is the clean one
assert raw(r["child"], "layers.0.w") == raw(dirty, "layers.0.w") # nothing else moved
assert r["changed"] == [["layers.1.w", "all"]] and r["badge"]["parents"] == [dirty]
child_t = S.checkpoint_info(ws, r["child"])["tensors"]["layers.1.w"]
assert SG.apply_inverse(ws, child_t, r["inverse"]["layers.1.w"]) == raw(dirty, "layers.1.w") # undo, byte for byte
changed: [['layers.1.w', 'all']] exact: True badge parents: ['5861411d9317a5cd']
The child's badge differs from its parent's in exactly one tensor:
before = {k: h for k, h, _ in SG.badge_items(ws, dirty)}
after = {k: h for k, h, _ in SG.badge_items(ws, r["child"])}
print("badge items that changed:", [k for k in after if after[k] != before[k]])
assert [k for k in after if after[k] != before[k]] == ["tensor:layers.1.w"]
badge items that changed: ['tensor:layers.1.w']
Rows, and a refusal before any write #
Ablate two rows of one tensor, and only those bytes change. Then try to overwrite a protected tensor: the Lock refuses it. Nothing is written except the frozen request itself (the Set), which keeps the refused road on record.
import sqlite3
a = sg.run({"op": "ablate", "base": dirty, "tensor": "layers.0.w", "rows": [3, 5]})
old, new = raw(dirty, "layers.0.w"), raw(a["child"], "layers.0.w")
row = len(old) // 8
diff = [i for i in range(len(old)) if old[i] != new[i]]
print("bytes changed: %d, all inside rows 3-4" % len(diff))
assert diff and min(diff) >= 3 * row and max(diff) < 5 * row and new[3 * row:5 * row] == bytes(2 * row)
count = lambda: sqlite3.connect("ws.sqlite").execute("SELECT COUNT(*) FROM tc_object").fetchone()[0]
n0 = count()
try:
sg.run({"op": "transplant", "base": dirty, "from": clean, "tensors": ["norm"], "protected": ["norm"]})
code = None
except SG.SurgeryRefused as e:
code = e.code
print("refused:", code, "; objects written:", count() - n0, "(the frozen request)")
assert code == "protected_tensor:norm" and count() <= n0 + 1
bytes changed: 16, all inside rows 3-4 refused: protected_tensor:norm ; objects written: 1 (the frozen request)
The child is a model you can load #
S.recall_checkpoint(ws, r["child"], Path("out"))
h = ST.read_header(Path("out") / "model.safetensors")
assert ST.read_tensor(Path("out") / "model.safetensors", h, "layers.1.w") == raw(clean, "layers.1.w")
print("out/model.safetensors written; layers.1.w equals the clean model's")
ws.__exit__(None, None, None)
out/model.safetensors written; layers.1.w equals the clean model's
What it does not do #
- Subtracting a delta is not exact. It is rounded to the tensor's dtype, and its record says
exact: false. - Surgery is only as good as the target. Naming the right tensors (from a badge comparison or a probe) is the hard part; surgery makes the change exact and reversible.
Next: was it really the badged model? checks a live deployment's answers against the badged weights.