#!/usr/bin/env python3
"""Train a donor, release its example geometry, and edit a fresh Pythia recipient on CPU.

Install PyTorch CPU, transformers==4.55.4, huggingface-hub>=0.34,<1 and safetensors>=0.5,<1.
Run python geometry_lab.py --help for the stages. The model files stay local after download.
"""
import argparse
import gc
import hashlib
import json
import math
import os
import random
import shutil
import subprocess
import sys
import tempfile
from collections import defaultdict
from pathlib import Path

MODEL = "EleutherAI/pythia-70m-deduped"
REV = "c92722694b14c67e3f8ed3bf164bb2456449e720"
WEIGHTS_SHA = "3da388330e4549156d76b58d6d268c63cd005e9336b4f4d2d378421e7b7a33fd"
CHECKPOINTS = {
    "70m": {"model": MODEL, "revision": REV, "sha256": WEIGHTS_SHA, "width": 512, "depth": 6, "heads": 8},
    "160m": {"model": "EleutherAI/pythia-160m-deduped", "revision": "582159a2dfe3e712a8d47ae83dec95ae3bde8e7e",
             "sha256": "bbaae5c00917b163baa499fc8eb64859ee0c850c5fdecfc32f4d70dc07213575",
             "width": 768, "depth": 12, "heads": 12},
}
FILES = ("config.json", "tokenizer.json", "tokenizer_config.json", "special_tokens_map.json", "model.safetensors")
CODES = (" A", " B")
SEEN = "oak elm ash pine fir birch cedar maple palm yew beech spruce".split()
NOVEL = "tin zinc iron lead gold brass steel copper".split()
TRAIN = ("Mark one {a}. Mark two {b}. Code:", "Slip: {a} / {b}. Code:",
         "Read the marks {a} and {b}. Code:", "First {a}, then {b}. Code:")
DEV = ("Examine the marks [{a}] [{b}]. Code:",)
PROBES = ("Tokens on the card: {a} | {b}. Code:", "Mark I is {a}; mark II is {b}. Code:",
          "Symbols received: {a}, {b}. Code:")
TEST = ("Two marks are printed: {a} alongside {b}. Code:", "This slip reads ({a}) followed by ({b}). Code:")
FIT_NEUTRAL = ("A warm loaf of", "A purple flower in the", "The planet has a", "The chapter begins with",
               "They walked across the", "A small music box", "Look at the clock", "Please pass the book")
CHECK_NEUTRAL = ("The capital of France is", "Salt dissolves in", "The opposite of up is", "The sun rises in the",
                 "A triangle has three", "The color of grass is", "The river flows through", "Ice melts into",
                 "Birds build their", "The baker makes fresh", "The teacher wrote on the", "A violin has")
PACKET_VERSION = "paired-activation-gram/1"
VIEW_VERSION = "weight-geometry-lab/a9-v1"


def stable_id(s):
    return hashlib.sha256(s.encode("utf-8")).hexdigest()[:20]


def immutable_json(path, item):
    """Publish a complete new file; a repeat run chooses a fresh output directory."""
    path.parent.mkdir(parents=True, exist_ok=True)
    if path.exists():
        raise FileExistsError(f"Output exists: {path}. Use a fresh --out directory.")
    data = json.dumps(item, allow_nan=False, ensure_ascii=False, separators=(",", ":"))
    # Creating the completed hard link is atomic and cannot replace an existing file.
    with tempfile.NamedTemporaryFile("w", dir=path.parent, encoding="utf-8", delete=False) as tmp:
        tmp.write(data)
        name = Path(tmp.name)
    try:
        os.link(name, path)
    finally:
        name.unlink(missing_ok=True)


def file_hash(path):
    with path.open("rb") as src:
        return hashlib.file_digest(src, "sha256").hexdigest()


def tensor_hash(t):
    return hashlib.sha256(t.detach().cpu().contiguous().numpy().tobytes()).hexdigest()


def data_split(templates, words, seed, split):
    """Each pair changes the second mark. Both paraphrases describe the same ordered marks."""
    rng = random.Random(seed)
    jump = rng.randrange(1, len(words))
    shift = rng.randrange(len(words))
    examples = []
    for i, left in enumerate(words):
        other = words[(i + jump) % len(words)]
        for form, template in enumerate(templates):
            # Changing neighbors across donor templates broadens training. Evaluation
            # keeps the pair fixed across its two paraphrases.
            if split == "train":
                other = words[(i + 1 + ((shift + form * 3 + i) % (len(words)-1))) % len(words)]
            pair = stable_id(f"{split}-{left}-{other}-{form}")
            for right in (left, other):
                plain = template.format(a=left, b=right)
                examples.append(dict(id=stable_id(plain), prompt=plain, pair=pair,
                    paraphrase=stable_id(f"{split}-{left}-{right}"), label=int(left == right)))
    rng.shuffle(examples)
    return examples


def make_data(seed):
    s = {"train": data_split(TRAIN, SEEN, seed+1, "train"),
         "dev": data_split(DEV, SEEN, seed+2, "dev"),
         "fit": data_split(PROBES, SEEN, seed+3, "fit"),
         "primary": data_split(TEST, SEEN, seed+4, "primary"),
         "novel": data_split(TEST, NOVEL, seed+5, "novel")}
    keys = [r["id"] for group in s.values() for r in group]
    if len(keys) != len(set(keys)):
        raise ValueError("Repeated prompt across splits")
    return s


