| """ |
| Drift Neuron Discovery via L1-Regularized Probing |
| =================================================== |
| Inspired by: |
| - Semantic Entropy Neurons (NeurIPS 2024): L1 probes find sparse neuron sets |
| - Neuron Circuits (Arora & Wu, 2026): MLP activations are a sparse basis |
| - Calibration paper (Radharapu et al.): Brier score loss for calibration |
| |
| Key idea: Train L1-regularized linear probes on MLP ACTIVATIONS (not outputs!) |
| to find the minimal set of neurons that predict whether knowledge has drifted. |
| |
| If a small set of "drift neurons" exists, this validates that: |
| 1. The model encodes temporal validity internally |
| 2. Drift detection can be done with minimal compute |
| 3. These neurons can potentially be steered (connecting to YaPO) |
| |
| Usage: |
| python drift_neuron_discovery.py \ |
| --model Qwen/Qwen2.5-7B-Instruct \ |
| --dataset data/knowledge_drift_dataset.json \ |
| --output data/drift_neurons/ \ |
| --max_samples 500 |
| """ |
|
|
| import argparse |
| import json |
| import os |
| import logging |
| import torch |
| import torch.nn as nn |
| import torch.nn.functional as F |
| import numpy as np |
| from tqdm import tqdm |
| from collections import defaultdict |
| from sklearn.model_selection import StratifiedKFold |
| from sklearn.metrics import roc_auc_score, average_precision_score |
|
|
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') |
| logger = logging.getLogger(__name__) |
|
|
|
|
| |
| |
| |
|
|
| class MLPActivationExtractor: |
| """ |
| Extract MLP activations (pre-down-projection) from each layer. |
| |
| Per Arora & Wu (2026): MLP activations are a PRIVILEGED BASIS |
| due to element-wise nonlinearity (SiLU/GeLU). Much sparser than |
| MLP outputs or residual stream. |
| """ |
| def __init__(self, model): |
| self.model = model |
| self.activations = {} |
| self.hooks = [] |
| self._register_hooks() |
| |
| def _register_hooks(self): |
| """Register forward hooks on MLP intermediate activations.""" |
| for name, module in self.model.named_modules(): |
| |
| |
| if 'mlp.gate_proj' in name or 'mlp.up_proj' in name: |
| layer_idx = name.split('.')[2] if 'layers' in name else name.split('.')[1] |
| hook = module.register_forward_hook( |
| lambda mod, inp, out, n=name, l=layer_idx: |
| self._save_activation(n, l, out) |
| ) |
| self.hooks.append(hook) |
| |
| def _save_activation(self, name, layer_idx, output): |
| key = f"layer_{layer_idx}" |
| if key not in self.activations: |
| self.activations[key] = {} |
| if 'gate' in name: |
| self.activations[key]['gate'] = output.detach() |
| elif 'up' in name: |
| self.activations[key]['up'] = output.detach() |
| |
| def get_mlp_activations(self): |
| """ |
| Get the actual MLP hidden activations: SiLU(gate) * up |
| This is the privileged basis from Arora & Wu (2026). |
| """ |
| result = {} |
| for key, acts in self.activations.items(): |
| if 'gate' in acts and 'up' in acts: |
| |
| hidden = F.silu(acts['gate']) * acts['up'] |
| result[key] = hidden |
| return result |
| |
| def clear(self): |
| self.activations = {} |
| |
| def remove_hooks(self): |
| for h in self.hooks: |
| h.remove() |
|
|
|
|
| def extract_features(model, tokenizer, query, extractor, device="cuda"): |
| """ |
| Extract MLP activations and hidden states for a single query. |
| Returns per-layer features at the last token position. |
| """ |
| prompt = f"<|im_start|>system\nAnswer concisely.<|im_end|>\n<|im_start|>user\n{query}<|im_end|>\n<|im_start|>assistant\n" |
| |
| inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512) |
| inputs = {k: v.to(device) for k, v in inputs.items()} |
| |
| extractor.clear() |
| with torch.no_grad(): |
| outputs = model(**inputs, output_hidden_states=True) |
| |
| |
| mlp_acts = extractor.get_mlp_activations() |
| |
| |
| hidden_states = outputs.hidden_states |
| |
| features = {} |
| |
| |
| for key, act in mlp_acts.items(): |
| layer_idx = int(key.split('_')[1]) |
| features[f"mlp_act_layer_{layer_idx}"] = act[0, -1, :].cpu() |
| |
| |
| for i, h in enumerate(hidden_states): |
| features[f"hidden_layer_{i}"] = h[0, -1, :].cpu() |
| |
| return features |
|
|
|
|
| |
| |
| |
|
|
| class DriftProbeL1(nn.Module): |
| """ |
| Linear probe with L1 regularization for drift detection. |
| |
| Trained with Brier score loss (proper scoring rule) for calibration. |
| L1 regularization forces sparsity, revealing "drift neurons." |
| """ |
| def __init__(self, input_dim): |
| super().__init__() |
| self.linear = nn.Linear(input_dim, 1) |
| |
| def forward(self, x): |
| return torch.sigmoid(self.linear(x)) |
| |
| def get_nonzero_weights(self, threshold=1e-4): |
| """Get indices of neurons with non-negligible weights.""" |
| weights = self.linear.weight.data.abs().squeeze() |
| nonzero = (weights > threshold).nonzero(as_tuple=True)[0] |
| return nonzero, weights[nonzero] |
|
|
|
|
| def brier_score_loss(pred, target): |
| """Brier score: proper scoring rule for calibration.""" |
| return ((pred.squeeze() - target.float()) ** 2).mean() |
|
|
|
|
| def train_probe(features, labels, layer_key, l1_lambda=0.01, epochs=200, lr=0.001): |
| """ |
| Train an L1-regularized probe on a specific layer's features. |
| |
| Returns: trained probe, metrics, discovered neurons |
| """ |
| X = torch.stack(features).float() |
| y = torch.tensor(labels).float() |
| |
| input_dim = X.shape[1] |
| |
| |
| skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) |
| fold_metrics = [] |
| best_probe = None |
| best_auroc = 0 |
| |
| for fold, (train_idx, val_idx) in enumerate(skf.split(X, y)): |
| X_train, X_val = X[train_idx], X[val_idx] |
| y_train, y_val = y[train_idx], y[val_idx] |
| |
| probe = DriftProbeL1(input_dim) |
| optimizer = torch.optim.Adam(probe.parameters(), lr=lr, weight_decay=0) |
| |
| for epoch in range(epochs): |
| probe.train() |
| pred = probe(X_train) |
| |
| |
| loss = brier_score_loss(pred, y_train) |
| l1_reg = l1_lambda * probe.linear.weight.abs().sum() |
| total_loss = loss + l1_reg |
| |
| optimizer.zero_grad() |
| total_loss.backward() |
| optimizer.step() |
| |
| |
| probe.eval() |
| with torch.no_grad(): |
| val_pred = probe(X_val).squeeze().numpy() |
| val_labels = y_val.numpy() |
| |
| try: |
| auroc = roc_auc_score(val_labels, val_pred) |
| auprc = average_precision_score(val_labels, val_pred) |
| except ValueError: |
| auroc, auprc = 0.5, 0.5 |
| |
| |
| brier = np.mean((val_pred - val_labels) ** 2) |
| |
| |
| nonzero_idx, nonzero_weights = probe.get_nonzero_weights() |
| n_neurons = len(nonzero_idx) |
| |
| fold_metrics.append({ |
| "auroc": auroc, "auprc": auprc, "brier": brier, "n_neurons": n_neurons |
| }) |
| |
| if auroc > best_auroc: |
| best_auroc = auroc |
| best_probe = probe |
| |
| avg_metrics = { |
| "auroc": np.mean([m["auroc"] for m in fold_metrics]), |
| "auroc_std": np.std([m["auroc"] for m in fold_metrics]), |
| "auprc": np.mean([m["auprc"] for m in fold_metrics]), |
| "brier": np.mean([m["brier"] for m in fold_metrics]), |
| "n_neurons": np.mean([m["n_neurons"] for m in fold_metrics]), |
| } |
| |
| |
| nonzero_idx, nonzero_weights = best_probe.get_nonzero_weights() |
| sorted_order = nonzero_weights.argsort(descending=True) |
| drift_neurons = [ |
| {"neuron_idx": nonzero_idx[i].item(), "weight": nonzero_weights[i].item()} |
| for i in sorted_order[:50] |
| ] |
| |
| return best_probe, avg_metrics, drift_neurons |
|
|
|
|
| |
| |
| |
|
|
| def run_full_analysis(model, tokenizer, samples, output_dir, device="cuda", max_samples=None): |
| os.makedirs(output_dir, exist_ok=True) |
| |
| if max_samples: |
| drifted = [s for s in samples if s.get("is_drifted_query")] |
| not_drifted = [s for s in samples if not s.get("is_drifted_query") |
| and s.get("temporal_zone") == "post_cutoff"] |
| import random; random.seed(42) |
| n_d = min(len(drifted), max_samples // 2) |
| n_nd = min(len(not_drifted), max_samples - n_d) |
| samples = random.sample(drifted, n_d) + random.sample(not_drifted, n_nd) |
| logger.info(f"Sampled {n_d} drifted + {n_nd} non-drifted = {len(samples)} total") |
| |
| extractor = MLPActivationExtractor(model) |
| |
| |
| logger.info("Extracting MLP activations and hidden states...") |
| all_features = defaultdict(list) |
| all_labels = [] |
| |
| for sample in tqdm(samples, desc="Extracting features"): |
| try: |
| features = extract_features(model, tokenizer, sample["query"], extractor, device) |
| for key, feat in features.items(): |
| all_features[key].append(feat) |
| all_labels.append(1 if sample.get("is_drifted_query") else 0) |
| except Exception as e: |
| logger.error(f"Error extracting: {e}") |
| |
| n_drifted = sum(all_labels) |
| n_total = len(all_labels) |
| logger.info(f"Extracted features: {n_total} samples ({n_drifted} drifted, {n_total-n_drifted} non-drifted)") |
| |
| |
| logger.info("Training L1-regularized drift probes...") |
| |
| layer_results = {} |
| |
| |
| l1_values = [0.001, 0.005, 0.01, 0.05, 0.1] |
| |
| for layer_key in sorted(all_features.keys()): |
| if not all_features[layer_key]: |
| continue |
| |
| best_l1_result = None |
| best_auroc = 0 |
| |
| for l1 in l1_values: |
| probe, metrics, neurons = train_probe( |
| all_features[layer_key], all_labels, layer_key, l1_lambda=l1 |
| ) |
| |
| if metrics["auroc"] > best_auroc: |
| best_auroc = metrics["auroc"] |
| best_l1_result = { |
| "layer": layer_key, "l1_lambda": l1, |
| "metrics": metrics, "drift_neurons": neurons, |
| } |
| |
| if best_l1_result: |
| layer_results[layer_key] = best_l1_result |
| |
| |
| print("\n" + "=" * 90) |
| print(" DRIFT NEURON DISCOVERY RESULTS") |
| print("=" * 90) |
| |
| |
| sorted_layers = sorted(layer_results.items(), key=lambda x: x[1]["metrics"]["auroc"], reverse=True) |
| |
| print(f"\n{'Layer':<30} {'AUROC':>8} {'AUPRC':>8} {'Brier':>8} {'#Neurons':>10} {'L1':>8}") |
| print("-" * 80) |
| |
| for layer_key, result in sorted_layers[:20]: |
| m = result["metrics"] |
| print(f"{layer_key:<30} {m['auroc']:>8.4f} {m['auprc']:>8.4f} {m['brier']:>8.4f} " |
| f"{m['n_neurons']:>10.1f} {result['l1_lambda']:>8.3f}") |
| |
| |
| if sorted_layers: |
| best_layer, best_result = sorted_layers[0] |
| print(f"\n 🏆 BEST LAYER: {best_layer}") |
| print(f" AUROC: {best_result['metrics']['auroc']:.4f} ± {best_result['metrics']['auroc_std']:.4f}") |
| print(f" Active neurons: {best_result['metrics']['n_neurons']:.0f}") |
| print(f" Top drift neurons:") |
| for n in best_result["drift_neurons"][:10]: |
| print(f" Neuron {n['neuron_idx']:>6d}: weight = {n['weight']:.4f}") |
| |
| |
| print("\n\n === MLP ACTIVATIONS vs HIDDEN STATES ===") |
| mlp_layers = [(k, v) for k, v in sorted_layers if "mlp_act" in k] |
| hidden_layers = [(k, v) for k, v in sorted_layers if "hidden" in k] |
| |
| if mlp_layers and hidden_layers: |
| best_mlp = mlp_layers[0][1]["metrics"]["auroc"] |
| best_hidden = hidden_layers[0][1]["metrics"]["auroc"] |
| print(f" Best MLP activation probe: AUROC = {best_mlp:.4f} ({mlp_layers[0][0]})") |
| print(f" Best hidden state probe: AUROC = {best_hidden:.4f} ({hidden_layers[0][0]})") |
| |
| if best_mlp > best_hidden: |
| print(f" ✅ MLP activations are MORE informative (consistent with Arora & Wu 2026)") |
| else: |
| print(f" ℹ️ Hidden states are more informative for this task") |
| |
| |
| save_results = {} |
| for k, v in layer_results.items(): |
| save_results[k] = { |
| "l1_lambda": v["l1_lambda"], |
| "metrics": v["metrics"], |
| "drift_neurons": v["drift_neurons"], |
| } |
| |
| with open(os.path.join(output_dir, "drift_neuron_results.json"), 'w') as f: |
| json.dump(save_results, f, indent=2) |
| |
| |
| ranking = [{"layer": k, **v["metrics"], "l1": v["l1_lambda"]} for k, v in sorted_layers] |
| with open(os.path.join(output_dir, "layer_ranking.json"), 'w') as f: |
| json.dump(ranking, f, indent=2) |
| |
| logger.info(f"Results saved to {output_dir}") |
| return layer_results |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--model", default="Qwen/Qwen2.5-7B-Instruct") |
| parser.add_argument("--dataset", default="data/knowledge_drift_dataset.json") |
| parser.add_argument("--output", default="data/drift_neurons/") |
| parser.add_argument("--max_samples", type=int, default=None) |
| parser.add_argument("--device", default="auto") |
| parser.add_argument("--post_cutoff_only", action="store_true") |
| args = parser.parse_args() |
| |
| from transformers import AutoModelForCausalLM, AutoTokenizer |
| |
| logger.info(f"Loading model: {args.model}") |
| tokenizer = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True) |
| if tokenizer.pad_token is None: |
| tokenizer.pad_token = tokenizer.eos_token |
| model = AutoModelForCausalLM.from_pretrained( |
| args.model, torch_dtype=torch.float16, device_map=args.device, trust_remote_code=True, |
| ) |
| model.eval() |
| |
| with open(args.dataset, 'r') as f: |
| dataset = json.load(f) |
| samples = dataset["samples"] |
| if args.post_cutoff_only: |
| samples = [s for s in samples if s.get("temporal_zone") == "post_cutoff"] |
| |
| device = "cuda" if torch.cuda.is_available() else "cpu" |
| run_full_analysis(model, tokenizer, samples, args.output, device, args.max_samples) |
|
|
|
|
| if __name__ == "__main__": |
| main() |