| |
| """ |
| The Subspace Illusion: Generalization Beyond VLMs |
| ==================================================== |
| Does the finding generalize to ALL transformers? |
| |
| Experiment A: MULTILINGUAL |
| - Model: BLOOM-560M (multilingual) |
| - Build PCA from French text hidden states ("French subspace") |
| - Test: does English/Chinese/gibberish project equally? |
| |
| Experiment B: CODE |
| - Model: deepseek-coder-1.3b-instruct (code model) |
| - Build PCA from Python code hidden states ("code subspace") |
| - Test: does English prose/gibberish project equally? |
| |
| If both show Gib/Target ≈ 1.0 → universal finding about transformers. |
| |
| Setup: |
| !pip install -q transformers accelerate torch tqdm |
| """ |
|
|
| import json, gc, warnings |
| from pathlib import Path |
| import numpy as np |
| import torch |
| from tqdm import tqdm |
| from sklearn.decomposition import PCA |
|
|
| warnings.filterwarnings("ignore") |
|
|
| from google.colab import drive |
| drive.mount("/content/drive", force_remount=False) |
| OUT = Path("/content/drive/MyDrive/topohd_generalize") |
| OUT.mkdir(exist_ok=True, parents=True) |
|
|
| print("=" * 65) |
| print("The Subspace Illusion: Generalization Beyond VLMs") |
| print("=" * 65) |
|
|
| K_SUB = 48 |
|
|
| |
| |
| |
| print("\n[A] MULTILINGUAL: BLOOM-560M") |
| print("=" * 65) |
|
|
| from transformers import AutoModelForCausalLM, AutoTokenizer |
|
|
| print(" Loading BLOOM-560M ...") |
| bloom = AutoModelForCausalLM.from_pretrained( |
| "bigscience/bloom-560m", torch_dtype=torch.float16, |
| low_cpu_mem_usage=True, device_map="auto") |
| bloom_tok = AutoTokenizer.from_pretrained("bigscience/bloom-560m") |
| bloom.eval() |
|
|
| HDIM_B = bloom.config.hidden_size |
| N_LAYERS_B = bloom.config.n_layer |
| TARGET_B = [0, N_LAYERS_B//4, N_LAYERS_B//2, 3*N_LAYERS_B//4, N_LAYERS_B] |
| TARGET_B = [l for l in TARGET_B if l <= N_LAYERS_B] |
| print(f" Hidden size: {HDIM_B}, Layers: {N_LAYERS_B}, Targets: {TARGET_B}") |
|
|
| |
| FRENCH_TEXTS = [ |
| "La cuisine est une grande pièce avec une table et des chaises.", |
| "Le jardin est rempli de fleurs colorées et d'arbres fruitiers.", |
| "Les enfants jouent dans le parc pendant que les parents regardent.", |
| "La bibliothèque contient des milliers de livres anciens et modernes.", |
| "Le restaurant propose des plats traditionnels français délicieux.", |
| "La ville est animée avec des voitures et des piétons partout.", |
| "L'hôpital a été construit il y a cinquante ans dans le centre-ville.", |
| "Les étudiants travaillent dur pour réussir leurs examens finaux.", |
| "Le musée expose des œuvres d'art contemporain et classique.", |
| "La montagne est couverte de neige en hiver et de fleurs au printemps.", |
| "Le marché propose des fruits frais, des légumes et du fromage.", |
| "La rivière coule doucement à travers la vallée verdoyante.", |
| "Le château médiéval domine la colline depuis des siècles.", |
| "Les oiseaux chantent dans les arbres au lever du soleil.", |
| "Le train arrive à la gare à huit heures chaque matin.", |
| "La plage est bondée de touristes pendant l'été.", |
| "Le professeur explique la leçon avec patience et clarté.", |
| "Les nuages gris annoncent une tempête pour ce soir.", |
| "Le boulanger prépare le pain frais avant l'aube chaque jour.", |
| "La forêt est dense et mystérieuse, pleine de vie sauvage.", |
| ] |
|
|
| |
| MULTI_PROMPTS = { |
| "french": FRENCH_TEXTS, |
| "english": [ |
| "The kitchen is a large room with a table and chairs.", |
| "The garden is full of colorful flowers and fruit trees.", |
| "Children play in the park while parents watch them.", |
| "The library contains thousands of ancient and modern books.", |
| "The restaurant serves delicious traditional French dishes.", |
| "The city is bustling with cars and pedestrians everywhere.", |
| "The hospital was built fifty years ago in the city center.", |
| "Students work hard to pass their final exams.", |
| "The museum exhibits contemporary and classical artworks.", |
| "The mountain is covered with snow in winter and flowers in spring.", |
| "The market offers fresh fruits, vegetables, and cheese.", |
| "The river flows gently through the green valley.", |
| "The medieval castle has dominated the hill for centuries.", |
| "Birds sing in the trees at sunrise every morning.", |
| "The train arrives at the station at eight each morning.", |
| "The beach is crowded with tourists during summer months.", |
| "The teacher explains the lesson with patience and clarity.", |
| "Gray clouds announce a storm coming this evening.", |
| "The baker prepares fresh bread before dawn each day.", |
| "The forest is dense and mysterious, full of wildlife.", |
| ], |
| "chinese": [ |
| "厨房是一个很大的房间,有桌子和椅子。", |
| "花园里满是五颜六色的鲜花和果树。", |
| "孩子们在公园里玩耍,父母在一旁看着。", |
| "图书馆里有成千上万的古代和现代书籍。", |
| "这家餐厅供应美味的法国传统菜肴。", |
| "城市里到处都是汽车和行人,非常热闹。", |
| "医院五十年前建在市中心。", |
| "学生们努力学习,争取通过期末考试。", |
| "博物馆展出当代和古典艺术作品。", |
| "山上冬天覆盖着雪,春天开满鲜花。", |
| ], |
| "gibberish": [ |
| "Xkq plm wvt zzz brrn flmp qrst.", |
| "Qwzyx nkl jjj hhh ttttt pppp mmm.", |
| "Aaaa bbbb cccc dddd eeee ffff gggg.", |
| "Mlkj hgfd sapo iuyt rewq zxcv bnm.", |
| "Fghjkl zxcvbnm qwertyuiop asdfg.", |
| "Jjjjj kkkkk lllll mmmmm nnnnn ooooo.", |
| "Bnmz xkwq plrv tsyg hdjf kcmw.", |
| "Wwww xxxx yyyy zzzz aaaa bbbb cccc.", |
| "Vcxz nmbl kpoj ihug yftd rews qasx.", |
| "Rrrr ssss tttt uuuu vvvv wwww xxxx.", |
| ], |
| } |
|
|
| |
| print(" Building French subspace ...") |
| french_vecs = {l: [] for l in TARGET_B} |
|
|
| for text in tqdm(FRENCH_TEXTS, desc="French PCA", ncols=80): |
| inp = bloom_tok(text, return_tensors="pt") |
| inp = {k: v.to(bloom.device) for k, v in inp.items()} |
| with torch.no_grad(): |
| out = bloom(**inp, output_hidden_states=True) |
| for l in TARGET_B: |
| if l < len(out.hidden_states): |
| hs = out.hidden_states[l][0].cpu().float().numpy() |
| valid = ~np.isnan(hs).any(axis=1) & ~np.isinf(hs).any(axis=1) |
| if valid.sum() > 0: |
| french_vecs[l].append(hs[valid]) |
| del out; torch.cuda.empty_cache() |
|
|
| french_basis = {} |
| rng = np.random.RandomState(42) |
| random_basis_b = np.linalg.qr(rng.randn(HDIM_B, K_SUB))[0].T[:K_SUB] |
|
|
| for l in TARGET_B: |
| if not french_vecs[l]: continue |
| all_v = np.concatenate(french_vecs[l]) |
| k = min(K_SUB, all_v.shape[0]-1, all_v.shape[1]-1) |
| if k < 2: continue |
| french_basis[l] = PCA(n_components=k).fit(all_v).components_ |
| del french_vecs |
|
|
| |
| print(" Testing all languages on French subspace ...") |
| multi_results = {} |
|
|
| for lang, prompts in MULTI_PROMPTS.items(): |
| multi_results[lang] = {str(l): [] for l in TARGET_B} |
| multi_results[f"{lang}_rnd"] = {str(l): [] for l in TARGET_B} |
|
|
| for text in tqdm(prompts, desc=lang[:8], ncols=80): |
| inp = bloom_tok(text, return_tensors="pt") |
| inp = {k: v.to(bloom.device) for k, v in inp.items()} |
| with torch.no_grad(): |
| out = bloom(**inp, output_hidden_states=True) |
| for l in french_basis: |
| if l >= len(out.hidden_states): continue |
| h = out.hidden_states[l][0, -1, :].cpu().float().numpy() |
| if np.isnan(h).any() or np.linalg.norm(h) < 1e-12: continue |
| hn = np.linalg.norm(h) |
| basis = french_basis[l] |
| proj = (basis @ h) @ basis |
| multi_results[lang][str(l)].append(float(np.linalg.norm(proj) / hn)) |
| rb = random_basis_b[:basis.shape[0]] |
| pr = (rb @ h) @ rb |
| multi_results[f"{lang}_rnd"][str(l)].append(float(np.linalg.norm(pr) / hn)) |
| del out; torch.cuda.empty_cache() |
|
|
| |
| print(f"\n MULTILINGUAL RESULTS (BLOOM-560M, French PCA):") |
| print(f" {'Language':<12}", end="") |
| for l in TARGET_B: |
| if l in french_basis: |
| print(f" L{l:>2}", end="") |
| print(f" {'Mean':>6} {'Gib/Lang':>8}") |
| print(f" {'-'*55}") |
|
|
| lang_means = {} |
| for lang in ["french", "english", "chinese", "gibberish"]: |
| ratios = [] |
| print(f" {lang:<12}", end="") |
| for l in TARGET_B: |
| if str(l) not in multi_results[lang]: continue |
| v = multi_results[lang][str(l)] |
| r = multi_results[f"{lang}_rnd"][str(l)] |
| if v and r: |
| ratio = np.mean(v) / (np.mean(r) + 1e-8) |
| ratios.append(ratio) |
| print(f" {ratio:>4.1f}x", end="") |
| mean_r = np.mean(ratios) if ratios else 0 |
| lang_means[lang] = mean_r |
| gv = lang_means.get("gibberish", 0) / (mean_r + 1e-8) if lang != "gibberish" else "" |
| print(f" {mean_r:>5.2f}x {gv if isinstance(gv, str) else f'{gv:.2f}':>8}") |
|
|
| del bloom, bloom_tok; gc.collect(); torch.cuda.empty_cache() |
|
|
| |
| |
| |
| print(f"\n\n[B] CODE: deepseek-coder-1.3b-instruct") |
| print("=" * 65) |
|
|
| print(" Loading deepseek-coder-1.3b ...") |
| coder = AutoModelForCausalLM.from_pretrained( |
| "deepseek-ai/deepseek-coder-1.3b-instruct", torch_dtype=torch.float16, |
| low_cpu_mem_usage=True, device_map="auto", |
| trust_remote_code=True) |
| coder_tok = AutoTokenizer.from_pretrained( |
| "deepseek-ai/deepseek-coder-1.3b-instruct", trust_remote_code=True) |
| coder.eval() |
|
|
| HDIM_C = coder.config.hidden_size |
| N_LAYERS_C = coder.config.num_hidden_layers |
| TARGET_C = [0, N_LAYERS_C//4, N_LAYERS_C//2, 3*N_LAYERS_C//4, N_LAYERS_C] |
| TARGET_C = [l for l in TARGET_C if l <= N_LAYERS_C] |
| print(f" Hidden size: {HDIM_C}, Layers: {N_LAYERS_C}, Targets: {TARGET_C}") |
|
|
| |
| PYTHON_CODE = [ |
| "def fibonacci(n):\n if n <= 1:\n return n\n return fibonacci(n-1) + fibonacci(n-2)", |
| "class Node:\n def __init__(self, val):\n self.val = val\n self.next = None", |
| "import numpy as np\nx = np.random.randn(100, 100)\ny = np.linalg.svd(x)", |
| "for i in range(10):\n if i % 2 == 0:\n print(f'{i} is even')", |
| "def quicksort(arr):\n if len(arr) <= 1:\n return arr\n pivot = arr[0]\n return quicksort([x for x in arr[1:] if x < pivot]) + [pivot] + quicksort([x for x in arr[1:] if x >= pivot])", |
| "with open('data.csv', 'r') as f:\n reader = csv.reader(f)\n for row in reader:\n process(row)", |
| "SELECT u.name, COUNT(o.id) FROM users u JOIN orders o ON u.id = o.user_id GROUP BY u.name HAVING COUNT(o.id) > 5", |
| "async def fetch_data(url):\n async with aiohttp.ClientSession() as session:\n async with session.get(url) as response:\n return await response.json()", |
| "def binary_search(arr, target):\n low, high = 0, len(arr) - 1\n while low <= high:\n mid = (low + high) // 2\n if arr[mid] == target: return mid\n elif arr[mid] < target: low = mid + 1\n else: high = mid - 1\n return -1", |
| "import torch\nmodel = torch.nn.Sequential(\n torch.nn.Linear(784, 256),\n torch.nn.ReLU(),\n torch.nn.Linear(256, 10))", |
| "def merge_sort(arr):\n if len(arr) <= 1: return arr\n mid = len(arr) // 2\n left = merge_sort(arr[:mid])\n right = merge_sort(arr[mid:])\n return merge(left, right)", |
| "try:\n result = dangerous_operation()\nexcept ValueError as e:\n logging.error(f'Value error: {e}')\nexcept Exception as e:\n logging.critical(f'Unexpected: {e}')", |
| "from collections import defaultdict\ngraph = defaultdict(list)\nfor u, v in edges:\n graph[u].append(v)\n graph[v].append(u)", |
| "def decorator(func):\n def wrapper(*args, **kwargs):\n print(f'Calling {func.__name__}')\n return func(*args, **kwargs)\n return wrapper", |
| "CREATE TABLE users (\n id SERIAL PRIMARY KEY,\n name VARCHAR(100) NOT NULL,\n email VARCHAR(255) UNIQUE,\n created_at TIMESTAMP DEFAULT NOW()\n);", |
| "lambda x: sorted(x.items(), key=lambda kv: kv[1], reverse=True)[:10]", |
| "def bfs(graph, start):\n visited = set()\n queue = [start]\n while queue:\n node = queue.pop(0)\n if node not in visited:\n visited.add(node)\n queue.extend(graph[node])", |
| "import pandas as pd\ndf = pd.read_csv('sales.csv')\nresult = df.groupby('region')['revenue'].agg(['sum', 'mean', 'count'])", |
| "class Stack:\n def __init__(self):\n self.items = []\n def push(self, item): self.items.append(item)\n def pop(self): return self.items.pop()", |
| "@app.route('/api/users', methods=['GET'])\ndef get_users():\n users = User.query.all()\n return jsonify([u.to_dict() for u in users])", |
| ] |
|
|
| CODE_PROMPTS = { |
| "python": PYTHON_CODE, |
| "english": [ |
| "The kitchen is a large room with a table and chairs.", |
| "Children play in the park while parents watch them.", |
| "The library contains thousands of books on many subjects.", |
| "The restaurant serves delicious meals every evening.", |
| "Students work hard to pass their final examinations.", |
| "The museum exhibits artworks from many different periods.", |
| "The mountain is covered with snow during winter months.", |
| "The river flows gently through the green valley below.", |
| "Birds sing in the trees at sunrise every morning.", |
| "The train arrives at the station at eight each day.", |
| ], |
| "gibberish": [ |
| "Xkq plm wvt zzz brrn flmp qrst.", |
| "Qwzyx nkl jjj hhh ttttt pppp mmm.", |
| "Aaaa bbbb cccc dddd eeee ffff gggg.", |
| "Mlkj hgfd sapo iuyt rewq zxcv bnm.", |
| "Fghjkl zxcvbnm qwertyuiop asdfg.", |
| "Jjjjj kkkkk lllll mmmmm nnnnn ooooo.", |
| "Bnmz xkwq plrv tsyg hdjf kcmw.", |
| "Wwww xxxx yyyy zzzz aaaa bbbb cccc.", |
| "Vcxz nmbl kpoj ihug yftd rews qasx.", |
| "Rrrr ssss tttt uuuu vvvv wwww xxxx.", |
| ], |
| } |
|
|
| |
| print(" Building Python code subspace ...") |
| code_vecs = {l: [] for l in TARGET_C} |
|
|
| for text in tqdm(PYTHON_CODE, desc="Code PCA", ncols=80): |
| inp = coder_tok(text, return_tensors="pt") |
| inp = {k: v.to(coder.device) for k, v in inp.items()} |
| with torch.no_grad(): |
| out = coder(**inp, output_hidden_states=True) |
| for l in TARGET_C: |
| if l < len(out.hidden_states): |
| hs = out.hidden_states[l][0].cpu().float().numpy() |
| valid = ~np.isnan(hs).any(axis=1) & ~np.isinf(hs).any(axis=1) |
| if valid.sum() > 0: |
| code_vecs[l].append(hs[valid]) |
| del out; torch.cuda.empty_cache() |
|
|
| code_basis = {} |
| random_basis_c = np.linalg.qr(rng.randn(HDIM_C, K_SUB))[0].T[:K_SUB] |
|
|
| for l in TARGET_C: |
| if not code_vecs[l]: continue |
| all_v = np.concatenate(code_vecs[l]) |
| k = min(K_SUB, all_v.shape[0]-1, all_v.shape[1]-1) |
| if k < 2: continue |
| code_basis[l] = PCA(n_components=k).fit(all_v).components_ |
| del code_vecs |
|
|
| |
| print(" Testing all types on Python code subspace ...") |
| code_results = {} |
|
|
| for ctype, prompts in CODE_PROMPTS.items(): |
| code_results[ctype] = {str(l): [] for l in TARGET_C} |
| code_results[f"{ctype}_rnd"] = {str(l): [] for l in TARGET_C} |
|
|
| for text in tqdm(prompts, desc=ctype[:8], ncols=80): |
| inp = coder_tok(text, return_tensors="pt") |
| inp = {k: v.to(coder.device) for k, v in inp.items()} |
| with torch.no_grad(): |
| out = coder(**inp, output_hidden_states=True) |
| for l in code_basis: |
| if l >= len(out.hidden_states): continue |
| h = out.hidden_states[l][0, -1, :].cpu().float().numpy() |
| if np.isnan(h).any() or np.linalg.norm(h) < 1e-12: continue |
| hn = np.linalg.norm(h) |
| basis = code_basis[l] |
| proj = (basis @ h) @ basis |
| code_results[ctype][str(l)].append(float(np.linalg.norm(proj) / hn)) |
| rb = random_basis_c[:basis.shape[0]] |
| pr = (rb @ h) @ rb |
| code_results[f"{ctype}_rnd"][str(l)].append(float(np.linalg.norm(pr) / hn)) |
| del out; torch.cuda.empty_cache() |
|
|
| |
| print(f"\n CODE RESULTS (deepseek-coder-1.3b, Python PCA):") |
| print(f" {'Type':<12}", end="") |
| for l in TARGET_C: |
| if l in code_basis: |
| print(f" L{l:>2}", end="") |
| print(f" {'Mean':>6} {'Gib/Type':>8}") |
| print(f" {'-'*55}") |
|
|
| code_means = {} |
| for ctype in ["python", "english", "gibberish"]: |
| ratios = [] |
| print(f" {ctype:<12}", end="") |
| for l in TARGET_C: |
| if str(l) not in code_results[ctype]: continue |
| v = code_results[ctype][str(l)] |
| r = code_results[f"{ctype}_rnd"][str(l)] |
| if v and r: |
| ratio = np.mean(v) / (np.mean(r) + 1e-8) |
| ratios.append(ratio) |
| print(f" {ratio:>4.1f}x", end="") |
| mean_r = np.mean(ratios) if ratios else 0 |
| code_means[ctype] = mean_r |
| gv = code_means.get("gibberish", 0) / (mean_r + 1e-8) if ctype != "gibberish" else "" |
| print(f" {mean_r:>5.2f}x {gv if isinstance(gv, str) else f'{gv:.2f}':>8}") |
|
|
| del coder, coder_tok; gc.collect(); torch.cuda.empty_cache() |
|
|
| |
| |
| |
| print(f"\n\n{'='*65}") |
| print("FINAL VERDICT: Does The Subspace Illusion Generalize?") |
| print(f"{'='*65}") |
|
|
| print(f"\n MULTILINGUAL (BLOOM, French PCA):") |
| print(f" French: {lang_means.get('french', 0):.2f}x") |
| print(f" English: {lang_means.get('english', 0):.2f}x") |
| print(f" Chinese: {lang_means.get('chinese', 0):.2f}x") |
| print(f" Gibberish: {lang_means.get('gibberish', 0):.2f}x") |
| gv_multi = lang_means.get('gibberish', 0) / (lang_means.get('french', 0) + 1e-8) |
| print(f" Gib/French: {gv_multi:.2f}") |
|
|
| print(f"\n CODE (deepseek-coder, Python PCA):") |
| print(f" Python: {code_means.get('python', 0):.2f}x") |
| print(f" English: {code_means.get('english', 0):.2f}x") |
| print(f" Gibberish: {code_means.get('gibberish', 0):.2f}x") |
| gv_code = code_means.get('gibberish', 0) / (code_means.get('python', 0) + 1e-8) |
| print(f" Gib/Python: {gv_code:.2f}") |
|
|
| print(f"\n VLM (LLaVA/Vicuna, prior results):") |
| print(f" Visual: ~9.94x") |
| print(f" Gibberish: ~9.93x") |
| print(f" Gib/Visual: ~1.00") |
|
|
| if gv_multi > 0.7 and gv_code > 0.7: |
| print(f"\n >>> THE SUBSPACE ILLUSION IS UNIVERSAL <<<") |
| print(f" PCA of token-type-specific hidden states captures") |
| print(f" generic network geometry in ALL transformer types:") |
| print(f" - Vision-Language Models (LLaVA)") |
| print(f" - Multilingual Models (BLOOM)") |
| print(f" - Code Models (deepseek-coder)") |
| print(f" This is a fundamental property of how transformers") |
| print(f" organize representations, not a VLM-specific artifact.") |
| elif gv_multi > 0.7 or gv_code > 0.7: |
| print(f"\n >>> PARTIALLY UNIVERSAL <<<") |
| print(f" The illusion extends to some but not all transformer types.") |
| else: |
| print(f"\n >>> VLM-SPECIFIC <<<") |
| print(f" The illusion does not generalize beyond VLMs.") |
| print(f" Multilingual and code models show type-specific PCA.") |
|
|
| |
| all_results = { |
| "multilingual": {lang: float(v) for lang, v in lang_means.items()}, |
| "code": {ct: float(v) for ct, v in code_means.items()}, |
| } |
| with open(OUT / "generalization_results.json", "w") as f: |
| json.dump(all_results, f, indent=2) |
| print(f"\n Saved to {OUT}/") |
|
|