def verify_weights(path, spec):
    target = path / "model.safetensors"
    if not target.is_file() or file_hash(target) != spec["sha256"]:
        raise ValueError(f"Base weights do not match {spec['model']}@{spec['revision']} in {path}.")


def resolve_base(path, size="70m"):
    """Verify the selected official tensor bytes and the companion files needed offline."""
    spec = CHECKPOINTS[size]
    verify_weights(path, spec)
    data = {}
    for name in FILES:
        if name.endswith(".json"):
            try:
                with (path / name).open(encoding="utf-8") as stream:
                    data[name] = json.load(stream)
            except (OSError, ValueError) as error:
                raise ValueError(f"Missing or invalid {name} in {path}. Run the download stage.") from error
            if not isinstance(data[name], dict) or not data[name]:
                raise ValueError(f"Invalid {name} in {path}")
    expected = {"model_type": "gpt_neox", "hidden_size": spec["width"],
                "num_hidden_layers": spec["depth"], "num_attention_heads": spec["heads"],
                "intermediate_size": 4*spec["width"], "vocab_size": 50304, "tie_word_embeddings": False}
    if any(data["config.json"].get(key) != value for key, value in expected.items()):
        raise ValueError(f"Configuration in {path} does not match {spec['model']}.")
    tokenizer = data["tokenizer.json"].get("model", {})
    if tokenizer.get("type") != "BPE" or not tokenizer.get("vocab") or not tokenizer.get("merges"):
        raise ValueError(f"Incomplete Pythia tokenizer in {path}.")
    return path


def donor_location(args):
    size = getattr(args, "donor_size", "70m")
    path = getattr(args, "donor_model", None)
    if path is None:
        path = args.model if size == "70m" else args.model.parent / "pythia160m-base"
    if size != "70m" and path.resolve() == args.model.resolve():
        raise ValueError("Choose separate folders for the 160M donor and 70M recipient.")
    return size, path


def download_checkpoint(path, size):
    spec = CHECKPOINTS[size]
    if path.exists() and not path.is_dir():
        raise ValueError(f"Use a model directory, not a file: {path}")
    if not all((path / name).is_file() for name in FILES):
        # Recover a partial download without overwriting an unrelated checkpoint.
        if (path / "model.safetensors").exists():
            verify_weights(path, spec)
        from huggingface_hub import snapshot_download
        snapshot_download(repo_id=spec["model"], revision=spec["revision"],
                          allow_patterns=list(FILES), local_dir=str(path))
    resolve_base(path, size)
    print(f"Verified {spec['model']}@{spec['revision']} in {path}", flush=True)


def load_local(path):
    from transformers import AutoModelForCausalLM, AutoTokenizer
    tok = AutoTokenizer.from_pretrained(str(path), local_files_only=True)
    tok.padding_side = "right"
    if tok.pad_token_id is None:
        tok.pad_token = tok.eos_token
    model = AutoModelForCausalLM.from_pretrained(str(path), torch_dtype=T.float32,
        local_files_only=True, use_safetensors=True, attn_implementation="eager").cpu().eval()
    if model.config.model_type != "gpt_neox":
        raise ValueError("This executable adapter implements GPT-NeoX")
    ids = [tok.encode(x, add_special_tokens=False) for x in CODES]
    if any(len(x) != 1 for x in ids) or ids[0] == ids[1]:
        raise ValueError(f"The answer codes must be two distinct individual tokens: {ids}")
    return model, tok, [x[0] for x in ids]


def batches(xs, size):
    for j in range(0, len(xs), size):
        yield xs[j:j+size]


def encode(tok, prompts):
    encoded = tok(prompts, return_tensors="pt", padding=True, add_special_tokens=False)
    mask = encoded.attention_mask
    return encoded.input_ids, mask, mask.sum(-1).long()-1


def last_values(x, positions):
    return x[T.arange(positions.numel()), positions]


def last_hidden(model, tok, prompts):
    ids, mask, pos = encode(tok, prompts)
    enc = model.gpt_neox(input_ids=ids, attention_mask=mask, use_cache=False, return_dict=True)
    return last_values(enc.last_hidden_state, pos), pos


def inspect_prompts(model, tok, codes, prompts, layer, batch, capture=False, full=False):
    """Use last non-padding prompt tokens, before any answer has been fed back."""
    block = model.gpt_neox.layers[layer]
    cache = {}
    hooks = []
    if capture:
        hooks.append(block.mlp.dense_4h_to_h.register_forward_pre_hook(
            lambda module, inputs: cache.update(x=inputs[0])))
        def save_state(module, inputs, output):
            cache["h"] = output[0] if isinstance(output, (tuple, list)) else output
        hooks.append(block.register_forward_hook(save_state))
    accum = defaultdict(list)
    try:
        with T.inference_mode():
            for part in batches(prompts, batch):
                h, pos = last_hidden(model, tok, part)
                logits = model.embed_out(h)
                accum["two"].append(logits[:, codes].clone())
                accum["top"].append(logits.argmax(-1))
                if full:
                    accum["prob"].append(logits.softmax(-1))
                if capture:
                    for name in ("x", "h"):
                        accum[name].append(last_values(cache[name], pos).clone())
    finally:
        for hook in hooks:
            hook.remove()
    return {k:T.cat(v) for k, v in accum.items()}


