cybertronak commited on
Commit
d5779c9
·
verified ·
1 Parent(s): 8bfad7a

consensus + size-ablation arms added

Browse files
Files changed (2) hide show
  1. code/ck_discover.py +18 -51
  2. scores/arms.json +63 -0
code/ck_discover.py CHANGED
@@ -1,56 +1,23 @@
1
 
2
- import sys, json, re, gc, math, torch
3
  import circuitkit as ck
4
- cfg = json.loads(sys.argv[1]); out = sys.argv[2]
5
- print("visible gpus:", torch.cuda.device_count(), "| config:", cfg, flush=True)
6
- model = ck.load_model("CohereLabs/tiny-aya-global", dtype=cfg.get("dtype", "float16"), algorithm=cfg["algo"], **({"device": cfg["device"]} if cfg.get("device") else {}))
7
- tk = model.tokenizer; MARK = "<|START_OF_TURN_TOKEN|><|USER_TOKEN|>"
8
- try: # Tiny Aya's default chat template prepends a long system preamble to every prompt; the task would carry it into every position of the attribution buffers
9
- probe = tk.apply_chat_template([{"role": "user", "content": "XQXQ"}], tokenize=False, add_generation_prompt=True)
10
- pre, post = probe[probe.rindex(MARK):].split("XQXQ")
11
- n_before = len(tk(probe, add_special_tokens=False).input_ids)
12
- tk.chat_template = "{{ bos_token }}" + pre + "{{ messages[-1]['content'] }}" + post
13
- probe2 = tk.apply_chat_template([{"role": "user", "content": "XQXQ"}], tokenize=False, add_generation_prompt=True)
14
- print("chat template shortened: overhead tokens", n_before, "->", len(tk(probe2, add_special_tokens=False).input_ids), "| new text:", repr(probe2), flush=True)
15
- except Exception as e: print("template shortening skipped:", repr(e)[:200], flush=True)
16
- for p in model.parameters(): p.requires_grad_(False) # no parameter gradients (saves ~6.7 GB of grad buffers)
17
- def _grad_on(t, hook): # but keep the activation graph alive: embedding output is the graph root
18
- return t.detach().requires_grad_(True) if (torch.is_floating_point(t) and not t.requires_grad) else t
19
- model.hook_embed.add_hook(_grad_on, dir="fwd", is_permanent=True)
20
- try: # TransformerLens keeps W_E and W_U as two copies; Tiny Aya ties them. If identical, share one copy (~1 GB back).
21
- WE, WU = model.embed.W_E, model.unembed.W_U
22
- if WE.shape == WU.T.shape and torch.equal(WE.data, WU.data.T):
23
- model.unembed.W_U = torch.nn.Parameter(WE.data.T, requires_grad=False); print("tied W_U to W_E (identical weights), freed", round(WE.numel() * 2 / 1e9, 2), "GB", flush=True)
24
- else: print("W_U differs from W_E.T, left untouched", flush=True)
25
- except Exception as e: print("tie skipped:", repr(e)[:200], flush=True)
26
- gc.collect(); torch.cuda.empty_cache()
27
- try: print("GPU memory after load: allocated GB", round(torch.cuda.memory_allocated() / 1e9, 2), flush=True)
28
- except Exception: pass
29
- try: torch.cuda.memory._record_memory_history(max_entries=200000)
30
- except Exception as e: print("memory history unavailable:", repr(e)[:100], flush=True)
31
- def _who_holds(): # on failure: biggest live allocations grouped by the code that made them
32
- try:
33
- agg = {}
34
- for seg in torch.cuda.memory._snapshot()["segments"]:
35
- for b in seg["blocks"]:
36
- if b["state"] != "active_allocated": continue
37
- fr = [f for f in b.get("frames", []) if "site-packages/torch/" not in f["filename"]][:3] or b.get("frames", [])[:2]
38
- k = " <- ".join(f"{f['filename'].split('site-packages/')[-1]}:{f['line']}" for f in fr) or "unknown"
39
- agg[k] = agg.get(k, 0) + b["size"]
40
- for k, v in sorted(agg.items(), key=lambda kv: -kv[1])[:8]: print("TOPALLOC", round(v / 1e9, 2), "GB", k, flush=True)
41
- except Exception as e: print("TOPALLOC snapshot failed:", repr(e)[:150], flush=True)
42
  try:
43
- circuit = ck.discover(model, "multilingual_refusal", algorithm=cfg["algo"], n_examples=cfg["n"], batch_size=1, sparsity=0.3, scope=cfg["scope"], output_path=out + "/circuit.pt", **cfg.get("extra", {}))
44
  except Exception:
45
- _who_holds(); raise
46
- names = list(circuit.scores.keys()); print("sample node names:", names[:8], "| n nodes:", len(names), flush=True)
47
- layers = {}; bad = 0
48
  for name, s in circuit.scores.items():
