| """ |
| Knowledge Drift Detection: Full Experiment Suite |
| ================================================== |
| Master runner for all experiments. Run on GPU cluster. |
| |
| Experiments (in order): |
| 1. Entropy & Confidence Analysis → Does the model show uncertainty on drifted facts? |
| 2. Year-Token Attention Analysis → Do attention heads attend differently to year tokens? |
| 3. Drift Neuron Discovery (L1) → Can we find sparse "drift neurons" in MLP activations? |
| |
| Each experiment produces: |
| - Raw results (JSON) |
| - Summary statistics (JSON) |
| - Console output with key findings |
| |
| Usage: |
| # Run everything |
| python run_experiments.py --model Qwen/Qwen2.5-7B-Instruct --all |
| |
| # Run individual experiments |
| python run_experiments.py --model Qwen/Qwen2.5-7B-Instruct --entropy |
| python run_experiments.py --model Qwen/Qwen2.5-7B-Instruct --attention |
| python run_experiments.py --model Qwen/Qwen2.5-7B-Instruct --neurons |
| |
| # Quick test (small sample) |
| python run_experiments.py --model Qwen/Qwen2.5-7B-Instruct --all --max_samples 50 |
| |
| Paper References: |
| - Entropy/Confidence: SEPs (Kossen et al., ICLR 2025), Calibration (Radharapu et al.) |
| - Attention: D-LEAF (Yang et al., 2025) adapted for temporal queries |
| - Neurons: SE Neurons (NeurIPS 2024), Neuron Circuits (Arora & Wu, 2026) |
| """ |
|
|
| import argparse |
| import json |
| import os |
| import sys |
| import time |
| import logging |
| from datetime import datetime |
|
|
| |
| try: |
| import sklearn |
| except ImportError: |
| print("Installing scikit-learn...") |
| import subprocess |
| subprocess.check_call([sys.executable, "-m", "pip", "install", "scikit-learn", "-q"]) |
|
|
| logging.basicConfig( |
| level=logging.INFO, |
| format='%(asctime)s - %(levelname)s - %(message)s', |
| handlers=[ |
| logging.StreamHandler(), |
| logging.FileHandler(f"experiment_log_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log") |
| ] |
| ) |
| logger = logging.getLogger(__name__) |
|
|
|
|
| def print_banner(text): |
| width = 80 |
| print("\n" + "█" * width) |
| print(f"█ {text:^{width-4}} █") |
| print("█" * width + "\n") |
|
|
|
|
| def run_entropy_analysis(args): |
| """Experiment 1: Output entropy, top-k probs, logit lens.""" |
| print_banner("EXPERIMENT 1: ENTROPY & CONFIDENCE ANALYSIS") |
| |
| from analyze_drift_signals import load_model, run_analysis |
| |
| 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"] |
| logger.info(f"Filtered to {len(samples)} post-cutoff samples") |
| |
| model, tokenizer = load_model(args.model, args.device) |
| |
| import torch |
| device = "cuda" if torch.cuda.is_available() else "cpu" |
| |
| output_dir = os.path.join(args.output_base, "entropy_analysis") |
| summary = run_analysis(model, tokenizer, samples, output_dir, device, args.max_samples) |
| |
| |
| del model |
| if torch.cuda.is_available(): |
| torch.cuda.empty_cache() |
| |
| return summary |
|
|
|
|
| def run_attention_analysis(args): |
| """Experiment 2: Year-token attention patterns (D-LEAF adapted).""" |
| print_banner("EXPERIMENT 2: YEAR-TOKEN ATTENTION ANALYSIS") |
| |
| from year_attention_analysis import load_model, run_analysis |
| |
| 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"] |
| |
| model, tokenizer = load_model(args.model, args.device) |
| |
| import torch |
| device = "cuda" if torch.cuda.is_available() else "cpu" |
| |
| output_dir = os.path.join(args.output_base, "attention_analysis") |
| summary = run_analysis(model, tokenizer, samples, output_dir, device, args.max_samples) |
| |
| del model |
| if torch.cuda.is_available(): |
| torch.cuda.empty_cache() |
| |
| return summary |
|
|
|
|
| def run_neuron_discovery(args): |
| """Experiment 3: L1-regularized drift neuron discovery.""" |
| print_banner("EXPERIMENT 3: DRIFT NEURON DISCOVERY (L1 PROBES)") |
| |
| from drift_neuron_discovery import run_full_analysis |
| from transformers import AutoModelForCausalLM, AutoTokenizer |
| import torch |
| |
| 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" |
| output_dir = os.path.join(args.output_base, "drift_neurons") |
| results = run_full_analysis(model, tokenizer, samples, output_dir, device, args.max_samples) |
| |
| del model |
| if torch.cuda.is_available(): |
| torch.cuda.empty_cache() |
| |
| return results |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Knowledge Drift Detection Experiments") |
| parser.add_argument("--model", default="Qwen/Qwen2.5-7B-Instruct", help="Model name/path") |
| parser.add_argument("--dataset", default="data/knowledge_drift_dataset.json", help="Dataset path") |
| parser.add_argument("--output_base", default="data/experiments/", help="Base output directory") |
| parser.add_argument("--device", default="auto", help="Device (auto/cuda/cpu)") |
| parser.add_argument("--max_samples", type=int, default=None, help="Max samples per experiment") |
| parser.add_argument("--post_cutoff_only", action="store_true", help="Only post-cutoff queries") |
| |
| |
| parser.add_argument("--all", action="store_true", help="Run all experiments") |
| parser.add_argument("--entropy", action="store_true", help="Run entropy analysis") |
| parser.add_argument("--attention", action="store_true", help="Run attention analysis") |
| parser.add_argument("--neurons", action="store_true", help="Run neuron discovery") |
| |
| args = parser.parse_args() |
| |
| if not any([args.all, args.entropy, args.attention, args.neurons]): |
| args.all = True |
| |
| os.makedirs(args.output_base, exist_ok=True) |
| |
| start_time = time.time() |
| all_results = {} |
| |
| print_banner("KNOWLEDGE DRIFT DETECTION EXPERIMENT SUITE") |
| print(f" Model: {args.model}") |
| print(f" Dataset: {args.dataset}") |
| print(f" Output: {args.output_base}") |
| print(f" Max samples: {args.max_samples or 'all'}") |
| print(f" Post-cutoff only: {args.post_cutoff_only}") |
| print() |
| |
| |
| if args.all or args.entropy: |
| t = time.time() |
| all_results["entropy"] = run_entropy_analysis(args) |
| logger.info(f"Entropy analysis completed in {time.time()-t:.1f}s") |
| |
| if args.all or args.attention: |
| t = time.time() |
| all_results["attention"] = run_attention_analysis(args) |
| logger.info(f"Attention analysis completed in {time.time()-t:.1f}s") |
| |
| if args.all or args.neurons: |
| t = time.time() |
| all_results["neurons"] = run_neuron_discovery(args) |
| logger.info(f"Neuron discovery completed in {time.time()-t:.1f}s") |
| |
| |
| total_time = time.time() - start_time |
| print_banner("ALL EXPERIMENTS COMPLETE") |
| print(f" Total time: {total_time/60:.1f} minutes") |
| print(f" Results saved to: {args.output_base}") |
| |
| |
| metadata = { |
| "model": args.model, |
| "dataset": args.dataset, |
| "max_samples": args.max_samples, |
| "post_cutoff_only": args.post_cutoff_only, |
| "total_time_seconds": total_time, |
| "experiments_run": list(all_results.keys()), |
| "timestamp": datetime.now().isoformat(), |
| } |
| with open(os.path.join(args.output_base, "experiment_metadata.json"), 'w') as f: |
| json.dump(metadata, f, indent=2) |
|
|
|
|
| if __name__ == "__main__": |
| main() |