def probe_layout(rows, seed):
    by_pair = defaultdict(list)
    for i, r in enumerate(rows):
        by_pair[r["pair"]].append(i)
    pairs = list(by_pair.values())
    if not all(len(p) == 2 for p in pairs):
        raise ValueError("Malformed contrast pairs")
    # The two selected pairs, their items and all nonanchor pair members have randomized order.
    anchors = random.Random(seed+333).sample(pairs, 2)
    return [sorted(p, key=lambda i:rows[i]["id"]) for p in pairs], [i for p in anchors for i in p]


def masked_packet(rows, reps, seed):
    """Pair-centering cancels the shared prompt context. Store only unit-vector inner products."""
    pairs, anchors = probe_layout(rows,seed)
    return {"schema":PACKET_VERSION, "seed":seed,
            "items":[{"id":r["id"], "prompt":r["prompt"]} for r in rows], "pairs":pairs,
            "anchors":[{"id":rows[i]["id"], "label":rows[i]["label"]} for i in anchors],
            "gram":pair_gram(reps,pairs)}


def pair_gram(reps, pairs):
    centered = T.zeros_like(reps)
    for a, b in pairs:
        centered[a] = (reps[a] - reps[b]) * .5
        centered[b] = -centered[a]
    z = T.nn.functional.normalize(centered.double(), dim=1)
    return (z @ z.T).clamp(-1,1).float().tolist()


def coordinate(packet):
    ids = [r["id"] for r in packet["items"]]
    if packet["schema"] != PACKET_VERSION or len(set(ids)) != len(ids):
        raise ValueError("Invalid geometry packet")
    G = T.tensor(packet["gram"], dtype=T.float64)
    if G.shape != (len(ids), len(ids)) or not T.isfinite(G).all() or not T.allclose(G, G.T, atol=1e-5):
        raise ValueError("Invalid Gram matrix")
    if sorted(i for pair in packet["pairs"] for i in pair) != list(range(len(ids))):
        raise ValueError("Each prompt must have exactly one paired contrast")
    a = packet["anchors"]
    if len(a) != 4 or len({r["id"] for r in a}) != 4:
        raise ValueError("Four different orientation anchors are required")
    indices = [[ids.index(r["id"]) for r in a if r["label"] == lab] for lab in (0,1)]
    if any(len(group)!=2 for group in indices):
        raise ValueError("The anchors must contain two examples per answer code")
    raw = (G[:,indices[1]].mean(1) - G[:,indices[0]].mean(1)) / 2
    contrast = raw[indices[1]].mean() - raw[indices[0]].mean()
    if contrast <= 1.e-10:
        return T.zeros_like(raw).float()
    midpoint = (raw[indices[1]].mean() + raw[indices[0]].mean()) / 2
    return (((raw-midpoint)*2/contrast).clamp(-3,3)).float()

def emit(args, stage, kind, message, **values):
    print("GEOLAB_EVENT " + json.dumps(dict(stage=stage, kind=kind, message=message,
          seed=args.seed, **values), separators=(",", ":"), allow_nan=False), flush=True)


def task_score(model, tok, codes, rows, layer, batch):
    values = inspect_prompts(model, tok, codes, [r["prompt"] for r in rows], layer, batch)
    margins = (values["two"][:,1] - values["two"][:,0]).tolist()
    rows_out, by_pair, by_surface = [], defaultdict(list), defaultdict(list)
    for r, margin, top in zip(rows, margins, values["top"].tolist()):
        correct = int(margin > 0) == r["label"]  # deterministic argmax, ties choose A
        by_pair[r["pair"]].append(correct)
        by_surface[r["paraphrase"]].append(correct)
        rows_out.append(dict(id=r["id"], margin=margin, correct=correct, greedy=top==codes[r["label"]]))
    return ({"n":len(rows), "accuracy":sum(v["correct"] for v in rows_out)/len(rows),
             "pairs":len(by_pair), "pair_both":sum(all(v) for v in by_pair.values())/len(by_pair),
             "paraphrase_both":sum(all(v) for v in by_surface.values())/len(by_surface),
             "greedy_accuracy":sum(v["greedy"] for v in rows_out)/len(rows)}, rows_out)


def donor_frame(args, model, tok, codes, rows, step, epoch, layer=None):
    """The same eight contrast pairs and same four orientation anchors appear in every frame."""
    pairs, anchor_indices = probe_layout(rows,args.seed)
    anchored = set(anchor_indices)
    preview_pairs = [p for p in pairs if p[0] in anchored]
    others = [p for p in pairs if p[0] not in anchored]
    preview_pairs += random.Random(args.seed+838).sample(others,6)
    chosen = sorted(i for pair in preview_pairs for i in pair)
    remap = {global_i:local_i for local_i,global_i in enumerate(chosen)}
    pairs = [[remap[i] for i in pair] for pair in preview_pairs]
    items = [{"id":rows[i]["id"],"prompt":rows[i]["prompt"]} for i in chosen]
    h = inspect_prompts(model,tok,codes,[r["prompt"] for r in items],
                        args.layer if layer is None else layer,args.batch,capture=True)["h"]
    gram = pair_gram(h,pairs)
    mini = {"schema":PACKET_VERSION,"items":items,"pairs":pairs,"gram":gram,
            "anchors":[{"id":rows[i]["id"],"label":rows[i]["label"]} for i in anchor_indices]}
    coord = coordinate(mini).tolist()
    spectrum = T.linalg.eigvalsh(T.tensor(gram,dtype=T.float64))
    top_fraction = float(spectrum[-1]/spectrum.sum().clamp_min(1.e-10))
    frame = dict(step=step,epoch=epoch,items=len(items),anchors=len(anchored),
                 top_eigen_fraction=top_fraction,
                 points=[dict(id=r["id"],anchor=chosen[i] in anchored,donor_coordinate=coord[i])
                         for i,r in enumerate(items)])
    emit(args,"donor","geometry_frame","Measured the same sixteen prompts inside the donor",**frame)
    return frame


