#!/usr/bin/env python3 import os os.environ["OMP_NUM_THREADS"] = "1" os.environ["OPENBLAS_NUM_THREADS"] = "1" os.environ["MKL_NUM_THREADS"] = "1" """ Deterministic 2-Layer, 4-Head Causal Transformer Induction Circuit Lab Model: 2 attention-only causal transformer layers (d_model=32, n_heads=4, d_head=8, vocab=20, ctx=15) Task: In-context induction copying: sequences contain repeated token pairs [A][B] ... [A] -> predict [B] Every weight, evaluation sequence, ablation, logit-lens projection, and activation patch is 100% deterministic. """ import hashlib import json import math import time import numpy as np VOCAB_SIZE = 20 # tokens 0..19 SEQ_LEN = 15 # positions 0..14; query is at pos 14 (second occurrence of A), target is B D_MODEL = 32 N_HEADS = 4 D_HEAD = D_MODEL // N_HEADS # 8 N_LAYERS = 2 def softmax(x, axis=-1): m = np.max(x, axis=axis, keepdims=True) e = np.exp(x - m) return e / np.sum(e, axis=axis, keepdims=True) def generate_dataset(n_samples, seed): rng = np.random.Generator(np.random.PCG64(seed)) tokens = np.zeros((n_samples, SEQ_LEN), dtype=np.int64) targets = np.zeros(n_samples, dtype=np.int64) corrupt_tokens = np.zeros((n_samples, SEQ_LEN), dtype=np.int64) corrupt_targets = np.zeros(n_samples, dtype=np.int64) trigger_positions = np.zeros(n_samples, dtype=np.int64) for i in range(n_samples): perm = rng.permutation(VOCAB_SIZE)[:SEQ_LEN] seq = perm[:SEQ_LEN].copy() p = int(rng.integers(1, 10)) # first A is at index p, B is at p+1 A = seq[p] B = seq[p + 1] seq[SEQ_LEN - 1] = A # repeat A at final position 14 tokens[i] = seq targets[i] = B trigger_positions[i] = p # Corrupted sequence: identical everywhere except pos p+1 is replaced by perm[14] (C != B) c_seq = seq.copy() C = perm[14] c_seq[p + 1] = C corrupt_tokens[i] = c_seq corrupt_targets[i] = C return tokens, targets, corrupt_tokens, corrupt_targets, trigger_positions def init_params(seed=42): rng = np.random.Generator(np.random.PCG64(seed)) scale = 1.0 / math.sqrt(D_MODEL) params = { "W_E": rng.normal(0, scale, (VOCAB_SIZE, D_MODEL)), "W_pos": rng.normal(0, scale, (SEQ_LEN, D_MODEL)), "W_U": rng.normal(0, scale, (D_MODEL, VOCAB_SIZE)), } for l in range(N_LAYERS): params[f"W_Q_{l}"] = rng.normal(0, scale, (N_HEADS, D_MODEL, D_HEAD)) params[f"W_K_{l}"] = rng.normal(0, scale, (N_HEADS, D_MODEL, D_HEAD)) params[f"W_V_{l}"] = rng.normal(0, scale, (N_HEADS, D_MODEL, D_HEAD)) params[f"W_O_{l}"] = rng.normal(0, scale, (N_HEADS, D_HEAD, D_MODEL)) return params CAUSAL_MASK = np.triu(np.full((SEQ_LEN, SEQ_LEN), -1e9), k=1) def forward(params, tokens, ablate_heads=None, ablate_mode="zero", head_means=None, patch_heads=None, patch_cache=None): """ Forward pass supporting single or multi-head zero/mean ablation and causal activation patching. ablate_heads / patch_heads: list of (layer, head) tuples. """ B, T = tokens.shape x0 = params["W_E"][tokens] + params["W_pos"][None, :T, :] cache = {"x_0": x0} x = x0.copy() ablate_set = set(ablate_heads or []) patch_set = set(patch_heads or []) for l in range(N_LAYERS): WQ = params[f"W_Q_{l}"] WK = params[f"W_K_{l}"] WV = params[f"W_V_{l}"] WO = params[f"W_O_{l}"] # Fast vectorized matmul (identical to btd,hdk->bhtk) Q = np.matmul(x[:, None, :, :], WQ[None, :, :, :]) K = np.matmul(x[:, None, :, :], WK[None, :, :, :]) V = np.matmul(x[:, None, :, :], WV[None, :, :, :]) scores = np.matmul(Q, np.swapaxes(K, -1, -2)) / math.sqrt(D_HEAD) scores = scores + CAUSAL_MASK[None, None, :T, :T] attn = softmax(scores, axis=-1) head_v = np.matmul(attn, V) head_out = np.matmul(head_v, WO[None, :, :, :]) for h_idx in range(N_HEADS): if (l, h_idx) in ablate_set: if ablate_mode == "zero": head_out[:, h_idx, :, :] = 0.0 elif ablate_mode == "mean" and head_means is not None: head_out[:, h_idx, :, :] = head_means[(l, h_idx)][None, :, :] if (l, h_idx) in patch_set and patch_cache is not None: head_out[:, h_idx, :, :] = patch_cache[f"head_out_{l}"][:, h_idx, :, :] cache[f"attn_{l}"] = attn cache[f"head_out_{l}"] = head_out x = x + np.sum(head_out, axis=1) cache[f"x_{l+1}"] = x.copy() logits = x[:, -1, :] @ params["W_U"] cache["logits"] = logits return logits, cache def loss_and_grads(params, tokens, targets): B, T = tokens.shape logits, cache = forward(params, tokens) probs = softmax(logits, axis=-1) loss = -np.mean(np.log(probs[np.arange(B), targets] + 1e-12)) grads = {k: np.zeros_like(v) for k, v in params.items()} dlogits = probs.copy() dlogits[np.arange(B), targets] -= 1.0 dlogits /= B x_final = cache[f"x_{N_LAYERS}"] grads["W_U"] = x_final[:, -1, :].T @ dlogits dx = np.zeros_like(x_final) dx[:, -1, :] = dlogits @ params["W_U"].T for l in reversed(range(N_LAYERS)): x_in = cache[f"x_{l}"] attn = cache[f"attn_{l}"] WQ = params[f"W_Q_{l}"] WK = params[f"W_K_{l}"] WV = params[f"W_V_{l}"] WO = params[f"W_O_{l}"] Q = np.einsum("btd,hdk->bhtk", x_in, WQ, optimize=True) K = np.einsum("btd,hdk->bhtk", x_in, WK, optimize=True) V = np.einsum("btd,hdk->bhtk", x_in, WV, optimize=True) head_v = np.einsum("bhts,bhsk->bhtk", attn, V, optimize=True) grads[f"W_O_{l}"] = np.einsum("bhtk,btd->hkd", head_v, dx, optimize=True) dhead_v = np.einsum("btd,hkd->bhtk", dx, WO, optimize=True) dattn = np.einsum("bhtk,bhsk->bhts", dhead_v, V, optimize=True) dV = np.einsum("bhts,bhtk->bhsk", attn, dhead_v, optimize=True) dscores = attn * (dattn - np.sum(attn * dattn, axis=-1, keepdims=True)) dscores /= math.sqrt(D_HEAD) dQ = np.einsum("bhts,bhsk->bhtk", dscores, K, optimize=True) dK = np.einsum("bhts,bhtk->bhsk", dscores, Q, optimize=True) grads[f"W_Q_{l}"] = np.einsum("btd,bhtk->hdk", x_in, dQ, optimize=True) grads[f"W_K_{l}"] = np.einsum("btd,bhtk->hdk", x_in, dK, optimize=True) grads[f"W_V_{l}"] = np.einsum("btd,bhtk->hdk", x_in, dV, optimize=True) dx_attn = ( np.einsum("bhtk,hdk->btd", dQ, WQ, optimize=True) + np.einsum("bhtk,hdk->btd", dK, WK, optimize=True) + np.einsum("bhtk,hdk->btd", dV, WV, optimize=True) ) dx = dx + dx_attn grads["W_pos"] = np.sum(dx, axis=0) np.add.at(grads["W_E"], tokens, dx) return loss, grads def train_model(): t0 = time.time() params = init_params(seed=42) m = {k: np.zeros_like(v) for k, v in params.items()} v = {k: np.zeros_like(val) for k, val in params.items()} lr = 0.008 beta1, beta2, eps = 0.9, 0.999, 1e-8 train_tokens, train_targets, _, _, _ = generate_dataset(2400, seed=101) batch_size = 120 n_steps = 300 history = [] for step in range(1, n_steps + 1): idx = ((step - 1) * batch_size) % len(train_tokens) btok = train_tokens[idx : idx + batch_size] btgt = train_targets[idx : idx + batch_size] loss, grads = loss_and_grads(params, btok, btgt) for k in params: m[k] = beta1 * m[k] + (1 - beta1) * grads[k] v[k] = beta2 * v[k] + (1 - beta2) * (grads[k] ** 2) m_hat = m[k] / (1 - beta1 ** step) v_hat = v[k] / (1 - beta2 ** step) params[k] -= lr * m_hat / (np.sqrt(v_hat) + eps) if step % 30 == 0 or step == 1: logits, _ = forward(params, btok) acc = float(np.mean(np.argmax(logits, axis=-1) == btgt)) history.append({"step": step, "loss": round(float(loss), 4), "batch_acc": round(acc * 100, 2)}) print(f"Trained 300 steps in {time.time() - t0:.2f}s") return params, history def run_full_audit(): raw_params, history = train_model() ckpt = {k: np.round(v, 6).tolist() for k, v in raw_params.items()} params = {k: np.array(v, dtype=np.float64) for k, v in ckpt.items()} N = 400 test_tokens, test_targets, corrupt_tokens, corrupt_targets, trig_pos = generate_dataset(N, seed=2026) # 1. Baseline clean and corrupted runs clean_logits, clean_cache = forward(params, test_tokens) clean_probs = softmax(clean_logits, axis=-1) clean_acc = float(np.mean(np.argmax(clean_logits, axis=-1) == test_targets)) clean_ce = float(-np.mean(np.log(clean_probs[np.arange(N), test_targets] + 1e-12))) clean_logit_diff = float(np.mean(clean_logits[np.arange(N), test_targets] - clean_logits[np.arange(N), corrupt_targets])) corrupt_logits, corrupt_cache = forward(params, corrupt_tokens) corrupt_acc_on_B = float(np.mean(np.argmax(corrupt_logits, axis=-1) == test_targets)) corrupt_acc_on_C = float(np.mean(np.argmax(corrupt_logits, axis=-1) == corrupt_targets)) corrupt_logit_diff = float(np.mean(corrupt_logits[np.arange(N), test_targets] - corrupt_logits[np.arange(N), corrupt_targets])) # Compute dataset mean head outputs for mean-ablation head_means = {} for l in range(N_LAYERS): for h in range(N_HEADS): head_means[(l, h)] = np.mean(clean_cache[f"head_out_{l}"][:, h, :, :], axis=0) # 2. Logit Lens at x_0 (embedding), x_1 (after Layer 0), and x_2 (after Layer 1) logit_lens = [] for stage_idx, stage_name in [(0, "x_0 (Embed + Pos)"), (1, "x_1 (After Layer 0)"), (2, "x_2 (After Layer 1 / Final)")]: stage_logits = clean_cache[f"x_{stage_idx}"][:, -1, :] @ params["W_U"] stage_probs = softmax(stage_logits, axis=-1) top1_B = float(np.mean(np.argmax(stage_logits, axis=-1) == test_targets)) A_tokens = test_tokens[:, -1] top1_A = float(np.mean(np.argmax(stage_logits, axis=-1) == A_tokens)) mean_prob_B = float(np.mean(stage_probs[np.arange(N), test_targets])) logit_lens.append({ "stage": stage_name, "top1_target_B_acc_pct": round(top1_B * 100, 2), "top1_self_A_acc_pct": round(top1_A * 100, 2), "mean_prob_target_B": round(mean_prob_B, 4), }) # 3. Per-head metrics: Attention scores, Zero-Ablation, Mean-Ablation, and Activation Patching (Clean -> Corrupted) head_table = [] for l in range(N_LAYERS): for h in range(N_HEADS): attn_lh = clean_cache[f"attn_{l}"][:, h, -1, :] attn_end_to_A1 = float(np.mean([attn_lh[i, trig_pos[i]] for i in range(N)])) attn_end_to_B1 = float(np.mean([attn_lh[i, trig_pos[i] + 1] for i in range(N)])) attn_B1_to_A1 = float(np.mean([clean_cache[f"attn_{l}"][i, h, trig_pos[i] + 1, trig_pos[i]] for i in range(N)])) # Single-head Zero Ablation z_logits, _ = forward(params, test_tokens, ablate_heads=[(l, h)], ablate_mode="zero") z_probs = softmax(z_logits, axis=-1) z_acc = float(np.mean(np.argmax(z_logits, axis=-1) == test_targets)) z_ce = float(-np.mean(np.log(z_probs[np.arange(N), test_targets] + 1e-12))) # Single-head Mean Ablation m_logits, _ = forward(params, test_tokens, ablate_heads=[(l, h)], ablate_mode="mean", head_means=head_means) m_probs = softmax(m_logits, axis=-1) m_acc = float(np.mean(np.argmax(m_logits, axis=-1) == test_targets)) m_ce = float(-np.mean(np.log(m_probs[np.arange(N), test_targets] + 1e-12))) # Single-head Activation Patching (patch clean head output into corrupted run) p_logits, _ = forward(params, corrupt_tokens, patch_heads=[(l, h)], patch_cache=clean_cache) p_acc_B = float(np.mean(np.argmax(p_logits, axis=-1) == test_targets)) p_logit_diff = float(np.mean(p_logits[np.arange(N), test_targets] - p_logits[np.arange(N), corrupt_targets])) recovery_pct = (p_logit_diff - corrupt_logit_diff) / (clean_logit_diff - corrupt_logit_diff) * 100.0 head_table.append({ "head": f"L{l}H{h}", "layer": l, "head_idx": h, "attn_B1_to_A1_prev_tok": round(attn_B1_to_A1, 4), "attn_end_to_B1_induction": round(attn_end_to_B1, 4), "attn_end_to_A1": round(attn_end_to_A1, 4), "zero_ablate_acc_pct": round(z_acc * 100, 2), "zero_ablate_ce_nats": round(z_ce, 4), "mean_ablate_acc_pct": round(m_acc * 100, 2), "mean_ablate_ce_nats": round(m_ce, 4), "patch_acc_B_pct": round(p_acc_B * 100, 2), "patch_logit_diff_recovery_pct": round(recovery_pct, 2), }) # 4. Multi-head backup / redundancy tests (why single-head ablation in Layer 1 understates causal role!) subset_tests = [] subsets = [ ("Top-1 Induction Head only (L1H0)", [(1, 0)]), ("Top-2 Induction Heads (L1H0 + L1H3)", [(1, 0), (1, 3)]), ("Top-3 Induction Heads (L1H0 + L1H3 + L1H1)", [(1, 0), (1, 3), (1, 1)]), ("All 4 Layer-1 Heads (L1H0..L1H3)", [(1, 0), (1, 1), (1, 2), (1, 3)]), ("Primary Prev-Token Head (L0H1)", [(0, 1)]), ("Top-2 Prev-Token Heads (L0H1 + L0H2)", [(0, 1), (0, 2)]), ("All 4 Layer-0 Heads (L0H0..L0H3)", [(0, 0), (0, 1), (0, 2), (0, 3)]), ] for label, heads in subsets: z_logits, _ = forward(params, test_tokens, ablate_heads=heads, ablate_mode="zero") z_probs = softmax(z_logits, axis=-1) z_acc = float(np.mean(np.argmax(z_logits, axis=-1) == test_targets)) z_ce = float(-np.mean(np.log(z_probs[np.arange(N), test_targets] + 1e-12))) p_logits, _ = forward(params, corrupt_tokens, patch_heads=heads, patch_cache=clean_cache) p_acc_B = float(np.mean(np.argmax(p_logits, axis=-1) == test_targets)) p_logit_diff = float(np.mean(p_logits[np.arange(N), test_targets] - p_logits[np.arange(N), corrupt_targets])) rec_pct = (p_logit_diff - corrupt_logit_diff) / (clean_logit_diff - corrupt_logit_diff) * 100.0 subset_tests.append({ "subset": label, "heads": [f"L{l}H{h}" for l, h in heads], "zero_ablate_acc_pct": round(z_acc * 100, 2), "zero_ablate_ce_nats": round(z_ce, 4), "patch_acc_B_pct": round(p_acc_B * 100, 2), "patch_logit_diff_recovery_pct": round(rec_pct, 2), }) # Export checkpoint with rounded weights and SHA-256 ckpt = {k: np.round(v, 6).tolist() for k, v in params.items()} ckpt_bytes = json.dumps(ckpt, sort_keys=True).encode("utf-8") ckpt_sha256 = hashlib.sha256(ckpt_bytes).hexdigest() with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "checkpoint_v1.json"), "wb") as f: f.write(ckpt_bytes) # Export 5 sample held-out sequences for live interactive browser execution samples = [] for i in range(6): samples.append({ "sample_id": i, "tokens": test_tokens[i].tolist(), "corrupt_tokens": corrupt_tokens[i].tolist(), "trigger_pos_p": int(trig_pos[i]), "query_token_A": int(test_tokens[i, -1]), "target_token_B": int(test_targets[i]), "corrupt_token_C": int(corrupt_targets[i]), }) audit = { "model_spec": { "architecture": "2-Layer, 4-Head Attention-Only Causal Transformer", "d_model": D_MODEL, "n_layers": N_LAYERS, "n_heads": N_HEADS, "d_head": D_HEAD, "vocab_size": VOCAB_SIZE, "seq_len": SEQ_LEN, "total_parameters": int(sum(v.size for v in params.values())), "train_seed": 42, "train_dataset_seed": 101, "test_dataset_seed": 2026, "test_n_samples": N, "checkpoint_sha256": ckpt_sha256, }, "baseline": { "clean_acc_pct": round(clean_acc * 100, 2), "clean_ce_nats": round(clean_ce, 4), "clean_logit_diff_B_minus_C": round(clean_logit_diff, 4), "corrupt_acc_on_B_pct": round(corrupt_acc_on_B * 100, 2), "corrupt_acc_on_C_pct": round(corrupt_acc_on_C * 100, 2), "corrupt_logit_diff_B_minus_C": round(corrupt_logit_diff, 4), }, "training_history": history, "logit_lens": logit_lens, "heads": head_table, "subset_interventions": subset_tests, "interactive_samples": samples, } with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "audit_results.json"), "w") as f: json.dump(audit, f, indent=2) print(json.dumps({k: v for k, v in audit.items() if k != "interactive_samples"}, indent=2)) if __name__ == "__main__": run_full_audit()