""" Drift Mechanism Analysis — Qwen2.5 ==================================== Three experiments to understand WHAT the probe is detecting. Experiment A: Volatility vs Drift Experiment B: Multi-year trajectory probing Experiment C: Representation structure analysis Uses cached hidden states. No model loading. Usage: cd ~/svd_kg/knowledge_drift python mechanism_analysis.py """ import json, os, sys, time import numpy as np import torch import torch.nn as nn from collections import Counter, defaultdict print("=" * 70) print(" DRIFT MECHANISM ANALYSIS — Qwen2.5") print("=" * 70) # ============================================================ # LOAD # ============================================================ CACHE_PATH = "data/experiments/tier1_qwen25_v2/cached_states.npz" DATASET_PATH = "data/tier1_qwen25.json" OUTPUT_DIR = "data/experiments/tier1_qwen25_v2/mechanism" os.makedirs(OUTPUT_DIR, exist_ok=True) print("\nLoading data...") t0 = time.time() results = np.load(CACHE_PATH, allow_pickle=True)["results"].tolist() with open(DATASET_PATH) as f: ds = json.load(f) samples_meta = ds.get("samples", ds) for r, s in zip(results, samples_meta): try: r["year"] = int(s.get("year", 0)) if s.get("year") else 0 except (ValueError, TypeError): r["year"] = 0 r["dataset_source"] = s.get("dataset_source", "unknown") r["entity"] = s.get("entity", "") r["parent_id"] = s.get("parent_id", "") r["drift_date"] = s.get("drift_date", "") r["fact_id"] = f"{s.get('entity', '')}||{r.get('relation', '')}" print(f" Loaded {len(results)} samples in {time.time()-t0:.1f}s") print(f" Categories: {Counter(r['category'] for r in results)}") print(f" Drifted: {sum(1 for r in results if r['is_drifted'])}") # ============================================================ # PROBING FUNCTIONS # ============================================================ def numpy_auroc(y_true, y_score): y_true = np.asarray(y_true, dtype=np.float64) y_score = np.asarray(y_score, dtype=np.float64) if len(np.unique(y_true)) < 2: return 0.5 n_pos = y_true.sum() n_neg = len(y_true) - n_pos if n_pos == 0 or n_neg == 0: return 0.5 asc = np.argsort(y_score, kind='stable') y_sorted = y_true[asc] s_sorted = y_score[asc] _, inverse, counts = np.unique(s_sorted, return_inverse=True, return_counts=True) cumcounts = np.cumsum(counts) avg_ranks = np.empty(len(y_true), dtype=np.float64) for i, c in enumerate(counts): start = cumcounts[i] - c end = cumcounts[i] avg_ranks[inverse == i] = (start + end + 1) / 2.0 rank_sum = avg_ranks[y_sorted == 1].sum() auroc = (rank_sum - n_pos * (n_pos + 1) / 2) / (n_pos * n_neg) return float(np.clip(auroc, 0.0, 1.0)) def stratified_kfold(y, n_splits, seed=42): rng = np.random.RandomState(seed) y = np.asarray(y) folds = [[] for _ in range(n_splits)] for cls in np.unique(y): idx = np.where(y == cls)[0].copy() rng.shuffle(idx) for i, v in enumerate(idx): folds[i % n_splits].append(v) splits = [] for i in range(n_splits): val_idx = np.array(folds[i], dtype=np.int64) train_idx = np.concatenate([np.array(folds[j], dtype=np.int64) for j in range(n_splits) if j != i]) splits.append((train_idx, val_idx)) return splits def prepare_tensors(X_np, y_np, device): X = np.nan_to_num(np.clip(X_np.astype(np.float32), -1e4, 1e4)) mean, std = X.mean(0, keepdims=True), X.std(0, keepdims=True) + 1e-8 return (torch.tensor((X - mean) / std, dtype=torch.float32, device=device), torch.tensor(y_np.astype(np.float32), device=device), mean, std) class LinearProbeGPU: def __init__(self, input_dim, C=1.0, lr=0.05, max_iter=500, device="cuda"): self.C, self.lr, self.max_iter, self.device = C, lr, max_iter, device self.model = nn.Linear(input_dim, 1, bias=True).to(device) self.coef_ = None def fit(self, X_t, y_t): X_t, y_t = X_t.contiguous(), y_t.contiguous() nn.init.zeros_(self.model.weight); nn.init.zeros_(self.model.bias) wd = 1.0 / (self.C * len(y_t) + 1e-8) opt = torch.optim.LBFGS(self.model.parameters(), lr=self.lr, max_iter=self.max_iter, tolerance_grad=1e-5, tolerance_change=1e-7) crit = nn.BCEWithLogitsLoss() def closure(): opt.zero_grad() loss = crit(self.model(X_t).squeeze(1), y_t) + wd * self.model.weight.pow(2).sum() loss.backward(); return loss opt.step(closure) self.coef_ = [self.model.weight.detach().cpu().numpy().flatten()] return self def predict_proba(self, X_t): with torch.no_grad(): p = torch.sigmoid(self.model(X_t.contiguous()).squeeze(1)).cpu().numpy() return np.column_stack([1 - p, p]) def train_probe_full(X_np, y_np, C=1.0, device="cuda"): X_t, y_t, mean, std = prepare_tensors(X_np, y_np, device) dim = X_t.shape[1] p = LinearProbeGPU(dim, C=C, device=device) p.fit(X_t.clone().contiguous(), y_t.clone().contiguous()) return p, mean, std def best_auroc(X_np, y_np, device="cuda", n_splits=3): best = 0.0 for C in [0.01, 0.1, 1.0]: X_t, y_t, mean, std = prepare_tensors(X_np, y_np, device) dim = X_t.shape[1] mc = min(int((y_np == 0).sum()), int((y_np == 1).sum())) ns = min(n_splits, mc) aurocs = [] if ns >= 2: for tr, va in stratified_kfold(y_np, ns): tr_t = torch.from_numpy(tr).long().to(device) va_t = torch.from_numpy(va).long().to(device) p = LinearProbeGPU(dim, C=C, device=device) p.fit(X_t[tr_t].clone().contiguous(), y_t[tr_t].clone().contiguous()) probs = p.predict_proba(X_t[va_t].clone().contiguous())[:, 1] if len(np.unique(y_np[va])) > 1: aurocs.append(numpy_auroc(y_np[va], probs)) a = float(np.mean(aurocs)) if aurocs else 0.5 if a > best: best = a return best device = "cuda:0" if torch.cuda.is_available() else "cpu" print(f"Device: {device}") # ============================================================ # EXPERIMENT A: VOLATILITY vs DRIFT # ============================================================ print("\n" + "=" * 70) print(" EXPERIMENT A: VOLATILITY vs DRIFT ANALYSIS") print(" Is the probe detecting 'this fact changes' or 'this fact HAS changed'?") print("=" * 70) for layer in [7, 13, 20, 27]: print(f"\n --- Layer {layer} ---") X_all = np.array([r["hidden_states"][layer] for r in results]) y_all = np.array([1 if r["is_drifted"] else 0 for r in results]) probe, mean, std = train_probe_full(X_all, y_all, C=0.1, device=device) X_norm = np.nan_to_num(np.clip(X_all.astype(np.float32), -1e4, 1e4)) X_t = torch.tensor((X_norm - mean) / std, dtype=torch.float32, device=device) all_scores = probe.predict_proba(X_t)[:, 1] categories = ["stable", "no_drift", "known_drift", "unknown_drift"] print(f"\n {'Category':20s} {'N':>6s} {'Mean':>8s} {'Std':>7s} {'Median':>7s} {'%>0.5':>7s}") print(" " + "-" * 62) for cat in categories: cat_idx = [i for i, r in enumerate(results) if r["category"] == cat] if not cat_idx: continue cs = all_scores[cat_idx] n_above = (cs > 0.5).sum() print(f" {cat:20s} {len(cat_idx):6d} {cs.mean():8.4f} {cs.std():7.4f} {np.median(cs):7.4f} {n_above/len(cat_idx)*100:6.1f}%") print(f"\n Drifted vs Stable within each category:") for cat in categories: for is_d, label in [(True, "DRIFTED"), (False, "STABLE ")]: idx = [i for i, r in enumerate(results) if r["category"] == cat and r["is_drifted"] == is_d] if len(idx) < 5: continue scores = all_scores[idx] print(f" {cat:20s} {label}: n={len(idx):5d}, mean={scores.mean():.4f}, median={np.median(scores):.4f}") no_drift_scores = all_scores[[i for i, r in enumerate(results) if r["category"] == "no_drift"]] unk_drifted_scores = all_scores[[i for i, r in enumerate(results) if r["category"] == "unknown_drift" and r["is_drifted"]]] if len(no_drift_scores) > 0 and len(unk_drifted_scores) > 0: y_nd = np.concatenate([np.zeros(len(no_drift_scores)), np.ones(len(unk_drifted_scores))]) s_nd = np.concatenate([no_drift_scores, unk_drifted_scores]) auroc_nd = numpy_auroc(y_nd, s_nd) print(f"\n * AUROC (no_drift vs unknown_drift+drifted): {auroc_nd:.4f}") print(f" no_drift mean: {no_drift_scores.mean():.4f}") print(f" unknown_drift+D mean: {unk_drifted_scores.mean():.4f}") if auroc_nd > 0.85: print(f" -> Probe CLEARLY distinguishes volatile-stable from actually-drifted") elif auroc_nd > 0.70: print(f" -> Probe PARTIALLY distinguishes, some volatility signal mixed in") else: print(f" -> Probe STRUGGLES -> likely detecting volatility not drift") stable_scores = all_scores[[i for i, r in enumerate(results) if r["category"] == "stable"]] if len(stable_scores) > 10 and len(no_drift_scores) > 10: print(f"\n Stable (never changes) mean: {stable_scores.mean():.4f}") print(f" No_drift (volatile, didn't change): {no_drift_scores.mean():.4f}") gap = no_drift_scores.mean() - stable_scores.mean() print(f" Gap: {gap:+.4f}") if abs(gap) > 0.1: print(f" -> VOLATILITY SIGNAL: probe scores volatile facts higher even when not drifted") else: print(f" -> NO volatility signal: similar scores, probe detects actual drift") # ============================================================ # EXPERIMENT B: MULTI-YEAR TRAJECTORY PROBING # ============================================================ print("\n\n" + "=" * 70) print(" EXPERIMENT B: MULTI-YEAR TRAJECTORY ANALYSIS") print(" How does the same fact's representation change across years?") print("=" * 70) # Try both grouping strategies facts_entity = defaultdict(list) facts_parent = defaultdict(list) for i, r in enumerate(results): fid = r["fact_id"] if fid and fid != "||": facts_entity[fid].append(i) pid = r.get("parent_id", "") if pid and str(pid).strip(): facts_parent[pid].append(i) multi_entity = {f: idx for f, idx in facts_entity.items() if len(idx) >= 3} multi_parent = {f: idx for f, idx in facts_parent.items() if len(idx) >= 3} print(f"\n Grouping by entity||relation: {len(facts_entity)} unique, {len(multi_entity)} with 3+ samples") print(f" Grouping by parent_id: {len(facts_parent)} unique, {len(multi_parent)} with 3+ samples") # Use whichever has more multi-year facts multi_year_facts = multi_entity if len(multi_entity) >= len(multi_parent) else multi_parent grouping = "entity||relation" if len(multi_entity) >= len(multi_parent) else "parent_id" print(f" Using: {grouping} ({len(multi_year_facts)} facts)") # Show some examples print(f"\n Example multi-year facts:") count = 0 for fid, indices in list(multi_year_facts.items())[:5]: years = sorted(set(results[i]["year"] for i in indices)) drifted = any(results[i]["is_drifted"] for i in indices) q_sample = results[indices[0]]["query"][:60] print(f" {fid[:40]:40s} years={years} drifted={drifted}") for layer in [7, 27]: print(f"\n --- Trajectory Analysis at Layer {layer} ---") traj_feats = [] traj_labels = [] for fid, indices in multi_year_facts.items(): sorted_idx = sorted(indices, key=lambda i: results[i]["year"]) is_drifted = any(results[i]["is_drifted"] for i in sorted_idx) states = np.array([results[i]["hidden_states"][layer] for i in sorted_idx]) mean_state = states.mean(axis=0) var_across = states.var(axis=0).mean() cos_dists = [] for j in range(len(states) - 1): n1 = np.linalg.norm(states[j]) n2 = np.linalg.norm(states[j + 1]) if n1 > 0 and n2 > 0: cos_dists.append(1 - np.dot(states[j], states[j + 1]) / (n1 * n2)) max_cos_dist = max(cos_dists) if cos_dists else 0 mean_cos_dist = np.mean(cos_dists) if cos_dists else 0 last_diff = np.linalg.norm(states[-1] - mean_state) mid = len(states) // 2 if mid > 0: var_first = states[:mid].var(axis=0).mean() var_last = states[mid:].var(axis=0).mean() var_ratio = var_last / (var_first + 1e-10) else: var_ratio = 1.0 feat = np.concatenate([ mean_state, [var_across, max_cos_dist, mean_cos_dist, last_diff, var_ratio, len(states)], ]) traj_feats.append(feat) traj_labels.append(1 if is_drifted else 0) X_traj = np.array(traj_feats) y_traj = np.array(traj_labels) n_d = int(y_traj.sum()) n_s = len(y_traj) - n_d print(f" Facts: {len(y_traj)}, Drifted: {n_d}, Stable: {n_s}") if n_d >= 10 and n_s >= 10: auroc_full = best_auroc(X_traj, y_traj, device=device) print(f" Trajectory probe AUROC (full features): {auroc_full:.4f}") X_stats = X_traj[:, -6:] auroc_stats = best_auroc(X_stats, y_traj, device=device) print(f" Trajectory probe AUROC (stats only): {auroc_stats:.4f}") dim = X_traj.shape[1] - 6 X_mean = X_traj[:, :dim] auroc_mean = best_auroc(X_mean, y_traj, device=device) print(f" Mean-state probe AUROC (baseline): {auroc_mean:.4f}") print(f"\n Trajectory statistics breakdown:") stat_names = ["var_across_years", "max_cos_dist", "mean_cos_dist", "last_diff", "var_ratio", "n_timepoints"] for j, name in enumerate(stat_names): vals_d = X_stats[y_traj == 1, j] vals_s = X_stats[y_traj == 0, j] print(f" {name:25s}: drifted={vals_d.mean():.6f}+/-{vals_d.std():.6f} stable={vals_s.mean():.6f}+/-{vals_s.std():.6f}") else: print(f" Not enough facts (need >=10 per class): {n_d} drifted, {n_s} stable") # ============================================================ # EXPERIMENT C: REPRESENTATION STRUCTURE ANALYSIS # ============================================================ print("\n\n" + "=" * 70) print(" EXPERIMENT C: REPRESENTATION STRUCTURE ANALYSIS") print(" What is structurally different about drifted vs stable hidden states?") print("=" * 70) for layer in [7, 13, 27]: print(f"\n --- Layer {layer} ---") drifted_idx = [i for i, r in enumerate(results) if r["is_drifted"]] stable_idx = [i for i, r in enumerate(results) if not r["is_drifted"]] X_d = np.array([results[i]["hidden_states"][layer] for i in drifted_idx]) X_s = np.array([results[i]["hidden_states"][layer] for i in stable_idx]) mag_d = np.linalg.norm(X_d, axis=1) mag_s = np.linalg.norm(X_s, axis=1) print(f"\n Activation magnitude (L2 norm):") print(f" Drifted: {mag_d.mean():.2f} +/- {mag_d.std():.2f}") print(f" Stable: {mag_s.mean():.2f} +/- {mag_s.std():.2f}") threshold = 0.01 sparse_d = (np.abs(X_d) < threshold).mean(axis=1) sparse_s = (np.abs(X_s) < threshold).mean(axis=1) print(f"\n Activation sparsity (fraction < {threshold}):") print(f" Drifted: {sparse_d.mean():.4f}") print(f" Stable: {sparse_s.mean():.4f}") def act_entropy(X): abs_X = np.abs(X) abs_X = abs_X / (abs_X.sum(axis=1, keepdims=True) + 1e-10) return -(abs_X * np.log(abs_X + 1e-10)).sum(axis=1) ent_d = act_entropy(X_d) ent_s = act_entropy(X_s) print(f"\n Activation entropy:") print(f" Drifted: {ent_d.mean():.4f} +/- {ent_d.std():.4f}") print(f" Stable: {ent_s.mean():.4f} +/- {ent_s.std():.4f}") for k in [10, 50, 100]: topk_d = np.sort(np.abs(X_d), axis=1)[:, -k:].sum(axis=1) / (np.abs(X_d).sum(axis=1) + 1e-10) topk_s = np.sort(np.abs(X_s), axis=1)[:, -k:].sum(axis=1) / (np.abs(X_s).sum(axis=1) + 1e-10) print(f"\n Top-{k} neuron concentration:") print(f" Drifted: {topk_d.mean():.4f}") print(f" Stable: {topk_s.mean():.4f}") ent_out_d = [results[i]["entropy"] for i in drifted_idx] ent_out_s = [results[i]["entropy"] for i in stable_idx] print(f"\n Output token entropy:") print(f" Drifted: {np.mean(ent_out_d):.4f} +/- {np.std(ent_out_d):.4f}") print(f" Stable: {np.mean(ent_out_s):.4f} +/- {np.std(ent_out_s):.4f}") prob_d = [results[i]["top_prob"] for i in drifted_idx] prob_s = [results[i]["top_prob"] for i in stable_idx] print(f"\n Top token probability (confidence):") print(f" Drifted: {np.mean(prob_d):.4f} +/- {np.std(prob_d):.4f}") print(f" Stable: {np.mean(prob_s):.4f} +/- {np.std(prob_s):.4f}") y_bin = np.array([1] * len(drifted_idx) + [0] * len(stable_idx)) stats_dict = { "L2 norm": np.concatenate([mag_d, mag_s]), "Sparsity": np.concatenate([sparse_d, sparse_s]), "Act entropy": np.concatenate([ent_d, ent_s]), "Output entropy": np.array(ent_out_d + ent_out_s), "Neg top prob": -np.array(prob_d + prob_s), "Top-10 conc": np.concatenate([ np.sort(np.abs(X_d), axis=1)[:, -10:].sum(axis=1) / (np.abs(X_d).sum(axis=1) + 1e-10), np.sort(np.abs(X_s), axis=1)[:, -10:].sum(axis=1) / (np.abs(X_s).sum(axis=1) + 1e-10), ]), } print(f"\n Single-statistic AUROC for drift detection:") for name, scores in stats_dict.items(): auroc = numpy_auroc(y_bin, scores) print(f" {name:25s}: {auroc:.4f}") # ============================================================ # SUMMARY # ============================================================ print("\n\n" + "=" * 70) print(" KEY QUESTIONS ANSWERED") print("=" * 70) print(""" A. VOLATILITY vs DRIFT If no_drift mean score ~ stable mean score -> probe detects DRIFT If no_drift mean score >> stable mean score -> probe detects VOLATILITY If AUROC(no_drift vs unknown_drift+drifted) > 0.85 -> clean drift detection B. TRAJECTORY VALUE If trajectory AUROC > mean-state AUROC -> temporal structure adds signal If stats-only AUROC is high -> the CHANGE PATTERN itself is informative If stats-only AUROC is low -> signal is in the representation not trajectory C. REPRESENTATION STRUCTURE If single-stat AUROC > 0.7 -> that stat is a simple baseline to beat If all single-stat AUROCs < 0.6 -> signal is in complex patterns Large gaps in any stat -> that is what the probe exploits """) print(f" Done.") print("=" * 70)