def donor(args):
    size, donor_dir = donor_location(args)
    spec = CHECKPOINTS[size]
    path = resolve_base(donor_dir, size)
    if any((args.out/n).exists() for n in ("geometry.json", "donor.json")):
        raise FileExistsError("Donor output exists. Choose a fresh --out directory.")
    model, tok, codes = load_local(path)
    splits = make_data(args.seed)
    layer = 8 if size == "160m" else args.layer
    emit(args, "donor", "start", "Training the donor with next-token cross-entropy",
         examples=len(splits["train"]), layer=layer, model=spec["model"], revision=spec["revision"],
         hidden_size=spec["width"], donor_size=size)
    optimizer = T.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=.01)
    rng = random.Random(args.seed)
    step, history = 0, []
    frames = [donor_frame(args,model,tok,codes,splits["fit"],step=0,epoch=0,layer=layer)]
    for epoch in range(1, args.epochs+1):
        model.train()
        train = list(splits["train"])
        rng.shuffle(train)
        total, count = 0., 0
        for part in batches(train, args.batch):
            optimizer.zero_grad(set_to_none=True)
            hidden, _ = last_hidden(model, tok, [r["prompt"] for r in part])
            ys = T.tensor([codes[r["label"]] for r in part], dtype=T.long)
            loss = T.nn.functional.cross_entropy(model.embed_out(hidden), ys)
            if not T.isfinite(loss):
                raise FloatingPointError("Nonfinite donor loss")
            loss.backward()
            T.nn.utils.clip_grad_norm_(model.parameters(), 1.)
            optimizer.step()
            step += 1
            total += loss.item()*len(part)
            count += len(part)
            if step == 1 or step % 10 == 0:
                emit(args, "donor", "train", "Donor optimization", step=step, loss=loss.item())
        model.eval()
        dev, _ = task_score(model, tok, codes, splits["dev"], layer, args.batch)
        history.append({"epoch":epoch,"step":step,"training_loss":total/count,"dev":dev})
        emit(args, "donor", "validation", "Fresh wording in the development set",
             step=step, epoch=epoch, accuracy=dev["accuracy"], pair_both=dev["pair_both"])
        frames.append(donor_frame(args,model,tok,codes,splits["fit"],step,epoch,layer=layer))
        if dev["pair_both"] >= .90:
            break
    del optimizer
    model.eval()
    primary, _ = task_score(model, tok, codes, splits["primary"], layer, args.batch)
    novel, _ = task_score(model, tok, codes, splits["novel"], layer, args.batch)
    rows = splits["fit"]
    hidden = inspect_prompts(model, tok, codes, [r["prompt"] for r in rows], layer, args.batch, capture=True)["h"]
    packet = masked_packet(rows, hidden, args.seed)
    coords = coordinate(packet).tolist()
    anchors = {a["id"] for a in packet["anchors"]}
    packet_path = args.out/"geometry.json"
    immutable_json(packet_path, packet)
    immutable_json(args.out/"donor.json", {"seed":args.seed,"model":spec["model"],"revision":spec["revision"],"layer":layer,
                         "size":size,"hidden_size":spec["width"],"base_weights_sha256":spec["sha256"],
                         "packet_sha256":file_hash(packet_path),
                         "primary":primary,"novel":novel,"history":history,"geometry_frames":frames,"training_examples":len(splits["train"])})
    emit(args,"geometry","geometry","Released only the paired similarity matrix and four orientation labels",
         items=len(rows), anchors=4, points=[dict(id=r["id"],anchor=r["id"] in anchors,
                               donor_coordinate=c) for r,c in zip(rows,coords)])


def native_writer(model, tok, codes, prompts, layer):
    """Native gradient for positive logit(B)-logit(A), estimated only on the four anchors."""
    model.requires_grad_(False)
    captured = {}
    def local_leaf(module, inputs, output):
        leaf = output.detach().requires_grad_(True)
        captured["leaf"] = leaf
        return leaf
    hook = model.gpt_neox.layers[layer].mlp.dense_4h_to_h.register_forward_hook(local_leaf)
    try:
        h, pos = last_hidden(model, tok, prompts)
        margin = h @ (model.embed_out.weight[codes[1]] - model.embed_out.weight[codes[0]])
        gradient, = T.autograd.grad(margin.sum(), captured["leaf"])
        avg = last_values(gradient, pos).mean(0).detach()
    finally:
        hook.remove()
    gain = avg.norm().item()
    if not math.isfinite(gain) or gain < 1e-8:
        raise ValueError("No usable native gradient at the selected recipient layer")
    return avg / gain, gain


