| """ |
| Year-Token Attention Analysis for Knowledge Drift Detection |
| ============================================================= |
| Adapted from D-LEAF (Yang et al., 2025) for temporal knowledge drift. |
| |
| Instead of measuring attention to image tokens (multimodal hallucination), |
| we measure attention to YEAR tokens in temporal queries. |
| |
| Key metrics (adapted from D-LEAF): |
| 1. LTAE - Layer Temporal Attention Entropy: flags layers with diffuse year-token attention |
| 2. TAF - Temporal Attention Focus: scores how much each head attends to year tokens |
| 3. Year-token attention distribution: per-head, per-layer analysis |
| |
| Hypothesis: Drifted facts show different attention patterns to year tokens |
| compared to non-drifted facts. Specific layers/heads fail to properly |
| process temporal context when the model's knowledge is outdated. |
| |
| Usage: |
| python year_attention_analysis.py \ |
| --model Qwen/Qwen2.5-7B-Instruct \ |
| --dataset data/knowledge_drift_dataset.json \ |
| --output data/attention_analysis/ \ |
| --max_samples 300 |
| """ |
|
|
| import argparse |
| import json |
| import os |
| import logging |
| import torch |
| import torch.nn.functional as F |
| import numpy as np |
| from tqdm import tqdm |
| from collections import defaultdict |
|
|
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') |
| logger = logging.getLogger(__name__) |
|
|
|
|
| def load_model(model_name, device="auto"): |
| from transformers import AutoModelForCausalLM, AutoTokenizer |
| logger.info(f"Loading model: {model_name}") |
| tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) |
| if tokenizer.pad_token is None: |
| tokenizer.pad_token = tokenizer.eos_token |
| model = AutoModelForCausalLM.from_pretrained( |
| model_name, torch_dtype=torch.float16, device_map=device, |
| trust_remote_code=True, output_attentions=True, |
| ) |
| model.eval() |
| return model, tokenizer |
|
|
|
|
| def find_year_token_positions(tokenizer, input_ids, years=[2015,2018,2020,2022,2023,2024,2025]): |
| """Find positions of year tokens in the input sequence. |
| |
| Strategy: Encode each year string with the tokenizer, then search for |
| those token IDs in the input. This handles any tokenizer quirks. |
| """ |
| input_id_list = input_ids[0].tolist() |
| year_positions = [] |
| |
| for year in years: |
| |
| for year_str in [str(year), f" {year}"]: |
| year_token_ids = tokenizer.encode(year_str, add_special_tokens=False) |
| if not year_token_ids: |
| continue |
| |
| |
| seq_len = len(year_token_ids) |
| for i in range(len(input_id_list) - seq_len + 1): |
| if input_id_list[i:i+seq_len] == year_token_ids: |
| year_positions.extend(range(i, i + seq_len)) |
| |
| return list(set(year_positions)) |
|
|
|
|
| def compute_layer_temporal_attention_entropy(attention_matrix, year_positions): |
| """ |
| LTAE: Layer Temporal Attention Entropy (adapted from LIAE in D-LEAF) |
| |
| For each layer, compute the Maximum Attention Matrix (MAM) across heads |
| for year tokens, then compute entropy. |
| |
| High LTAE = diffuse attention to year tokens = potential temporal confusion |
| Low LTAE = focused attention to year tokens = clear temporal processing |
| """ |
| if not year_positions: |
| return 0.0 |
| |
| |
| num_heads = attention_matrix.shape[0] |
| |
| |
| |
| year_attention = attention_matrix[:, -1, year_positions] |
| |
| |
| mam = year_attention.max(dim=0).values |
| |
| |
| if mam.sum() > 0: |
| p = mam / mam.sum() |
| |
| entropy = -(p * (p + 1e-10).log()).sum().item() |
| else: |
| entropy = 0.0 |
| |
| return entropy |
|
|
|
|
| def compute_temporal_attention_focus(attention_matrix, year_positions): |
| """ |
| TAF: Temporal Attention Focus per head (adapted from IAF in D-LEAF) |
| |
| Sum of attention weights each head assigns to year tokens. |
| Higher TAF = head attends more to temporal context. |
| """ |
| if not year_positions: |
| return torch.zeros(attention_matrix.shape[0]) |
| |
| |
| year_attention = attention_matrix[:, -1, year_positions] |
| taf = year_attention.sum(dim=-1) |
| return taf |
|
|
|
|
| def analyze_single_query(model, tokenizer, query, device="cuda"): |
| """Run a query and extract all attention-based temporal signals.""" |
| |
| 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()} |
| |
| year_positions = find_year_token_positions(tokenizer, inputs['input_ids']) |
| |
| if not year_positions: |
| |
| logger.debug(f"No year tokens found in: {query[:80]}...") |
| logger.debug(f" Token IDs for '2025': {tokenizer.encode('2025', add_special_tokens=False)}") |
| logger.debug(f" Input token count: {inputs['input_ids'].shape[1]}") |
| |
| with torch.no_grad(): |
| outputs = model(**inputs, output_attentions=True) |
| |
| attentions = outputs.attentions |
| num_layers = len(attentions) |
| num_heads = attentions[0].shape[1] |
| |
| |
| layer_ltae = [] |
| layer_taf_mean = [] |
| layer_taf_std = [] |
| layer_taf_min = [] |
| layer_taf_max = [] |
| all_head_tafs = [] |
| |
| for layer_idx in range(num_layers): |
| attn = attentions[layer_idx][0] |
| |
| ltae = compute_layer_temporal_attention_entropy(attn, year_positions) |
| taf = compute_temporal_attention_focus(attn, year_positions) |
| |
| layer_ltae.append(ltae) |
| layer_taf_mean.append(taf.mean().item()) |
| layer_taf_std.append(taf.std().item()) |
| layer_taf_min.append(taf.min().item()) |
| layer_taf_max.append(taf.max().item()) |
| all_head_tafs.append(taf.cpu().numpy().tolist()) |
| |
| |
| total_year_attention = sum( |
| attentions[l][0][:, -1, year_positions].sum().item() |
| for l in range(num_layers) |
| ) if year_positions else 0.0 |
| |
| |
| with torch.no_grad(): |
| gen = model.generate(**inputs, max_new_tokens=30, do_sample=False) |
| answer = tokenizer.decode(gen[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True).strip() |
| |
| return { |
| "num_year_tokens": len(year_positions), |
| "year_positions": year_positions, |
| "generated_answer": answer, |
| "layer_ltae": layer_ltae, |
| "layer_taf_mean": layer_taf_mean, |
| "layer_taf_std": layer_taf_std, |
| "layer_taf_min": layer_taf_min, |
| "layer_taf_max": layer_taf_max, |
| "all_head_tafs": all_head_tafs, |
| "total_year_attention": total_year_attention, |
| "num_layers": num_layers, |
| "num_heads": num_heads, |
| } |
|
|
|
|
| def run_analysis(model, tokenizer, samples, output_dir, device="cuda", max_samples=None): |
| os.makedirs(output_dir, exist_ok=True) |
| |
| |
| logger.info("Year token diagnostic:") |
| for year in [2020, 2024, 2025]: |
| toks = tokenizer.encode(str(year), add_special_tokens=False) |
| toks_sp = tokenizer.encode(f" {year}", add_special_tokens=False) |
| logger.info(f" '{year}' -> {toks} ({tokenizer.convert_ids_to_tokens(toks)})") |
| logger.info(f" ' {year}' -> {toks_sp} ({tokenizer.convert_ids_to_tokens(toks_sp)})") |
| |
| if samples: |
| test_q = samples[0].get("query", "In 2025, the PM of UK was ___") |
| test_ids = tokenizer.encode(test_q, add_special_tokens=False) |
| test_tokens = tokenizer.convert_ids_to_tokens(test_ids) |
| logger.info(f" Sample query tokens: {list(zip(range(len(test_tokens)), test_tokens))[:20]}") |
| test_year_pos = find_year_token_positions(tokenizer, |
| torch.tensor([test_ids])) |
| logger.info(f" Year positions found: {test_year_pos}") |
| |
| 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")] |
| n_d = min(len(drifted), max_samples // 3) |
| n_nd = min(len(not_drifted), max_samples - n_d) |
| import random; random.seed(42) |
| samples = random.sample(drifted, n_d) + random.sample(not_drifted, n_nd) |
| |
| all_results = [] |
| group_signals = defaultdict(lambda: { |
| "ltae": [], "taf_mean": [], "taf_std": [], "total_year_attn": [], |
| "layer_ltae_all": [], "layer_taf_mean_all": [], "head_tafs_all": [], |
| }) |
| |
| year_token_hits = 0 |
| year_token_misses = 0 |
| |
| for sample in tqdm(samples, desc="Analyzing attention"): |
| query = sample["query"] |
| category = sample.get("category", "unknown") |
| is_drifted = sample.get("is_drifted_query", False) |
| |
| try: |
| result = analyze_single_query(model, tokenizer, query, device) |
| except Exception as e: |
| logger.error(f"Error: {e}") |
| continue |
| |
| if result["num_year_tokens"] > 0: |
| year_token_hits += 1 |
| else: |
| year_token_misses += 1 |
| |
| result["query"] = query |
| result["category"] = category |
| result["is_drifted_query"] = is_drifted |
| result["expected_answer"] = sample.get("expected_answer", "") |
| result["entity"] = sample.get("entity", "") |
| result["year"] = sample.get("year", 0) |
| all_results.append(result) |
| |
| |
| group = "DRIFTED" if is_drifted else f"{category}_not_drifted" |
| signals = group_signals[group] |
| signals["ltae"].append(np.mean(result["layer_ltae"])) |
| signals["taf_mean"].append(np.mean(result["layer_taf_mean"])) |
| signals["taf_std"].append(np.mean(result["layer_taf_std"])) |
| signals["total_year_attn"].append(result["total_year_attention"]) |
| signals["layer_ltae_all"].append(result["layer_ltae"]) |
| signals["layer_taf_mean_all"].append(result["layer_taf_mean"]) |
| signals["head_tafs_all"].append(result["all_head_tafs"]) |
| |
| |
| print("\n" + "=" * 90) |
| print(" YEAR-TOKEN ATTENTION ANALYSIS: DRIFTED vs NON-DRIFTED") |
| print("=" * 90) |
| print(f"\n Year token detection: {year_token_hits} hits / {year_token_misses} misses out of {year_token_hits+year_token_misses} samples") |
| if year_token_misses > year_token_hits: |
| print(f" ⚠️ Most queries have NO year tokens detected! Check tokenizer diagnostic above.") |
| |
| print(f"\n{'Group':<45} {'N':>5} {'LTAE':>10} {'TAF mean':>10} {'TAF std':>10} {'YearAttn':>10}") |
| print("-" * 95) |
| |
| summary = {} |
| for group in sorted(group_signals.keys()): |
| s = group_signals[group] |
| n = len(s["ltae"]) |
| if n == 0: continue |
| print(f"{group:<45} {n:>5} {np.mean(s['ltae']):>10.4f} {np.mean(s['taf_mean']):>10.4f} " |
| f"{np.mean(s['taf_std']):>10.4f} {np.mean(s['total_year_attn']):>10.4f}") |
| |
| summary[group] = { |
| "count": n, |
| "avg_ltae": float(np.mean(s["ltae"])), |
| "avg_taf_mean": float(np.mean(s["taf_mean"])), |
| "avg_taf_std": float(np.mean(s["taf_std"])), |
| "avg_total_year_attn": float(np.mean(s["total_year_attn"])), |
| } |
| |
| if s["layer_ltae_all"]: |
| summary[group]["layer_avg_ltae"] = np.array(s["layer_ltae_all"]).mean(axis=0).tolist() |
| summary[group]["layer_avg_taf_mean"] = np.array(s["layer_taf_mean_all"]).mean(axis=0).tolist() |
| |
| |
| if "DRIFTED" in summary: |
| d = summary["DRIFTED"] |
| nd_keys = [k for k in summary if k != "DRIFTED"] |
| if nd_keys: |
| nd = summary[nd_keys[0]] |
| print(f"\n === DRIFTED vs {nd_keys[0]} ===") |
| print(f" LTAE: {d['avg_ltae']:.4f} vs {nd['avg_ltae']:.4f} (Δ={d['avg_ltae']-nd['avg_ltae']:+.4f})") |
| print(f" TAF mean: {d['avg_taf_mean']:.4f} vs {nd['avg_taf_mean']:.4f} (Δ={d['avg_taf_mean']-nd['avg_taf_mean']:+.4f})") |
| |
| if d['avg_ltae'] > nd['avg_ltae']: |
| print(f" ✅ Drifted facts have HIGHER temporal entropy (more confused about time)") |
| if d['avg_taf_mean'] < nd['avg_taf_mean']: |
| print(f" ✅ Drifted facts have LOWER temporal focus (ignoring year token)") |
| |
| |
| if "DRIFTED" in summary and "layer_avg_ltae" in summary["DRIFTED"]: |
| d_layers = np.array(summary["DRIFTED"]["layer_avg_ltae"]) |
| if nd_keys and "layer_avg_ltae" in summary[nd_keys[0]]: |
| nd_layers = np.array(summary[nd_keys[0]]["layer_avg_ltae"]) |
| layer_diff = d_layers - nd_layers |
| top_layers = np.argsort(layer_diff)[-5:][::-1] |
| print(f"\n Top 5 layers where DRIFTED has higher LTAE than non-drifted:") |
| for l in top_layers: |
| print(f" Layer {l}: Δ LTAE = {layer_diff[l]:+.4f}") |
| |
| |
| with open(os.path.join(output_dir, "attention_raw.json"), 'w') as f: |
| json.dump([{k:v for k,v in r.items()} for r in all_results], f, indent=2, default=str) |
| with open(os.path.join(output_dir, "attention_summary.json"), 'w') as f: |
| json.dump(summary, f, indent=2) |
| |
| logger.info(f"Results saved to {output_dir}") |
| return summary |
|
|
|
|
| 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/attention_analysis/") |
| 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() |
| |
| 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) |
| device = "cuda" if torch.cuda.is_available() else "cpu" |
| run_analysis(model, tokenizer, samples, args.output, device, args.max_samples) |
|
|
|
|
| if __name__ == "__main__": |
| main() |