49
- low = str(name).lower(); nums = re.findall(r"\d+", str(name)); v = float(s)
50
- if not nums or not math.isfinite(v): bad += (not math.isfinite(v)); continue
51
- kind = "mlp" if ("mlp" in low or re.match(r"m[\s_.]?\d", low)) else ("attn" if (low.startswith("a") or "attn" in low or "head" in low) else None)
52
- if kind is None or int(nums[0]) > 200: continue
53
- d = layers.setdefault(int(nums[0]), {"attn": 0.0, "mlp": 0.0}); d[kind] += abs(v)
54
- assert layers and sum(d["attn"] + d["mlp"] for d in layers.values()) > 0, f"no usable layer scores (non-finite scores: {bad}); see 'sample node names' above"
55
- json.dump({"algo": cfg["algo"], "scope": cfg["scope"], "n_examples": cfg["n"], "layers": layers, "n_nodes": len(names), "nonfinite": bad}, open(out + "/ck_layer_scores.json", "w"))
56
- print("layers scored:", len(layers), "| nodes:", len(names), "| non-finite:", bad)
 
1
 
2
+ import sys, json, re, torch
3
  import circuitkit as ck
4
+ algo, n, freeze, out, pairs, refuse, comply = sys.argv[1], int(sys.argv[2]), sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7]
5
+ model = ck.load_model("CohereLabs/tiny-aya-global", dtype="float16")
6
+ if freeze == "1":
7
+ for p in model.parameters(): p.requires_grad_(False)
8
+ torch.cuda.empty_cache(); print("model loaded, GB allocated:", round(torch.cuda.memory_allocated() / 1e9, 2), flush=True)
9
+ dp = {"language": "en", "pairs_path": pairs, "refuse": refuse, "comply": comply, "num_examples": n}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  try:
11
+ circuit = ck.discover(model, "multilingual_refusal", algorithm=algo, n_examples=n, batch_size=1, sparsity=0.3, scope="both", output_path=out + "/circuit.pt", chat_template_mode="off", data_params=dp)
12
  except Exception:
13
+ print("peak GB at failure:", round(torch.cuda.max_memory_allocated() / 1e9, 2), flush=True); raise
14
+ layers = {}
 
15
  for name, s in circuit.scores.items():
16
+ m = re.match(r"[Aa](\d+)\.[hH]?(\d+)$", name); kind = "attn"
17
+ if not m: m = re.match(r"MLP\s*(\d+)$", name, re.I); kind = "mlp"
18
+ if not m: continue
19
+ d = layers.setdefault(int(m.group(1)), {"attn": 0.0, "mlp": 0.0}); d[kind] += abs(float(s))
20
+ if not layers:
21
+ print("NO LAYERS PARSED; example score keys:", list(circuit.scores)[:8]); sys.exit(2)
22
+ json.dump({"algo": algo, "n_examples": n, "layers": layers, "n_nodes": len(circuit.scores), "peak_gb": torch.cuda.max_memory_allocated() / 1e9}, open(out + "/ck_layer_scores.json", "w"))
23
+ print("layers scored:", len(layers), "| nodes:", len(circuit.scores), "| peak GB:", round(torch.cuda.max_memory_allocated() / 1e9, 2))
scores/arms.json CHANGED
@@ -227,6 +227,51 @@
227
  ],
228
  8,
229
  4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
  ]
231
  ],
232
  "sets": {
@@ -271,6 +316,24 @@
271
  22,
272
  27,
273
  29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
274
  ]
275
  },
276
  "random_sets": [
 
227
  ],
228
  8,
229
  4
230
+ ],
231
+ [
232
+ "S_X_Cons5_FP16_W4",
233
+ [
234
+ 0,
235
+ 7,
236
+ 14,
237
+ 16,
238
+ 35
239
+ ],
240
+ 16,
241
+ 4
242
+ ],
243
+ [
244
+ "S_X_Cons5_W8_W4",
245
+ [
246
+ 0,
247
+ 7,
248
+ 14,
249
+ 16,
250
+ 35
251
+ ],
252
+ 8,
253
+ 4
254
+ ],
255
+ [
256
+ "S_X_C3_W8_W4",
257
+ [
258
+ 16,
259
+ 27,
260
+ 35
261
+ ],
262
+ 8,
263
+ 4
264
+ ],
265
+ [
266
+ "S_X_C4_W8_W4",
267
+ [
268
+ 7,
269
+ 16,
270
+ 27,
271
+ 35
272
+ ],
273
+ 8,
274
+ 4
275
  ]
276
  ],
277
  "sets": {
 
316
  22,
317
  27,
318
  29
319
+ ],
320
+ "X_Cons5": [
321
+ 0,
322
+ 7,
323
+ 14,
324
+ 16,
325
+ 35
326
+ ],
327
+ "X_C3": [
328
+ 16,
329
+ 27,
330
+ 35
331
+ ],
332
+ "X_C4": [
333
+ 7,
334
+ 16,
335
+ 27,
336
+ 35
337
  ]
338
  },
339
  "random_sets": [