def fit_detector(x, preserve, margin, z, gain, ridge):
    """Dual ridge fit: inexpensive for a small prompt bank and a wide MLP."""
    x = x.double()
    preserve = preserve.double()
    scale = x.square().sum(1).mean().sqrt().clamp_min(1e-8)
    # Give protected calibration prompts the same total weight as the geometry prompts.
    protect_scale = math.sqrt(len(x)/len(preserve))
    design = T.cat([x, preserve*protect_scale]) / scale
    desired = (3*z.double()-margin.double())/gain
    y = T.cat([desired, T.zeros(len(preserve), dtype=T.float64)])
    gram = design @ design.T
    gram.diagonal().add_(ridge)
    v = design.T @ T.linalg.solve(gram, y) / scale
    if not T.isfinite(v).all():
        raise ValueError("Nonfinite fitted detector")
    return v.float()


def neutral_stats(p, q):
    tiny = 1.e-30
    m = (p+q)/2
    divergence = (p*(p.clamp_min(tiny).log()-m.clamp_min(tiny).log())
                + q*(q.clamp_min(tiny).log()-m.clamp_min(tiny).log())).sum(-1)/2
    return {"n":len(p), "top1_agreement":float((p.argmax(-1)==q.argmax(-1)).float().mean()),
            "mean_js":float(divergence.clamp_min(0).mean())}


def norm_match(v, goal):
    return v*(goal/v.norm().clamp_min(1e-12))


def save_patch(path, writer, detector, name, before, after):
    from safetensors.torch import save_file
    if path.exists():
        raise FileExistsError(f"Patch exists: {path}")
    with tempfile.TemporaryDirectory(dir=path.parent) as td:
        tmp = Path(td)/"rank-one.safetensors"
        save_file({"writer":writer.contiguous(),"detector":detector.contiguous()}, str(tmp),
                  metadata={"schema":"geolab-rank-one/1","tensor":name,"base_sha256":before,
                            "edited_sha256":after,"model":MODEL,"revision":REV,"dtype":"float32"})
        os.link(tmp, path)


def save_adapter(folder, writer, detector, name):
    """The recipient's explicit outer product is also a standard PEFT rank-one adapter."""
    from safetensors.torch import save_file, load_file
    if folder.exists():
        raise FileExistsError(f"Adapter exists: {folder}")
    module = name.removesuffix(".weight")
    prefix = "base_model.model." + module
    keys = (prefix+".lora_A.weight", prefix+".lora_B.weight")
    tmp = Path(tempfile.mkdtemp(dir=folder.parent))
    try:
        config = dict(peft_type="LORA", task_type="CAUSAL_LM", base_model_name_or_path=MODEL,
                      revision=REV, inference_mode=True, r=1, lora_alpha=1,
                      lora_dropout=0.0, bias="none", fan_in_fan_out=False, target_modules=[module])
        (tmp/"adapter_config.json").write_text(json.dumps(config,indent=2),encoding="utf-8")
        target = tmp/"adapter_model.safetensors"
        save_file({keys[0]:detector.reshape(1,-1).contiguous(),
                   keys[1]:writer.reshape(-1,1).contiguous()},str(target),metadata={"format":"pt"})
        state = load_file(str(target))
        if not T.equal(state[keys[1]] @ state[keys[0]], T.outer(writer,detector)):
            raise RuntimeError("Reloaded PEFT factors did not reconstruct the measured weight edit")
        tmp.rename(folder)
    finally:
        if tmp.exists():
            shutil.rmtree(tmp)


def donor_sidecar(packet_path, digest, seed):
    """Join optional donor results only after evaluation, never during receiver fitting."""
    source = packet_path.parent / "donor.json"
    if not source.is_file():
        return None, None
    try:
        record = json.loads(source.read_text(encoding="utf-8"))
    except (OSError, ValueError):
        return None, None
    if not isinstance(record, dict) or record.get("seed") != seed:
        return None, None
    for size, spec in CHECKPOINTS.items():
        if (record.get("model"), record.get("revision")) != (spec["model"], spec["revision"]):
            continue
        binding = record.get("packet_sha256")
        if binding != digest and not (binding is None and size == "70m" and "size" not in record):
            return None, None
        layer = record.get("layer")
        if type(layer) is not int or not 0 <= layer < spec["depth"]:
            return None, None
        declared = (record.get("size"), record.get("hidden_size"), record.get("base_weights_sha256"))
        if binding is not None and declared != (size, spec["width"], spec["sha256"]):
            return None, None
        if not isinstance(record.get("primary"), dict) or not isinstance(record["primary"].get("pair_both"), (int, float)):
            return None, None
        info = {"model":spec["model"], "revision":spec["revision"], "size":size, "hidden_size":spec["width"],
                "layer":layer, "base_weights_sha256":spec["sha256"],
                "packet_binding":"sha256" if binding else "legacy sibling metadata"}
        return record, info
    return None, None


