knowledge-drift-experiments / year_controlled_analysis.py
Raniahossam33's picture
Upload folder using huggingface_hub
14b2318 verified
Raw
History Blame Contribute Delete
18.9 kB
"""
Year-Controlled Analysis — Qwen2.5 (v2 — all issues fixed)
=============================================================
Uses EXISTING cached hidden states. No model loading needed.
Fixes:
- Year type normalization (int vs str)
- Source/format confound tracking
- Zip verification (query match between cache and dataset)
- Proper category handling
Usage:
cd ~/svd_kg/knowledge_drift
python year_controlled_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(" YEAR-CONTROLLED ANALYSIS v2 — Qwen2.5")
print(" Using cached hidden states (no GPU extraction needed)")
print("=" * 70)
# ============================================================
# LOAD CACHED STATES + DATASET
# ============================================================
CACHE_PATH = "data/experiments/tier1_qwen25_v2/cached_states.npz"
DATASET_PATH = "data/tier1_qwen25.json"
OUTPUT_DIR = "data/experiments/tier1_qwen25_v2/year_controlled"
os.makedirs(OUTPUT_DIR, exist_ok=True)
print("\nLoading cached hidden states...")
t0 = time.time()
results = np.load(CACHE_PATH, allow_pickle=True)["results"].tolist()
print(f" Loaded {len(results)} cached results in {time.time()-t0:.1f}s")
print("Loading dataset for metadata...")
with open(DATASET_PATH) as f:
ds = json.load(f)
samples_meta = ds.get("samples", ds)
print(f" Loaded {len(samples_meta)} dataset samples")
# ============================================================
# VERIFY ZIP ALIGNMENT (critical safety check)
# ============================================================
print("\nVerifying cache-dataset alignment...")
mismatches = 0
for i in range(min(100, len(results))):
cached_q = results[i].get("query", "")[:50]
meta_q = samples_meta[i].get("query", "")[:50]
if cached_q != meta_q:
mismatches += 1
if mismatches <= 3:
print(f" MISMATCH at {i}: cache='{cached_q}' vs meta='{meta_q}'")
if mismatches > 0:
print(f" ⚠️ {mismatches}/100 mismatches! Zip alignment is BROKEN.")
print(" Cannot proceed — cached states don't match dataset order.")
sys.exit(1)
else:
print(f" ✅ First 100 queries match. Alignment verified.")
# ============================================================
# ATTACH METADATA FROM DATASET TO CACHED RESULTS
# ============================================================
print("\nAttaching metadata...")
for r, s in zip(results, samples_meta):
# Normalize year to int
raw_year = s.get("year", 0)
try:
r["year"] = int(raw_year) if raw_year else 0
except (ValueError, TypeError):
r["year"] = 0
r["dataset_source"] = s.get("dataset_source", "unknown")
r["drift_date"] = s.get("drift_date", "")
r["sample_id"] = s.get("sample_id", "")
# Extract year mentioned in query text
query_year = None
q = r.get("query", "")
for y in range(2010, 2027):
if str(y) in q:
query_year = y
break
r["query_year"] = query_year
r["has_year_in_query"] = query_year is not None
# Print summary of attached metadata
year_counts = Counter(r["year"] for r in results)
source_counts = Counter(r["dataset_source"] for r in results)
qy_counts = Counter(r["has_year_in_query"] for r in results)
print(f" Years: {dict(sorted(year_counts.items()))}")
print(f" Sources: {dict(source_counts)}")
print(f" Has year in query: {dict(qy_counts)}")
print(f" Drifted: {sum(1 for r in results if r['is_drifted'])}")
print(f" Stable: {sum(1 for r in results if not r['is_drifted'])}")
# ============================================================
# PROBING FUNCTIONS (minimal, from disentanglement_v2.py)
# ============================================================
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 best_auroc(X_np, y_np, device="cuda", n_splits=3):
"""Try multiple C values, return best AUROC."""
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
# ============================================================
device = "cuda:0" if torch.cuda.is_available() else "cpu"
print(f"\nProbe device: {device}")
# ============================================================
# TEST LAYERS
# ============================================================
test_layers = [0, 3, 7, 13, 20, 27]
def run_analysis(name, subset, test_layers, device, baseline=None):
"""Run probe on a subset and print results."""
n_d = sum(1 for r in subset if r["is_drifted"])
n_s = len(subset) - n_d
print(f" Samples: {len(subset)}, Drifted: {n_d}, Stable: {n_s}")
if n_d < 10 or n_s < 10:
print(f" ⚠️ Too few samples to probe (need >=10 per class)")
return {}
results_dict = {}
if baseline:
print(f"\n {'Layer':>5s} {'Baseline':>8s} {name:>8s} {'Delta':>7s}")
else:
print(f"\n {'Layer':>5s} {'AUROC':>7s}")
print(" " + "-" * 40)
for layer in test_layers:
X = np.array([r["hidden_states"][layer] for r in subset])
y = np.array([1 if r["is_drifted"] else 0 for r in subset])
auroc = best_auroc(X, y, device=device)
results_dict[layer] = auroc
if baseline:
delta = auroc - baseline.get(layer, 0)
print(f" {layer:5d} {baseline.get(layer, 0):8.4f} {auroc:8.4f} {delta:+7.4f}")
else:
print(f" {layer:5d} {auroc:7.4f}")
return results_dict
# ============================================================
# ANALYSIS 0: SOURCE/FORMAT CONFOUND CHECK
# ============================================================
print("\n" + "=" * 70)
print(" ANALYSIS 0: SOURCE & FORMAT CONFOUND CHECK")
print("=" * 70)
print("\n Drift rate by data source:")
for src in sorted(source_counts.keys()):
src_results = [r for r in results if r["dataset_source"] == src]
n_d = sum(1 for r in src_results if r["is_drifted"])
n_s = len(src_results) - n_d
pct = n_d / len(src_results) * 100 if src_results else 0
has_yr = sum(1 for r in src_results if r["has_year_in_query"])
print(f" {src:25s}: {n_d:5d}/{len(src_results):5d} drifted ({pct:5.1f}%), {has_yr} with year in query")
print("\n Drift rate by query format:")
for has_yr in [True, False]:
fmt_results = [r for r in results if r["has_year_in_query"] == has_yr]
n_d = sum(1 for r in fmt_results if r["is_drifted"])
label = "with year" if has_yr else "no year"
pct = n_d / len(fmt_results) * 100 if fmt_results else 0
print(f" {label:25s}: {n_d:5d}/{len(fmt_results):5d} drifted ({pct:5.1f}%)")
# ============================================================
# ANALYSIS 1: FULL DATASET (baseline)
# ============================================================
print("\n" + "=" * 70)
print(" ANALYSIS 1: FULL DATASET (baseline)")
print("=" * 70)
baseline = run_analysis("Full", results, test_layers, device)
# ============================================================
# ANALYSIS 2: YEAR-CONTROLLED (2024+ only)
# ============================================================
print("\n" + "=" * 70)
print(" ANALYSIS 2: YEAR-CONTROLLED (2024+ only)")
print(" Both drifted and stable share same year range")
print("=" * 70)
subset_2024 = [r for r in results if r["year"] >= 2024]
print("\n Year breakdown in 2024+ subset:")
for yr in sorted(set(r["year"] for r in subset_2024)):
d = sum(1 for r in subset_2024 if r["year"] == yr and r["is_drifted"])
s = sum(1 for r in subset_2024 if r["year"] == yr and not r["is_drifted"])
print(f" {yr}: {d} drifted, {s} stable")
print("\n Sources in 2024+ subset:")
for src in sorted(set(r["dataset_source"] for r in subset_2024)):
n = sum(1 for r in subset_2024 if r["dataset_source"] == src)
nd = sum(1 for r in subset_2024 if r["dataset_source"] == src and r["is_drifted"])
print(f" {src}: {n} total, {nd} drifted")
yc_results = run_analysis("2024+", subset_2024, test_layers, device, baseline)
# ============================================================
# ANALYSIS 3: SINGLE-YEAR (2025 only)
# ============================================================
print("\n" + "=" * 70)
print(" ANALYSIS 3: SINGLE-YEAR (2025 only)")
print(" Zero year variation — strictest year control")
print("=" * 70)
subset_2025 = [r for r in results if r["year"] == 2025]
sy_results = run_analysis("2025", subset_2025, test_layers, device, baseline)
# ============================================================
# ANALYSIS 4: FORMAT-CONTROLLED (only queries WITH year prefix)
# ============================================================
print("\n" + "=" * 70)
print(" ANALYSIS 4: FORMAT-CONTROLLED")
print(" Only queries with year in text (removes TempLAMA cloze format)")
print("=" * 70)
subset_withyear = [r for r in results if r["has_year_in_query"]]
print(f"\n Sources in this subset:")
for src in sorted(set(r["dataset_source"] for r in subset_withyear)):
n = sum(1 for r in subset_withyear if r["dataset_source"] == src)
nd = sum(1 for r in subset_withyear if r["dataset_source"] == src and r["is_drifted"])
print(f" {src}: {n} total, {nd} drifted")
fc_results = run_analysis("WithYear", subset_withyear, test_layers, device, baseline)
# ============================================================
# ANALYSIS 5: COMBINED STRICTEST (2024+ AND format-matched)
# ============================================================
print("\n" + "=" * 70)
print(" ANALYSIS 5: STRICTEST CONTROL")
print(" 2024+ only, queries with year, excludes known_drift edge cases")
print("=" * 70)
subset_strict = [r for r in results
if r["year"] >= 2024
and r["has_year_in_query"]
and r["category"] in ("unknown_drift", "no_drift", "stable")]
strict_results = run_analysis("Strict", subset_strict, test_layers, device, baseline)
# ============================================================
# ANALYSIS 6: PER-YEAR AUROC (Layer 7)
# ============================================================
print("\n" + "=" * 70)
print(" ANALYSIS 6: PER-YEAR DRIFT AUROC (Layer 7)")
print("=" * 70)
best_layer = 7
all_years = sorted(set(r["year"] for r in results if r["year"] > 0))
print(f"\n {'Year':>6s} {'N':>6s} {'Drifted':>8s} {'Stable':>8s} {'AUROC':>7s}")
print(" " + "-" * 45)
for yr in all_years:
yr_results = [r for r in results if r["year"] == yr]
n_d = sum(1 for r in yr_results if r["is_drifted"])
n_s = len(yr_results) - n_d
if n_d >= 5 and n_s >= 5:
X = np.array([r["hidden_states"][best_layer] for r in yr_results])
y = np.array([1 if r["is_drifted"] else 0 for r in yr_results])
auroc = best_auroc(X, y, device=device)
print(f" {yr:6d} {len(yr_results):6d} {n_d:8d} {n_s:8d} {auroc:7.4f}")
elif n_d == 0:
print(f" {yr:6d} {len(yr_results):6d} {n_d:8d} {n_s:8d} {'--':>7s} (all stable)")
else:
print(f" {yr:6d} {len(yr_results):6d} {n_d:8d} {n_s:8d} {'--':>7s}")
# ============================================================
# ANALYSIS 7: PER-RELATION on year-controlled subset (Layer 7)
# ============================================================
print("\n" + "=" * 70)
print(" ANALYSIS 7: PER-RELATION AUROC (2024+ only, Layer 7)")
print("=" * 70)
rels = Counter(r["relation"] for r in subset_2024)
print(f"\n {'Relation':30s} {'N':>5s} {'Drifted':>7s} {'Stable':>7s} {'AUROC':>7s}")
print(" " + "-" * 65)
for rel in sorted(rels.keys()):
rel_results = [r for r in subset_2024 if r["relation"] == rel]
n_d = sum(1 for r in rel_results if r["is_drifted"])
n_s = len(rel_results) - n_d
if n_d >= 5 and n_s >= 5:
X = np.array([r["hidden_states"][best_layer] for r in rel_results])
y = np.array([1 if r["is_drifted"] else 0 for r in rel_results])
auroc = best_auroc(X, y, device=device)
print(f" {rel:30s} {len(rel_results):5d} {n_d:7d} {n_s:7d} {auroc:7.4f}")
else:
print(f" {rel:30s} {len(rel_results):5d} {n_d:7d} {n_s:7d} {'N/A':>7s}")
# ============================================================
# ANALYSIS 8: NAIVE YEAR BASELINE
# ============================================================
print("\n" + "=" * 70)
print(" ANALYSIS 8: NAIVE YEAR BASELINE")
print(" How well does 'year >= 2024' predict drift? (no probe needed)")
print("=" * 70)
y_true = np.array([1 if r["is_drifted"] else 0 for r in results])
y_year = np.array([1 if r["year"] >= 2024 else 0 for r in results])
tp = int(((y_true == 1) & (y_year == 1)).sum())
fp = int(((y_true == 0) & (y_year == 1)).sum())
tn = int(((y_true == 0) & (y_year == 0)).sum())
fn = int(((y_true == 1) & (y_year == 0)).sum())
acc = (tp + tn) / len(y_true)
prec = tp / (tp + fp) if (tp + fp) > 0 else 0
rec = tp / (tp + fn) if (tp + fn) > 0 else 0
year_auroc = numpy_auroc(y_true, y_year.astype(np.float64))
print(f" Year >= 2024 as drift predictor:")
print(f" AUROC: {year_auroc:.4f}")
print(f" Accuracy: {acc:.4f}")
print(f" Precision: {prec:.4f}")
print(f" Recall: {rec:.4f}")
print(f" TP={tp}, FP={fp}, TN={tn}, FN={fn}")
print(f"\n Compare: Probe AUROC at layer 7 = {baseline.get(7, 0):.4f}")
print(f" Gap: {baseline.get(7, 0) - year_auroc:.4f} (probe advantage over year baseline)")
# ============================================================
# SUMMARY
# ============================================================
print("\n" + "=" * 70)
print(" SUMMARY TABLE")
print("=" * 70)
print(f"\n {'Condition':30s} " + " ".join(f"L{l:2d}" for l in test_layers))
print(" " + "-" * (30 + 8 * len(test_layers)))
for name, res in [("Full dataset", baseline),
("2024+ only", yc_results),
("2025 only", sy_results),
("Format-controlled", fc_results),
("Strictest control", strict_results)]:
if res:
vals = " ".join(f"{res.get(l, 0):.3f}" for l in test_layers)
print(f" {name:30s} {vals}")
print(f"\n {'Year baseline AUROC':30s} {year_auroc:.3f}")
print(f"""
INTERPRETATION:
- If 2024+ AUROC ~ Full AUROC → year is NOT the main signal
- If 2024+ AUROC << Full AUROC → year WAS helping, check if still >0.7
- If 2025-only AUROC still high → probe works with zero year variation
- If year baseline ~ probe AUROC → probe might just read years
- If probe AUROC >> year baseline → probe captures MORE than year info
- If per-relation AUROCs are high → signal is real within content domains
""")
# Save
summary = {
"baseline": baseline,
"year_controlled_2024": yc_results,
"single_year_2025": sy_results,
"format_controlled": fc_results,
"strictest": strict_results,
"year_baseline_auroc": float(year_auroc),
}
with open(os.path.join(OUTPUT_DIR, "year_controlled_results.json"), "w") as f:
json.dump(summary, f, indent=2, default=str)
print(f" Results saved to {OUTPUT_DIR}/year_controlled_results.json")
print("=" * 70)