svs-subspace-validity-suite / experiments /impossible_classification.py
Anonymousblind's picture
Upload folder using huggingface_hub
17373f3 verified
Raw
History Blame Contribute Delete
9.49 kB
#!/usr/bin/env python3
"""
The Impossible Classification Test
=====================================
If 9 methods x 4 layers = 36 features can't distinguish visual
from gibberish, the subspace projections contain ZERO content info.
CPU only. Loads data from scaled gibberish GPU checkpoint.
Setup:
!pip install -q scikit-learn scipy xgboost
"""
import json
import numpy as np
from pathlib import Path
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.metrics import roc_auc_score, classification_report
from sklearn.preprocessing import StandardScaler
from scipy import stats as sp
from google.colab import drive
drive.mount("/content/drive", force_remount=False)
print("=" * 65)
print("The Impossible Classification Test")
print("=" * 65)
# ---- Load data from scaled gibberish checkpoint ----
CHECKPOINT = Path("/content/drive/MyDrive/topohd_scaled_gib/gpu_checkpoint.json")
assert CHECKPOINT.exists(), "Run scaled_gibberish_gpu.py first!"
with open(CHECKPOINT) as f:
raw = json.load(f)
# Parse keys: format is "prompttype|method|layer"
TARGET_LAYERS = [8, 16, 24, 32]
methods = set()
for key in raw:
if key.startswith("_"): continue
parts = key.split("|")
if len(parts) == 3:
methods.add(parts[1])
methods.discard("random")
methods = sorted(methods)
print(f"\n Methods: {methods}")
print(f" Layers: {TARGET_LAYERS}")
print(f" Feature dimensions: {len(methods)} x {len(TARGET_LAYERS)} = {len(methods)*len(TARGET_LAYERS)}")
# ---- Build feature matrix ----
# For each prompt index, build a feature vector from all (method, layer) combinations
feature_names = [f"{m}_L{l}" for m in methods for l in TARGET_LAYERS]
N_FEATURES = len(feature_names)
# Get prompt counts
n_visual = raw.get("_progress_visual", 0)
n_gibberish = raw.get("_progress_gibberish", 0)
print(f" Visual prompts: {n_visual}")
print(f" Gibberish prompts: {n_gibberish}")
N = min(n_visual, n_gibberish)
print(f" Using {N} per class (balanced)")
# Build matrices
X_visual = np.zeros((N, N_FEATURES))
X_gibberish = np.zeros((N, N_FEATURES))
for fi, (m, l) in enumerate([(m, l) for m in methods for l in TARGET_LAYERS]):
v_key = f"visual|{m}|{l}"
g_key = f"gibberish|{m}|{l}"
v_vals = raw.get(v_key, [])
g_vals = raw.get(g_key, [])
for i in range(min(N, len(v_vals))):
X_visual[i, fi] = v_vals[i]
for i in range(min(N, len(g_vals))):
X_gibberish[i, fi] = g_vals[i]
X = np.vstack([X_visual, X_gibberish])
y = np.array([1]*N + [0]*N) # 1=visual, 0=gibberish
# Remove any rows with all zeros (missing data)
valid = X.sum(axis=1) != 0
X = X[valid]
y = y[valid]
print(f" Valid samples: {len(X)} ({sum(y)} visual, {len(y)-sum(y)} gibberish)")
# ---- Train classifiers ----
print(f"\n Training 5 classifiers with 10-fold stratified CV ...")
print(f" (Chance level = 50%)")
print(f"\n {'Classifier':<30} {'Accuracy':>10} {'Std':>8} {'AUROC':>8}")
print(f" {'-'*56}")
cv = StratifiedKFold(n_splits=10, shuffle=True, random_state=42)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
classifiers = {
"Logistic Regression": LogisticRegression(max_iter=1000, random_state=42),
"SVM (RBF kernel)": SVC(kernel='rbf', probability=True, random_state=42),
"Random Forest (100 trees)": RandomForestClassifier(n_estimators=100, random_state=42),
"Gradient Boosted Trees": GradientBoostingClassifier(
n_estimators=200, max_depth=4, random_state=42),
"MLP (128-64-32)": MLPClassifier(
hidden_layer_sizes=(128, 64, 32), max_iter=500, random_state=42),
}
all_results = {}
for name, clf in classifiers.items():
# Accuracy
acc_scores = cross_val_score(clf, X_scaled, y, cv=cv, scoring='accuracy')
# AUROC
auc_scores = cross_val_score(clf, X_scaled, y, cv=cv, scoring='roc_auc')
mean_acc = acc_scores.mean()
std_acc = acc_scores.std()
mean_auc = auc_scores.mean()
all_results[name] = dict(accuracy=float(mean_acc), std=float(std_acc),
auroc=float(mean_auc))
marker = " <<<" if mean_acc > 0.55 else ""
print(f" {name:<30} {mean_acc*100:>9.1f}% {std_acc*100:>7.1f}% "
f"{mean_auc:>7.3f}{marker}")
# ---- Statistical test: is the best classifier better than chance? ----
print(f"\n Statistical test: best classifier vs chance (50%)")
best_name = max(all_results, key=lambda k: all_results[k]["accuracy"])
best_acc = all_results[best_name]["accuracy"]
best_std = all_results[best_name]["std"] if "std" in all_results[best_name] else 0
# Re-run best classifier to get per-fold accuracies
best_clf = classifiers[best_name]
fold_accs = cross_val_score(best_clf, X_scaled, y, cv=cv, scoring='accuracy')
# One-sample t-test: is mean accuracy > 0.50?
t_stat, p_val = sp.ttest_1samp(fold_accs, 0.50)
p_one_sided = p_val / 2 if t_stat > 0 else 1.0
print(f" Best: {best_name} ({best_acc*100:.1f}%)")
print(f" Per-fold: {[f'{a*100:.1f}%' for a in fold_accs]}")
print(f" t-test vs 50%: t={t_stat:.3f}, p={p_one_sided:.4f} (one-sided)")
if p_one_sided > 0.05:
print(f" >>> NOT SIGNIFICANT: best classifier ≈ chance <<<")
else:
print(f" >>> SIGNIFICANT: classifier beats chance (but check effect size) <<<")
print(f" Effect: {(best_acc - 0.50)*100:+.1f}pp above chance")
# ---- Feature importance (from gradient boosted) ----
print(f"\n Feature Importance (Gradient Boosted Trees):")
gb = GradientBoostingClassifier(n_estimators=200, max_depth=4, random_state=42)
gb.fit(X_scaled, y)
importances = gb.feature_importances_
# Top 10 features
top_idx = np.argsort(importances)[::-1][:10]
print(f" {'Feature':<25} {'Importance':>12}")
print(f" {'-'*37}")
for idx in top_idx:
print(f" {feature_names[idx]:<25} {importances[idx]:>12.4f}")
# Check if any single feature is useful
print(f"\n Max single-feature importance: {importances.max():.4f}")
print(f" (Uniform = {1/N_FEATURES:.4f})")
if importances.max() < 2/N_FEATURES:
print(f" No feature is more important than chance → no signal exists")
# ---- Also test with factual and math ----
print(f"\n Bonus: Can classifier distinguish visual from factual?")
n_factual = raw.get("_progress_factual", 0)
if n_factual > 0:
X_factual = np.zeros((min(N, n_factual), N_FEATURES))
for fi, (m, l) in enumerate([(m, l) for m in methods for l in TARGET_LAYERS]):
f_key = f"factual|{m}|{l}"
f_vals = raw.get(f_key, [])
for i in range(min(N, len(f_vals))):
X_factual[i, fi] = f_vals[i]
X_vf = np.vstack([X_visual[:min(N, n_factual)], X_factual])
y_vf = np.array([1]*min(N, n_factual) + [0]*min(N, n_factual))
valid_vf = X_vf.sum(axis=1) != 0
X_vf, y_vf = X_vf[valid_vf], y_vf[valid_vf]
X_vf_s = scaler.transform(X_vf)
gb_vf = GradientBoostingClassifier(n_estimators=200, max_depth=4, random_state=42)
vf_scores = cross_val_score(gb_vf, X_vf_s, y_vf, cv=cv, scoring='accuracy')
print(f" Visual vs Factual: {vf_scores.mean()*100:.1f}% ± {vf_scores.std()*100:.1f}%")
print(f"\n Bonus: Can classifier distinguish visual from math?")
n_math = raw.get("_progress_math", 0)
if n_math > 0:
X_math = np.zeros((min(N, n_math), N_FEATURES))
for fi, (m, l) in enumerate([(m, l) for m in methods for l in TARGET_LAYERS]):
mk = f"math|{m}|{l}"
m_vals = raw.get(mk, [])
for i in range(min(N, len(m_vals))):
X_math[i, fi] = m_vals[i]
X_vm = np.vstack([X_visual[:min(N, n_math)], X_math])
y_vm = np.array([1]*min(N, n_math) + [0]*min(N, n_math))
valid_vm = X_vm.sum(axis=1) != 0
X_vm, y_vm = X_vm[valid_vm], y_vm[valid_vm]
X_vm_s = scaler.transform(X_vm)
gb_vm = GradientBoostingClassifier(n_estimators=200, max_depth=4, random_state=42)
vm_scores = cross_val_score(gb_vm, X_vm_s, y_vm, cv=cv, scoring='accuracy')
print(f" Visual vs Math: {vm_scores.mean()*100:.1f}% ± {vm_scores.std()*100:.1f}%")
# ---- Verdict ----
print(f"\n{'='*65}")
print("VERDICT")
print(f"{'='*65}")
all_at_chance = all(r["accuracy"] < 0.55 for r in all_results.values())
if all_at_chance:
print(f"""
>>> ZERO DISCRIMINATIVE INFORMATION <<<
Five classifiers (logistic regression, SVM, random forest,
gradient boosted trees, neural network) trained on the full
{N_FEATURES}-dimensional subspace projection profile
({len(methods)} methods x {len(TARGET_LAYERS)} layers) cannot distinguish
visual prompts from gibberish above chance level.
The 'visual subspace' projections contain ZERO information
about whether the input describes visual content or is
random character sequences. This is not a limitation of
any individual method — it is a fundamental property of
how PCA/SVD extracts directions from transformer hidden states.
""")
else:
above = {k: v for k, v in all_results.items() if v["accuracy"] >= 0.55}
print(f"\n {len(above)} classifiers achieved >55% accuracy.")
print(f" Some weak signal exists in the projection profiles.")
for k, v in above.items():
print(f" {k}: {v['accuracy']*100:.1f}%")
# Save
OUT = Path("/content/drive/MyDrive/topohd_classification")
OUT.mkdir(exist_ok=True, parents=True)
with open(OUT / "classification_results.json", "w") as f:
json.dump(all_results, f, indent=2)
print(f"\n Saved to {OUT}/")