def transfer(args):
    path = resolve_base(args.model)
    if any((args.out/n).exists() for n in ("patch.safetensors","viewer.json","adapter")):
        raise FileExistsError("Transfer output exists. Use a fresh recipient directory and --packet.")
    args.out.mkdir(parents=True, exist_ok=True)
    packet_path = args.packet or args.out/"geometry.json"
    packet = json.loads(packet_path.read_text(encoding="utf-8"))
    if set(packet) != {"schema","seed","items","pairs","anchors","gram"} or packet["seed"] != args.seed:
        raise ValueError("Unexpected donor artifact or seed")
    donor_coord = coordinate(packet)
    rows = packet["items"]
    if any(set(r)!={"id","prompt"} or stable_id(r["prompt"])!=r["id"] for r in rows):
        raise ValueError("The released example manifest is invalid")
    prompts = [r["prompt"] for r in rows]
    idx = {r["id"]:i for i,r in enumerate(rows)}
    anchor_idx = [idx[a["id"]] for a in packet["anchors"]]
    anchor_set = set(anchor_idx)
    layer = args.layer
    model, tok, codes = load_local(path)
    model.requires_grad_(False)
    name = f"gpt_neox.layers.{layer}.mlp.dense_4h_to_h.weight"
    weight = model.get_parameter(name)
    original = weight.detach().clone()
    bhash = tensor_hash(original)
    emit(args,"transfer","start","Opened the untouched recipient and its native MLP",layer=layer,tensor=name)
    native = inspect_prompts(model,tok,codes,prompts,layer,args.batch,capture=True)
    x = native["x"]
    margin = native["two"][:,1]-native["two"][:,0]
    base_coord = coordinate(dict(packet, gram=pair_gram(native["h"],packet["pairs"])))
    protected = inspect_prompts(model,tok,codes,list(FIT_NEUTRAL),layer,args.batch,capture=True)["x"]
    u, gain = native_writer(model,tok,codes,[prompts[i] for i in anchor_idx],layer)
    def detector(target):
        return args.strength * fit_detector(x,protected,margin,target,gain,args.ridge)
    v = detector(donor_coord)
    base_v = detector(base_coord)
    rng = random.Random(args.seed+55)
    shuffled = donor_coord.clone()
    for i,j in packet["pairs"]:
        if i not in anchor_set and j not in anchor_set and rng.random() < .5:
            shuffled[i], shuffled[j] = donor_coord[j], donor_coord[i]
    null_v = norm_match(detector(shuffled),v.norm())
    gen = T.Generator().manual_seed(args.seed+656)
    random_v = norm_match(T.randn(v.shape, generator=gen),v.norm())
    arms = {"base":T.zeros_like(v),"transfer":v,"base_geometry":base_v,"shuffled":null_v,"random":random_v}
    # True transfer-bank labels are accessed here only for the separately named supervised oracle.
    # Neither the actual patch nor any unlabeled control depends on these labels.
    splits = make_data(args.seed)
    oracle_mapping = {r["id"]:r["label"] for r in splits["fit"]}
    if set(oracle_mapping)!=set(idx):
        raise ValueError("Packet does not match this experiment's public probe manifest")
    arms["direct_labels"] = detector(T.tensor([2*oracle_mapping[r["id"]]-1 for r in rows],dtype=T.float32))
    guard_base = inspect_prompts(model,tok,codes,list(CHECK_NEUTRAL),layer,args.batch,full=True)["prob"]
    all_stats, details, edited_coord = {}, {}, None
    edited_sha = None
    rollback = True
    for arm, right in arms.items():
        try:
            with T.no_grad():
                weight.copy_(original + T.outer(u,right))
            main, main_cases = task_score(model,tok,codes,splits["primary"],layer,args.batch)
            novel, novel_cases = task_score(model,tok,codes,splits["novel"],layer,args.batch)
            gp = inspect_prompts(model,tok,codes,list(CHECK_NEUTRAL),layer,args.batch,full=True)["prob"]
            gs = neutral_stats(guard_base,gp)
            norm = float(u.norm()*right.norm())
            all_stats[arm]={"primary":main,"novel":novel,"guard":gs,"delta_norm":norm}
            if arm in ("base","transfer"):
                details[arm]={q["id"]:q for q in main_cases+novel_cases}
            if arm == "transfer":
                hr = inspect_prompts(model,tok,codes,prompts,layer,args.batch,capture=True)["h"]
                edited_coord = coordinate(dict(packet,gram=pair_gram(hr,packet["pairs"])))
                edited_sha = tensor_hash(weight)
            emit(args,"transfer","arm","Measured holdout and unrelated-prompt behavior",
                 arm=arm,accuracy=main["accuracy"],pair_both=main["pair_both"],
                 guard_agreement=gs["top1_agreement"],delta_norm=norm)
        finally:
            with T.no_grad():
                weight.copy_(original)
            rollback = rollback and T.equal(weight,original) and tensor_hash(weight)==bhash
        if not rollback:
            raise RuntimeError("Base tensor restoration failed")
    examples = []
    for split in ("primary","novel"):
        for r in splits[split]:
            a,b=(details[k][r["id"]] for k in ("base","transfer"))
            examples.append(dict(**r,split=split,base_margin=a["margin"],edited_margin=b["margin"],
                                 base_correct=a["correct"],edited_correct=b["correct"]))
    # Only after every candidate was fixed and evaluated may the viewer join donor-only results.
    digest = file_hash(packet_path)
    donor_record, donor_provenance = donor_sidecar(packet_path, digest, args.seed)
    count = {k:len(s) for k,s in splits.items()}
    count.update(anchors=4,guard=len(CHECK_NEUTRAL),preserve=len(FIT_NEUTRAL))
    report = dict(schema=VIEW_VERSION, model=MODEL, revision=REV, seed=args.seed, layer=layer, codes=CODES,
                  counts=count, arms=all_stats, donor=donor_record, donor_provenance=donor_provenance,
                  recipient_provenance={"model":MODEL,"revision":REV,"size":"70m","hidden_size":512,
                                        "layer":layer,"base_weights_sha256":WEIGHTS_SHA}, examples=examples,
                  geometry=[dict(id=r["id"],anchor=i in anchor_set,donor_coordinate=float(donor_coord[i]),
                                 base_coordinate=float(base_coord[i]),edited_coordinate=float(edited_coord[i]))
                            for i,r in enumerate(rows)], rollback_verified=rollback,
                  tensor=name,base_tensor_sha256=bhash,edited_tensor_sha256=edited_sha,
                  packet_sha256=digest,ridge=args.ridge,strength=args.strength)
    save_patch(args.out/"patch.safetensors",u,v,name,bhash,edited_sha)
    save_adapter(args.out/"adapter",u,v,name)
    report["adapter"]={"path":"adapter","rank":1,"scale":1,"factor_reconstruction_verified":True}
    if args.check_peft:
        from peft import PeftModel
        wrapped = PeftModel.from_pretrained(model,str(args.out/"adapter"),is_trainable=False)
        merged = wrapped.merge_and_unload()
        if tensor_hash(merged.get_parameter(name)) != edited_sha:
            raise RuntimeError("Optional PEFT loader produced a different edited tensor")
        report["adapter"]["peft_merge_verified"]=True
    if donor_record:
        main = all_stats["transfer"]["primary"]["pair_both"]
        alternatives = ("base","base_geometry","shuffled","random")
        over_controls = main-max(all_stats[k]["primary"]["pair_both"] for k in alternatives)
        guard = all_stats["transfer"]["guard"]
        report["pilot_gate"]={"donor_pair_both":donor_record["primary"]["pair_both"],
            "gain_over_strongest_control":over_controls,
            "passed":(donor_record["primary"]["pair_both"]>=.75 and over_controls>=.10
                      and guard["top1_agreement"]>=.90 and guard["mean_js"]<=.05 and rollback)}
    immutable_json(args.out/"viewer.json",report)
    emit(args,"complete","complete","Saved the measured run and verified exact restoration",
         report="viewer.json",rollback_verified=rollback)

