{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "f515fe66", "metadata": { "_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19", "_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5", "execution": { "iopub.execute_input": "2026-01-01T23:57:22.502961Z", "iopub.status.busy": "2026-01-01T23:57:22.502733Z", "iopub.status.idle": "2026-01-01T23:57:23.179613Z", "shell.execute_reply": "2026-01-01T23:57:23.178817Z" }, "papermill": { "duration": 0.68675, "end_time": "2026-01-01T23:57:23.181316", "exception": false, "start_time": "2026-01-01T23:57:22.494566", "status": "completed" }, "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "/kaggle/input/wikitext103-encoded/train.bin\n", "/kaggle/input/wikitext103-encoded/test.bin\n", "/kaggle/input/wikitext103-encoded/val.bin\n", "/kaggle/input/text8-encoded/train.bin\n", "/kaggle/input/text8-encoded/test.bin\n", "/kaggle/input/text8-encoded/val.bin\n", "/kaggle/input/penn-treebank-encoded/train.bin\n", "/kaggle/input/penn-treebank-encoded/test.bin\n", "/kaggle/input/penn-treebank-encoded/val.bin\n", "/kaggle/input/lambada-encoded/test_dev.bin\n", "/kaggle/input/lambada-encoded/train.bin\n", "/kaggle/input/lambada-encoded/test.bin\n", "/kaggle/input/lambada-encoded/val.bin\n", "/kaggle/input/enwik8-encoded/train.bin\n", "/kaggle/input/enwik8-encoded/test.bin\n", "/kaggle/input/enwik8-encoded/val.bin\n", "/kaggle/input/tinyshakespeare-encoded/train.bin\n", "/kaggle/input/tinyshakespeare-encoded/test.bin\n", "/kaggle/input/tinyshakespeare-encoded/val.bin\n" ] } ], "source": [ "# This Python 3 environment comes with many helpful analytics libraries installed\n", "# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n", "# For example, here's several helpful packages to load\n", "\n", "import numpy as np # linear algebra\n", "import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n", "\n", "# Input data files are available in the read-only \"../input/\" directory\n", "# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n", "\n", "import os\n", "for dirname, _, filenames in os.walk('/kaggle/input'):\n", " for filename in filenames:\n", " print(os.path.join(dirname, filename))\n", "\n", "# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n", "# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session" ] }, { "cell_type": "code", "execution_count": 2, "id": "737d4f15", "metadata": { "execution": { "iopub.execute_input": "2026-01-01T23:57:23.194869Z", "iopub.status.busy": "2026-01-01T23:57:23.194551Z", "iopub.status.idle": "2026-01-01T23:57:28.143879Z", "shell.execute_reply": "2026-01-01T23:57:28.143251Z" }, "papermill": { "duration": 4.95793, "end_time": "2026-01-01T23:57:28.145646", "exception": false, "start_time": "2026-01-01T23:57:23.187716", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "import torch\n", "from torch.utils.data import Dataset, DataLoader,IterableDataset\n", "from typing import Tuple, Dict, List, Optional\n", "import numpy as np\n", "from collections import Counter\n", "import requests\n", "import os\n", "import zipfile\n", "import tiktoken\n", "import torch\n", "from torch import Tensor\n", "from tqdm.notebook import tqdm\n", "import time\n", "import math\n", "from torch.nn import functional as F\n", "from torch.amp import GradScaler, autocast\n", "import torch.nn as nn\n", "from torch.optim import lr_scheduler\n", "from functools import partial\n", "from pathlib import Path\n", "from collections import defaultdict\n", "import json\n", "import matplotlib.pyplot as plt\n", "import seaborn as sns\n", "from IPython.display import display\n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "n_layer = 6 \n", "n_head = 8" ] }, { "cell_type": "code", "execution_count": 3, "id": "36529f3d", "metadata": { "execution": { "iopub.execute_input": "2026-01-01T23:57:28.159396Z", "iopub.status.busy": "2026-01-01T23:57:28.158979Z", "iopub.status.idle": "2026-01-01T23:57:28.170430Z", "shell.execute_reply": "2026-01-01T23:57:28.169854Z" }, "papermill": { "duration": 0.019941, "end_time": "2026-01-01T23:57:28.171843", "exception": false, "start_time": "2026-01-01T23:57:28.151902", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "from collections import defaultdict\n", "import torch\n", "\n", "class GradientLogger:\n", " def __init__(self):\n", " self.data = defaultdict(list)\n", "\n", " def attach(self, model):\n", " for name, param in model.named_parameters():\n", " if param.requires_grad:\n", " param.register_hook(self._make_hook(name))\n", "\n", " def _make_hook(self, name):\n", " def hook(grad):\n", " if grad is not None:\n", " self.data[name].append(grad.norm().item())\n", " return hook\n", "\n", " def summary(self, substr=None):\n", " out = {}\n", " for k, v in self.data.items():\n", " if substr is None or substr in k:\n", " out[k] = sum(v) / max(len(v), 1)\n", " return out\n", "def gate_entropy(g, eps=1e-6):\n", " g = g.clamp(eps, 1 - eps)\n", " return -(g * g.log() + (1 - g) * (1 - g).log()).mean()\n", "\n", "def gate_stats(gate, eps=1e-8):\n", " # gate in (0,1), shape [B, S, D]\n", " p = gate.clamp(eps, 1 - eps)\n", "\n", " entropy = -(p * p.log() + (1 - p) * (1 - p).log()).mean().item()\n", " frac_low = (gate < 0.05).float().mean().item()\n", " frac_high = (gate > 0.95).float().mean().item()\n", " mean = gate.mean().item()\n", "\n", " return {\n", " \"entropy\": entropy,\n", " \"frac_low\": frac_low,\n", " \"frac_high\": frac_high,\n", " \"mean\": mean,\n", " }\n", "def collect_gate_entropy(model):\n", " entropies = []\n", " for m in model.modules():\n", " if isinstance(m, RemixedLinear) and hasattr(m, \"last_gate_entropy\"):\n", " entropies.append(m.last_gate_entropy)\n", " if len(entropies) == 0:\n", " return None\n", " return torch.stack(entropies).mean()\n", "\n", "def collect_gate_stats(model):\n", " stats = []\n", " for m in model.modules():\n", " if isinstance(m, RemixedLinear) and hasattr(m, \"last_gate_stats\"):\n", " stats.append(m.last_gate_stats)\n", " return stats\n", "class TemperatureAnnealer:\n", " def __init__(\n", " self,\n", " start=1.5,\n", " end=0.2,\n", " total_steps=100_000,\n", " mode=\"cosine\" # or \"linear\", \"exp\"\n", " ):\n", " self.start = start\n", " self.end = end\n", " self.total_steps = total_steps\n", " self.mode = mode\n", "\n", " def __call__(self, step):\n", " t = min(step / self.total_steps, 1.0)\n", "\n", " if self.mode == \"linear\":\n", " tau = self.start + t * (self.end - self.start)\n", "\n", " elif self.mode == \"cosine\":\n", " tau = self.end + 0.5 * (self.start - self.end) * (1 + math.cos(math.pi * t))\n", "\n", " elif self.mode == \"exp\":\n", " tau = self.start * (self.end / self.start) ** t\n", "\n", " else:\n", " raise ValueError(self.mode)\n", "\n", " return max(tau, 1e-3) # HARD FLOOR\n" ] }, { "cell_type": "code", "execution_count": 4, "id": "ac251a32", "metadata": { "execution": { "iopub.execute_input": "2026-01-01T23:57:28.185289Z", "iopub.status.busy": "2026-01-01T23:57:28.185037Z", "iopub.status.idle": "2026-01-01T23:57:28.517490Z", "shell.execute_reply": "2026-01-01T23:57:28.516722Z" }, "papermill": { "duration": 0.341273, "end_time": "2026-01-01T23:57:28.519139", "exception": false, "start_time": "2026-01-01T23:57:28.177866", "status": "completed" }, "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "============================================================\n", "COMPARISON: Standard 512 vs Remix 64\n", "============================================================\n", "Baseline (512-dim Dense):\n", " Params: 25,731,584\n", " Memory: 98.16 MB\n", "\n", "Pure Remix (64-dim Contextual):\n", " Total Params: 3,246,274\n", " - Seed Table: 3,216,448\n", " - Router Overhead: 29,826 (Only ~0.3M params!)\n", " Memory: 12.38 MB\n", "\n", "FINAL STATS:\n", " Compression Ratio: 7.93x smaller than Baseline\n", " Output Dimension: 64 (As requested)\n", "\n", "Output Shape: torch.Size([2, 32, 64]) -> Correct\n" ] } ], "source": [ "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "\n", "# ==========================================\n", "# 1. The Core Router (Your provided class)\n", "# ==========================================\n", "class ImprovedContextAwareRouter(nn.Module):\n", " \"\"\"Enhanced router with vocabulary-aware initialization and better scaling.\"\"\"\n", " def __init__(\n", " self,\n", " vocab_size,\n", " num_experts, \n", " router_dim,\n", " full_embed_dim,\n", " context_window=8,\n", " causal=True,\n", " num_heads=4,\n", " num_queries=8,\n", " n_layers=1,\n", " use_vocab_prior=True,\n", " ):\n", " super().__init__()\n", " # In this specific config, num_experts will equal target_dim (64)\n", " self.num_experts = num_experts \n", " self.router_dim = router_dim\n", " self.context_window = context_window\n", " self.causal = causal\n", " self.num_heads = num_heads\n", " self.head_dim = router_dim // num_heads\n", " self.num_queries = num_queries\n", " self.n_layers = n_layers\n", " self.use_vocab_prior = use_vocab_prior\n", " \n", " # Project full embeddings to router dimension\n", " self.embed_proj = nn.Linear(full_embed_dim, router_dim)\n", " \n", " # Multi-head attention\n", " self.qkv_proj = nn.Linear(router_dim, 3 * router_dim, bias=False)\n", " self.out_proj = nn.Linear(router_dim, router_dim)\n", " \n", " # Expert projection with layer norm for stability\n", " self.ln = nn.LayerNorm(router_dim)\n", " self.routing_queries = nn.Parameter(torch.randn(num_queries, router_dim))\n", " self.temperature_predictor = nn.Linear(router_dim, 1)\n", " \n", " self.expert_proj = nn.Linear(router_dim, num_experts)\n", " self.cross_expert_proj = nn.Linear(router_dim, num_experts)\n", " self.alpha_gate = nn.Linear(router_dim, 1)\n", " \n", " # Vocabulary prior for better initialization\n", " if use_vocab_prior:\n", " self.vocab_routing_bias = nn.Embedding(vocab_size, num_experts)\n", " nn.init.normal_(self.vocab_routing_bias.weight, mean=0, std=0.02)\n", " \n", " # Better initialization for large vocab\n", " nn.init.normal_(self.expert_proj.weight, mean=0, std=0.02)\n", " nn.init.normal_(self.cross_expert_proj.weight, mean=0, std=0.02)\n", " \n", " def forward(self, full_embeds, input_ids=None):\n", " batch_size, seq_len, _ = full_embeds.shape\n", " \n", " # Project to router dimension\n", " x = self.embed_proj(full_embeds)\n", " \n", " # Multi-head context attention\n", " for _ in range(self.n_layers):\n", " x = self._multi_head_attention(x)\n", " \n", " # Layer norm before expert projection\n", " x = self.ln(x)\n", " \n", " # Get expert logits\n", " self_attn_logits = self.expert_proj(x)\n", " cross_attn_logits = self.cross_expert_proj(self._cross_attention(self.routing_queries, x))\n", " \n", " alpha = torch.sigmoid(self.alpha_gate(x))\n", " expert_logits = alpha * self_attn_logits + (1 - alpha) * cross_attn_logits\n", " \n", " # Add vocabulary prior if available\n", " if self.use_vocab_prior and input_ids is not None:\n", " vocab_bias = self.vocab_routing_bias(input_ids)\n", " expert_logits = expert_logits + vocab_bias\n", " \n", " adaptive_temp = torch.sigmoid(self.temperature_predictor(x)) * 2.0 + 0.1\n", " \n", " # We return expert_logits as the embedding itself\n", " return expert_logits, adaptive_temp, self.expert_proj.weight\n", "\n", " def _cross_attention(self, queries, context):\n", " batch_size, seq_len, dim = context.shape\n", " num_queries = queries.shape[0]\n", " \n", " queries = queries.unsqueeze(0).expand(batch_size, num_queries, dim)\n", " attn_scores = torch.matmul(queries, context.transpose(1, 2)) / (dim ** 0.5)\n", " attn_weights = torch.softmax(attn_scores, dim=-1)\n", " attended = torch.matmul(attn_weights, context)\n", " fused = attended.mean(dim=1).unsqueeze(1).expand(-1, seq_len, -1)\n", " return fused\n", " \n", " def _multi_head_attention(self, x):\n", " batch_size, seq_len, _ = x.shape\n", " \n", " qkv = self.qkv_proj(x).reshape(batch_size, seq_len, 3, self.num_heads, self.head_dim)\n", " qkv = qkv.permute(2, 0, 3, 1, 4)\n", " q, k, v = qkv[0], qkv[1], qkv[2]\n", " \n", " attn_scores = torch.matmul(q, k.transpose(-2, -1)) / (self.head_dim ** 0.5)\n", " mask = self._create_mask(seq_len, x.device).unsqueeze(0).unsqueeze(0)\n", " attn_scores = attn_scores.masked_fill(mask, float('-inf'))\n", " \n", " attn_weights = F.softmax(attn_scores, dim=-1)\n", " context = torch.matmul(attn_weights, v)\n", " context = context.transpose(1, 2).reshape(batch_size, seq_len, self.router_dim)\n", " output = self.out_proj(context) + x\n", " return output\n", " \n", " def _create_mask(self, seq_len, device):\n", " if self.context_window == -1:\n", " if self.causal:\n", " positions = torch.arange(seq_len, device=device)\n", " pos_diff = positions.unsqueeze(0) - positions.unsqueeze(1)\n", " return pos_diff > 0\n", " else:\n", " return torch.zeros(seq_len, seq_len, dtype=torch.bool, device=device)\n", " \n", " positions = torch.arange(seq_len, device=device)\n", " pos_diff = positions.unsqueeze(0) - positions.unsqueeze(1)\n", " \n", " if self.causal:\n", " return (pos_diff > 0) | (pos_diff < -self.context_window)\n", " else:\n", " window_half = self.context_window // 2\n", " return torch.abs(pos_diff) > window_half\n", "\n", "\n", "# ==========================================\n", "# 2. Pure Router Remix (64 -> 64)\n", "# ==========================================\n", "class DirectContextualEmbedding(nn.Module):\n", " \"\"\"\n", " Directly uses the Router to transform a static 64-dim seed into \n", " a dynamic 64-dim embedding. No experts, no MoE weighted sums.\n", " \"\"\"\n", " def __init__(\n", " self, \n", " vocab_size, \n", " dim=64, # Staying in 64 dimensions\n", " context_window=32,\n", " dropout=0.0\n", " ):\n", " super().__init__()\n", " \n", " # 1. Static Seed (The \"Base\" meaning)\n", " # Size: [Vocab, 64]\n", " self.seed_embeddings = nn.Embedding(vocab_size, dim)\n", " \n", " # 2. The Router (The \"Remixer\")\n", " # - Inputs 64 dims\n", " # - \"Thinks\" in 64 dims\n", " # - Outputs 64 \"logits\" -> These ARE the new embedding\n", " self.router = ImprovedContextAwareRouter(\n", " vocab_size=vocab_size,\n", " num_experts=dim, # CRITICAL: We want exactly 64 output values\n", " router_dim=dim, # Internal thinking size\n", " full_embed_dim=dim, # Input size\n", " context_window=context_window,\n", " causal=True,\n", " n_layers=2, # Depth of reasoning\n", " use_vocab_prior=False\n", " )\n", " \n", " self.dropout = nn.Dropout(dropout)\n", " \n", " # 3. Norm ensures the router output behaves like a stable embedding\n", " self.out_norm = nn.LayerNorm(dim)\n", "\n", " def forward(self, input_ids):\n", " # 1. Get Static Seed\n", " # [B, S, 64]\n", " seeds = self.seed_embeddings(input_ids)\n", " \n", " # 2. Remix via Router\n", " # The router returns (logits, temp, weights). \n", " # Here, 'logits' is our 64-dim vector.\n", " # It has looked at the surrounding tokens to decide these values.\n", " remixed_embeds, _, _ = self.router(seeds, input_ids)\n", " \n", " # 3. Residual Connection (Optional but recommended)\n", " # Keeps the base meaning while adding context\n", " output = self.dropout(remixed_embeds)# +seeds\n", " \n", " return self.out_norm(output)\n", "\n", "def count_parameters(model):\n", " return sum(p.numel() for p in model.parameters())\n", "\n", "# ==========================================\n", "# 3. Parameter Efficiency Verification\n", "# ==========================================\n", "if __name__ == \"__main__\":\n", " vocab_size = 50257\n", " dim = 64 # The target constraint\n", " \n", " print(\"=\"*60)\n", " print(\"COMPARISON: Standard 512 vs Remix 64\")\n", " print(\"=\"*60)\n", " \n", " # --- 1. Baseline (Standard Dense 512) ---\n", " baseline_emb = nn.Embedding(vocab_size, 512)\n", " base_params = count_parameters(baseline_emb)\n", " print(f\"Baseline (512-dim Dense):\")\n", " print(f\" Params: {base_params:,}\")\n", " print(f\" Memory: {base_params * 4 / 1024 / 1024:.2f} MB\")\n", " \n", " # --- 2. Pure Remix (64 -> 64) ---\n", " remix_model = DirectContextualEmbedding(vocab_size, dim=64)\n", " remix_params = count_parameters(remix_model)\n", " \n", " # Calculate Router Overhead\n", " seed_params = vocab_size * 64\n", " router_overhead = remix_params - seed_params\n", " \n", " print(f\"\\nPure Remix (64-dim Contextual):\")\n", " print(f\" Total Params: {remix_params:,}\")\n", " print(f\" - Seed Table: {seed_params:,}\")\n", " print(f\" - Router Overhead: {router_overhead:,} (Only ~0.3M params!)\")\n", " print(f\" Memory: {remix_params * 4 / 1024 / 1024:.2f} MB\")\n", " \n", " # --- 3. The Result ---\n", " ratio = base_params / remix_params\n", " print(f\"\\nFINAL STATS:\")\n", " print(f\" Compression Ratio: {ratio:.2f}x smaller than Baseline\")\n", " print(f\" Output Dimension: {dim} (As requested)\")\n", " \n", " # --- 4. Forward Check ---\n", " dummy = torch.randint(0, vocab_size, (2, 32))\n", " out = remix_model(dummy)\n", " print(f\"\\nOutput Shape: {out.shape} -> Correct\")" ] }, { "cell_type": "code", "execution_count": 5, "id": "0c0a0a75", "metadata": { "execution": { "iopub.execute_input": "2026-01-01T23:57:28.535739Z", "iopub.status.busy": "2026-01-01T23:57:28.535492Z", "iopub.status.idle": "2026-01-01T23:57:29.139334Z", "shell.execute_reply": "2026-01-01T23:57:29.138215Z" }, "papermill": { "duration": 0.613577, "end_time": "2026-01-01T23:57:29.140865", "exception": false, "start_time": "2026-01-01T23:57:28.527288", "status": "completed" }, "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "============================================================\n", "TESTING PERMUTATION-BASED MOE VARIANTS\n", "============================================================\n", "\n", "============================================================\n", "Test 1: Soft Selection WITH Replacement\n", "- Allows dimension repetition\n", "- MLP refinement AFTER selection\n", "============================================================\n", "\n", "============================================================\n", "Soft Selection (with replacement, MLP after)\n", "============================================================\n", "Output shape: torch.Size([4, 32, 64])\n", "Total params: 5,540,946\n", "Trainable params: 5,540,946\n", "Expert usage: [0.13273143768310547, 0.1276526302099228, 0.11820174753665924, 0.1328621804714203, 0.11222454160451889, 0.1277965009212494, 0.12425566464662552, 0.12427528202533722]\n", "Aux losses: {'load_balance': tensor(0.0071, grad_fn=), 'z_loss': tensor(0.0045, grad_fn=), 'diversity': tensor(0.0093, grad_fn=)}\n", "Total aux loss: 0.0209\n", "\n", "============================================================\n", "Test 2: Soft Selection WITHOUT Replacement\n", "- Encourages true permutations\n", "- MLP refinement BEFORE selection\n", "============================================================\n", "\n", "============================================================\n", "Soft Selection (no replacement, MLP before)\n", "============================================================\n", "Output shape: torch.Size([4, 32, 64])\n", "Total params: 5,424,018\n", "Trainable params: 5,424,018\n", "Expert usage: [0.11979085206985474, 0.1197608932852745, 0.12937600910663605, 0.1317342072725296, 0.1281149983406067, 0.12400589883327484, 0.13020813465118408, 0.1170090064406395]\n", "Aux losses: {'load_balance': tensor(0.0045, grad_fn=), 'z_loss': tensor(0.0042, grad_fn=), 'diversity': tensor(0.0093, grad_fn=)}\n", "Total aux loss: 0.0181\n", "\n", "============================================================\n", "Test 3: Hard Selection (Gumbel) WITH Replacement\n", "- Discrete sampling via Gumbel-Softmax\n", "- No MLP refinement\n", "============================================================\n", "\n", "============================================================\n", "Hard Selection (Gumbel, with replacement, no MLP)\n", "============================================================\n", "Output shape: torch.Size([4, 32, 64])\n", "Total params: 5,407,314\n", "Trainable params: 5,407,314\n", "Expert usage: [0.1175321638584137, 0.12889240682125092, 0.12830305099487305, 0.12332159280776978, 0.14207515120506287, 0.11214744299650192, 0.13089771568775177, 0.11683046817779541]\n", "Aux losses: {'load_balance': tensor(0.0132, grad_fn=), 'z_loss': tensor(0.0044, grad_fn=), 'diversity': tensor(0.0081, grad_fn=)}\n", "Total aux loss: 0.0256\n", "\n", "============================================================\n", "Test 4: Minimal Configuration\n", "- Soft selection, replacement allowed\n", "- No MLP refinement (fastest)\n", "============================================================\n", "\n", "============================================================\n", "Minimal (4 experts, no MLP)\n", "============================================================\n", "Output shape: torch.Size([4, 32, 64])\n", "Total params: 4,324,682\n", "Trainable params: 4,324,682\n", "Expert usage: [0.2508999705314636, 0.269468754529953, 0.24839530885219574, 0.23123595118522644]\n", "Aux losses: {'load_balance': tensor(0.0301, grad_fn=), 'z_loss': tensor(0.0021, grad_fn=), 'diversity': tensor(0.0093, grad_fn=)}\n", "Total aux loss: 0.0415\n", "\n", "============================================================\n", "PARAMETER COMPARISON\n", "============================================================\n", "Model Total Params Non-Embed\n", "----------------------------------------------------------------------\n", "Soft + Replacement + MLP(after) 5,540,946 2,320,402\n", "Soft + No Replace + MLP(before) 5,424,018 2,203,474\n", "Hard(Gumbel) + Replace + No MLP 5,407,314 2,186,770\n", "Minimal (4 experts) 4,324,682 1,104,138\n", "\n", "============================================================\n", "SELECTION PATTERN ANALYSIS (Model 1)\n", "============================================================\n", "Shape: torch.Size([8, 64, 64]) [num_experts, D_out, D_in]\n", "\n", "Expert 0:\n", " Input dim usage statistics:\n", " Mean: 1.000 (expect ~1.0 for uniform)\n", " Std: 0.053 (higher = more specialization)\n", " Max: 1.178 (>1.0 indicates replacement)\n", " Min: 0.902 (<1.0 indicates some dims ignored)\n", " Replacement evidence:\n", " Dims used >1.2x: 0/64 (replicated)\n", " Dims used <0.8x: 0/64 (under-utilized)\n", " Selection entropy: 260.79 (lower = more concentrated)\n", " Top 5 input dims: [61, 2, 6, 41, 7]\n", " Usage: [1.1777575016021729, 1.1511168479919434, 1.1282435655593872, 1.096906304359436, 1.0853846073150635]\n", " Bottom 5 input dims: [26, 60, 3, 16, 24]\n", " Usage: [0.9020634889602661, 0.9048243165016174, 0.927437424659729, 0.9283398389816284, 0.9339427947998047]\n", "\n", "Expert 1:\n", " Input dim usage statistics:\n", " Mean: 1.000 (expect ~1.0 for uniform)\n", " Std: 0.040 (higher = more specialization)\n", " Max: 1.096 (>1.0 indicates replacement)\n", " Min: 0.924 (<1.0 indicates some dims ignored)\n", " Replacement evidence:\n", " Dims used >1.2x: 0/64 (replicated)\n", " Dims used <0.8x: 0/64 (under-utilized)\n", " Selection entropy: 262.78 (lower = more concentrated)\n", " Top 5 input dims: [40, 1, 7, 11, 58]\n", " Usage: [1.0961997509002686, 1.080493688583374, 1.0657689571380615, 1.0643558502197266, 1.0541001558303833]\n", " Bottom 5 input dims: [54, 2, 44, 15, 62]\n", " Usage: [0.9240748286247253, 0.9244208335876465, 0.9278965592384338, 0.9331811666488647, 0.9357923865318298]\n", "\n", "Expert 2:\n", " Input dim usage statistics:\n", " Mean: 1.000 (expect ~1.0 for uniform)\n", " Std: 0.039 (higher = more specialization)\n", " Max: 1.098 (>1.0 indicates replacement)\n", " Min: 0.906 (<1.0 indicates some dims ignored)\n", " Replacement evidence:\n", " Dims used >1.2x: 0/64 (replicated)\n", " Dims used <0.8x: 0/64 (under-utilized)\n", " Selection entropy: 262.52 (lower = more concentrated)\n", " Top 5 input dims: [8, 53, 54, 34, 45]\n", " Usage: [1.0978304147720337, 1.084855556488037, 1.0641298294067383, 1.0602707862854004, 1.0566030740737915]\n", " Bottom 5 input dims: [56, 50, 48, 60, 18]\n", " Usage: [0.9061851501464844, 0.9119699001312256, 0.9142280220985413, 0.9164605140686035, 0.9220935702323914]\n", "\n", "============================================================\n", "✅ All tests passed!\n", "Peak memory: 0.00 GB\n", "============================================================\n" ] } ], "source": [ "\n", "class PermutationMoE(nn.Module):\n", " \"\"\"\n", " Learns context-aware permutations (with optional replacement) of a base embedding.\n", " Instead of selecting from 512 dims, we start with 64 dims and learn optimal\n", " permutations/selections with repetition.\n", " \"\"\"\n", " def __init__(\n", " self,\n", " vocab_size,\n", " block_size=64,\n", " base_embed_dim=64, # Start with smaller embedding\n", " num_experts=8,\n", " router_dim=64,\n", " selection_mode='soft', # 'soft' (differentiable) or 'hard' (Gumbel)\n", " use_dim_mlp_refinement=True,\n", " mlp_refinement_position='after', # 'before' or 'after' selection\n", " allow_replacement=True, # If True, dims can be repeated\n", " temperature=1.0,\n", " dropout=0.0,\n", " load_balance_weight=0.01,\n", " z_loss_weight=0.001,\n", " diversity_weight=0.01,\n", " # Router params\n", " context_window=-1,\n", " causal=True,\n", " num_queries=8,\n", " n_layers=2,\n", " use_vocab_prior=False,\n", " num_heads=8,\n", " ):\n", " super().__init__()\n", " \n", " self.vocab_size = vocab_size\n", " self.base_embed_dim = base_embed_dim\n", " self.num_experts = num_experts\n", " self.selection_mode = selection_mode\n", " self.use_dim_mlp_refinement = use_dim_mlp_refinement\n", " self.mlp_refinement_position = mlp_refinement_position\n", " self.allow_replacement = allow_replacement\n", " self.load_balance_weight = load_balance_weight\n", " self.z_loss_weight = z_loss_weight\n", " self.diversity_weight = diversity_weight\n", " \n", " # Base embeddings (much smaller than 512)\n", " self.embeddings = nn.Embedding(vocab_size, base_embed_dim)\n", " self.position_embeddings = nn.Embedding(block_size, base_embed_dim)\n", " \n", " # Each expert learns a context-dependent dimension selector\n", " # For each output dimension, select/weight from input dimensions\n", " self.dim_selectors = nn.ModuleList([\n", " nn.Sequential(\n", " nn.Linear(base_embed_dim, router_dim),\n", " nn.LayerNorm(router_dim),\n", " nn.GELU(),\n", " nn.Dropout(dropout),\n", " # Output: for each output dim, logits over input dims\n", " nn.Linear(router_dim, base_embed_dim * base_embed_dim),\n", " ) for _ in range(num_experts)\n", " ])\n", " \n", " # Optional MLP refinement\n", " if use_dim_mlp_refinement:\n", " if mlp_refinement_position == 'before':\n", " # Single shared MLP before expert selection\n", " self.refinement_mlp = nn.Sequential(\n", " nn.LayerNorm(base_embed_dim),\n", " nn.Linear(base_embed_dim, base_embed_dim * 2),\n", " nn.GELU(),\n", " nn.Dropout(dropout),\n", " nn.Linear(base_embed_dim * 2, base_embed_dim)\n", " )\n", " else: # 'after'\n", " # Per-expert MLPs after selection\n", " self.expert_mlps = nn.ModuleList([\n", " nn.Sequential(\n", " nn.LayerNorm(base_embed_dim),\n", " nn.Linear(base_embed_dim, base_embed_dim * 2),\n", " nn.GELU(),\n", " nn.Dropout(dropout),\n", " nn.Linear(base_embed_dim * 2, base_embed_dim)\n", " ) for _ in range(num_experts)\n", " ])\n", " \n", " # Expert router\n", " self.expert_router = ImprovedContextAwareRouter(\n", " vocab_size=vocab_size,\n", " num_experts=num_experts,\n", " router_dim=router_dim,\n", " full_embed_dim=base_embed_dim,\n", " context_window=context_window,\n", " causal=causal,\n", " num_heads=num_heads,\n", " num_queries=num_queries,\n", " n_layers=n_layers,\n", " use_vocab_prior=use_vocab_prior,\n", " )\n", " \n", " self.ln = nn.LayerNorm(base_embed_dim)\n", " self.dropout = nn.Dropout(dropout)\n", " self.register_buffer('temperature', torch.tensor(temperature))\n", " \n", " # # Initialize selectors to favor identity (no permutation initially)\n", " # for module in self.dim_selectors:\n", " # last_layer = module[-1]\n", " # # Bias toward identity permutation\n", " # identity_flat = torch.eye(base_embed_dim).flatten()\n", " # last_layer.bias.data.copy_(identity_flat * 2.0)\n", " # nn.init.normal_(last_layer.weight, mean=0, std=0.02)\n", " \n", " def forward(self, input_ids):\n", " batch_size, seq_len = input_ids.shape\n", " device = input_ids.device\n", " positions = torch.arange(seq_len, device=device)\n", " \n", " # Get base embeddings [B, L, D]\n", " embeds = self.embeddings(input_ids) + self.position_embeddings(positions)\n", " \n", " # Optional refinement before selection\n", " if self.use_dim_mlp_refinement and self.mlp_refinement_position == 'before':\n", " embeds = embeds + self.refinement_mlp(embeds)\n", " \n", " # Each expert generates context-aware permuted embeddings\n", " expert_outputs = []\n", " selection_patterns = []\n", " \n", " for expert_idx in range(self.num_experts):\n", " # Generate selection matrix based on context\n", " # Use per-position context to decide dimension selection\n", " selection_logits = self.dim_selectors[expert_idx](embeds)\n", " # [B, L, D*D] -> [B, L, D_out, D_in]\n", " selection_logits = selection_logits.view(\n", " batch_size, seq_len, self.base_embed_dim, self.base_embed_dim\n", " )\n", " \n", " # Apply selection based on mode\n", " if self.selection_mode == 'soft':# or self.allow_replacement:\n", " # print(\"soft\")\n", " # Soft attention: each output dim is weighted sum of input dims\n", " # This naturally allows replacement\n", " selection_weights = F.softmax(\n", " selection_logits / self.temperature, dim=-1\n", " ) # [B, L, D_out, D_in]\n", " \n", " # For each position, apply the selection matrix\n", " # embeds: [B, L, D_in]\n", " # selection_weights: [B, L, D_out, D_in]\n", " selected = torch.einsum('bloi,bli->blo', selection_weights, embeds)\n", " # [B, L, D_out]\n", " \n", " elif self.selection_mode == 'hard' and not self.allow_replacement:\n", " # Hard selection without replacement (true permutation)\n", " # Use Gumbel-Softmax with straight-through estimator\n", " selection_weights = F.gumbel_softmax(\n", " selection_logits, tau=self.temperature, hard=True, dim=-1\n", " ) # [B, L, D_out, D_in]\n", " \n", " selected = torch.einsum('bloi,bli->blo', selection_weights, embeds)\n", " \n", " else: # Hard with replacement\n", " # Sample hard indices but allow duplicates\n", " selection_weights = F.gumbel_softmax(\n", " selection_logits, tau=self.temperature, hard=False, dim=-1\n", " )\n", " selected = torch.einsum('bloi,bli->blo', selection_weights, embeds)\n", " \n", " # Optional refinement after selection\n", " if self.use_dim_mlp_refinement and self.mlp_refinement_position == 'after':\n", " selected = selected + self.expert_mlps[expert_idx](selected)\n", " \n", " expert_outputs.append(selected)\n", " selection_patterns.append(selection_weights)\n", " \n", " # Stack expert outputs [B, L, num_experts, D]\n", " expert_outputs = torch.stack(expert_outputs, dim=2)\n", " selection_patterns = torch.stack(selection_patterns, dim=2) # [B, L, E, D, D]\n", " \n", " # Route among experts based on context\n", " expert_logits, adaptive_temp, _ = self.expert_router(embeds, input_ids)\n", " expert_weights = F.softmax(expert_logits / (self.temperature * adaptive_temp), dim=-1)\n", " expert_weights = self.dropout(expert_weights)\n", " \n", " # Combine expert outputs\n", " output = (expert_weights.unsqueeze(-1) * expert_outputs).sum(dim=2)\n", " output = self.ln(output)\n", " \n", " # Compute auxiliary losses\n", " aux_losses = self._compute_aux_losses(\n", " expert_logits, expert_weights, selection_patterns\n", " )\n", " \n", " routing_info = {\n", " 'expert_logits': expert_logits,\n", " 'expert_weights': expert_weights,\n", " 'selection_patterns': selection_patterns,\n", " 'expert_usage': expert_weights.mean(dim=[0, 1]),\n", " 'aux_losses': aux_losses,\n", " 'total_aux_loss': sum(aux_losses.values())\n", " }\n", " \n", " return output, routing_info\n", " \n", " def _compute_aux_losses(self, expert_logits, expert_weights, selection_patterns):\n", " losses = {}\n", " \n", " # Expert load balancing\n", " expert_usage = expert_weights.sum(dim=[0, 1])\n", " mean_usage = expert_usage.mean()\n", " losses['load_balance'] = self.load_balance_weight * \\\n", " (expert_usage - mean_usage).pow(2).mean()\n", " \n", " # Z-loss for routing stability\n", " losses['z_loss'] = self.z_loss_weight * \\\n", " torch.logsumexp(expert_logits, dim=-1).pow(2).mean()\n", " \n", " # Diversity loss: encourage experts to learn different selection patterns\n", " # Average selection pattern per expert across batch and sequence\n", " avg_patterns = selection_patterns.mean(dim=[0, 1]) # [E, D_out, D_in]\n", " # Flatten to [E, D*D]\n", " avg_patterns_flat = avg_patterns.reshape(self.num_experts, -1)\n", " # Normalize and compute correlation\n", " normed = F.normalize(avg_patterns_flat, dim=-1)\n", " correlation = torch.matmul(normed, normed.T)\n", " # Penalize high correlation (exclude diagonal)\n", " mask = ~torch.eye(self.num_experts, device=correlation.device, dtype=torch.bool)\n", " diversity_loss = correlation[mask].pow(2).mean()\n", " losses['diversity'] = self.diversity_weight * diversity_loss\n", " \n", " return losses\n", "\n", "\n", "def count_parameters(model):\n", " \"\"\"Count total and trainable parameters.\"\"\"\n", " total = sum(p.numel() for p in model.parameters())\n", " trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", " return total, trainable\n", "\n", "\n", "def print_model_info(name, model, output, info):\n", " \"\"\"Print model statistics.\"\"\"\n", " total, trainable = count_parameters(model)\n", " print(f\"\\n{'='*60}\")\n", " print(f\"{name}\")\n", " print(f\"{'='*60}\")\n", " print(f\"Output shape: {output.shape}\")\n", " print(f\"Total params: {total:,}\")\n", " print(f\"Trainable params: {trainable:,}\")\n", " print(f\"Expert usage: {info['expert_usage'].tolist()}\")\n", " print(f\"Aux losses: {info['aux_losses']}\")\n", " print(f\"Total aux loss: {info['total_aux_loss']:.4f}\")\n", "\n", "\n", "# Testing\n", "if __name__ == \"__main__\":\n", " vocab_size = 50257\n", " batch_size = 4\n", " seq_len = 32\n", " \n", " print(\"\\n\" + \"=\"*60)\n", " print(\"TESTING PERMUTATION-BASED MOE VARIANTS\")\n", " print(\"=\"*60)\n", " \n", " input_ids = torch.randint(0, vocab_size, (batch_size, seq_len))\n", " \n", " # Test 1: Soft selection with replacement (default)\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"Test 1: Soft Selection WITH Replacement\")\n", " print(\"- Allows dimension repetition\")\n", " print(\"- MLP refinement AFTER selection\")\n", " print(\"=\"*60)\n", " model1 = PermutationMoE(\n", " vocab_size=vocab_size,\n", " base_embed_dim=64,\n", " num_experts=8,\n", " selection_mode='soft',\n", " allow_replacement=True,\n", " use_dim_mlp_refinement=True,\n", " mlp_refinement_position='after',\n", " )\n", " output1, info1 = model1(input_ids)\n", " print_model_info(\"Soft Selection (with replacement, MLP after)\", model1, output1, info1)\n", " \n", " # Test 2: Soft selection WITHOUT replacement\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"Test 2: Soft Selection WITHOUT Replacement\")\n", " print(\"- Encourages true permutations\")\n", " print(\"- MLP refinement BEFORE selection\")\n", " print(\"=\"*60)\n", " model2 = PermutationMoE(\n", " vocab_size=vocab_size,\n", " base_embed_dim=64,\n", " num_experts=8,\n", " selection_mode='soft',\n", " allow_replacement=False,\n", " use_dim_mlp_refinement=True,\n", " mlp_refinement_position='before',\n", " )\n", " output2, info2 = model2(input_ids)\n", " print_model_info(\"Soft Selection (no replacement, MLP before)\", model2, output2, info2)\n", " \n", " # Test 3: Hard selection with Gumbel\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"Test 3: Hard Selection (Gumbel) WITH Replacement\")\n", " print(\"- Discrete sampling via Gumbel-Softmax\")\n", " print(\"- No MLP refinement\")\n", " print(\"=\"*60)\n", " model3 = PermutationMoE(\n", " vocab_size=vocab_size,\n", " base_embed_dim=64,\n", " num_experts=8,\n", " selection_mode='hard',\n", " allow_replacement=True,\n", " use_dim_mlp_refinement=False,\n", " )\n", " output3, info3 = model3(input_ids)\n", " print_model_info(\"Hard Selection (Gumbel, with replacement, no MLP)\", model3, output3, info3)\n", " \n", " # Test 4: No MLP, soft selection\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"Test 4: Minimal Configuration\")\n", " print(\"- Soft selection, replacement allowed\")\n", " print(\"- No MLP refinement (fastest)\")\n", " print(\"=\"*60)\n", " model4 = PermutationMoE(\n", " vocab_size=vocab_size,\n", " base_embed_dim=64,\n", " num_experts=4, # Fewer experts\n", " selection_mode='soft',\n", " allow_replacement=True,\n", " use_dim_mlp_refinement=False,\n", " )\n", " output4, info4 = model4(input_ids)\n", " print_model_info(\"Minimal (4 experts, no MLP)\", model4, output4, info4)\n", " \n", " # Parameter comparison\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"PARAMETER COMPARISON\")\n", " print(\"=\"*60)\n", " models = [\n", " (\"Soft + Replacement + MLP(after)\", model1),\n", " (\"Soft + No Replace + MLP(before)\", model2),\n", " (\"Hard(Gumbel) + Replace + No MLP\", model3),\n", " (\"Minimal (4 experts)\", model4),\n", " ]\n", " \n", " print(f\"{'Model':<35} {'Total Params':>15} {'Non-Embed':>15}\")\n", " print(\"-\"*70)\n", " for name, model in models:\n", " total, _ = count_parameters(model)\n", " embed_params = sum(p.numel() for pname, p in model.named_parameters() \n", " if 'embedding' in pname.lower())\n", " print(f\"{name:<35} {total:>15,} {total-embed_params:>15,}\")\n", " \n", " # Analyze selection patterns - PROPER REPLACEMENT ANALYSIS\n", " print(\"\\n\" + \"=\"*60)\n", " print(\"SELECTION PATTERN ANALYSIS (Model 1)\")\n", " print(\"=\"*60)\n", " patterns = info1['selection_patterns'][0, 0] # First batch, first position\n", " print(f\"Shape: {patterns.shape} [num_experts, D_out, D_in]\")\n", " \n", " for expert_idx in range(min(3, model1.num_experts)):\n", " pattern = patterns[expert_idx] # [D_out, D_in]\n", " \n", " # PROPER ANALYSIS: Sum of weights each input dim receives\n", " input_dim_usage = pattern.sum(dim=0) # Sum across output dims [D_in]\n", " \n", " # Statistics\n", " max_usage = input_dim_usage.max().item()\n", " min_usage = input_dim_usage.min().item()\n", " mean_usage = input_dim_usage.mean().item()\n", " std_usage = input_dim_usage.std().item()\n", " \n", " # Check for replacement: are some dims used >1.0x?\n", " heavily_used = (input_dim_usage > 1.2).sum().item()\n", " barely_used = (input_dim_usage < 0.8).sum().item()\n", " \n", " # Entropy of selection (lower = more concentrated)\n", " pattern_flat = pattern.flatten()\n", " entropy = -(pattern_flat * torch.log(pattern_flat + 1e-10)).sum().item()\n", " \n", " # Top input dims by total usage\n", " top_vals, top_indices = input_dim_usage.topk(5)\n", " bottom_vals, bottom_indices = input_dim_usage.topk(5, largest=False)\n", " \n", " print(f\"\\nExpert {expert_idx}:\")\n", " print(f\" Input dim usage statistics:\")\n", " print(f\" Mean: {mean_usage:.3f} (expect ~1.0 for uniform)\")\n", " print(f\" Std: {std_usage:.3f} (higher = more specialization)\")\n", " print(f\" Max: {max_usage:.3f} (>1.0 indicates replacement)\")\n", " print(f\" Min: {min_usage:.3f} (<1.0 indicates some dims ignored)\")\n", " print(f\" Replacement evidence:\")\n", " print(f\" Dims used >1.2x: {heavily_used}/64 (replicated)\")\n", " print(f\" Dims used <0.8x: {barely_used}/64 (under-utilized)\")\n", " print(f\" Selection entropy: {entropy:.2f} (lower = more concentrated)\")\n", " print(f\" Top 5 input dims: {top_indices.tolist()}\")\n", " print(f\" Usage: {top_vals.tolist()}\")\n", " print(f\" Bottom 5 input dims: {bottom_indices.tolist()}\")\n", " print(f\" Usage: {bottom_vals.tolist()}\")\n", " \n", " print(\"\\n\" + \"=\"*60)\n", " print(\"✅ All tests passed!\")\n", " print(f\"Peak memory: {torch.cuda.max_memory_allocated() / 1e9:.2f} GB\" \n", " if torch.cuda.is_available() else \"CPU mode\")\n", " print(\"=\"*60)" ] }, { "cell_type": "code", "execution_count": 6, "id": "28c56cf5", "metadata": { "execution": { "iopub.execute_input": "2026-01-01T23:57:29.155485Z", "iopub.status.busy": "2026-01-01T23:57:29.155117Z", "iopub.status.idle": "2026-01-01T23:57:29.162230Z", "shell.execute_reply": "2026-01-01T23:57:29.161652Z" }, "papermill": { "duration": 0.015993, "end_time": "2026-01-01T23:57:29.163558", "exception": false, "start_time": "2026-01-01T23:57:29.147565", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "# import torch\n", "# import torch.nn as nn\n", "# import torch.nn.functional as F\n", "\n", "# # --- 1. The Core Component: Remixed Linear Expert ---\n", "# class RemixedExpert(nn.Module):\n", "# \"\"\"\n", "# The 'Context-Aware Basis' Layer.\n", "# Replaces the heavy \"generate a whole matrix\" approach.\n", "# \"\"\"\n", "# def __init__(self, in_features, out_features, context_dim, basis_size=64):\n", "# super().__init__()\n", "# self.basis_size = basis_size\n", " \n", "# # A. The Basis Bank (Input -> Basis Features)\n", "# # \"Here are the 64 fundamental ingredients we can use\"\n", "# self.basis = nn.Linear(in_features, basis_size, bias=False)\n", " \n", "# # CRITICAL FIX: Normalize basis before gating to prevent \"loud\" features leaking\n", "# self.ln_basis = nn.LayerNorm(basis_size)\n", " \n", "# # B. The Template Mixing (Basis -> Output)\n", "# # \"Here is the standard recipe for combining ingredients\"\n", "# self.template_mixing = nn.Parameter(torch.randn(out_features, basis_size))\n", " \n", "# # C. The Context Controller (Input -> Gates)\n", "# # \"Decide which ingredients and which recipes to use right now\"\n", "# # Outputs: [Basis_Gate (64) + Output_Gate (512)]\n", "# self.context_modulator = nn.Sequential(\n", "# nn.Linear(context_dim, basis_size), # Compress context\n", "# nn.GELU(),\n", "# nn.Linear(basis_size, basis_size + out_features),\n", "# nn.Sigmoid() # Soft Gating (0.0 to 1.0)\n", "# )\n", " \n", "# self.bias = nn.Parameter(torch.zeros(out_features))\n", "# self.reset_parameters()\n", "# self.final_ln = nn.Linear(out_features, out_features)\n", "\n", "# def reset_parameters(self):\n", "# nn.init.orthogonal_(self.basis.weight)\n", "# nn.init.kaiming_normal_(self.template_mixing)\n", "# # Initialize gates to be mostly OPEN (bias=2.0 -> sigmoid=0.88)\n", "# # This prevents \"dead expert\" start\n", "# nn.init.constant_(self.context_modulator[-2].bias, 2.0) \n", "\n", "# def forward(self, x, context):\n", "# # x: [Batch, Seq, In]\n", " \n", "# # 1. Project to Basis & Normalize\n", "# h_basis = self.basis(x)\n", "# h_basis = self.ln_basis(h_basis) # The \"Loudness\" Fix\n", " \n", "# # 2. Generate Gates from Context\n", "# gates = self.context_modulator(context)\n", "# gate_basis = gates[..., :self.basis_size]\n", "# gate_out = gates[..., self.basis_size:]\n", " \n", "# # 3. Apply Basis Gating (Select features)\n", "# h_gated = h_basis * gate_basis\n", " \n", "# # 4. Apply Template Mixing (The Remix)\n", "# # F.linear uses the weight matrix (Output, Input), so we use standard broadcast\n", "# pre_output = F.linear(h_gated, self.template_mixing)\n", " \n", "# # 5. Apply Output Gating (Select active neurons)\n", "# output = (pre_output * gate_out) + self.bias\n", "# output = self.final_ln(output)# + output\n", " \n", " \n", "# return output , gates\n", "\n", "# # --- 2. The Main Module: Permutation MOE ---\n", "# class PermutationMoE(nn.Module):\n", "# \"\"\"\n", "# Revised MoE using Remixed Basis Experts.\n", "# \"\"\"\n", "# def __init__(\n", "# self,\n", "# vocab_size,\n", "# block_size=64,\n", "# base_embed_dim=64,\n", "# num_experts=8,\n", "# router_dim=64,\n", "# context_window=-1,\n", "# causal=True,\n", "# num_queries=8,\n", "# n_layers=2,\n", "# use_vocab_prior=False,\n", "# num_heads=8,\n", "# # Legacy params we might ignore now but keep for compatibility\n", "# selection_mode='soft', \n", "# allow_replacement=True,\n", "# dropout=0.0,\n", "# load_balance_weight=0.01,\n", "# z_loss_weight=0.001,\n", "# diversity_weight=0.01,\n", "# use_dim_mlp_refinement=True,\n", "# mlp_refinement_position='after', # 'before' or 'after' selection\n", " \n", "# ):\n", "# super().__init__()\n", " \n", "# self.base_embed_dim = base_embed_dim\n", "# self.num_experts = num_experts\n", "# self.load_balance_weight = load_balance_weight\n", "# self.z_loss_weight = z_loss_weight\n", "# self.diversity_weight = diversity_weight\n", " \n", "# # 1. Embeddings\n", "# self.embeddings = nn.Embedding(vocab_size, base_embed_dim)\n", "# self.position_embeddings = nn.Embedding(block_size, base_embed_dim)\n", " \n", "# # 2. The Experts (Now RemixedLinear instances)\n", "# # Note: We treat 'x' and 'context' as the same input (self-driven)\n", "# self.experts = nn.ModuleList([\n", "# RemixedExpert(\n", "# in_features=base_embed_dim,\n", "# out_features=base_embed_dim,\n", "# context_dim=base_embed_dim,\n", "# basis_size=base_embed_dim # Keeping basis size same as embed dim for 1:1 mapping potential\n", "# ) for _ in range(num_experts)\n", "# ])\n", " \n", "# # 3. Router (Assuming ImprovedContextAwareRouter exists in your scope)\n", "# # For this snippet to run standalone, I'll mock a simple router if that class is missing\n", "# try:\n", "# self.expert_router = ImprovedContextAwareRouter(\n", "# vocab_size=vocab_size, num_experts=num_experts, router_dim=router_dim,\n", "# full_embed_dim=base_embed_dim, context_window=context_window, causal=causal,\n", "# num_heads=num_heads, num_queries=num_queries, n_layers=n_layers,\n", "# use_vocab_prior=use_vocab_prior,\n", "# )\n", "# except NameError:\n", "# print(\"Warning: ImprovedContextAwareRouter not found. Using simple Linear Router.\")\n", "# self.expert_router = nn.Linear(base_embed_dim, num_experts)\n", "# self.simple_router = True\n", "# else:\n", "# self.simple_router = False\n", "\n", "# self.ln = nn.LayerNorm(base_embed_dim)\n", "# self.dropout = nn.Dropout(dropout)\n", "# self.register_buffer('temperature', torch.tensor(1.0))\n", "\n", "# def forward(self, input_ids):\n", "# batch_size, seq_len = input_ids.shape\n", "# device = input_ids.device\n", "# positions = torch.arange(seq_len, device=device)\n", " \n", "# # 1. Base Embeddings\n", "# embeds = self.embeddings(input_ids) + self.position_embeddings(positions)\n", " \n", "# # 2. Run Experts\n", "# # Each expert acts as a \"Remixer\"\n", "# expert_outputs = []\n", "# all_gates = [] # To track patterns for diversity loss\n", " \n", "# for expert in self.experts:\n", "# # Pass (x, context) -> in this case, both are 'embeds'\n", "# out, gates = expert(embeds, embeds) \n", "# expert_outputs.append(out)\n", "# all_gates.append(gates)\n", " \n", "# # Stack: [B, L, Num_Experts, D]\n", "# expert_outputs = torch.stack(expert_outputs, dim=2)\n", "# # Stack Gates: [B, L, Num_Experts, Gate_Dim]\n", "# all_gates = torch.stack(all_gates, dim=2)\n", "\n", "# # 3. Routing\n", "# if not self.simple_router:\n", "# expert_logits, adaptive_temp, _ = self.expert_router(embeds, input_ids)\n", "# expert_weights = F.softmax(expert_logits / (self.temperature * adaptive_temp), dim=-1)\n", "# else:\n", "# expert_logits = self.expert_router(embeds)\n", "# expert_weights = F.softmax(expert_logits, dim=-1)\n", " \n", "# expert_weights = self.dropout(expert_weights)\n", " \n", "# # 4. Combine (Weighted Sum)\n", "# # [B, L, E, 1] * [B, L, E, D] -> Sum over E\n", "# output = (expert_weights.unsqueeze(-1) * expert_outputs).sum(dim=2)\n", "# output = self.ln(output)\n", " \n", "# # 5. Aux Losses\n", "# aux_losses = self._compute_aux_losses(expert_logits, expert_weights, all_gates)\n", " \n", "# routing_info = {\n", "# 'expert_usage': expert_weights.mean(dim=[0, 1]),\n", "# 'aux_losses': aux_losses,\n", "# 'total_aux_loss': sum(aux_losses.values())\n", "# }\n", " \n", "# return output, routing_info\n", "\n", "# def _compute_aux_losses(self, expert_logits, expert_weights, all_gates):\n", "# losses = {}\n", " \n", "# # A. Load Balancing (Standard)\n", "# expert_usage = expert_weights.sum(dim=[0, 1])\n", "# mean_usage = expert_usage.mean()\n", "# losses['load_balance'] = self.load_balance_weight * (expert_usage - mean_usage).pow(2).mean()\n", " \n", "# # B. Z-Loss (Router Stability)\n", "# losses['z_loss'] = self.z_loss_weight * torch.logsumexp(expert_logits, dim=-1).pow(2).mean()\n", " \n", "# # C. Diversity Loss (New: Based on Gates)\n", "# # We want experts to use DIFFERENT basis features.\n", "# # all_gates: [B, L, E, Gate_Dim]\n", "# # Average gate activation per expert: [E, Gate_Dim]\n", "# avg_gates = all_gates.mean(dim=[0, 1])\n", " \n", "# # Normalize to compare shapes of gate vectors\n", "# normed = F.normalize(avg_gates, dim=-1)\n", "# correlation = torch.matmul(normed, normed.T) # [E, E]\n", " \n", "# # Penalize off-diagonal correlations (experts looking identical)\n", "# mask = ~torch.eye(self.num_experts, device=correlation.device, dtype=torch.bool)\n", "# losses['diversity'] = self.diversity_weight * correlation[mask].pow(2).mean()\n", " \n", "# return losses\n", "\n", "# # --- Testing Block (Copy-Paste this to verify) ---\n", "# if __name__ == \"__main__\":\n", "# vocab_size = 50257\n", "# model = PermutationMoE(vocab_size=vocab_size, base_embed_dim=64, num_experts=4)\n", " \n", "# # Dummy Input\n", "# x = torch.randint(0, vocab_size, (2, 32))\n", " \n", "# # Forward\n", "# out, info = model(x)\n", " \n", "# print(\"Output Shape:\", out.shape)\n", "# print(\"Expert Usage:\", info['expert_usage'])\n", "# print(\"Total Aux Loss:\", info['total_aux_loss'])\n", " \n", "# # Verify the Gates are moving (The Pulse Check)\n", "# # We access the first expert to see if gates are 0.5 or varied\n", "# first_expert_gates = model.experts[0].context_modulator(model.embeddings(x))\n", "# print(f\"Gate Std (Should be > 0.2): {first_expert_gates.std().item():.4f}\")" ] }, { "cell_type": "code", "execution_count": 7, "id": "2e6c81d6", "metadata": { "execution": { "iopub.execute_input": "2026-01-01T23:57:29.177294Z", "iopub.status.busy": "2026-01-01T23:57:29.176786Z", "iopub.status.idle": "2026-01-01T23:57:29.337957Z", "shell.execute_reply": "2026-01-01T23:57:29.337132Z" }, "papermill": { "duration": 0.169882, "end_time": "2026-01-01T23:57:29.339534", "exception": false, "start_time": "2026-01-01T23:57:29.169652", "status": "completed" }, "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Input: torch.Size([2, 64])\n", "Output: torch.Size([2, 64, 50257])\n", "\n", "Standard Linear Layer Params: 262,656\n", "Remixed Linear Layer Params: 14,688\n", "\n", "Concept validated: Global Context drives Local Remixing.\n" ] } ], "source": [ "\n", "\n", "# ==========================================\n", "# 1. The Core Router (Your provided class)\n", "# ==========================================\n", "class ImprovedContextAwareRouter(nn.Module):\n", " \"\"\"Enhanced router with vocabulary-aware initialization and better scaling.\"\"\"\n", " def __init__(\n", " self,\n", " vocab_size,\n", " num_experts, \n", " router_dim,\n", " full_embed_dim,\n", " context_window=8,\n", " causal=True,\n", " num_heads=4,\n", " num_queries=8,\n", " n_layers=1,\n", " use_vocab_prior=True,\n", " ):\n", " super().__init__()\n", " # In this specific config, num_experts will equal target_dim (64)\n", " self.num_experts = num_experts \n", " self.router_dim = router_dim\n", " self.context_window = context_window\n", " self.causal = causal\n", " self.num_heads = num_heads\n", " self.head_dim = router_dim // num_heads\n", " self.num_queries = num_queries\n", " self.n_layers = n_layers\n", " self.use_vocab_prior = use_vocab_prior\n", " \n", " # Project full embeddings to router dimension\n", " self.embed_proj = nn.Linear(full_embed_dim, router_dim)\n", " \n", " # Multi-head attention\n", " self.qkv_proj = nn.Linear(router_dim, 3 * router_dim, bias=False)\n", " self.out_proj = nn.Linear(router_dim, router_dim)\n", " \n", " # Expert projection with layer norm for stability\n", " self.ln = nn.LayerNorm(router_dim)\n", " self.routing_queries = nn.Parameter(torch.randn(num_queries, router_dim))\n", " self.temperature_predictor = nn.Linear(router_dim, 1)\n", " \n", " self.expert_proj = nn.Linear(router_dim, num_experts)\n", " self.cross_expert_proj = nn.Linear(router_dim, num_experts)\n", " self.alpha_gate = nn.Linear(router_dim, 1)\n", " \n", " # Vocabulary prior for better initialization\n", " if use_vocab_prior:\n", " self.vocab_routing_bias = nn.Embedding(vocab_size, num_experts)\n", " nn.init.normal_(self.vocab_routing_bias.weight, mean=0, std=0.02)\n", " \n", " # Better initialization for large vocab\n", " nn.init.normal_(self.expert_proj.weight, mean=0, std=0.02)\n", " nn.init.normal_(self.cross_expert_proj.weight, mean=0, std=0.02)\n", " \n", " def forward(self, full_embeds, input_ids=None):\n", " batch_size, seq_len, _ = full_embeds.shape\n", " \n", " # Project to router dimension\n", " x = self.embed_proj(full_embeds)\n", " \n", " # Multi-head context attention\n", " for _ in range(self.n_layers):\n", " x = self._multi_head_attention(x)\n", " \n", " # Layer norm before expert projection\n", " x = self.ln(x)\n", " \n", " # Get expert logits\n", " self_attn_logits = self.expert_proj(x)\n", " cross_attn_logits = self.cross_expert_proj(self._cross_attention(self.routing_queries, x))\n", " \n", " alpha = torch.sigmoid(self.alpha_gate(x))\n", " expert_logits = alpha * self_attn_logits + (1 - alpha) * cross_attn_logits\n", " \n", " # Add vocabulary prior if available\n", " if self.use_vocab_prior and input_ids is not None:\n", " vocab_bias = self.vocab_routing_bias(input_ids)\n", " expert_logits = expert_logits + vocab_bias\n", " \n", " adaptive_temp = torch.sigmoid(self.temperature_predictor(x)) * 2.0 + 0.1\n", " \n", " # We return expert_logits as the embedding itself\n", " return expert_logits, adaptive_temp, self.expert_proj.weight\n", "\n", " def _cross_attention(self, queries, context):\n", " batch_size, seq_len, dim = context.shape\n", " num_queries = queries.shape[0]\n", " \n", " queries = queries.unsqueeze(0).expand(batch_size, num_queries, dim)\n", " attn_scores = torch.matmul(queries, context.transpose(1, 2)) / (dim ** 0.5)\n", " attn_weights = torch.softmax(attn_scores, dim=-1)\n", " attended = torch.matmul(attn_weights, context)\n", " fused = attended.mean(dim=1).unsqueeze(1).expand(-1, seq_len, -1)\n", " return fused\n", " \n", " def _multi_head_attention(self, x):\n", " batch_size, seq_len, _ = x.shape\n", " \n", " qkv = self.qkv_proj(x).reshape(batch_size, seq_len, 3, self.num_heads, self.head_dim)\n", " qkv = qkv.permute(2, 0, 3, 1, 4)\n", " q, k, v = qkv[0], qkv[1], qkv[2]\n", " \n", " attn_scores = torch.matmul(q, k.transpose(-2, -1)) / (self.head_dim ** 0.5)\n", " mask = self._create_mask(seq_len, x.device).unsqueeze(0).unsqueeze(0)\n", " attn_scores = attn_scores.masked_fill(mask, float('-inf'))\n", " \n", " attn_weights = F.softmax(attn_scores, dim=-1)\n", " context = torch.matmul(attn_weights, v)\n", " context = context.transpose(1, 2).reshape(batch_size, seq_len, self.router_dim)\n", " output = self.out_proj(context) + x\n", " return output\n", " \n", " def _create_mask(self, seq_len, device):\n", " if self.context_window == -1:\n", " if self.causal:\n", " positions = torch.arange(seq_len, device=device)\n", " pos_diff = positions.unsqueeze(0) - positions.unsqueeze(1)\n", " return pos_diff > 0\n", " else:\n", " return torch.zeros(seq_len, seq_len, dtype=torch.bool, device=device)\n", " \n", " positions = torch.arange(seq_len, device=device)\n", " pos_diff = positions.unsqueeze(0) - positions.unsqueeze(1)\n", " \n", " if self.causal:\n", " return (pos_diff > 0) | (pos_diff < -self.context_window)\n", " else:\n", " window_half = self.context_window // 2\n", " return torch.abs(pos_diff) > window_half\n", "\n", "\n", "# Re-using your provided ImprovedContextAwareRouter class\n", "# (Assuming it is defined as in your snippet above)\n", "\n", "class GlobalContextManager(nn.Module):\n", " \"\"\"\n", " The 'Brain'. Runs once per forward pass.\n", " Extracts a compact context representation to control all downstream layers.\n", " \"\"\"\n", " def __init__(self, vocab_size, d_model, router_dim=64, context_window=128):\n", " super().__init__()\n", " # We reuse your existing robust router\n", " # We set num_experts to 'router_dim' because we want a dense context vector\n", " # not necessarily sparse expert logits for this specific role.\n", " self.router = ImprovedContextAwareRouter(\n", " vocab_size=vocab_size,\n", " num_experts=router_dim, # Output a dense vector of this size\n", " router_dim=router_dim,\n", " full_embed_dim=d_model,\n", " context_window=context_window,\n", " causal=True,\n", " num_heads=4,\n", " n_layers=2\n", " )\n", " self.router_dim = router_dim\n", "\n", " def forward(self, x_embeds, input_ids=None):\n", " \"\"\"\n", " Args:\n", " x_embeds: [Batch, Seq, D_model]\n", " Returns:\n", " context_state: [Batch, Seq, router_dim] \n", " This is the 'control signal' for all layers.\n", " \"\"\"\n", " # We use the 'expert_logits' as our continuous context representation\n", " # rather than softmaxing them into probabilities, as we want dense info.\n", " context_logits, _, _ = self.router(x_embeds, input_ids)\n", " \n", " # Normalize for stability in downstream projections\n", " context_state = F.layer_norm(context_logits, context_logits.shape[-1:])\n", " return context_state\n", "\n", "class RemixedLinear(nn.Module):\n", " def __init__(self, in_features, out_features, context_dim, basis_size=64, remixed_linear_kwargs = dict(use_basis_gate=True, use_output_gate=True, use_context=True)):\n", " super().__init__()\n", " self.in_features = in_features\n", " self.out_features = out_features\n", " self.basis_size = basis_size\n", " self.use_basis_gate = remixed_linear_kwargs['use_basis_gate']\n", " self.use_output_gate = remixed_linear_kwargs['use_output_gate']\n", " self.use_context = remixed_linear_kwargs['use_context']\n", " # self.last_gate_stats = {}\n", " \n", " # 1. STATIC COMPONENTS (The \"Body\")\n", " # A. The Basis Bank (Input -> Basis)\n", " self.basis = nn.Linear(in_features, basis_size, bias=False)\n", " # self.register_buffer(\"global_step\", torch.zeros(1))\n", " # self.annealer = TemperatureAnnealer(\n", " # start=1.5,\n", " # end=0.3, # do NOT go to zero\n", " # total_steps=5_000,\n", " # mode=\"cosine\"\n", " # )\n", " \n", " # B. The Template Mixing Matrix (Basis -> Output)\n", " # This represents the \"standard\" way features are combined.\n", " # We learn this once. It is NOT generated.\n", " self.template_mixing = nn.Parameter(torch.randn(out_features, basis_size))\n", " # self.temperature = nn.Parameter(torch.tensor(1.0))\n", " # 2. DYNAMIC COMPONENTS (The \"Controller\")\n", " # instead of generating the whole matrix, we generate two small vectors:\n", " # a. Basis Gate: Which basis features are active? (Size: 64)\n", " # b. Output Gate: Which output neurons are active? (Size: 512)\n", " self.context_modulator = nn.Sequential(\n", " nn.Linear(context_dim, basis_size // 2),\n", " nn.GELU(),\n", " # Output size: basis_size + out_features (e.g., 64 + 512)\n", " nn.Linear(basis_size // 2, basis_size + out_features),\n", " # nn.Sigmoid() # Gating (0 to 1) or Tanh (-1 to 1) depending on preference\n", " )\n", " \n", " self.bias = nn.Parameter(torch.zeros(out_features))\n", " self.ln_basis = nn.LayerNorm(basis_size)\n", " self.reset_parameters()\n", "\n", " def reset_parameters(self):\n", " nn.init.orthogonal_(self.basis.weight)\n", " nn.init.kaiming_normal_(self.template_mixing)\n", " # Initialize modulator to close to 1.0 (Identity pass-through)\n", " nn.init.constant_(self.context_modulator[-1].bias, 2.0) \n", "\n", " def forward(self, x, context_state):\n", " B, S, C = x.shape\n", " # self.global_step += 1\n", " \n", " # tau = self.annealer(int(self.global_step.item()))\n", " # x: [Batch, Seq, In]\n", " # context_state: [Batch, Seq, Context_Dim]\n", "\n", " # 1. Project to Basis\n", " h_basis = self.ln_basis(self.basis(x)) # [B, S, Basis]\n", " \n", " # 2. Get Dynamic Modulation Gates\n", " # Shape: [B, S, Basis + Out]\n", " if self.use_context:\n", " gates = torch.sigmoid(self.context_modulator(context_state))#/self.temperature)\n", " B, S, C = gates.shape\n", " # Split into Basis Gate and Output Gate\n", " \n", " \n", " if not self.use_basis_gate:\n", " gate_basis = torch.ones(B, S, self.basis_size, device=device)\n", " else:\n", " gate_basis = gates[..., :self.basis_size] # [B, S, Basis]\n", " if not self.use_output_gate:\n", " gate_out = torch.ones(B, S, C - self.basis_size, device=device)\n", " else:\n", " gate_out = gates[..., self.basis_size:] # [B, S, Out]\n", " h_gated = h_basis * gate_basis\n", " \n", " # B. Apply Static Template Mixing (The heavy lifting matrix mul)\n", " # [B, S, Basis] @ [Basis, Out] -> [B, S, Out]\n", " pre_output = F.linear(h_gated, self.template_mixing)\n", " else:\n", " gate_basis = torch.ones_like(h_basis)\n", " h_gated = h_basis * gate_basis\n", " # B. Apply Static Template Mixing (The heavy lifting matrix mul)\n", " # [B, S, Basis] @ [Basis, Out] -> [B, S, Out]\n", " pre_output = F.linear(h_gated, self.template_mixing)\n", " gate_out = torch.ones_like(pre_output)\n", "\n", " # if not self.use_basis_gate:\n", " # gate_basis = torch.ones_like(gate_basis)\n", "\n", " # if not self.use_output_gate:\n", " # gate_out = torch.ones_like(gate_out)\n", "\n", " self.last_gate_entropy = gate_entropy(gate_out)\n", "\n", " # Check the spread of your Basis Gate\n", " # We want to see a standard deviation > 0.\n", " # gate_std = gates[..., :self.basis_size].std()\n", " # gate_mean = gates[..., :self.basis_size].mean()\n", " # if self.global_step % 1000 ==0:\n", " # print(f\"Gate Mean: {gate_mean:.4f} | Gate Std: {gate_std:.4f}\")\n", "\n", " # if self.training:\n", " # self.last_gate_stats = {\n", " # \"basis\": gate_stats(gate_basis.detach()),\n", " # \"out\": gate_stats(gate_out.detach())\n", " # }\n", " \n", " # 3. The \"Modulated\" Remix\n", " # We want to perform: Output = (Basis * Gate_Basis) @ Template.T * Gate_Out\n", " \n", " # A. Apply Basis Gating (Context decides which input features matter)\n", "\n", " \n", " # C. Apply Output Gating (Context decides which output neurons fire)\n", " output = pre_output * gate_out\n", " \n", " return output + self.bias\n", "\n", "\n", "class DynamicRemixNet(nn.Module):\n", " \"\"\"Example Model putting it all together\"\"\"\n", " def __init__(self, vocab_size, d_model, n_layers, context_dim=64):\n", " super().__init__()\n", " \n", " self.embeddings = nn.Embedding(vocab_size, d_model)\n", " \n", " # 1. The Global Brain\n", " self.context_manager = GlobalContextManager(vocab_size, d_model, router_dim=context_dim)\n", " \n", " # 2. The Layers (using RemixedLinear instead of nn.Linear)\n", " self.layers = nn.ModuleList([\n", " RemixedLinear(d_model, d_model, context_dim, basis_size=64)\n", " for _ in range(n_layers)\n", " ])\n", " \n", " self.norm = nn.LayerNorm(d_model)\n", " self.head = nn.Linear(d_model, vocab_size, bias=False)\n", "\n", " def forward(self, input_ids):\n", " x = self.embeddings(input_ids)\n", " \n", " # 1. Compute Context ONCE\n", " context_state = self.context_manager(x, input_ids)\n", " \n", " # 2. Pass context to all dynamic layers\n", " for layer in self.layers:\n", " # Standard residual connection\n", " residual = x\n", " x = layer(x, context_state)\n", " x = self.norm(x + residual)\n", " \n", " return self.head(x)\n", "\n", "# --- Verification Code ---\n", "if __name__ == \"__main__\":\n", " B, S, D = 2, 64, 512\n", " V = 50257\n", " \n", " model = DynamicRemixNet(vocab_size=V, d_model=D//8, n_layers=4)\n", " inputs = torch.randint(0, V, (B, S))\n", " \n", " # Forward pass\n", " out = model(inputs)\n", " \n", " print(f\"Input: {inputs.shape}\")\n", " print(f\"Output: {out.shape}\")\n", " \n", " # Parameter Efficiency Check\n", " std_linear = nn.Linear(D,D) #D * D\n", " remix_linear = RemixedLinear(D//8, D//8, 64, basis_size=64) #(D * 64) + (64 * 64 * D) # Basis + Hypernet approximation\n", " # Note: Hypernet can be optimized further with low-rank factorization\n", " \n", " print(f\"\\nStandard Linear Layer Params: {sum(p.numel() for p in std_linear.parameters()):,}\")\n", " print(f\"Remixed Linear Layer Params: {sum(p.numel() for p in remix_linear.parameters()):,}\")\n", "\n", " # print(f\"Remixed Linear Layer Params: {sum(p.numel() for p in model.layers[0].parameters()):,}\")\n", " print(\"\\nConcept validated: Global Context drives Local Remixing.\")" ] }, { "cell_type": "code", "execution_count": null, "id": "03ac3f4d", "metadata": { "papermill": { "duration": 0.006511, "end_time": "2026-01-01T23:57:29.354293", "exception": false, "start_time": "2026-01-01T23:57:29.347782", "status": "completed" }, "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "10053b91", "metadata": { "papermill": { "duration": 0.005995, "end_time": "2026-01-01T23:57:29.367213", "exception": false, "start_time": "2026-01-01T23:57:29.361218", "status": "completed" }, "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 8, "id": "11349ba9", "metadata": { "execution": { "iopub.execute_input": "2026-01-01T23:57:29.381721Z", "iopub.status.busy": "2026-01-01T23:57:29.380956Z", "iopub.status.idle": "2026-01-01T23:57:29.421166Z", "shell.execute_reply": "2026-01-01T23:57:29.420677Z" }, "papermill": { "duration": 0.048963, "end_time": "2026-01-01T23:57:29.422549", "exception": false, "start_time": "2026-01-01T23:57:29.373586", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "from tqdm.notebook import tqdm\n", "\n", "# ==============================================================================\n", "# 2. TRANSFORMER COMPONENTS (Modified for Remixing)\n", "# ==============================================================================\n", "class Head(nn.Module):\n", " \"\"\" one head of self-attention \"\"\"\n", "\n", " def __init__(self, head_size):\n", " super().__init__()\n", " self.key = nn.Linear(n_embd, head_size, bias=False)\n", " self.query = nn.Linear(n_embd, head_size, bias=False)\n", "\n", " self.value = nn.Linear(n_embd, head_size, bias=False)\n", " self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))\n", "\n", " self.dropout = nn.Dropout(dropout)\n", "\n", " def forward(self, x):\n", " B,T,C = x.shape\n", " \n", " k = self.key(x) # (B,T,C)\n", " q = self.query(x) # (B,T,C)\n", " # compute attention scores (\"affinities\")\n", " wei = q @ k.transpose(-2,-1) * C**-0.5 # (B, T, C) @ (B, C, T) -> (B, T, T)\n", " wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)\n", " wei = F.softmax(wei, dim=-1) # (B, T, T)\n", " wei = self.dropout(wei)\n", " # perform the weighted aggregation of the values\n", " v = self.value(x) # (B,T,C)\n", " out = wei @ v # (B, T, T) @ (B, T, C) -> (B, T, C)\n", " return out\n", "\n", "# class MultiHeadAttention(nn.Module):\n", "# \"\"\" multiple heads of self-attention in parallel \"\"\"\n", "\n", "# def __init__(self, n_embd, num_heads, head_size):\n", "# super().__init__()\n", "# self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])\n", "# self.proj = nn.Linear(n_embd, n_embd)\n", "# self.dropout = nn.Dropout(dropout)\n", "\n", "# def forward(self, x):\n", "# out = torch.cat([h(x) for h in self.heads], dim=-1)\n", "# out = self.dropout(self.proj(out))\n", "# return out\n", "class MultiHeadAttention(nn.Module):\n", " def __init__(self, n_embd, n_heads, head_size, dropout, block_size):\n", " super().__init__()\n", " self.n_heads = n_heads\n", " self.head_size = head_size\n", " self.dropout_p = dropout\n", " \n", " # Projections for Q, K, V\n", " self.block_proj = nn.Linear(n_embd, n_embd * 3)\n", " self.dropout = nn.Dropout(dropout)\n", " self.proj = nn.Linear(n_embd, n_embd)\n", " \n", " # Causal mask\n", " self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))\n", " \n", " def forward(self, blocks, attention_mask=None):\n", " B, T, C = blocks.shape\n", " \n", " # 1. Project to Q, K, V\n", " Q, K, V = self.block_proj(blocks).chunk(3, dim=-1)\n", " \n", " # 2. Split into heads: (B, T, C) -> (B, n_heads, T, head_size)\n", " Q = Q.view(B, T, self.n_heads, self.head_size).permute(0, 2, 1, 3)\n", " K = K.view(B, T, self.n_heads, self.head_size).permute(0, 2, 1, 3)\n", " V = V.view(B, T, self.n_heads, self.head_size).permute(0, 2, 1, 3)\n", " \n", " # 3. Apply attention with masking\n", " if attention_mask is not None:\n", " # Causal mask: (T, T)\n", " causal_mask = self.tril[:T, :T]\n", " \n", " # Padding mask: attention_mask is (B, T) where 1=valid, 0=padding\n", " # Create (B, T, T) mask where both query and key must be valid\n", " padding_mask = attention_mask.unsqueeze(1) * attention_mask.unsqueeze(2) # (B, T, T)\n", " \n", " # Combine masks: both causal AND padding must allow attention\n", " combined_mask = causal_mask.unsqueeze(0) & padding_mask.bool() # (B, T, T)\n", " combined_mask = combined_mask.unsqueeze(1) # (B, 1, T, T) for broadcasting\n", " \n", " output = F.scaled_dot_product_attention(\n", " Q, K, V,\n", " attn_mask=combined_mask,\n", " dropout_p=self.dropout_p if self.training else 0.0\n", " )\n", " else:\n", " # Only causal mask (use is_causal for efficiency)\n", " output = F.scaled_dot_product_attention(\n", " Q, K, V,\n", " is_causal=True,\n", " dropout_p=self.dropout_p if self.training else 0.0\n", " )\n", " \n", " # 4. Concatenate heads and project\n", " output = output.transpose(1, 2).contiguous().view(B, T, C)\n", " output = self.dropout(self.proj(output))\n", " \n", " return output\n", "\n", "\n", "\n", "\n", "class FeedFoward(nn.Module):\n", " \"\"\" a simple linear layer followed by a non-linearity \"\"\"\n", "\n", " def __init__(self, n_embd, dropout):\n", " super().__init__()\n", " self.net = nn.Sequential(\n", " nn.Linear(n_embd, 4 * n_embd),\n", " nn.ReLU(),\n", " nn.Linear(4 * n_embd, n_embd),\n", " nn.Dropout(dropout),\n", " )\n", "\n", " def forward(self, x):\n", " return self.net(x)\n", "\n", "class Block(nn.Module):\n", " \"\"\" Transformer block: communication followed by computation \"\"\"\n", "\n", " def __init__(self, n_embd, n_head, dropout, block_size):\n", " # n_embd: embedding dimension, n_head: the number of heads we'd like\n", " super().__init__()\n", " head_size = n_embd // n_head\n", " self.sa = MultiHeadAttention(n_embd, n_head, head_size, dropout, block_size)\n", " # self.sa = MultiTokenAttention(n_head, head_size)\n", " self.ffwd = FeedFoward(n_embd,dropout)\n", " self.ln1 = nn.LayerNorm(n_embd)\n", " self.ln2 = nn.LayerNorm(n_embd)\n", "\n", " def forward(self, x):\n", " x = x + self.sa(self.ln1(x))\n", " x = x + self.ffwd(self.ln2(x))\n", " return x\n", "class RemixedFeedFoward(nn.Module):\n", " \"\"\"\n", " FeedForward Network using RemixedLinear.\n", " Replaces static up/down projections with dynamic, context-aware remixing.\n", " \"\"\"\n", " def __init__(self, n_embd, dropout, context_dim, basis_size=64, remixed_linear_kwargs = dict(use_basis_gate=True, use_output_gate=True, use_context=True)):\n", " super().__init__()\n", " # 1. Expansion: n_embd -> 4 * n_embd\n", " # Uses dynamic mixing to expand features\n", " self.w1 = RemixedLinear(\n", " in_features=n_embd, \n", " out_features=4 * n_embd, \n", " context_dim=context_dim,\n", " basis_size=basis_size, remixed_linear_kwargs = remixed_linear_kwargs\n", " )\n", " \n", " self.act = nn.ReLU()\n", " \n", " # 2. Projection: 4 * n_embd -> n_embd\n", " # Uses dynamic mixing to compress back to model dim\n", " self.w2 = RemixedLinear(\n", " in_features=4 * n_embd, \n", " out_features=n_embd, \n", " context_dim=context_dim,\n", " basis_size=basis_size, remixed_linear_kwargs=remixed_linear_kwargs\n", " )\n", " \n", " self.dropout = nn.Dropout(dropout)\n", "\n", " def forward(self, x, context_state):\n", " # Pass context_state to both RemixedLinear layers\n", " x = self.w1(x, context_state)\n", " x = self.act(x)\n", " x = self.w2(x, context_state)\n", " x = self.dropout(x)\n", " return x\n", "\n", "class RemixedMultiHeadAttention(nn.Module):\n", " \"\"\"Attention mechanism using RemixedLinear for Q, K, V projections.\"\"\"\n", " def __init__(self, n_embd, n_heads, head_size, dropout, block_size, context_dim, basis_size=64, remixed_linear_kwargs = dict(use_basis_gate=True, use_output_gate=True, use_context=True)):\n", " super().__init__()\n", " self.n_heads = n_heads\n", " self.head_size = head_size\n", " self.dropout_p = dropout\n", " \n", " # REPLACE Standard Linear with RemixedLinear for QKV\n", " self.qkv_proj = RemixedLinear(\n", " in_features=n_embd, \n", " out_features=n_embd * 3, \n", " context_dim=context_dim,\n", " basis_size=basis_size,remixed_linear_kwargs = remixed_linear_kwargs \n", " )\n", " \n", " self.dropout = nn.Dropout(dropout)\n", " self.proj = nn.Linear(n_embd, n_embd) # Keeping output proj standard for aggregation\n", " \n", " self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))\n", " \n", " def forward(self, blocks, context_state, attention_mask=None):\n", " B, T, C = blocks.shape\n", " \n", " # 1. Remixed Projection\n", " qkv = self.qkv_proj(blocks, context_state)\n", " Q, K, V = qkv.chunk(3, dim=-1)\n", " \n", " # 2. Split Heads\n", " Q = Q.view(B, T, self.n_heads, self.head_size).permute(0, 2, 1, 3)\n", " K = K.view(B, T, self.n_heads, self.head_size).permute(0, 2, 1, 3)\n", " V = V.view(B, T, self.n_heads, self.head_size).permute(0, 2, 1, 3)\n", " \n", " # 3. Attention Logic\n", " if attention_mask is not None:\n", " causal_mask = self.tril[:T, :T]\n", " padding_mask = attention_mask.unsqueeze(1) * attention_mask.unsqueeze(2)\n", " combined_mask = causal_mask.unsqueeze(0) & padding_mask.bool()\n", " combined_mask = combined_mask.unsqueeze(1)\n", " \n", " output = F.scaled_dot_product_attention(\n", " Q, K, V, attn_mask=combined_mask, \n", " dropout_p=self.dropout_p if self.training else 0.0\n", " )\n", " else:\n", " output = F.scaled_dot_product_attention(\n", " Q, K, V, is_causal=True, \n", " dropout_p=self.dropout_p if self.training else 0.0\n", " )\n", " \n", " output = output.transpose(1, 2).contiguous().view(B, T, C)\n", " output = self.dropout(self.proj(output))\n", " return output\n", "\n", "class RemixedBlock(nn.Module):\n", " \"\"\"Transformer Block that accepts context_state\"\"\"\n", " def __init__(self, n_embd, n_head, dropout, block_size, context_dim, basis_size=64, remixed_linear_kwargs = dict(use_basis_gate=True, use_output_gate=True, use_context=True)):\n", " super().__init__()\n", " head_size = n_embd // n_head\n", " # Pass basis_size to Attention as well (optional consistency)\n", " self.sa = RemixedMultiHeadAttention(\n", " n_embd, n_head, head_size, dropout, block_size, context_dim, basis_size, remixed_linear_kwargs = remixed_linear_kwargs\n", " )\n", " # CHANGE: Initialize FeedFoward with context_dim and basis_size\n", " self.ffwd = RemixedFeedFoward(n_embd, dropout, context_dim, basis_size, remixed_linear_kwargs = remixed_linear_kwargs)\n", " self.ln1 = nn.LayerNorm(n_embd)\n", " self.ln2 = nn.LayerNorm(n_embd)\n", "\n", " def forward(self, x, context_state):\n", " x = x + self.sa(self.ln1(x), context_state)\n", " # CHANGE: Pass context_state to FeedFoward\n", " x = x + self.ffwd(self.ln2(x), context_state)\n", " return x\n", "\n", "# ==============================================================================\n", "# 3. THE MAIN MODEL\n", "# ==============================================================================\n", "\n", "class BigramLanguageModel(nn.Module):\n", " def __init__(self, vocab_size, seq_len, **kwargs):\n", " super().__init__()\n", " \n", " # --- Parsing Kwargs ---\n", " allowed_keys = {\n", " \"use_moe\", \"num_experts\", 'total_embed_dim', \"router_dim\", \"capacity_factor\",\n", " \"use_sparse_top_k\", \"top_k\", \"routing_mode\", \"context_window\",\n", " \"causal\", \"use_expert_mlp\", \"use_output_projection\",\n", " \"use_expert_bias\", \"dropout\", \"use_shared_base\", \"shared_base_dim\", \n", " \"use_vocab_prior\", \"expert_residual\", 'allow_replacement', \n", " 'use_embed_refine', 'target_dim', 'selection_mode', \"use_perm\",\n", " \n", " # NEW KWARGS FOR LINEAR REMIXING\n", " \"use_remixed_linear\", \"context_dim\", \"linear_basis_size\", \"remixed_linear_kwargs\"\n", " }\n", "\n", " for key in kwargs:\n", " if key not in allowed_keys:\n", " print(f\"Warning: Unexpected keyword argument '{key}'\")\n", "\n", " self.vocab_size = vocab_size\n", " self.seq_len = seq_len\n", " self.block_size = seq_len # Consistency alias\n", " self.entropy_weight = 1e-3\n", "\n", "\n", " # Embedding & MoE Config\n", " self.use_moe = kwargs.get(\"use_moe\", False)\n", " self.use_perm = kwargs.get(\"use_perm\", False)\n", " self.use_embed_refine = kwargs.get(\"use_embed_refine\", False)\n", " self.remixed_linear_kwargs = kwargs.get(\"remixed_linear_kwargs\", dict(use_basis_gate=True, use_output_gate=True, use_context=True))\n", " self.num_experts = kwargs.get(\"num_experts\", 8)\n", " self.router_dim = kwargs.get(\"router_dim\", 64)\n", " self.target_dim = kwargs.get(\"target_dim\", 64)\n", " self.total_embed_dim = kwargs.get(\"total_embed_dim\", self.num_experts*self.router_dim)\n", " self.selection_mode = kwargs.get(\"selection_mode\", \"soft\")\n", " self.allow_replacement = kwargs.get(\"allow_replacement\", False)\n", " self.dropout = kwargs.get(\"dropout\", 0.0)\n", " \n", " # Linear Remixing Config\n", " self.use_remixed_linear = kwargs.get(\"use_remixed_linear\", False)\n", " self.context_dim = kwargs.get(\"context_dim\", 64)\n", " self.linear_basis_size = kwargs.get(\"linear_basis_size\", 64)\n", "\n", " # Calculate Model Dimension (n_embd)\n", " if self.use_moe:\n", " self.n_embd = self.target_dim\n", " else:\n", " self.n_embd = self.total_embed_dim\n", " \n", "\n", "\n", " # ----------------------------------------------------------------------\n", " # 1. Embedding Layers\n", " # ----------------------------------------------------------------------\n", " if self.use_moe:\n", " if self.use_perm:\n", " self.embedding_model = PermutationMoE(\n", " vocab_size=vocab_size,\n", " base_embed_dim=self.n_embd,\n", " num_experts=self.num_experts,\n", " selection_mode=self.selection_mode,\n", " router_dim=self.router_dim,\n", " allow_replacement=self.allow_replacement,\n", " use_dim_mlp_refinement=True,\n", " mlp_refinement_position='after',\n", " )\n", " else:\n", " self.embedding_model = DirectContextualEmbedding(\n", " vocab_size=vocab_size, dim=self.n_embd\n", " )\n", " else:\n", " self.token_embedding_table = nn.Embedding(vocab_size, self.n_embd)\n", " self.position_embedding_table = nn.Embedding(self.block_size, self.n_embd)\n", " \n", " if self.use_embed_refine:\n", " self.refine_embed_layer = nn.Sequential(\n", " nn.LayerNorm(self.n_embd),\n", " nn.Linear(self.n_embd, self.n_embd * 2),\n", " nn.GELU(),\n", " nn.Dropout(self.dropout),\n", " nn.Linear(self.n_embd * 2, self.n_embd)\n", " )\n", " self.embd_ln = nn.LayerNorm(self.n_embd)\n", " \n", "\n", " # ----------------------------------------------------------------------\n", " # 2. Global Context Manager (The \"Brain\")\n", " # ----------------------------------------------------------------------\n", " if self.use_remixed_linear:\n", " self.context_manager = GlobalContextManager(\n", " vocab_size=vocab_size, \n", " d_model=self.n_embd, \n", " router_dim=self.context_dim,\n", " context_window=self.block_size\n", " )\n", "\n", " # ----------------------------------------------------------------------\n", " # 3. Transformer Blocks (The \"Body\")\n", " # ----------------------------------------------------------------------\n", " # ... inside BigramLanguageModel.__init__ ...\n", " if self.use_remixed_linear:\n", " # Use ModuleList for Remixed Blocks\n", " self.blocks = nn.ModuleList([\n", " RemixedBlock(\n", " self.n_embd, n_head, self.dropout, \n", " self.block_size, self.context_dim,\n", " basis_size=self.linear_basis_size, remixed_linear_kwargs = self.remixed_linear_kwargs # <--- ADD THIS LINE\n", " ) \n", " for _ in range(n_layer)\n", " ])\n", " else:\n", " # Standard Sequential Blocks\n", " self.blocks = nn.Sequential(*[\n", " Block(self.n_embd, n_head, self.dropout, self.block_size) \n", " for _ in range(n_layer)\n", " ])\n", "\n", " # ----------------------------------------------------------------------\n", " # 4. Heads\n", " # ----------------------------------------------------------------------\n", " self.ln_f = nn.LayerNorm(self.n_embd)\n", " self.lm_head = nn.Linear(self.n_embd, vocab_size)\n", "\n", " def forward(self, idx, targets=None):\n", " B, T = idx.shape\n", " device = idx.device\n", " routing_info = None\n", "\n", " # --- A. Embeddings ---\n", " if self.use_moe:\n", " # Context-Aware Embedding Routing\n", " if self.use_perm:\n", " tok_emb, routing_info = self.embedding_model(idx) \n", " else:\n", " tok_emb = self.embedding_model(idx)\n", " x = tok_emb\n", " else:\n", " # Standard Static Embeddings\n", " tok_emb = self.token_embedding_table(idx)\n", " pos_emb = self.position_embedding_table(torch.arange(T, device=device))\n", " x = tok_emb + pos_emb\n", " \n", " if self.use_embed_refine:\n", " x = self.refine_embed_layer(x)\n", " if not self.use_remixed_linear:\n", " x = self.embd_ln(x)\n", "\n", " # --- B. Global Context Calculation ---\n", " context_state = None\n", " if self.use_remixed_linear:\n", " # Run the router once to get the global control signal\n", " # Note: We pass the embeddings 'x' to the router\n", " context_state = self.context_manager(x, idx)\n", "\n", " # --- C. Transformer Blocks ---\n", " if self.use_remixed_linear:\n", " # Manual loop to pass context_state\n", " for block in self.blocks:\n", " x = block(x, context_state)\n", " else:\n", " # Standard sequential execution\n", " x = self.blocks(x)\n", "\n", " # --- D. Output ---\n", " x = self.ln_f(x)\n", " logits = self.lm_head(x)\n", "\n", " # --- E. Loss ---\n", " loss = None\n", " total_loss = None\n", " \n", " if targets is not None:\n", " B, T, C = logits.shape\n", " logits_flat = logits.view(B*T, C)\n", " targets_flat = targets.view(B*T)\n", " loss = F.cross_entropy(logits_flat, targets_flat)\n", " \n", " if self.use_moe and routing_info and 'total_aux_loss' in routing_info:\n", " total_loss = loss #+ routing_info['total_aux_loss']\n", " else:\n", " total_loss = loss\n", " if self.use_remixed_linear:\n", " gate_entropy = collect_gate_entropy(self)\n", " if gate_entropy is not None:\n", " total_loss = loss + self.entropy_weight * gate_entropy\n", " return loss, total_loss, routing_info\n", "\n", " def generate(self, idx, max_new_tokens):\n", " for _ in tqdm(range(max_new_tokens), desc=\"Generating\"):\n", " # Crop context if too long\n", " idx_cond = idx if idx.size(1) <= self.block_size else idx[:, -self.block_size:]\n", " \n", " # Forward pass\n", " _, _, _ = self(idx_cond) # We need to get logits, but forward returns losses\n", " # Wait, forward returns (loss, total_loss, routing). We need LOGITS.\n", " # FIX: We need to access the logic inside forward that produces logits.\n", " # OR modify forward to return logits if targets is None.\n", " \n", " # Re-running forward logic locally for generation (cleaner than refactoring return signature significantly)\n", " # NOTE: For cleaner code, one usually splits forward() into body() and loss(), \n", " # but per your request to recreate the class, I will patch it here efficiently.\n", " \n", " # ... (Embedding) ...\n", " B, T = idx_cond.shape\n", " device = idx_cond.device\n", " \n", " if self.use_moe:\n", " if self.use_perm: tok_emb, _ = self.embedding_model(idx_cond)\n", " else: tok_emb = self.embedding_model(idx_cond)\n", " x = tok_emb\n", " else:\n", " tok_emb = self.token_embedding_table(idx_cond)\n", " pos_emb = self.position_embedding_table(torch.arange(T, device=device))\n", " x = tok_emb + pos_emb\n", " if self.use_embed_refine: x = self.refine_embed_layer(x)\n", " x = self.embd_ln(x)\n", " \n", " # ... (Context) ...\n", " context_state = None\n", " if self.use_remixed_linear:\n", " context_state = self.context_manager(x, idx_cond)\n", " \n", " # ... (Blocks) ...\n", " if self.use_remixed_linear:\n", " for block in self.blocks: x = block(x, context_state)\n", " else:\n", " x = self.blocks(x)\n", " \n", " x = self.ln_f(x)\n", " logits = self.lm_head(x)\n", " \n", " \n", " # ... (Sampling) ...\n", " logits = logits[:, -1, :] \n", " probs = F.softmax(logits, dim=-1)\n", " idx_next = torch.multinomial(probs, num_samples=1)\n", " idx = torch.cat((idx, idx_next), dim=1)\n", " \n", " return idx" ] }, { "cell_type": "code", "execution_count": null, "id": "47cef385", "metadata": { "papermill": { "duration": 0.006004, "end_time": "2026-01-01T23:57:29.434872", "exception": false, "start_time": "2026-01-01T23:57:29.428868", "status": "completed" }, "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "e9d3cb4d", "metadata": { "papermill": { "duration": 0.006, "end_time": "2026-01-01T23:57:29.446870", "exception": false, "start_time": "2026-01-01T23:57:29.440870", "status": "completed" }, "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 9, "id": "ace6ec91", "metadata": { "execution": { "iopub.execute_input": "2026-01-01T23:57:29.460486Z", "iopub.status.busy": "2026-01-01T23:57:29.460200Z", "iopub.status.idle": "2026-01-01T23:57:29.487817Z", "shell.execute_reply": "2026-01-01T23:57:29.487118Z" }, "papermill": { "duration": 0.036187, "end_time": "2026-01-01T23:57:29.489123", "exception": false, "start_time": "2026-01-01T23:57:29.452936", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "\n", "\n", "class TextDataset(Dataset):\n", " \"\"\"Simple text dataset that returns sequences of tokens\"\"\"\n", " def __init__(self, data, seq_len):\n", " self.data = data\n", " self.seq_len = seq_len\n", " \n", " def __len__(self):\n", " return max(1, (len(self.data) - 1) // self.seq_len)\n", " \n", " def __getitem__(self, idx):\n", " start = idx * self.seq_len\n", " end = start + self.seq_len\n", " x = self.data[start:end]\n", " y = self.data[start+1:end+1]\n", " \n", " # Pad if necessary\n", " if len(x) < self.seq_len:\n", " x = np.pad(x, (0, self.seq_len - len(x)), constant_values=0)\n", " y = np.pad(y, (0, self.seq_len - len(y)), constant_values=0)\n", " \n", " return torch.tensor(x, dtype=torch.long), torch.tensor(y, dtype=torch.long)\n", "\n", "\n", "# class Tokenizer:\n", "# \"\"\"Simple character or word-level tokenizer\"\"\"\n", "# def __init__(self, vocab_type='char'):\n", "# self.vocab_type = vocab_type\n", "# self.char_to_idx = {}\n", "# self.idx_to_char = {}\n", "# self.vocab_size = 0\n", " \n", "# def build_vocab(self, text: str, min_freq: int = 1):\n", "# \"\"\"Build vocabulary from text\"\"\"\n", "# if self.vocab_type == 'char':\n", "# chars = sorted(set(text))\n", "# self.char_to_idx = {ch: i for i, ch in enumerate(chars)}\n", "# self.idx_to_char = {i: ch for i, ch in enumerate(chars)}\n", "# self.vocab_size = len(chars)\n", "# else: # word-level\n", "# words = text.split()\n", "# counter = Counter(words)\n", "# vocab = [w for w, c in counter.items() if c >= min_freq]\n", "# vocab = ['', ''] + sorted(vocab)\n", "# self.char_to_idx = {w: i for i, w in enumerate(vocab)}\n", "# self.idx_to_char = {i: w for i, w in enumerate(vocab)}\n", "# self.vocab_size = len(vocab)\n", " \n", "# def encode(self, text: str) -> List[int]:\n", "# \"\"\"Encode text to token indices\"\"\"\n", "# if self.vocab_type == 'char':\n", "# return [self.char_to_idx.get(ch, 0) for ch in text]\n", "# else: # word-level\n", "# words = text.split()\n", "# unk_idx = self.char_to_idx.get('', 0)\n", "# return [self.char_to_idx.get(w, unk_idx) for w in words]\n", " \n", "# def decode(self, indices: List[int]) -> str:\n", "# \"\"\"Decode token indices to text\"\"\"\n", "# if self.vocab_type == 'char':\n", "# return ''.join([self.idx_to_char.get(i, '') for i in indices])\n", "# else: # word-level\n", "# return ' '.join([self.idx_to_char.get(i, '') for i in indices])\n", "\n", "\n", "def download_file(url: str, filepath: str):\n", " \"\"\"Download file from URL\"\"\"\n", " if os.path.exists(filepath):\n", " return\n", " \n", " print(f\"Downloading {url}...\")\n", " os.makedirs(os.path.dirname(filepath), exist_ok=True)\n", " response = requests.get(url, stream=True)\n", " response.raise_for_status()\n", " \n", " with open(filepath, 'wb') as f:\n", " for chunk in response.iter_content(chunk_size=8192):\n", " f.write(chunk)\n", " print(f\"Downloaded to {filepath}\")\n", "\n", "\n", "def load_wikitext103(seq_len,seed) -> Tuple[str, str, str]:\n", " \"\"\"Load WikiText-103 dataset\"\"\"\n", "# Create datasets\n", " data_dir = \"/kaggle/input/wikitext103-encoded/\"\n", " train_dataset = WikiText103Dataset(\n", " data_path=os.path.join(data_dir, 'train.bin'),\n", " block_size=seq_len, seed=seed\n", " # length=10000 # Number of samples per epoch (adjust as needed)\n", " )\n", " \n", " val_dataset = WikiText103Dataset(\n", " data_path=os.path.join(data_dir, 'val.bin'),\n", " block_size=seq_len, seed=seed\n", " # length=1000 # Smaller for validation\n", " )\n", " test_dataset = WikiText103Dataset(\n", " data_path=os.path.join(data_dir, 'test.bin'),\n", " block_size=seq_len, seed=seed\n", " # length=1000 # Smaller for validation\n", " )\n", " # base_url = \"https://s3.amazonaws.com/research.metamind.io/wikitext\"\n", " # data_dir = \"data/wikitext-103\"\n", " \n", " # # Download if needed\n", " # for split in ['train', 'valid', 'test']:\n", " # url = f\"{base_url}/wikitext-103-raw-v1.zip\"\n", " # zip_path = os.path.join(data_dir, \"wikitext-103-raw-v1.zip\")\n", " \n", " # if not os.path.exists(zip_path):\n", " # download_file(url, zip_path)\n", " \n", " # # Extract\n", " # with zipfile.ZipFile(zip_path, 'r') as zip_ref:\n", " # zip_ref.extractall(data_dir)\n", " \n", " # # Load splits\n", " # base_path = os.path.join(data_dir, \"wikitext-103-raw\")\n", " # with open(f\"{base_path}/wiki.train.raw\", 'r', encoding='utf-8') as f:\n", " # train_text = f.read()\n", " # with open(f\"{base_path}/wiki.valid.raw\", 'r', encoding='utf-8') as f:\n", " # val_text = f.read()\n", " # with open(f\"{base_path}/wiki.test.raw\", 'r', encoding='utf-8') as f:\n", " # test_text = f.read()\n", " \n", " return train_dataset, val_dataset, test_dataset\n", "\n", "# class WikiText103Dataset(IterableDataset):\n", "# def __init__(self, data_path, block_size, length=None):\n", "# \"\"\"\n", "# Args:\n", "# data_path: Path to the .bin file\n", "# block_size: Sequence length for each sample\n", "# length: Optional dataset length (number of samples per epoch)\n", "# If None, uses the maximum possible samples from the file\n", "# \"\"\"\n", "# self.data_path = data_path\n", "# self.block_size = block_size\n", " \n", "# # Get file size to determine max samples\n", "# file_size = os.path.getsize(data_path)\n", "# num_tokens = file_size // np.dtype(np.uint16).itemsize\n", "# max_samples = num_tokens - block_size\n", " \n", "# self.length = length if length is not None else max_samples\n", "# self.max_samples = max_samples\n", " \n", "# def __iter__(self):\n", "# # Create memmap for this worker\n", "# data = np.memmap(self.data_path, dtype=np.uint16, mode='r')\n", " \n", "# # Handle multi-worker data loading\n", "# worker_info = torch.utils.data.get_worker_info()\n", "# if worker_info is not None:\n", "# # Split workload among workers\n", "# per_worker = int(np.ceil(self.length / worker_info.num_workers))\n", "# worker_id = worker_info.id\n", "# iter_start = worker_id * per_worker\n", "# iter_end = min(iter_start + per_worker, self.length)\n", "# else:\n", "# iter_start = 0\n", "# iter_end = self.length\n", " \n", "# # Generate samples\n", "# for _ in range(iter_end - iter_start):\n", "# # Random index for this sample\n", "# idx = np.random.randint(0, self.max_samples)\n", " \n", "# # Extract x and y\n", "# x = torch.from_numpy(data[idx:idx + self.block_size].astype(np.int64))\n", "# y = torch.from_numpy(data[idx + 1:idx + 1 + self.block_size].astype(np.int64))\n", " \n", "# yield x, y\n", " \n", "# def __len__(self):\n", "# return self.length\n", "\n", "\n", "class WikiText103Dataset(IterableDataset):\n", " def __init__(self, data_path, block_size, length=None, seed=None):\n", " \"\"\"\n", " Args:\n", " data_path: Path to the .bin file\n", " block_size: Sequence length for each sample\n", " length: Optional dataset length (number of samples per epoch)\n", " seed: Optional random seed for reproducibility\n", " \"\"\"\n", " self.data_path = data_path\n", " self.block_size = block_size\n", " self.seed = seed\n", "\n", " file_size = os.path.getsize(data_path)\n", " num_tokens = file_size // np.dtype(np.uint16).itemsize\n", " max_samples = num_tokens - block_size\n", "\n", " self.length = length if length is not None else max_samples\n", " self.max_samples = max_samples\n", "\n", " def __iter__(self):\n", " # Create memmap for this worker\n", " data = np.memmap(self.data_path, dtype=np.uint16, mode='r')\n", "\n", " # Handle multi-worker data loading\n", " worker_info = torch.utils.data.get_worker_info()\n", " if worker_info is not None:\n", " per_worker = int(np.ceil(self.length / worker_info.num_workers))\n", " worker_id = worker_info.id\n", " iter_start = worker_id * per_worker\n", " iter_end = min(iter_start + per_worker, self.length)\n", "\n", " # Adjust seed per worker for reproducibility\n", " seed = self.seed + worker_id if self.seed is not None else None\n", " else:\n", " iter_start = 0\n", " iter_end = self.length\n", " seed = self.seed\n", "\n", " # Set seed for reproducibility\n", " if seed is not None:\n", " np.random.seed(seed)\n", "\n", " # Generate samples\n", " for _ in range(iter_end - iter_start):\n", " idx = np.random.randint(0, self.max_samples)\n", " x = torch.from_numpy(data[idx:idx + self.block_size].astype(np.int64))\n", " y = torch.from_numpy(data[idx + 1:idx + 1 + self.block_size].astype(np.int64))\n", " yield x, y\n", "\n", " def __len__(self):\n", " return self.length\n", "\n", "\n", "\n", "# Usage example\n", "\n", "device ='cuda' if torch.cuda.is_available() else 'cpu'\n", "\n", "\n", "\n", "def load_penn_treebank(seq_len,seed) -> Tuple[str, str, str]:\n", " \"\"\"Load Penn Treebank dataset\"\"\"\n", " # Create datasets\n", " data_dir = \"/kaggle/input/penn-treebank-encoded/\"\n", " train_dataset = WikiText103Dataset(\n", " data_path=os.path.join(data_dir, 'train.bin'),\n", " block_size=seq_len, seed=seed\n", " # length=10000 # Number of samples per epoch (adjust as needed)\n", " )\n", " \n", " val_dataset = WikiText103Dataset(\n", " data_path=os.path.join(data_dir, 'val.bin'),\n", " block_size=seq_len, seed=seed\n", " # length=1000 # Smaller for validation\n", " )\n", " test_dataset = WikiText103Dataset(\n", " data_path=os.path.join(data_dir, 'test.bin'),\n", " block_size=seq_len, seed=seed\n", " # length=1000 # Smaller for validation\n", " )\n", " # base_url = \"https://raw.githubusercontent.com/wojzaremba/lstm/master/data\"\n", " # data_dir = \"data/penn_treebank\"\n", " \n", " # files = {\n", " # 'train': 'ptb.train.txt',\n", " # 'valid': 'ptb.valid.txt', \n", " # 'test': 'ptb.test.txt'\n", " # }\n", " \n", " # texts = []\n", " # for split, filename in files.items():\n", " # filepath = os.path.join(data_dir, filename)\n", " # if not os.path.exists(filepath):\n", " # url = f\"{base_url}/{filename}\"\n", " # download_file(url, filepath)\n", " \n", " # with open(filepath, 'r', encoding='utf-8') as f:\n", " # texts.append(f.read())\n", " \n", " # return texts[0], texts[1], texts[2]\n", " return train_dataset, val_dataset, test_dataset\n", "\n", "def load_enwik8(seq_len,seed) -> Tuple[str, str, str]:\n", " \"\"\"Load enwik8 dataset (first 100M bytes of Wikipedia)\"\"\"\n", " data_dir = \"/kaggle/input/enwik8-encoded/\"\n", " train_dataset = WikiText103Dataset(\n", " data_path=os.path.join(data_dir, 'train.bin'),\n", " block_size=seq_len, seed=seed\n", " # length=10000 # Number of samples per epoch (adjust as needed)\n", " )\n", " \n", " val_dataset = WikiText103Dataset(\n", " data_path=os.path.join(data_dir, 'val.bin'),\n", " block_size=seq_len, seed=seed\n", " # length=1000 # Smaller for validation\n", " )\n", " test_dataset = WikiText103Dataset(\n", " data_path=os.path.join(data_dir, 'test.bin'),\n", " block_size=seq_len, seed=seed\n", " # length=1000 # Smaller for validation\n", " )\n", " # url = \"http://mattmahoney.net/dc/enwik8.zip\"\n", " # data_dir = \"data/enwik8\"\n", " # zip_path = os.path.join(data_dir, \"enwik8.zip\")\n", " # file_path = os.path.join(data_dir, \"enwik8\")\n", " \n", " # if not os.path.exists(file_path):\n", " # download_file(url, zip_path)\n", " # with zipfile.ZipFile(zip_path, 'r') as zip_ref:\n", " # zip_ref.extractall(data_dir)\n", " \n", " # with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:\n", " # text = f.read()\n", " \n", " # # Standard split: 90M train, 5M val, 5M test\n", " # n = len(text)\n", " # train_text = text[:90_000_000]\n", " # val_text = text[90_000_000:95_000_000]\n", " # test_text = text[95_000_000:100_000_000]\n", " \n", " # return train_text, val_text, test_text\n", " return train_dataset, val_dataset, test_dataset\n", "\n", "def load_text8(seq_len,seed) -> Tuple[str, str, str]:\n", " \"\"\"Load text8 dataset (cleaned enwik8)\"\"\"\n", " data_dir = \"/kaggle/input/text8-encoded/\"\n", " train_dataset = WikiText103Dataset(\n", " data_path=os.path.join(data_dir, 'train.bin'),\n", " block_size=seq_len, seed=seed\n", " # length=10000 # Number of samples per epoch (adjust as needed)\n", " )\n", " \n", " val_dataset = WikiText103Dataset(\n", " data_path=os.path.join(data_dir, 'val.bin'),\n", " block_size=seq_len, seed=seed\n", " # length=1000 # Smaller for validation\n", " )\n", " test_dataset = WikiText103Dataset(\n", " data_path=os.path.join(data_dir, 'test.bin'),\n", " block_size=seq_len, seed=seed\n", " # length=1000 # Smaller for validation\n", " )\n", " # url = \"http://mattmahoney.net/dc/text8.zip\"\n", " # data_dir = \"data/text8\"\n", " # zip_path = os.path.join(data_dir, \"text8.zip\")\n", " # file_path = os.path.join(data_dir, \"text8\")\n", " \n", " # if not os.path.exists(file_path):\n", " # download_file(url, zip_path)\n", " # with zipfile.ZipFile(zip_path, 'r') as zip_ref:\n", " # zip_ref.extractall(data_dir)\n", " \n", " # with open(file_path, 'r', encoding='utf-8') as f:\n", " # text = f.read()\n", " \n", " # # Standard split: 90M train, 5M val, 5M test\n", " # n = len(text)\n", " # train_text = text[:90_000_000]\n", " # val_text = text[90_000_000:95_000_000]\n", " # test_text = text[95_000_000:]\n", " \n", " # return train_text, val_text, test_text\n", " return train_dataset, val_dataset, test_dataset\n", "\n", "def load_tinyshakespeare(seq_len,seed) -> Tuple[str, str, str]:\n", " \"\"\"Load WikiText-103 dataset\"\"\"\n", "# Create datasets\n", " data_dir = \"/kaggle/input/tinyshakespeare-encoded/\"\n", " train_dataset = WikiText103Dataset(\n", " data_path=os.path.join(data_dir, 'train.bin'),\n", " block_size=seq_len, seed=seed\n", " # length=10000 # Number of samples per epoch (adjust as needed)\n", " )\n", " \n", " val_dataset = WikiText103Dataset(\n", " data_path=os.path.join(data_dir, 'val.bin'),\n", " block_size=seq_len, seed=seed\n", " # length=1000 # Smaller for validation\n", " )\n", " test_dataset = WikiText103Dataset(\n", " data_path=os.path.join(data_dir, 'test.bin'),\n", " block_size=seq_len, seed=seed\n", " # length=1000 # Smaller for validation\n", " )\n", " return train_dataset, val_dataset, test_dataset\n", "\n", "\n", " \n", "def load_lambada(seq_len,seed) -> Tuple[str, str, str]:\n", " \"\"\"Load LAMBADA dataset\"\"\"\n", " data_dir = \"/kaggle/input/lambada-encoded/\"\n", " train_dataset = WikiText103Dataset(\n", " data_path=os.path.join(data_dir, 'train.bin'),\n", " block_size=seq_len, seed=seed\n", " # length=10000 # Number of samples per epoch (adjust as needed)\n", " )\n", " \n", " val_dataset = WikiText103Dataset(\n", " data_path=os.path.join(data_dir, 'val.bin'),\n", " block_size=seq_len, seed=seed\n", " # length=1000 # Smaller for validation\n", " )\n", " test_dataset = WikiText103Dataset(\n", " data_path=os.path.join(data_dir, 'test.bin'),\n", " block_size=seq_len, seed=seed\n", " # length=1000 # Smaller for validation\n", " )\n", " # url = \"https://raw.githubusercontent.com/cybertronai/bflm/master/lambada_test.jsonl\"\n", " # data_dir = \"data/lambada\"\n", " # file_path = os.path.join(data_dir, \"lambada_test.jsonl\")\n", " \n", " # if not os.path.exists(file_path):\n", " # download_file(url, file_path)\n", " \n", " # import json\n", " # texts = []\n", " # with open(file_path, 'r', encoding='utf-8') as f:\n", " # for line in f:\n", " # data = json.loads(line)\n", " # texts.append(data['text'])\n", " \n", " # full_text = '\\n'.join(texts)\n", " \n", " # # LAMBADA is test-only, so we'll create artificial splits\n", " # n = len(full_text)\n", " # train_text = full_text[:int(0.8*n)]\n", " # val_text = full_text[int(0.8*n):int(0.9*n)]\n", " # test_text = full_text[int(0.9*n):]\n", " \n", " # return train_text, val_text, test_text\n", " return train_dataset, val_dataset, test_dataset\n", "\n", "\n", "def load_dataset(name: str, config,seed):\n", " \"\"\"Load and prepare dataset with proper tokenization and data loaders\n", " \n", " Args:\n", " name: Dataset name\n", " config: Configuration object with attributes:\n", " - batch_size: Batch size for data loaders\n", " - seq_len: Sequence length for training\n", " - num_workers: Number of workers for data loading (default: 0)\n", " \n", " Returns:\n", " Tuple of (train_loader, val_loader, test_loader, vocab_size)\n", " \"\"\"\n", " # Load dataset based on name\n", " dataset_loaders = {\n", " 'wikitext-103': load_wikitext103,\n", " 'penn_treebank': load_penn_treebank,\n", " 'enwik8': load_enwik8,\n", " 'text8': load_text8,\n", " 'lambada': load_lambada,\n", " 'tinyshakespeare' : load_tinyshakespeare,\n", "\n", " }\n", " \n", " if name not in dataset_loaders:\n", " raise ValueError(f\"Unknown dataset: {name}. Available: {list(dataset_loaders.keys())}\")\n", " \n", " print(f\"\\nLoading {name}...\")\n", " # Determine tokenization type (char-level for enwik8/text8, word-level for others)\n", " vocab_type = 'char' if name in ['enwik8', 'text8'] else 'word'\n", " # Build tokenizer\n", " print(\"Building vocabulary...\")\n", " tokenizer = tiktoken.get_encoding(\"gpt2\")#Tokenizer(vocab_type=vocab_type)\n", " batch_size = getattr(config, 'BATCH_SIZE', 32)\n", "\n", " if name not in ['wikitext-103', 'penn_treebank','enwik8','text8','lambada', 'tinyshakespeare']:\n", " train_text, val_text, test_text = dataset_loaders[name](config)\n", " \n", "\n", " # tokenizer.build_vocab(train_text, min_freq=1)\n", " \n", " print(f\"Vocabulary size: {tokenizer.n_vocab}\")\n", " \n", " # Encode datasets\n", " print(\"Encoding datasets...\")\n", " train_data = np.array(tokenizer.encode(train_text), dtype=np.int16)\n", " val_data = np.array(tokenizer.encode(val_text), dtype=np.int16)\n", " test_data = np.array(tokenizer.encode(test_text), dtype=np.int16)\n", " \n", " print(f\"Train tokens: {len(train_data):,}\")\n", " print(f\"Val tokens: {len(val_data):,}\")\n", " print(f\"Test tokens: {len(test_data):,}\")\n", " \n", " # Create datasets\n", " seq_len = getattr(config, 'SEQ_LEN', 512)\n", " train_dataset = TextDataset(train_data, seq_len)\n", " val_dataset = TextDataset(val_data, seq_len)\n", " test_dataset = TextDataset(test_data, seq_len)\n", " shuffle= True\n", " else:\n", " seq_len = getattr(config, 'SEQ_LEN', 512)\n", " shuffle= False\n", " train_dataset, val_dataset, test_dataset = dataset_loaders[name](seq_len,seed)\n", " \n", " # Create data loaders\n", " num_workers = getattr(config, 'num_workers', 2)\n", " batch_size = getattr(config, 'batch_size', 32)\n", " \n", " train_loader = DataLoader(\n", " train_dataset,\n", " batch_size=batch_size,\n", " shuffle=shuffle,\n", " num_workers=num_workers,\n", " worker_init_fn=lambda worker_id: np.random.seed(seed + worker_id),\n", " pin_memory=True\n", " )\n", " \n", " val_loader = DataLoader(\n", " val_dataset,\n", " batch_size=batch_size,\n", " shuffle=shuffle,\n", " num_workers=num_workers,\n", " worker_init_fn=lambda worker_id: np.random.seed(seed + worker_id),\n", " pin_memory=True\n", " )\n", " \n", " test_loader = DataLoader(\n", " test_dataset,\n", " batch_size=batch_size,\n", " shuffle=shuffle,\n", " num_workers=num_workers,\n", " worker_init_fn=lambda worker_id: np.random.seed(seed + worker_id),\n", " pin_memory=True\n", " )\n", " \n", " return train_loader, val_loader, test_loader, tokenizer.n_vocab\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "38d30478", "metadata": { "papermill": { "duration": 0.006073, "end_time": "2026-01-01T23:57:29.501230", "exception": false, "start_time": "2026-01-01T23:57:29.495157", "status": "completed" }, "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "229b6def", "metadata": { "papermill": { "duration": 0.006179, "end_time": "2026-01-01T23:57:29.513634", "exception": false, "start_time": "2026-01-01T23:57:29.507455", "status": "completed" }, "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "6805ec8c", "metadata": { "papermill": { "duration": 0.006002, "end_time": "2026-01-01T23:57:29.525794", "exception": false, "start_time": "2026-01-01T23:57:29.519792", "status": "completed" }, "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 10, "id": "89412c46", "metadata": { "execution": { "iopub.execute_input": "2026-01-01T23:57:29.540178Z", "iopub.status.busy": "2026-01-01T23:57:29.539966Z", "iopub.status.idle": "2026-01-02T00:01:55.286136Z", "shell.execute_reply": "2026-01-02T00:01:55.285459Z" }, "papermill": { "duration": 265.75601, "end_time": "2026-01-02T00:01:55.287993", "exception": false, "start_time": "2026-01-01T23:57:29.531983", "status": "completed" }, "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "================================================================================\n", "Multi-Seed Evaluation (1 seeds)\n", "================================================================================\n", "\n", "================================================================================\n", "Dataset: wikitext-103\n", "================================================================================\n", "\n", "--------------------------------------------------------------------------------\n", "Model: moe_remixed_lin\n", "--------------------------------------------------------------------------------\n", "\n", "Loading wikitext-103...\n", "Building vocabulary...\n", "\n", " Seed 1/1 (seed=42)\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "0fad986247e048e69a222bb7f1a92d25", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Seed 42: 0%| | 0/5000 [00:00 pd.DataFrame:\n", " \"\"\"Aggregate results across seeds with mean and std\"\"\"\n", " results = []\n", " \n", " for dataset in self.metrics:\n", " for model in self.metrics[dataset]:\n", " # Collect final perplexities across all seeds\n", " ppls = []\n", " losses = []\n", " \n", " for seed in self.metrics[dataset][model]:\n", " final = self.metrics[dataset][model][seed].get('final', {})\n", " if 'perplexity' in final:\n", " ppls.append(final['perplexity'])\n", " if 'loss' in final:\n", " losses.append(final['loss'])\n", " \n", " if ppls:\n", " results.append({\n", " 'Dataset': dataset,\n", " 'Model': model,\n", " 'PPL_Mean': np.mean(ppls),\n", " 'PPL_Std': np.std(ppls),\n", " 'PPL_Min': np.min(ppls),\n", " 'PPL_Max': np.max(ppls),\n", " 'Loss_Mean': np.mean(losses) if losses else None,\n", " 'Loss_Std': np.std(losses) if losses else None,\n", " 'Num_Seeds': len(ppls)\n", " })\n", " \n", " return pd.DataFrame(results)\n", " \n", " def get_comparison_table(self, format='pretty') -> str:\n", " \"\"\"Generate comparison table with mean ± std\"\"\"\n", " df = self.get_aggregated_results()\n", " \n", " if df.empty:\n", " return \"No results available\"\n", " \n", " # Pivot for better display\n", " pivot_data = []\n", " for dataset in df['Dataset'].unique():\n", " row = {'Dataset': dataset}\n", " dataset_df = df[df['Dataset'] == dataset]\n", " \n", " for _, model_row in dataset_df.iterrows():\n", " model = model_row['Model']\n", " mean = model_row['PPL_Mean']\n", " std = model_row['PPL_Std']\n", " row[model] = f\"{mean:.2f} ± {std:.2f}\"\n", " \n", " pivot_data.append(row)\n", " \n", " pivot_df = pd.DataFrame(pivot_data).set_index('Dataset')\n", " \n", " if format == 'dataframe':\n", " return pivot_df\n", " elif format == 'markdown':\n", " return pivot_df.to_markdown()\n", " elif format == 'latex':\n", " return self._format_latex_table(df)\n", " else:\n", " return self._format_pretty_table(pivot_df)\n", " \n", " def _format_pretty_table(self, df: pd.DataFrame) -> str:\n", " \"\"\"Format as pretty ASCII table with statistical markers\"\"\"\n", " lines = []\n", " \n", " # Column widths\n", " col_widths = {'Dataset': max(15, max(len(str(idx)) for idx in df.index))}\n", " for col in df.columns:\n", " col_widths[col] = max(len(col), 20) # Space for \"XX.XX ± X.XX\"\n", " \n", " # Top border\n", " lines.append('┌' + '─' * (col_widths['Dataset'] + 2) + '┬' + \n", " '┬'.join('─' * (col_widths[col] + 2) for col in df.columns) + '┐')\n", " \n", " # Header\n", " header = '│ ' + 'Dataset'.ljust(col_widths['Dataset']) + ' │'\n", " for col in df.columns:\n", " header += ' ' + col.ljust(col_widths[col]) + ' │'\n", " lines.append(header)\n", " \n", " # Separator\n", " lines.append('├' + '─' * (col_widths['Dataset'] + 2) + '┼' + \n", " '┼'.join('─' * (col_widths[col] + 2) for col in df.columns) + '┤')\n", " \n", " # Data rows\n", " for idx, row in df.iterrows():\n", " line = '│ ' + str(idx).ljust(col_widths['Dataset']) + ' │'\n", " for col in df.columns:\n", " val = str(row[col]) if pd.notna(row[col]) else 'N/A'\n", " line += ' ' + val.ljust(col_widths[col]) + ' │'\n", " lines.append(line)\n", " \n", " # Bottom border\n", " lines.append('└' + '─' * (col_widths['Dataset'] + 2) + '┴' + \n", " '┴'.join('─' * (col_widths[col] + 2) for col in df.columns) + '┘')\n", " \n", " return '\\n'.join(lines)\n", " \n", " def _format_latex_table(self, df: pd.DataFrame) -> str:\n", " \"\"\"Generate LaTeX table with statistical formatting\"\"\"\n", " datasets = df['Dataset'].unique()\n", " models = df['Model'].unique()\n", " \n", " lines = [\n", " r\"\\begin{table}[t]\",\n", " r\"\\centering\",\n", " r\"\\caption{Perplexity comparison across datasets (mean $\\pm$ std over 5 seeds)}\",\n", " r\"\\label{tab:results}\",\n", " r\"\\begin{tabular}{l\" + \"c\" * len(models) + \"}\",\n", " r\"\\toprule\",\n", " \"Dataset & \" + \" & \".join(models) + r\" \\\\\",\n", " r\"\\midrule\"\n", " ]\n", " \n", " for dataset in datasets:\n", " row = [dataset]\n", " dataset_df = df[df['Dataset'] == dataset]\n", " \n", " best_mean = dataset_df['PPL_Mean'].min()\n", " \n", " for model in models:\n", " model_data = dataset_df[dataset_df['Model'] == model]\n", " if not model_data.empty:\n", " mean = model_data['PPL_Mean'].values[0]\n", " std = model_data['PPL_Std'].values[0]\n", " \n", " cell = f\"${mean:.2f} \\\\pm {std:.2f}$\"\n", " if mean == best_mean:\n", " cell = r\"\\textbf{\" + cell + \"}\"\n", " row.append(cell)\n", " else:\n", " row.append(\"--\")\n", " \n", " lines.append(\" & \".join(row) + r\" \\\\\")\n", " \n", " lines.extend([\n", " r\"\\bottomrule\",\n", " r\"\\end{tabular}\",\n", " r\"\\end{table}\"\n", " ])\n", " \n", " return \"\\n\".join(lines)\n", " \n", " def perform_statistical_tests(self) -> pd.DataFrame:\n", " \"\"\"Perform paired t-tests between models\"\"\"\n", " from scipy import stats\n", " \n", " results = []\n", " df = self.get_aggregated_results()\n", " \n", " for dataset in df['Dataset'].unique():\n", " dataset_df = df[df['Dataset'] == dataset]\n", " models = dataset_df['Model'].tolist()\n", " \n", " # Compare each pair of models\n", " for i, model1 in enumerate(models):\n", " for model2 in models[i+1:]:\n", " # Get perplexities for each seed\n", " ppls1 = []\n", " ppls2 = []\n", " \n", " for seed in self.metrics[dataset][model1]:\n", " final1 = self.metrics[dataset][model1][seed].get('final', {})\n", " final2 = self.metrics[dataset][model2][seed].get('final', {})\n", " \n", " if 'perplexity' in final1 and 'perplexity' in final2:\n", " ppls1.append(final1['perplexity'])\n", " ppls2.append(final2['perplexity'])\n", " \n", " if len(ppls1) >= 3: # Need at least 3 samples\n", " t_stat, p_value = stats.ttest_rel(ppls1, ppls2)\n", " \n", " results.append({\n", " 'Dataset': dataset,\n", " 'Model_1': model1,\n", " 'Model_2': model2,\n", " 'Mean_Diff': np.mean(ppls1) - np.mean(ppls2),\n", " 'T_Statistic': t_stat,\n", " 'P_Value': p_value,\n", " 'Significant': p_value < 0.05\n", " })\n", " \n", " return pd.DataFrame(results)\n", "\n", "def get_optimizer(model, config, is_moe=False):\n", " if not is_moe:\n", " return torch.optim.AdamW(\n", " model.parameters(), \n", " lr=config.LEARNING_RATE\n", " )\n", " \n", " # For MoE: split parameters\n", " expert_params = []\n", " non_expert_params = []\n", " \n", " for name, param in model.named_parameters():\n", " if any(x in name for x in ['embedding_model']): #'dim_selectors', 'expert_mlps', 'expert_mlp' 'embeddings', 'expert_router']):\n", " expert_params.append(param)\n", " else:\n", " non_expert_params.append(param)\n", " \n", " return torch.optim.AdamW([\n", " {'params': expert_params, 'lr': config.LEARNING_RATE * config.MOE_SCALE},\n", " {'params': non_expert_params, 'lr': config.LEARNING_RATE}\n", " ], weight_decay=0.01)\n", "# ============================================================================\n", "# TRAINING WITH SEED CONTROL\n", "# ============================================================================\n", "\n", "def set_seed(seed: int):\n", " \"\"\"Set random seed for reproducibility\"\"\"\n", " torch.manual_seed(seed)\n", " torch.cuda.manual_seed_all(seed)\n", " np.random.seed(seed)\n", " # Python random seed\n", " import random\n", " random.seed(seed)\n", " \n", " # Deterministic operations (may slow down training)\n", " torch.backends.cudnn.deterministic = True\n", " torch.backends.cudnn.benchmark = False\n", "\n", "\n", "def train_and_evaluate_with_seed(\n", " model, train_loader, val_loader, test_loader,\n", " config, tracker, dataset_name, model_name, seed, device\n", "):\n", " \"\"\"Training pipeline with seed tracking\"\"\"\n", " # print(model.selection_mode)\n", " set_seed(seed) # Reset seed before training\n", " # ADD THIS: Count and store parameters\n", " total_params = sum(p.numel() for p in model.parameters())\n", " trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", " \n", " \n", " \n", " \n", " optimizer = torch.optim.AdamW(\n", " model.parameters(),\n", " lr=config.LEARNING_RATE *config.MOE_SCALE if \"moe\" in model_name else config.LEARNING_RATE,\n", " weight_decay=0.01\n", " )\n", " # optimizer = get_optimizer(model, config, is_moe=\"moe\" in model_name)\n", " \n", " scheduler = torch.optim.lr_scheduler.OneCycleLR(\n", " optimizer,\n", " max_lr=config.LEARNING_RATE *config.MOE_SCALE if \"moe\" in model_name else config.LEARNING_RATE,\n", " total_steps=config.MAX_ITERS,\n", " pct_start=config.WARMUP_PCT\n", " )\n", " \n", " model.train()\n", " best_val_loss = float('inf')\n", " best_model_state = None\n", " train_iter = iter(train_loader)\n", " # grad_logger = GradientLogger()\n", " # grad_logger.attach(model)\n", "\n", " for step in tqdm(range(config.MAX_ITERS), desc=f\"Seed {seed}\"):\n", " try:\n", " x, y = next(train_iter)\n", " except StopIteration:\n", " train_iter = iter(train_loader)\n", " x, y = next(train_iter)\n", " \n", " x, y = x.to(device), y.to(device)\n", " \n", " # Forward pass\n", " loss, total_loss, info = model(x, y)\n", " \n", " # Backward pass\n", " optimizer.zero_grad()\n", " total_loss.backward()\n", " torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n", " optimizer.step()\n", " scheduler.step()\n", " \n", " # Evaluation\n", " if step % config.EVAL_INTERVAL == 0 or step == config.MAX_ITERS - 1:\n", " val_results = evaluate_model(\n", " model, val_loader, device, config.EVAL_ITERS\n", " )\n", " \n", " # Log with seed\n", " tracker.log(dataset_name, model_name, seed, 'train_loss', loss.item(), step)\n", " tracker.log(dataset_name, model_name, seed, 'val_loss', val_results['loss'], step)\n", " tracker.log(dataset_name, model_name, seed, 'val_perplexity', val_results['perplexity'], step)\n", " # print(\"Context Modulator:\", grad_logger.summary(\"context_modulator\"))\n", " # print(\"Basis:\", grad_logger.summary(\"basis\"))\n", " # print(\"Template Mixing:\", grad_logger.summary(\"template_mixing\"))\n", "\n", "\n", " \n", " if step % (config.EVAL_INTERVAL * config.PRINT_INTERVAL) == 0:\n", " print(f\"[Seed {seed}] Step {step}: val_ppl={val_results['perplexity']:.2f}\")\n", " \n", " if val_results['loss'] < best_val_loss:\n", " best_val_loss = val_results['loss']\n", " best_model_state = {k: v.cpu().clone() for k, v in model.state_dict().items()}\n", " \n", " model.train()\n", " \n", " # Load best model and test\n", " if best_model_state:\n", " model.load_state_dict(best_model_state)\n", " \n", " test_results = evaluate_model(model, test_loader, device, config.EVAL_ITERS)\n", " test_results['total_params'] = total_params\n", " test_results['trainable_params'] = trainable_params\n", " tracker.log_final(dataset_name, model_name, seed, test_results)\n", " \n", " return test_results\n", "\n", "\n", "def evaluate_model(model, dataloader, device, max_iters=100):\n", " \"\"\"Evaluate model\"\"\"\n", " model.eval()\n", " losses = []\n", " \n", " with torch.no_grad():\n", " for i, (x, y) in enumerate(dataloader):\n", " if i >= max_iters:\n", " break\n", " \n", " x, y = x.to(device), y.to(device)\n", " loss, _, _ = model(x, y)\n", " losses.append(loss.item())\n", " \n", " model.train()\n", " \n", " avg_loss = np.mean(losses)\n", " return {\n", " 'loss': avg_loss,\n", " 'perplexity': np.exp(avg_loss)\n", " }\n", "\n", "\n", "# ============================================================================\n", "# MAIN EVALUATION WITH MULTI-SEED\n", "# ============================================================================\n", "\n", "def run_multi_seed_evaluation():\n", " \"\"\"Run evaluation across multiple seeds\"\"\"\n", " \n", " config = EvalConfig()\n", " tracker = MultiSeedMetricsTracker('results')\n", " device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", " \n", " print(\"=\" * 80)\n", " print(f\"Multi-Seed Evaluation ({config.NUM_SEEDS} seeds)\")\n", " print(\"=\" * 80)\n", " \n", " for dataset_name in config.DATASETS:\n", " print(f\"\\n{'=' * 80}\")\n", " print(f\"Dataset: {dataset_name}\")\n", " print(f\"{'=' * 80}\")\n", " \n", "\n", " \n", " for model_name, model_config in config.MODEL_CONFIGS.items():\n", " print(f\"\\n{'-' * 80}\")\n", " print(f\"Model: {model_name}\")\n", " print(f\"{'-' * 80}\")\n", " \n", " # Run across multiple seeds\n", " for seed_idx in range(config.NUM_SEEDS):\n", " seed = config.BASE_SEED + seed_idx\n", "\n", " # for seed_idx, seed in enumerate(config.SEEDS):\n", " # num_seeds = len(config.SEEDS)\n", " # Load dataset\n", " train_loader, val_loader, test_loader, vocab_size = load_dataset(\n", " dataset_name, config,seed)\n", " \n", " \n", " num_seeds = config.NUM_SEEDS\n", " print(f\"\\n Seed {seed_idx + 1}/{num_seeds} (seed={seed})\")\n", " \n", " # Build fresh model for each seed\n", " set_seed(seed)\n", " model = build_model(vocab_size, model_config, config).to(device)\n", " \n", " # Train and evaluate\n", " results = train_and_evaluate_with_seed(\n", " model, train_loader, val_loader, test_loader,\n", " config, tracker, dataset_name, model_name, seed, device\n", " )\n", " \n", " print(f\" Test PPL: {results['perplexity']:.2f}\")\n", " torch.save(model.state_dict(), \"model.pt\")\n", " # Inside your training loop\n", " # total_norm_static = torch.norm(model.blocks[0].sa.qkv_proj.template_mixing.grad)\n", " # total_norm_dynamic = 0\n", " # for p in model.blocks[0].sa.qkv_proj.context_modulator.parameters():\n", " # if p.grad is not None:\n", " # total_norm_dynamic += torch.norm(p.grad)\n", " \n", " # print(f\"Static Grad: {total_norm_static} | Dynamic Grad: {total_norm_dynamic}\")\n", " # print(f\"Gate Stats: {collect_gate_stats(model)}\")\n", " # Clean up\n", " del model\n", " torch.cuda.empty_cache()\n", " \n", " # Save results\n", " tracker.save()\n", " \n", " # Display aggregated results\n", " print(\"\\n\" + \"=\" * 80)\n", " print(\"AGGREGATED RESULTS (Mean ± Std)\")\n", " print(\"=\" * 80 + \"\\n\")\n", " \n", " print(tracker.get_comparison_table())\n", " \n", " # Statistical significance tests\n", " print(\"\\n\" + \"=\" * 80)\n", " print(\"STATISTICAL SIGNIFICANCE TESTS\")\n", " print(\"=\" * 80 + \"\\n\")\n", " \n", " stats_df = tracker.perform_statistical_tests()\n", " print(stats_df.to_string())\n", " \n", " # Generate LaTeX table\n", " latex_path = tracker.save_dir / 'results_table.tex'\n", " with open(latex_path, 'w') as f:\n", " f.write(tracker.get_comparison_table(format='latex'))\n", " print(f\"\\nLaTeX table saved to: {latex_path}\")\n", " # Generate plots\n", " plot_comparison_results(tracker, 'results/figures')\n", " \n", " print(\"\\nEvaluation complete! Results saved to 'results/' directory\")\n", " \n", " return tracker\n", "\n", "\n", "\n", "\n", "# # ============================================================================\n", "# # VISUALIZATION\n", "# # ============================================================================\n", "\n", "\n", "def plot_seed_variance(tracker: MultiSeedMetricsTracker, save_dir: str):\n", " \"\"\"Plot variance across seeds\"\"\"\n", " save_dir = Path(save_dir)\n", " save_dir.mkdir(parents=True, exist_ok=True)\n", " \n", " df = tracker.get_aggregated_results()\n", " \n", " fig, ax = plt.subplots(figsize=(12, 6))\n", " \n", " for dataset in df['Dataset'].unique():\n", " dataset_df = df[df['Dataset'] == dataset]\n", " \n", " x = range(len(dataset_df))\n", " means = dataset_df['PPL_Mean'].values\n", " stds = dataset_df['PPL_Std'].values\n", " \n", " ax.errorbar(x, means, yerr=stds, label=dataset, \n", " marker='o', capsize=5, capthick=2)\n", " \n", " ax.set_xticks(range(len(dataset_df)))\n", " ax.set_xticklabels(dataset_df['Model'].values, rotation=45)\n", " ax.set_ylabel('Perplexity')\n", " ax.set_title('Model Performance Across Seeds (Mean ± Std)')\n", " ax.legend()\n", " ax.grid(alpha=0.3)\n", " \n", " plt.tight_layout()\n", " plt.savefig(save_dir / 'seed_variance.png', dpi=300)\n", " plt.close()\n", "\n", "\n", "def plot_parameter_efficiency(tracker: MultiSeedMetricsTracker, save_dir: Path, \n", " model_params: Dict[str, int] = None):\n", " \"\"\"\n", " Plot performance vs parameter count across seeds\n", " \n", " Args:\n", " tracker: Metrics tracker with multi-seed results\n", " save_dir: Directory to save plots\n", " model_params: Dict mapping model_name -> parameter_count\n", " If None, will attempt to extract from saved models\n", " \"\"\"\n", " save_dir = Path(save_dir)\n", " save_dir.mkdir(parents=True, exist_ok=True)\n", " \n", " df = tracker.get_aggregated_results()\n", " \n", " # if model_params is None:\n", " # # Default parameter counts (update based on your actual models)\n", " # model_params = {\n", " # 'baseline_512': 1,#26_214_400, # 512 * 50257 (vocab size)\n", " # 'baseline_256': 1,#3_276_800, # 64 * 50257\n", " # 'baseline_64': 1,#3_276_800, # 64 * 50257\n", " # 'moe_dense_8x64': 1,#3_276_800 + 400_000, # Smaller base + experts\n", " # 'moe_sparse_top8_8x64': 1,#26_214_400 + 500_000, # Base + routing overhead\n", " # 'moe_expert_choice_8x64': 1,#3_276_800 + 400_000, # Smaller base + experts\n", " # }\n", " # REPLACE THIS BLOCK:\n", " if model_params is None:\n", " # Extract from tracker instead of hardcoding\n", " model_params = {}\n", " for dataset in tracker.metrics:\n", " for model in tracker.metrics[dataset]:\n", " seeds = tracker.metrics[dataset][model]\n", " first_seed = list(seeds.keys())[0]\n", " final = seeds[first_seed].get('final', {})\n", " \n", " # Get params (should be same across seeds)\n", " if 'total_params' in final:\n", " model_params[model] = final['total_params']\n", " \n", " fig, ax = plt.subplots(figsize=(10, 6))\n", " \n", " # Group by dataset for different colors\n", " datasets = df['Dataset'].unique()\n", " colors = plt.cm.tab10(np.linspace(0, 1, len(datasets)))\n", " \n", " for dataset, color in zip(datasets, colors):\n", " dataset_df = df[df['Dataset'] == dataset]\n", " \n", " params = []\n", " means = []\n", " stds = []\n", " labels = []\n", " \n", " for _, row in dataset_df.iterrows():\n", " model = row['Model']\n", " if model in model_params:\n", " params.append(model_params[model] / 1e6) # Convert to millions\n", " means.append(row['PPL_Mean'])\n", " stds.append(row['PPL_Std'])\n", " labels.append(model)\n", " \n", " # Plot with error bars\n", " ax.errorbar(params, means, yerr=stds, \n", " fmt='o', label=dataset, color=color,\n", " capsize=5, capthick=2, markersize=8, alpha=0.7)\n", " \n", " # Annotate points with model names\n", " for p, m, s, l in zip(params, means, stds, labels):\n", " ax.annotate(l, (p, m), textcoords=\"offset points\",\n", " xytext=(0, 10), ha='center', fontsize=8, alpha=0.7)\n", " \n", " ax.set_xlabel('Parameters (Millions)')\n", " ax.set_ylabel('Perplexity (Mean ± Std)')\n", " ax.set_title('Parameter Efficiency: Performance vs Model Size')\n", " ax.legend()\n", " ax.grid(alpha=0.3)\n", " ax.set_xscale('log')\n", " \n", " plt.tight_layout()\n", " plt.savefig(save_dir / 'parameter_efficiency.png', dpi=300, bbox_inches='tight')\n", " plt.close()\n", " \n", " # Also create a table\n", " efficiency_data = []\n", " for dataset in datasets:\n", " dataset_df = df[df['Dataset'] == dataset]\n", " for _, row in dataset_df.iterrows():\n", " model = row['Model']\n", " if model in model_params:\n", " efficiency_data.append({\n", " 'Dataset': dataset,\n", " 'Model': model,\n", " 'Params (M)': model_params[model] / 1e6,\n", " 'PPL Mean': row['PPL_Mean'],\n", " 'PPL Std': row['PPL_Std'],\n", " 'PPL per M params': row['PPL_Mean'] / (model_params[model] / 1e6)\n", " })\n", " \n", " efficiency_df = pd.DataFrame(efficiency_data)\n", " efficiency_df.to_csv(save_dir / 'parameter_efficiency.csv', index=False)\n", " print(f\"\\nParameter efficiency table saved to {save_dir / 'parameter_efficiency.csv'}\")\n", "\n", "\n", "def plot_expert_usage(tracker: MultiSeedMetricsTracker, save_dir: Path):\n", " \"\"\"\n", " Visualize expert usage patterns aggregated across seeds\n", " Shows mean usage with error bars representing variance across seeds\n", " \"\"\"\n", " save_dir = Path(save_dir)\n", " save_dir.mkdir(parents=True, exist_ok=True)\n", " \n", " # Collect all MoE models with expert usage data\n", " moe_results = []\n", " \n", " for dataset in tracker.metrics:\n", " for model in tracker.metrics[dataset]:\n", " # Check if this is an MoE model by looking at any seed\n", " seeds = tracker.metrics[dataset][model]\n", " if not seeds:\n", " continue\n", " \n", " # Get first seed to check if expert usage exists\n", " first_seed = list(seeds.keys())[0]\n", " final = seeds[first_seed].get('final', {})\n", " \n", " if 'expert_usage_mean' in final or 'expert_usage' in final:\n", " moe_results.append((dataset, model))\n", " \n", " if not moe_results:\n", " print(\"No MoE models with expert usage data found. Skipping expert usage plot.\")\n", " return\n", " \n", " # Create subplots\n", " n_plots = len(moe_results)\n", " n_cols = min(3, n_plots)\n", " n_rows = (n_plots + n_cols - 1) // n_cols\n", " \n", " fig, axes = plt.subplots(n_rows, n_cols, figsize=(6 * n_cols, 5 * n_rows))\n", " if n_plots == 1:\n", " axes = np.array([axes])\n", " axes = axes.flatten()\n", " \n", " for idx, (dataset, model) in enumerate(moe_results):\n", " ax = axes[idx]\n", " \n", " # Aggregate expert usage across seeds\n", " all_expert_usages = []\n", " \n", " for seed in tracker.metrics[dataset][model]:\n", " final = tracker.metrics[dataset][model][seed].get('final', {})\n", " usage = final.get('expert_usage_mean', final.get('expert_usage', None))\n", " \n", " if usage is not None:\n", " # Convert to numpy if needed\n", " if isinstance(usage, list):\n", " usage = np.array(usage)\n", " elif hasattr(usage, 'cpu'):\n", " usage = usage.cpu().numpy()\n", " all_expert_usages.append(usage)\n", " \n", " if not all_expert_usages:\n", " continue\n", " \n", " # Compute mean and std across seeds\n", " all_expert_usages = np.array(all_expert_usages) # [num_seeds, num_experts]\n", " usage_mean = all_expert_usages.mean(axis=0)\n", " usage_std = all_expert_usages.std(axis=0)\n", " \n", " # Plot\n", " experts = range(len(usage_mean))\n", " bars = ax.bar(experts, usage_mean, yerr=usage_std, capsize=5, \n", " alpha=0.7, edgecolor='black', linewidth=1.5)\n", " \n", " # Color bars by usage level\n", " norm_usage = usage_mean / usage_mean.max() if usage_mean.max() > 0 else usage_mean\n", " colors = plt.cm.viridis(norm_usage)\n", " for bar, color in zip(bars, colors):\n", " bar.set_color(color)\n", " \n", " # Add horizontal line for uniform usage\n", " uniform_usage = 1.0 / len(usage_mean)\n", " ax.axhline(uniform_usage, color='red', linestyle='--', \n", " label=f'Uniform ({uniform_usage:.3f})', alpha=0.7)\n", " \n", " ax.set_xlabel('Expert ID', fontsize=11)\n", " ax.set_ylabel('Usage Frequency', fontsize=11)\n", " ax.set_title(f'{dataset}\\n{model}', fontsize=12, fontweight='bold')\n", " ax.legend(fontsize=9)\n", " ax.grid(axis='y', alpha=0.3)\n", " \n", " # Add text annotation with stats\n", " usage_cv = usage_std.mean() / usage_mean.mean() if usage_mean.mean() > 0 else 0\n", " ax.text(0.02, 0.98, f'CV: {usage_cv:.3f}', \n", " transform=ax.transAxes, fontsize=9,\n", " verticalalignment='top',\n", " bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))\n", " \n", " # Hide unused subplots\n", " for idx in range(n_plots, len(axes)):\n", " axes[idx].set_visible(False)\n", " \n", " plt.tight_layout()\n", " plt.savefig(save_dir / 'expert_usage.png', dpi=300, bbox_inches='tight')\n", " plt.close()\n", " \n", " print(f\"Expert usage plot saved to {save_dir / 'expert_usage.png'}\")\n", "\n", "\n", "def plot_comparison_results(tracker: MultiSeedMetricsTracker, save_dir: str,\n", " model_params: Dict[str, int] = None):\n", " \"\"\"\n", " Generate comprehensive comparison plots for paper\n", " \n", " Args:\n", " tracker: Multi-seed metrics tracker\n", " save_dir: Directory to save plots\n", " model_params: Optional dict of model -> parameter count\n", " \"\"\"\n", " save_dir = Path(save_dir)\n", " save_dir.mkdir(parents=True, exist_ok=True)\n", " \n", " df = tracker.get_aggregated_results()\n", " \n", " if df.empty:\n", " print(\"No results to plot. Skipping visualization.\")\n", " return\n", " \n", " # 1. Perplexity comparison across datasets with error bars\n", " fig, ax = plt.subplots(figsize=(14, 7))\n", " \n", " datasets = sorted(df['Dataset'].unique())\n", " models = sorted(df['Model'].unique())\n", " \n", " x = np.arange(len(datasets))\n", " width = 0.8 / len(models) # Adjust width based on number of models\n", " \n", " for i, model in enumerate(models):\n", " means = []\n", " stds = []\n", " \n", " for dataset in datasets:\n", " dataset_model = df[(df['Dataset'] == dataset) & (df['Model'] == model)]\n", " if not dataset_model.empty:\n", " means.append(dataset_model['PPL_Mean'].values[0])\n", " stds.append(dataset_model['PPL_Std'].values[0])\n", " else:\n", " means.append(0)\n", " stds.append(0)\n", " \n", " # Plot bars with error bars\n", " bars = ax.bar(x + i * width, means, width, \n", " yerr=stds, capsize=4, label=model,\n", " alpha=0.8, edgecolor='black', linewidth=1)\n", " \n", " ax.set_xlabel('Dataset', fontsize=12, fontweight='bold')\n", " ax.set_ylabel('Perplexity (Mean ± Std)', fontsize=12, fontweight='bold')\n", " ax.set_title('Model Comparison Across Datasets (Multi-Seed)', \n", " fontsize=14, fontweight='bold')\n", " ax.set_xticks(x + width * (len(models) - 1) / 2)\n", " ax.set_xticklabels(datasets, rotation=45, ha='right')\n", " ax.legend(loc='upper left', fontsize=10)\n", " ax.grid(axis='y', alpha=0.3)\n", " \n", " plt.tight_layout()\n", " plt.savefig(save_dir / 'perplexity_comparison.png', dpi=300, bbox_inches='tight')\n", " plt.close()\n", " \n", " print(f\"Perplexity comparison saved to {save_dir / 'perplexity_comparison.png'}\")\n", " \n", " # 2. Parameter efficiency plot\n", " plot_parameter_efficiency(tracker, save_dir, model_params)\n", " \n", " # 3. Expert usage visualization (for MoE models)\n", " plot_expert_usage(tracker, save_dir)\n", " \n", " # 4. Seed variance visualization\n", " plot_seed_variance(tracker, save_dir)\n", "\n", "# # ============================================================================\n", "# # MAIN EVALUATION SCRIPT\n", "# # ============================================================================\n", "# checkpoint_dir = \"./checkpoints\"\n", "# os.makedirs(checkpoint_dir, exist_ok=True)\n", "# def run_full_evaluation():\n", "# \"\"\"Run complete evaluation suite\"\"\"\n", " \n", "# config = EvalConfig()\n", "# tracker = MetricsTracker('results')\n", "# device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n", " \n", "# print(\"=\" * 80)\n", "# print(\"MoE Embeddings: Systematic Evaluation\")\n", "# print(\"=\" * 80)\n", " \n", "# # For each dataset\n", "# for dataset_name in tqdm(config.DATASETS):\n", "# print(f\"\\n{'=' * 80}\")\n", "# print(f\"Dataset: {dataset_name}\")\n", "# print(f\"{'=' * 80}\\n\")\n", " \n", "# # Load dataset (implement your data loading)\n", "# train_loader, val_loader, test_loader, vocab_size = load_dataset(dataset_name, config)\n", " \n", "# # For each model configuration\n", "# for model_name, model_config in config.MODEL_CONFIGS.items():\n", "# print(f\"\\nTraining {model_name}...\")\n", " \n", "# # Build model (implement based on your architecture)\n", "# model = build_model(vocab_size, model_config,config ).to(device)\n", "# print(sum(p.numel() for p in model.parameters())/1e6, 'M parameters')\n", " \n", " \n", "# # Train and evaluate\n", "# results = train_and_evaluate(\n", "# model, train_loader, val_loader, test_loader,\n", "# config, tracker, dataset_name, model_name, device\n", "# )\n", " \n", "# # Save checkpoint\n", "# torch.save(\n", "# model.state_dict(),\n", "# f'{checkpoint_dir}/{dataset_name}_{model_name}.pt'\n", "# )\n", " \n", "# # Save all results\n", "# tracker.save()\n", " \n", "# # Generate comparison table\n", "# print(\"\\n\" + \"=\" * 80)\n", "# print(\"FINAL RESULTS\")\n", "# print(\"=\" * 80 + \"\\n\")\n", "# display(tracker.get_comparison_table(format='dataframe'))\n", "# tracker.print_comparison()\n", " \n", "# # Generate plots\n", "# plot_comparison_results(tracker, 'results/figures')\n", " \n", "# print(\"\\nEvaluation complete! Results saved to 'results/' directory\")\n", "\n", "\n", "# # ============================================================================\n", "# # PAPER-READY RESULTS FORMATTER\n", "# # ============================================================================\n", "\n", "# def generate_latex_table(tracker: MetricsTracker, output_file: str = 'results_table.tex'):\n", "# \"\"\"Generate LaTeX table for paper\"\"\"\n", " \n", "# datasets = set()\n", "# models = set()\n", "# for key in tracker.metrics.keys():\n", "# dataset, model = key.split('/')\n", "# datasets.add(dataset)\n", "# models.add(model)\n", " \n", "# lines = []\n", "# lines.append(r\"\\begin{table}[t]\")\n", "# lines.append(r\"\\centering\")\n", "# lines.append(r\"\\caption{Perplexity comparison across datasets}\")\n", "# lines.append(r\"\\label{tab:results}\")\n", "# lines.append(r\"\\begin{tabular}{l\" + \"c\" * len(models) + \"}\")\n", "# lines.append(r\"\\toprule\")\n", " \n", "# # Header\n", "# header = \"Dataset & \" + \" & \".join(models) + r\" \\\\\"\n", "# lines.append(header)\n", "# lines.append(r\"\\midrule\")\n", " \n", "# # Data rows\n", "# for dataset in sorted(datasets):\n", "# row = [dataset]\n", "# for model in sorted(models):\n", "# key = f\"{dataset}/{model}\"\n", "# if key in tracker.metrics and 'final' in tracker.metrics[key]:\n", "# ppl = tracker.metrics[key]['final'].get('perplexity', float('inf'))\n", "# row.append(f\"{ppl:.2f}\")\n", "# else:\n", "# row.append(\"--\")\n", "# lines.append(\" & \".join(row) + r\" \\\\\")\n", " \n", "# lines.append(r\"\\bottomrule\")\n", "# lines.append(r\"\\end{tabular}\")\n", "# lines.append(r\"\\end{table}\")\n", " \n", "# latex = \"\\n\".join(lines)\n", " \n", "# with open(output_file, 'w') as f:\n", "# f.write(latex)\n", " \n", "# return latex\n", "\n", "\n", "# ============================================================================\n", "# HELPER FUNCTIONS (TO BE IMPLEMENTED)\n", "# ============================================================================\n", "\n", "\n", "\n", "def build_model(vocab_size: int, model_config: Dict, config):\n", " # print(model_config)\n", "\n", " model = BigramLanguageModel(vocab_size, config.SEQ_LEN, **model_config)\n", " \"\"\"Build model from configuration - integrate with your TrueSoftRoutingEmbeddings\"\"\"\n", " # Placeholder - implement based on your model architecture\n", " return model# NotImplementedError(\"Implement model building with your MoE embeddings\")\n", "\n", "\n", "# if __name__ == \"__main__\":\n", "# # Run evaluation\n", "# run_full_evaluation()\n", " \n", "# # Generate paper-ready outputs\n", "# tracker = MetricsTracker('results')\n", "# tracker.load() # Implement load method\n", " \n", "# print(\"\\nGenerating LaTeX table...\")\n", "# latex_table = generate_latex_table(tracker)\n", "# print(latex_table)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " tracker = run_multi_seed_evaluation()\n", " plot_seed_variance(tracker, 'results/figures')" ] }, { "cell_type": "code", "execution_count": 11, "id": "be61b07f", "metadata": { "execution": { "iopub.execute_input": "2026-01-02T00:01:55.303752Z", "iopub.status.busy": "2026-01-02T00:01:55.303129Z", "iopub.status.idle": "2026-01-02T00:01:55.307616Z", "shell.execute_reply": "2026-01-02T00:01:55.307003Z" }, "papermill": { "duration": 0.013695, "end_time": "2026-01-02T00:01:55.308901", "exception": false, "start_time": "2026-01-02T00:01:55.295206", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "ABLATIONS = {\n", " \"full\": dict(use_basis_gate=True, use_output_gate=True, use_context=True),\n", " \"no_basis_gate\": dict(use_basis_gate=False, use_output_gate=True, use_context=True),\n", " \"no_output_gate\": dict(use_basis_gate=True, use_output_gate=False, use_context=True),\n", " \"no_context\": dict(use_basis_gate=True, use_output_gate=True, use_context=False),\n", " \"static_linear\": dict(use_basis_gate=False, use_output_gate=False, use_context=False),\n", "}\n" ] }, { "cell_type": "code", "execution_count": 12, "id": "218bfe6f", "metadata": { "execution": { "iopub.execute_input": "2026-01-02T00:01:55.323399Z", "iopub.status.busy": "2026-01-02T00:01:55.323148Z", "iopub.status.idle": "2026-01-02T00:01:55.326915Z", "shell.execute_reply": "2026-01-02T00:01:55.326349Z" }, "papermill": { "duration": 0.012572, "end_time": "2026-01-02T00:01:55.328193", "exception": false, "start_time": "2026-01-02T00:01:55.315621", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "\n", "base_config = {\n", " \n", " 'use_moe': False,\n", " 'total_embed_dim': 64,\n", " 'use_remixed_linear':True,\n", " }\n", "def build_model_with_ablation(base_config, ablation_cfg, config):\n", " cfg = base_config\n", " cfg['remixed_linear_kwargs'] = ablation_cfg\n", "\n", " return build_model(vocab_size, cfg, config)\n", "\n", "\n", "\n", "seed = 42\n" ] }, { "cell_type": "code", "execution_count": 13, "id": "cf2fec32", "metadata": { "execution": { "iopub.execute_input": "2026-01-02T00:01:55.342860Z", "iopub.status.busy": "2026-01-02T00:01:55.342660Z", "iopub.status.idle": "2026-01-02T00:01:55.355470Z", "shell.execute_reply": "2026-01-02T00:01:55.354746Z" }, "papermill": { "duration": 0.022159, "end_time": "2026-01-02T00:01:55.357063", "exception": false, "start_time": "2026-01-02T00:01:55.334904", "status": "completed" }, "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Loading wikitext-103...\n", "Building vocabulary...\n" ] } ], "source": [ "config = EvalConfig()\n", "train_loader, val_loader, test_loader, vocab_size = load_dataset(\n", " \"wikitext-103\", config,42)\n", "def run_ablation_experiment(\n", " ABLATIONS,\n", " base_config,\n", " config, \n", " build_model_fn,\n", " train_loader,\n", " val_loader,\n", " device,\n", " seed,\n", "):\n", " all_results = {}\n", "\n", " for model_name, ablation_cfg in ABLATIONS.items():\n", " print(f\"\\n=== Ablation: {model_name} ===\")\n", "\n", " # ---- Reproducibility ----\n", " set_seed(seed)\n", "\n", " # ---- Build model ----\n", " model = build_model_fn(base_config, ablation_cfg, config)\n", " model = model.to(device)\n", "\n", " # ---- Parameter counts ----\n", " total_params = sum(p.numel() for p in model.parameters())\n", " trainable_params = sum(\n", " p.numel() for p in model.parameters() if p.requires_grad\n", " )\n", "\n", " print(f\"Total params: {total_params:,}\")\n", " print(f\"Trainable params: {trainable_params:,}\")\n", "\n", " # ---- Optimizer ----\n", " optimizer = torch.optim.AdamW(\n", " model.parameters(),\n", " lr=config.LEARNING_RATE *config.MOE_SCALE ,\n", " weight_decay=0.01,\n", " )\n", "\n", " scheduler = torch.optim.lr_scheduler.OneCycleLR(\n", " optimizer,\n", " max_lr=config.LEARNING_RATE*config.MOE_SCALE,\n", " total_steps=config.MAX_ITERS,\n", " pct_start=config.WARMUP_PCT,\n", " )\n", "\n", " model.train()\n", " best_val_loss = float(\"inf\")\n", " train_iter = iter(train_loader)\n", "\n", " train_losses = []\n", " grad_norms = []\n", "\n", " for step in tqdm(\n", " range(config.MAX_ITERS),\n", " desc=f\"{model_name} | Seed {seed}\",\n", " ):\n", " try:\n", " x, y = next(train_iter)\n", " except StopIteration:\n", " train_iter = iter(train_loader)\n", " x, y = next(train_iter)\n", "\n", " x, y = x.to(device), y.to(device)\n", "\n", " # ---- Forward ----\n", " loss, total_loss, info = model(x, y)\n", "\n", " # ---- Backward ----\n", " optimizer.zero_grad()\n", " total_loss.backward()\n", "\n", " grad_norm = torch.nn.utils.clip_grad_norm_(\n", " model.parameters(), 1.0\n", " )\n", "\n", " optimizer.step()\n", " scheduler.step()\n", "\n", " train_losses.append(loss.item())\n", " grad_norms.append(grad_norm.item())\n", "\n", " # ---- Evaluation ----\n", " if (\n", " step % config.EVAL_INTERVAL == 0\n", " or step == config.MAX_ITERS - 1\n", " ):\n", " val_results = evaluate_model(\n", " model,\n", " val_loader,\n", " device,\n", " config.EVAL_ITERS,\n", " )\n", "\n", " if val_results[\"loss\"] < best_val_loss:\n", " best_val_loss = val_results[\"loss\"]\n", "\n", " tqdm.write(\n", " f\"[{model_name}] \"\n", " f\"step={step} \"\n", " f\"train_loss={loss.item():.4f} \"\n", " f\"val_loss={val_results['loss']:.4f} \"\n", " f\"ppl={val_results['perplexity']:.2f}\"\n", " )\n", "\n", " # ---- Store results ----\n", " all_results[model_name] = {\n", " \"best_val_loss\": best_val_loss,\n", " \"final_train_loss\": np.mean(train_losses[-100:]),\n", " \"perplexity\": np.exp(best_val_loss),\n", " \"grad_norm_mean\": float(np.mean(grad_norms)),\n", " \"grad_norm_std\": float(np.std(grad_norms)),\n", " \"total_params\": total_params,\n", " \"trainable_params\": trainable_params,\n", " }\n", "\n", " return all_results\n" ] }, { "cell_type": "code", "execution_count": 14, "id": "03874468", "metadata": { "execution": { "iopub.execute_input": "2026-01-02T00:01:55.373173Z", "iopub.status.busy": "2026-01-02T00:01:55.372548Z", "iopub.status.idle": "2026-01-02T00:21:18.486481Z", "shell.execute_reply": "2026-01-02T00:21:18.485637Z" }, "papermill": { "duration": 1163.123743, "end_time": "2026-01-02T00:21:18.488498", "exception": false, "start_time": "2026-01-02T00:01:55.364755", "status": "completed" }, "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "=== Ablation: full ===\n", "Total params: 10,286,419\n", "Trainable params: 10,286,419\n" ] }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "14a79268073547869ce8414386c5e270", "version_major": 2, "version_minor": 0 }, "text/plain": [ "full | Seed 42: 0%| | 0/5000 [00:00