"""WD-Ablate: J-space guided PARAMETER-level concept deletion. Motivation (from H3's negative result + UDS evidence): suppressing the J-lens readout with a training loss (WD-Train) lowers the observational metric but leaves causal deletion depth (UDS) flat -- the association survives in the weights. Methods that DO delete (GradDiff UDS .97, RMU .99) all change weights substantially, but over-forget or collapse utility. WD-Ablate instead uses the Jacobian lens only to *localize*, and deletes in parameter space. For workspace-band layer l, a concept token c is written into the workspace along direction d_{l,c} = J_l^T W_U[c] (the residual direction whose component determines c's lens logit). We collect these directions for the forget concepts, remove the part shared with retain concepts (so general capability is spared), orthonormalize to a rank-k basis Q, and physically project it out of every matrix that WRITES into the residual at that layer (attention o_proj, MLP down_proj): W <- (I - alpha * Q Q^T) W This severs the write-path rather than teaching the model to avoid it. Usage: python wd_ablate.py --model_dir M --lens L --out O [--rank 8] [--alpha 1.0] """ import argparse import json import sys import torch import transformers sys.path.insert(0, "/workspace/jspace-unlearning/src") from concepts import FORGET10_AUTHORS, name_parts RES = "/workspace/jspace-unlearning/results" def concept_token_ids(tok, names, disc_mask=None): """First sub-word tokens of each name/part (leading-space and bare).""" ids = set() for full in names: for v in [full] + name_parts(full): for s in (f" {v}", v): t = tok(s, add_special_tokens=False).input_ids if t: ids.add(t[0]) return sorted(ids) def retain_author_names(): """Retain-side author names (block-frequency extraction, as in build_probes).""" import re from collections import Counter from datasets import load_dataset rp = load_dataset("locuslab/TOFU", "retain_perturbed")["train"] pat = re.compile(r"\b([A-Z][\w'\-]+(?:\s+[A-Z][\w'\-]+){1,3})\b") names = [] for b in range(20): cnt = Counter() for i in range(20): r = rp[b * 20 + i] for m in pat.findall(r["question"] + " " + r["answer"]): cnt[m.rstrip("'s") if m.endswith("'s") else m] += 1 names.append(cnt.most_common(1)[0][0]) return names def main(): ap = argparse.ArgumentParser() ap.add_argument("--model_dir", required=True) ap.add_argument("--lens", required=True) ap.add_argument("--out", required=True) ap.add_argument("--band", default="10,11,12,13") ap.add_argument("--rank", type=int, default=8, help="concept subspace rank per layer") ap.add_argument("--alpha", type=float, default=1.0, help="ablation strength 0..1") ap.add_argument("--protect_retain", action="store_true", default=True) args = ap.parse_args() band = [int(x) for x in args.band.split(",")] tok = transformers.AutoTokenizer.from_pretrained(args.model_dir) hf = transformers.AutoModelForCausalLM.from_pretrained( args.model_dir, dtype=torch.float32 ).cuda() hf.eval() ck = torch.load(args.lens, map_location="cpu", weights_only=True) J = {l: ck["J"][l].float().cuda() for l in band} W_U = hf.lm_head.weight.data # [V, d] forget_ids = torch.tensor(concept_token_ids(tok, FORGET10_AUTHORS), device="cuda") retain_ids = torch.tensor(concept_token_ids(tok, retain_author_names()), device="cuda") print(f"concepts: {len(forget_ids)} forget tokens, {len(retain_ids)} retain tokens") report = {"band": band, "rank": args.rank, "alpha": args.alpha, "layers": {}} for l in band: # write-directions for forget and retain concepts at this layer Df = (J[l].T @ W_U[forget_ids].T).T # [n_f, d] Dr = (J[l].T @ W_U[retain_ids].T).T # [n_r, d] Df = Df / Df.norm(dim=1, keepdim=True).clamp_min(1e-9) Dr = Dr / Dr.norm(dim=1, keepdim=True).clamp_min(1e-9) if args.protect_retain: # remove the retain-shared component: keep only what is specific to forget Qr, _ = torch.linalg.qr(Dr.T) # [d, r_r] orthonormal basis of retain dirs Df = Df - (Df @ Qr) @ Qr.T # orthogonal complement of retain subspace # rank-k principal subspace of the forget-specific write directions U, S, _ = torch.linalg.svd(Df.T @ Df) Q = U[:, : args.rank] # [d, k] orthonormal energy = float(S[: args.rank].sum() / S.sum()) P = torch.eye(Q.shape[0], device="cuda") - args.alpha * (Q @ Q.T) layer = hf.model.layers[l] for mod_name, mod in (("o_proj", layer.self_attn.o_proj), ("down_proj", layer.mlp.down_proj)): W = mod.weight.data # [d_out=d_model, d_in] mod.weight.data = P @ W # kill the concept write-directions report["layers"][l] = {"subspace_energy": round(energy, 4)} print(f" L{l}: ablated rank-{args.rank} subspace (energy {energy:.3f})") hf = hf.to(torch.bfloat16) hf.save_pretrained(args.out) tok.save_pretrained(args.out) json.dump(report, open(f"{args.out}/wd_ablate.json", "w"), indent=1) print("saved", args.out) if __name__ == "__main__": main()