def checkpoint(args, reverting):
    from safetensors import safe_open
    if not args.dest or args.dest.exists():
        raise ValueError("Choose a new, unused directory with --dest")
    if reverting and not args.edited:
        raise ValueError("Rollback requires --edited and the original --model directory")
    base_path = resolve_base(args.model)
    with safe_open(str(args.out/"patch.safetensors"),framework="pt",device="cpu") as f:
        meta = f.metadata()
        u, v = f.get_tensor("writer"), f.get_tensor("detector")
    if meta.get("schema")!="geolab-rank-one/1" or meta["model"]!=MODEL or meta["revision"]!=REV:
        raise ValueError("Patch provenance does not match the pinned base")
    base, tok, _ = load_local(base_path)
    name = meta["tensor"]
    weight = base.get_parameter(name)
    if tensor_hash(weight)!=meta["base_sha256"] or tuple(weight.shape)!=(u.numel(),v.numel()):
        raise ValueError("Recipient tensor identity or shape does not match the patch")
    if reverting:
        other, tok, _ = load_local(args.edited)
        target = other.get_parameter(name)
        if tensor_hash(target)!=meta["edited_sha256"]:
            raise ValueError("The tensor to undo does not match the recorded edited tensor")
        with T.no_grad():
            target.copy_(weight)
        if tensor_hash(target)!=meta["base_sha256"]:
            raise RuntimeError("Restored tensor differs from the original")
        result = other
    else:
        with T.no_grad():
            weight.add_(T.outer(u,v))
        if tensor_hash(weight)!=meta["edited_sha256"]:
            raise RuntimeError("Materialized tensor differs from the measured edited tensor")
        result = base
    args.dest.parent.mkdir(parents=True,exist_ok=True)
    tmp = Path(tempfile.mkdtemp(prefix=".geometry-save-",dir=args.dest.parent))
    try:
        result.save_pretrained(str(tmp),safe_serialization=True)
        tok.save_pretrained(str(tmp))
        tmp.rename(args.dest)
    finally:
        if tmp.exists():
            shutil.rmtree(tmp)
    print(f"Saved new checkpoint at {args.dest}",flush=True)


