""" Subspace Validity Suite (SVS) — v1.0 ====================================== A diagnostic toolkit for validating claimed "visual directions" in Vision-Language Models. Usage: from svs_toolkit import SubspaceValiditySuite svs = SubspaceValiditySuite() report = svs.full_report( directions, # (k, d) numpy array of claimed visual directions hidden_states_visual, # list of (d,) arrays from visual prompts hidden_states_gibberish, # list of (d,) arrays from gibberish hidden_states_factual, # optional hidden_states_math, # optional ) svs.print_report(report) Reference: "The Subspace Validity Suite: Do Visual Directions in Vision-Language Models Survive Basic Sanity Checks?" WACV 2027, Evaluations and Datasets Track """ import numpy as np from typing import Dict, List, Optional, Tuple from dataclasses import dataclass, field from scipy import stats @dataclass class TestResult: """Result of a single SVS test.""" name: str passed: bool score: float threshold: float details: Dict = field(default_factory=dict) interpretation: str = "" class SubspaceValiditySuite: """ Subspace Validity Suite: 6 diagnostic tests for visual directions. Test 1: Gibberish Specificity (Gib/Vis ratio + TOST equivalence) Test 2: Cross-Type Discrimination (AUROC for visual vs non-visual) Test 3: Projection Magnitude (directions above random baseline) Test 4: Anisotropy Orthogonality (overlap with random subspace) Test 5: Direction Consistency (stability across calibration splits) Test 6: Pairwise Discrimination (classifier on joint profiles) """ def __init__(self, equivalence_margin: float = 0.2, alpha: float = 0.05, n_bootstrap: int = 10000): self.equivalence_margin = equivalence_margin self.alpha = alpha self.n_bootstrap = n_bootstrap # ============================================================== # Test 1: Gibberish Specificity # ============================================================== def test_gibberish_specificity( self, directions: np.ndarray, h_visual: List[np.ndarray], h_gibberish: List[np.ndarray], random_basis: Optional[np.ndarray] = None, ) -> TestResult: """ Test whether directions respond more to visual input than gibberish. PASS: Gib/Vis < 1 - margin AND TOST rejects equivalence FAIL: Gib/Vis ≈ 1.0 (directions are content-blind) Args: directions: (k, d) claimed visual directions h_visual: list of (d,) hidden states from visual prompts h_gibberish: list of (d,) hidden states from gibberish random_basis: optional (k, d) random baseline """ if random_basis is None: d = directions.shape[1] rng = np.random.RandomState(42) random_basis = np.linalg.qr( rng.randn(d, directions.shape[0]))[0].T[:directions.shape[0]] def compute_alpha(h, dirs, rand): hn = np.linalg.norm(h) if hn < 1e-12: return 0.0 proj = (dirs @ h) @ dirs proj_r = (rand @ h) @ rand return float(np.linalg.norm(proj) / (np.linalg.norm(proj_r) + 1e-10)) alphas_vis = [compute_alpha(h, directions, random_basis) for h in h_visual] alphas_gib = [compute_alpha(h, directions, random_basis) for h in h_gibberish] mean_vis = np.mean(alphas_vis) mean_gib = np.mean(alphas_gib) gib_vis = mean_gib / (mean_vis + 1e-10) # TOST equivalence test n = min(len(alphas_vis), len(alphas_gib)) ratios = np.array(alphas_gib[:n]) / (np.array(alphas_vis[:n]) + 1e-10) delta = self.equivalence_margin t_lo, p_lo = stats.ttest_1samp(ratios, 1 - delta) t_hi, p_hi = stats.ttest_1samp(ratios, 1 + delta) p_tost = max(p_lo / 2 if t_lo > 0 else 1.0, p_hi / 2 if t_hi < 0 else 1.0) # Cohen's d sp_val = np.sqrt((np.var(alphas_vis, ddof=1) + np.var(alphas_gib, ddof=1)) / 2) cohens_d = (mean_vis - mean_gib) / (sp_val + 1e-10) # Bootstrap CI gv_samples = np.array(alphas_gib[:n]) / (np.array(alphas_vis[:n]) + 1e-10) boot = [np.mean(np.random.choice(gv_samples, n, replace=True)) for _ in range(self.n_bootstrap)] ci_lo, ci_hi = np.percentile(boot, [2.5, 97.5]) # PASS only if Gib/Vis is clearly below 1 - margin passed = gib_vis < (1 - self.equivalence_margin) and p_tost > self.alpha return TestResult( name="Gibberish Specificity", passed=passed, score=gib_vis, threshold=1 - self.equivalence_margin, details={ "gib_vis_ratio": float(gib_vis), "visual_mean": float(mean_vis), "gibberish_mean": float(mean_gib), "tost_p": float(p_tost), "cohens_d": float(cohens_d), "ci_95": [float(ci_lo), float(ci_hi)], "n_visual": len(alphas_vis), "n_gibberish": len(alphas_gib), "tost_equivalent": p_tost < self.alpha, }, interpretation=( "FAIL: Gibberish activates these directions as strongly as " "visual content. Directions capture network geometry, not " "visual information." if not passed else "PASS: Directions respond preferentially to visual content." ), ) # ============================================================== # Test 2: Cross-Type Discrimination # ============================================================== def test_discrimination( self, directions: np.ndarray, h_visual: List[np.ndarray], h_other: List[np.ndarray], label: str = "other", ) -> TestResult: """ Test whether projection magnitude discriminates visual from other. PASS: AUROC > 0.65 FAIL: AUROC ≈ 0.5 (no discrimination) """ def proj_magnitude(h): hn = np.linalg.norm(h) if hn < 1e-12: return 0.0 proj = (directions @ h) @ directions return float(np.linalg.norm(proj) / hn) scores_vis = [proj_magnitude(h) for h in h_visual] scores_oth = [proj_magnitude(h) for h in h_other] labels = [1] * len(scores_vis) + [0] * len(scores_oth) scores = scores_vis + scores_oth # Compute AUROC from sklearn.metrics import roc_auc_score try: auroc = roc_auc_score(labels, scores) except: auroc = 0.5 passed = auroc > 0.65 return TestResult( name=f"Discrimination (visual vs {label})", passed=passed, score=float(auroc), threshold=0.65, details={ "auroc": float(auroc), "n_visual": len(scores_vis), "n_other": len(scores_oth), "mean_visual": float(np.mean(scores_vis)), "mean_other": float(np.mean(scores_oth)), }, interpretation=( f"FAIL: AUROC={auroc:.3f}. Projection magnitude cannot " f"discriminate visual from {label}." if not passed else f"PASS: AUROC={auroc:.3f}. Directions preferentially " f"activate on visual content." ), ) # ============================================================== # Test 3: Projection Magnitude # ============================================================== def test_projection_magnitude( self, directions: np.ndarray, h_visual: List[np.ndarray], ) -> TestResult: """ Test whether directions capture meaningful variance. PASS: Mean projection ratio > 1.5x random baseline FAIL: Projections near random level """ d = directions.shape[1] k = directions.shape[0] rng = np.random.RandomState(42) random_basis = np.linalg.qr(rng.randn(d, k))[0].T[:k] ratios = [] for h in h_visual: hn = np.linalg.norm(h) if hn < 1e-12: continue proj_d = np.linalg.norm((directions @ h) @ directions) proj_r = np.linalg.norm((random_basis @ h) @ random_basis) ratios.append(proj_d / (proj_r + 1e-10)) mean_ratio = np.mean(ratios) if ratios else 0 return TestResult( name="Projection Magnitude", passed=mean_ratio > 1.5, score=float(mean_ratio), threshold=1.5, details={ "mean_ratio_over_random": float(mean_ratio), "std": float(np.std(ratios)) if ratios else 0, "n_samples": len(ratios), }, interpretation=( f"Projection ratio: {mean_ratio:.2f}x random. " + ("PASS" if mean_ratio > 1.5 else "FAIL: directions don't capture more variance than random.") ), ) # ============================================================== # Test 4: Anisotropy Orthogonality # ============================================================== def test_anisotropy_orthogonality( self, directions: np.ndarray, h_all: List[np.ndarray], ) -> TestResult: """ Test whether directions are orthogonal to the general anisotropy of the representation space. PASS: Directions capture variance BEYOND general anisotropy FAIL: Directions align with top PCA of all tokens """ from sklearn.decomposition import PCA all_h = np.array(h_all) valid = ~np.isnan(all_h).any(axis=1) all_h = all_h[valid] k = directions.shape[0] if all_h.shape[0] > k: general_pca = PCA(n_components=k).fit(all_h).components_ else: return TestResult( name="Anisotropy Orthogonality", passed=False, score=0, threshold=0.5, interpretation="Insufficient data.") cos_matrix = np.abs(directions @ general_pca.T) mean_alignment = float(cos_matrix.mean()) max_alignment = float(cos_matrix.max()) passed = mean_alignment < 0.3 return TestResult( name="Anisotropy Orthogonality", passed=passed, score=float(mean_alignment), threshold=0.3, details={ "mean_cosine": float(mean_alignment), "max_cosine": float(max_alignment), }, interpretation=( f"Mean |cosine| with general PCA: {mean_alignment:.4f}. " + ("PASS: directions capture variance beyond anisotropy." if passed else "FAIL: directions align with general anisotropy.") ), ) # ============================================================== # Test 5: Direction Consistency # ============================================================== def test_consistency( self, h_visual: List[np.ndarray], k: int = 48, n_splits: int = 5, ) -> TestResult: """ Test whether directions are stable across random splits. PASS: Mean alignment > 0.8 across splits FAIL: Directions change with calibration data """ from sklearn.decomposition import PCA rng = np.random.RandomState(42) indices = rng.permutation(len(h_visual)) split_size = len(indices) // n_splits bases = [] for i in range(n_splits): split = indices[i * split_size:(i + 1) * split_size] data = np.array([h_visual[j] for j in split]) valid = ~np.isnan(data).any(axis=1) data = data[valid] if data.shape[0] > k: basis = PCA(n_components=k).fit(data).components_ bases.append(basis) if len(bases) < 2: return TestResult( name="Direction Consistency", passed=False, score=0, threshold=0.8, interpretation="Insufficient data for splits.") alignments = [] for i in range(len(bases)): for j in range(i + 1, len(bases)): cos = np.abs(bases[i] @ bases[j].T) alignments.append(cos.max(axis=1).mean()) mean_align = float(np.mean(alignments)) return TestResult( name="Direction Consistency", passed=mean_align > 0.8, score=float(mean_align), threshold=0.8, details={ "mean_split_alignment": float(mean_align), "n_splits": n_splits, "n_comparisons": len(alignments), }, interpretation=( f"Split alignment: {mean_align:.4f}. " + ("PASS" if mean_align > 0.8 else "FAIL: unstable directions.") ), ) # ============================================================== # Test 6: Pairwise Discrimination # ============================================================== def test_pairwise_discrimination( self, directions_dict: Dict[str, np.ndarray], h_by_type: Dict[str, List[np.ndarray]], layers: Optional[List[int]] = None, ) -> TestResult: """ Test whether a classifier can distinguish content types using joint projection profiles across methods. PASS: Only visual-vs-other pairs separable (visual-specific) FAIL: ALL pairs separable (generic geometry) Args: directions_dict: {"method_name": (k, d) array} h_by_type: {"visual": [...], "gibberish": [...], ...} """ from sklearn.ensemble import GradientBoostingClassifier from sklearn.model_selection import cross_val_score, StratifiedKFold from sklearn.preprocessing import StandardScaler types = list(h_by_type.keys()) methods = list(directions_dict.keys()) # Build feature matrices def build_features(hidden_states): X = np.zeros((len(hidden_states), len(methods))) for mi, (mname, dirs) in enumerate(directions_dict.items()): for i, h in enumerate(hidden_states): hn = np.linalg.norm(h) if hn > 1e-12: proj = (dirs @ h) @ dirs X[i, mi] = np.linalg.norm(proj) / hn return X type_features = {t: build_features(hs) for t, hs in h_by_type.items()} # Pairwise classification cv = StratifiedKFold(n_splits=min(10, min(len(v) for v in h_by_type.values()) // 2), shuffle=True, random_state=42) scaler = StandardScaler() pair_accs = {} for i, t1 in enumerate(types): for t2 in types[i + 1:]: X1, X2 = type_features[t1], type_features[t2] N = min(len(X1), len(X2)) X = np.vstack([X1[:N], X2[:N]]) y = np.array([1] * N + [0] * N) X_s = scaler.fit_transform(X) clf = GradientBoostingClassifier( n_estimators=100, max_depth=3, random_state=42) scores = cross_val_score(clf, X_s, y, cv=cv, scoring='accuracy') pair_accs[f"{t1}_vs_{t2}"] = float(scores.mean()) # Diagnosis visual_pairs = {k: v for k, v in pair_accs.items() if "visual" in k} nonvis_pairs = {k: v for k, v in pair_accs.items() if "visual" not in k} mean_vis = np.mean(list(visual_pairs.values())) if visual_pairs else 0 mean_nonvis = np.mean(list(nonvis_pairs.values())) if nonvis_pairs else 0 if mean_nonvis > 0.80: diagnosis = "generic_geometry" passed = False elif mean_vis > 0.80 and mean_nonvis < 0.60: diagnosis = "visual_specific" passed = True else: diagnosis = "mixed" passed = False return TestResult( name="Pairwise Discrimination", passed=passed, score=float(mean_vis), threshold=0.80, details={ "pair_accuracies": pair_accs, "mean_visual_pairs": float(mean_vis), "mean_nonvisual_pairs": float(mean_nonvis), "diagnosis": diagnosis, }, interpretation={ "generic_geometry": ( "FAIL: ALL content type pairs separable. Projections encode " "general linguistic features, not visual content."), "visual_specific": ( "PASS: Only visual-vs-other pairs separable. Projections " "are visual-specific."), "mixed": ( "INCONCLUSIVE: Mixed separability pattern."), }.get(diagnosis, "Unknown"), ) # ============================================================== # Full Report # ============================================================== def full_report( self, directions: np.ndarray, h_visual: List[np.ndarray], h_gibberish: List[np.ndarray], h_factual: Optional[List[np.ndarray]] = None, h_math: Optional[List[np.ndarray]] = None, directions_dict: Optional[Dict[str, np.ndarray]] = None, ) -> Dict[str, TestResult]: """Run all applicable SVS tests and return results.""" results = {} # Test 1: Gibberish Specificity results["gibberish"] = self.test_gibberish_specificity( directions, h_visual, h_gibberish) # Test 2: Discrimination results["discrimination_gib"] = self.test_discrimination( directions, h_visual, h_gibberish, "gibberish") # Test 3: Projection Magnitude results["magnitude"] = self.test_projection_magnitude( directions, h_visual) # Test 4: Anisotropy Orthogonality all_h = h_visual + h_gibberish if h_factual: all_h += h_factual if h_math: all_h += h_math results["anisotropy"] = self.test_anisotropy_orthogonality( directions, all_h) # Test 5: Direction Consistency results["consistency"] = self.test_consistency(h_visual) # Test 6: Pairwise Discrimination if directions_dict and h_factual and h_math: h_by_type = { "visual": h_visual, "gibberish": h_gibberish, "factual": h_factual, "math": h_math, } results["pairwise"] = self.test_pairwise_discrimination( directions_dict, h_by_type) return results def print_report(self, results: Dict[str, TestResult]): """Print a formatted validity report.""" print("\n" + "=" * 60) print(" SUBSPACE VALIDITY SUITE — REPORT") print("=" * 60) n_pass = sum(1 for r in results.values() if r.passed) n_total = len(results) for key, result in results.items(): status = "PASS" if result.passed else "FAIL" print(f"\n [{status}] {result.name}") print(f" Score: {result.score:.4f} " f"(threshold: {result.threshold})") print(f" {result.interpretation}") print(f"\n{'='*60}") print(f" SUMMARY: {n_pass}/{n_total} tests passed") if n_pass == 0: print(f" VERDICT: Directions do NOT capture visual content.") print(f" They reflect generic network geometry.") elif n_pass == n_total: print(f" VERDICT: Directions appear to capture visual content.") else: print(f" VERDICT: Mixed results. {n_pass}/{n_total} validity " f"tests passed.") print(f"{'='*60}\n")