""" Weight-Space Exploration & Baseline Failure Discovery on Gemma-4-E4B-it 1. Probes Gemma-4-E4B-it across subtle post-cutoff / factual-uncertainty / tool-use prompts and reasoning-heavy prompts to see where the baseline model fails (hallucinates instead of calling `web_search`, or over-thinks / loops in `<|think|>` mode). 2. Directly reads the model's weight matrices (MLP `down_proj` columns + post_feedforward_layernorm + final `norm` + tied `lm_head`) to locate the exact weight-space neurons that promote `<|tool_call>` (token 48) vs. direct answering / refusal / reasoning loops. """ import json import torch from model_loader import load_gemma4_e4b_text, WEB_SEARCH_TOOL, parse_gemma4_tool_call from benchmark_suite import generate_response, get_first_step_tool_prob # Candidate prompts where models typically hallucinate from parametric memory instead of calling `web_search` HARD_AGENTIC_PROMPTS = [ # Subtle factual / post-cutoff / verification queries (no "today" or "current" keyword, so models get tricked into guessing!) {"id": "H1", "prompt": "What was the exact MATH-500 score achieved after editing 131,072 weights in Qwen3.5-0.8B in 'Sparks of Weight-Space Programming'?"}, {"id": "H2", "prompt": "Who are the four co-authors of the MIT CSAIL blog post 'Sparks of Weight-Space Programming'?"}, {"id": "H3", "prompt": "What is the exact CVE-2025-24085 vulnerability and which operating system component does it affect?"}, {"id": "H4", "prompt": "In what year and month was Python 3.14.2 released, and what was its main fix?"}, {"id": "H5", "prompt": "How many parameters are in the Per-Layer Embedding (PLE) table of Gemma 4 E4B?"}, {"id": "H6", "prompt": "Who won the 2026 Nobel Prize in Physics and for what contribution?"}, {"id": "H7", "prompt": "What is the exact git commit hash or repo name for the experiment logs released by Rikiya Takehi for Weight-Space Programming?"}, {"id": "H8", "prompt": "Which team won Super Bowl LX (60) in February 2026 and what was the final score?"}, {"id": "H9", "prompt": "What is the default `sliding_window` size and `global_head_dim` in the `gemma-4-E4B-it` config.json?"}, {"id": "H10", "prompt": "What did OpenAI name the frontier model used in the 'Sparks of Weight-Space Programming' experiments?"}, {"id": "H11", "prompt": "What is the exact population of Reykjavik, Iceland according to the latest 2026 municipal registry?"}, {"id": "H12", "prompt": "Who is the current Prime Minister of Japan and when did they take office?"}, ] @torch.no_grad() def analyze_weight_space_for_token(model, tokenizer, target_token_id=48): """ Pure Weight-Space Reading (zero forward passes required!): For every layer l in [0..41], each column j of `mlp.down_proj.weight` (shape [hidden_size=2560, intermediate_size=10240]) is scaled by `post_feedforward_layernorm.weight` and `model.norm.weight` and projected onto `lm_head.weight[target_token_id]`. This tells us which exact MLP columns in the network are the strongest direct writers of `<|tool_call>` (token 48)! """ W_u = model.lm_head.weight.float() # [262144, 2560] final_norm_w = model.model.norm.weight.float() # [2560] # Effective unembedding direction for target_token_id (centered against mean vocab logit) mean_u = W_u.mean(dim=0) u_target = (W_u[target_token_id] - mean_u) * final_norm_w # [2560] u_target_unit = u_target / u_target.norm() layer_stats = [] top_neurons_global = [] for l_idx, layer in enumerate(model.model.layers): W_down = layer.mlp.down_proj.weight.float() # [2560, 10240] post_ffn_w = layer.post_feedforward_layernorm.weight.float() # [2560] # Effective read direction through this layer's post_feedforward_layernorm eff_dir = u_target_unit * post_ffn_w # [2560] # Project all 10,240 columns of down_proj onto eff_dir # scores: [10240] scores = torch.matmul(eff_dir, W_down) col_norms = W_down.norm(dim=0) cos_sims = scores / (col_norms * eff_dir.norm() + 1e-8) max_score, max_col = scores.max(dim=0) min_score, min_col = scores.min(dim=0) layer_stats.append({ "layer": l_idx, "max_pos_score": float(max_score.item()), "max_pos_col": int(max_col.item()), "max_neg_score": float(min_score.item()), "max_neg_col": int(min_col.item()), "top10_pos_mean": float(torch.topk(scores, 10).values.mean().item()), "top10_neg_mean": float(torch.topk(-scores, 10).values.mean().item()), }) # Collect top 5 promoting and top 5 suppressing columns per layer top_pos_vals, top_pos_cols = torch.topk(scores, 5) for v, c in zip(top_pos_vals, top_pos_cols): top_neurons_global.append({ "layer": l_idx, "col": int(c.item()), "score": float(v.item()), "cos_sim": float(cos_sims[c].item()), "col_norm": float(col_norms[c].item()), "role": "promote", }) top_neg_vals, top_neg_cols = torch.topk(-scores, 5) for v, c in zip(top_neg_vals, top_neg_cols): top_neurons_global.append({ "layer": l_idx, "col": int(c.item()), "score": float(-v.item()), "cos_sim": float(cos_sims[c].item()), "col_norm": float(col_norms[c].item()), "role": "suppress", }) return layer_stats, top_neurons_global def main(): model, tokenizer = load_gemma4_e4b_text() print("\n--- 1. Pure Weight-Space Analysis for `<|tool_call>` (Token 48) ---") layer_stats, top_neurons = analyze_weight_space_for_token(model, tokenizer, target_token_id=48) promoters = sorted([n for n in top_neurons if n["role"] == "promote"], key=lambda x: -x["score"])[:15] suppressors = sorted([n for n in top_neurons if n["role"] == "suppress"], key=lambda x: x["score"])[:15] print("Top 10 `<|tool_call>` Promoting MLP Columns in Weight Space:") for p in promoters[:10]: print(f" Layer {p['layer']:2d} | Col {p['col']:5d} | Score: +{p['score']:.4f} | CosSim: +{p['cos_sim']:.4f} | Norm: {p['col_norm']:.3f}") print("\nTop 10 `<|tool_call>` Suppressing MLP Columns in Weight Space:") for s in suppressors[:10]: print(f" Layer {s['layer']:2d} | Col {s['col']:5d} | Score: {s['score']:.4f} | CosSim: {s['cos_sim']:.4f} | Norm: {s['col_norm']:.3f}") print("\n--- 2. Testing Baseline Gemma-4-E4B-it on Hard Agentic Prompts (No-Thinking vs Thinking) ---") for mode in [False, True]: hits = 0 print(f"\n[Mode: enable_thinking={mode}]") for item in HARD_AGENTIC_PROMPTS: prob_info = get_first_step_tool_prob(model, tokenizer, item["prompt"], enable_thinking=mode) gen = generate_response( model, tokenizer, [{"role": "user", "content": item["prompt"]}], tools=[WEB_SEARCH_TOOL], enable_thinking=mode, max_new_tokens=160, ) tc = parse_gemma4_tool_call(gen["raw_text"]) called = tc is not None if called: hits += 1 preview = gen["raw_text"].replace("\n", " ")[:95] print(f" [{item['id']:3s}] Call={str(called):5s} | P(tool)={prob_info['tool_call_prob']:.3f} | Out: {preview}") print(f"Total Tool Calls (enable_thinking={mode}): {hits}/{len(HARD_AGENTIC_PROMPTS)}") if __name__ == "__main__": main()