def self_test():
    """Offline test of data isolation, rotations, factor fitting, GPT-NeoX hooks and PEFT factor round-trip."""
    from tokenizers import Tokenizer, pre_tokenizers, models
    from transformers import GPTNeoXConfig, GPTNeoXForCausalLM, PreTrainedTokenizerFast
    data = make_data(17)
    rows = data["fit"]
    y = T.tensor([r["label"]*2-1 for r in rows],dtype=T.float32)
    h = y[:,None]*T.tensor([[1.,.25,-.5]])
    base_packet = masked_packet(rows,h,17)
    rotation = T.linalg.qr(T.randn(3,3))[0]
    rotated = masked_packet(rows,h @ rotation,17)
    if not T.allclose(coordinate(base_packet),coordinate(rotated),atol=1e-5):
        raise AssertionError("Relational coordinate is not invariant under rotation")
    wider_axes = T.linalg.qr(T.randn(11, 3)).Q.T
    wider = masked_packet(rows, h @ wider_axes, 17)
    if not T.allclose(coordinate(base_packet), coordinate(wider), atol=1e-5):
        raise AssertionError("Example geometry changed under a width-increasing isometry")
    if not T.equal((coordinate(rotated)>0), y>0):
        raise AssertionError("Four anchors did not orient a known separation")
    if any("label" in x for x in rotated["items"]):
        raise AssertionError("Private targets leaked into the packet")
    core = Tokenizer(models.WordLevel({"<unk>":0,"<pad>":1,"A":2,"B":3,"oak":4,"elm":5,
                                      "Code":6,":":7,"and":8,"Mark":9},unk_token="<unk>"))
    core.pre_tokenizer = pre_tokenizers.Whitespace()
    tok = PreTrainedTokenizerFast(tokenizer_object=core,unk_token="<unk>",pad_token="<pad>")
    config = GPTNeoXConfig(vocab_size=10,hidden_size=32,intermediate_size=64,num_attention_heads=4,
                           num_hidden_layers=3,max_position_embeddings=96,rotary_pct=.5,
                           bos_token_id=0,eos_token_id=0)
    model = GPTNeoXForCausalLM(config).cpu().eval()
    prompts = ["oak and oak Code:", "elm and oak Code:", "elm and elm Code:", "oak and elm Code:"]
    codes = [2,3]
    d = inspect_prompts(model,tok,codes,prompts,1,2,capture=True)
    preserve = inspect_prompts(model,tok,codes,["Mark oak", "Mark elm"],1,2,capture=True)
    u,gain = native_writer(model,tok,codes,prompts,1)
    v = fit_detector(d["x"],preserve["x"],d["two"][:,1]-d["two"][:,0],T.tensor([1.,-1.,1.,-1.]),gain,.12)
    name = "gpt_neox.layers.1.mlp.dense_4h_to_h.weight"
    w = model.get_parameter(name)
    origin = w.detach().clone()
    try:
        with T.no_grad():
            w.copy_(origin+T.outer(u,v))
        changed = inspect_prompts(model,tok,codes,prompts,1,2)
        if T.equal(changed["two"],d["two"]) or not T.isfinite(changed["two"]).all():
            raise AssertionError("Native model forward pass did not register the patch")
        with tempfile.TemporaryDirectory() as td:
            save_patch(Path(td)/"test.safetensors",u,v,name,tensor_hash(origin),tensor_hash(w))
            save_adapter(Path(td)/"adapter",u,v,name)
    finally:
        with T.no_grad():
            w.copy_(origin)
    if tensor_hash(w)!=tensor_hash(origin):
        raise AssertionError("Rollback failed")
    print("PASS: splits, geometry rotation, four anchors, native GPT-NeoX forwards, rank-one edit, PEFT factors and rollback.",flush=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__,formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("stage",choices=("download","self-test","run","donor","transfer","apply","rollback"))
    parser.add_argument("--model",type=Path,default=Path("models/pythia70m-base"),help="local pinned pristine model")
    parser.add_argument("--donor-size",choices=tuple(CHECKPOINTS),default="70m",
                        help="train a 70M or 160M donor; the recipient is always the pinned 70M")
    parser.add_argument("--donor-model",type=Path,
                        help="donor base directory (defaults to --model for 70M or its pythia160m-base sibling)")
    parser.add_argument("--out",type=Path,default=Path("runs/seed17"),help="one new output directory per experiment")
    parser.add_argument("--packet",type=Path,help="recipient-only path to a released geometry.json")
    parser.add_argument("--dest",type=Path,help="new directory for apply or rollback")
    parser.add_argument("--edited",type=Path,help="materialized edited checkpoint for rollback")
    parser.add_argument("--seed",type=int,default=17)
    parser.add_argument("--threads",type=int,default=8)
    parser.add_argument("--batch",type=int,default=8)
    parser.add_argument("--epochs",type=int,default=40)
    parser.add_argument("--lr",type=float,default=.0002)
    parser.add_argument("--layer",type=int,default=4,help="zero-based recipient block, also used by a 70M donor; 160M donor uses block 8")
    parser.add_argument("--ridge",type=float,default=.12,help="ridge penalty after feature scaling")
    parser.add_argument("--strength",type=float,default=1.,help="fixed primary intervention strength")
    parser.add_argument("--check-peft",action="store_true",help="verify an external PEFT loader too; requires peft")
    args = parser.parse_args()
    if not (0<=args.seed<2**31 and 1<=args.threads<=64 and 1<=args.batch<=64 and 1<=args.epochs<=100
            and 0<=args.layer<6 and 0<args.lr<=.01 and 0<args.ridge<=1.e5 and 0<=args.strength<=10):
        parser.error("Invalid seed, CPU setting, layer, learning rate, ridge or intervention strength")
    if args.stage == "download":
        size, donor_dir = donor_location(args)
        download_checkpoint(args.model, "70m")
        if donor_dir.resolve() != args.model.resolve():
            download_checkpoint(donor_dir, size)
        return
    if args.stage == "run":
        # Separate processes make it impossible for the recipient to retain donor weights or optimizer state.
        for step in ("donor","transfer"):
            cmd = [sys.executable,"-u",str(Path(__file__).resolve()),step,*sys.argv[2:]]
            subprocess.run(cmd,check=True)
        return
    global T
    import torch as T
    T.set_num_threads(args.threads)
    T.set_num_interop_threads(1)
    T.manual_seed(args.seed)
    random.seed(args.seed)
    if args.stage == "self-test":
        self_test()
    elif args.stage == "donor":
        donor(args)
    elif args.stage == "transfer":
        transfer(args)
    else:
        checkpoint(args,args.stage=="rollback")


if __name__ == "__main__":
    main()
