Upload 5 files
Browse filesWikitext mlm model training codes. All baselines and experimental architectures.
- FNet_Hybrid_Wikitext_Training.ipynb +600 -0
- HSSM_Wikitext_Training.ipynb +951 -0
- PRISM_wikitext_103_last.ipynb +589 -0
- WPT_Wikitext_103_Training.ipynb +1061 -0
- WT103_Transformer_Baseline.ipynb +357 -0
FNet_Hybrid_Wikitext_Training.ipynb
ADDED
|
@@ -0,0 +1,600 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"nbformat": 4,
|
| 3 |
+
"nbformat_minor": 0,
|
| 4 |
+
"metadata": {
|
| 5 |
+
"colab": {
|
| 6 |
+
"provenance": [],
|
| 7 |
+
"gpuType": "A100"
|
| 8 |
+
},
|
| 9 |
+
"kernelspec": {
|
| 10 |
+
"name": "python3",
|
| 11 |
+
"display_name": "Python 3"
|
| 12 |
+
},
|
| 13 |
+
"language_info": {
|
| 14 |
+
"name": "python"
|
| 15 |
+
},
|
| 16 |
+
"accelerator": "GPU"
|
| 17 |
+
},
|
| 18 |
+
"cells": [
|
| 19 |
+
{
|
| 20 |
+
"cell_type": "code",
|
| 21 |
+
"source": [
|
| 22 |
+
"!pip install -q x-transformers\n",
|
| 23 |
+
"!pip install -q flash-attn --no-build-isolation"
|
| 24 |
+
],
|
| 25 |
+
"metadata": {
|
| 26 |
+
"id": "6q9RTvlf5IiS"
|
| 27 |
+
},
|
| 28 |
+
"execution_count": null,
|
| 29 |
+
"outputs": []
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"cell_type": "code",
|
| 33 |
+
"source": [
|
| 34 |
+
"import torch\n",
|
| 35 |
+
"import torch.nn as nn\n",
|
| 36 |
+
"import torch.nn.functional as F\n",
|
| 37 |
+
"import torch.optim as optim\n",
|
| 38 |
+
"import math\n",
|
| 39 |
+
"import os\n",
|
| 40 |
+
"import sys\n",
|
| 41 |
+
"import subprocess\n",
|
| 42 |
+
"import hashlib\n",
|
| 43 |
+
"import gc\n",
|
| 44 |
+
"import platform\n",
|
| 45 |
+
"from datetime import datetime\n",
|
| 46 |
+
"from tqdm.auto import tqdm\n",
|
| 47 |
+
"from torch.utils.data import DataLoader\n",
|
| 48 |
+
"from torch.utils.tensorboard import SummaryWriter\n",
|
| 49 |
+
"from transformers import RobertaTokenizerFast, get_cosine_schedule_with_warmup, DataCollatorForLanguageModeling\n",
|
| 50 |
+
"from datasets import load_dataset\n",
|
| 51 |
+
"from x_transformers import Encoder\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# ==========================================\n",
|
| 54 |
+
"# 1. CONFIGURATION\n",
|
| 55 |
+
"# ==========================================\n",
|
| 56 |
+
"# YOUR REPO ID (Created in previous step)\n",
|
| 57 |
+
"HF_ID = \"prism-lab/wikitext-103-prism-32k-seq4k\"\n",
|
| 58 |
+
"\n",
|
| 59 |
+
"# Hyperparameters\n",
|
| 60 |
+
"VOCAB_SIZE = 32768\n",
|
| 61 |
+
"SEQ_LEN = 4096\n",
|
| 62 |
+
"BATCH_SIZE = 8\n",
|
| 63 |
+
"EPOCHS = 40\n",
|
| 64 |
+
"LR = 1e-3\n",
|
| 65 |
+
"D_MODEL = 512\n",
|
| 66 |
+
"RESUME_PATH = None\n",
|
| 67 |
+
"DEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 68 |
+
"torch.set_float32_matmul_precision(\"high\")\n",
|
| 69 |
+
"\n",
|
| 70 |
+
"# ==========================================\n",
|
| 71 |
+
"# 2. DATA PIPELINE (The \"Pro\" Way)\n",
|
| 72 |
+
"# ==========================================\n",
|
| 73 |
+
"def prepare_data_from_hub():\n",
|
| 74 |
+
" print(f\"⬇️ Pulling Pre-Tokenized Data from {HF_ID}...\")\n",
|
| 75 |
+
"\n",
|
| 76 |
+
" # 1. Load Tokenizer (Instant)\n",
|
| 77 |
+
" # This pulls the exact tokenizer you uploaded\n",
|
| 78 |
+
" tokenizer = RobertaTokenizerFast.from_pretrained(HF_ID)\n",
|
| 79 |
+
"\n",
|
| 80 |
+
" # 2. Load Dataset (Instant)\n",
|
| 81 |
+
" # This pulls the already chunked/tokenized data\n",
|
| 82 |
+
" dataset = load_dataset(HF_ID)\n",
|
| 83 |
+
"\n",
|
| 84 |
+
" print(f\"✅ Loaded {len(dataset['train'])} training chunks.\")\n",
|
| 85 |
+
"\n",
|
| 86 |
+
" # 3. Collator\n",
|
| 87 |
+
" data_collator = DataCollatorForLanguageModeling(\n",
|
| 88 |
+
" tokenizer=tokenizer,\n",
|
| 89 |
+
" mlm=True,\n",
|
| 90 |
+
" mlm_probability=0.15\n",
|
| 91 |
+
" )\n",
|
| 92 |
+
"\n",
|
| 93 |
+
" return dataset, data_collator\n",
|
| 94 |
+
"\n",
|
| 95 |
+
"\n",
|
| 96 |
+
"class FNetBlock(nn.Module):\n",
|
| 97 |
+
" def __init__(self, d_model, d_ff, dropout):\n",
|
| 98 |
+
" super().__init__()\n",
|
| 99 |
+
" self.norm_mix = nn.LayerNorm(d_model) # LayerNorm is safer for FNet than RMSNorm\n",
|
| 100 |
+
" self.norm_ff = nn.LayerNorm(d_model)\n",
|
| 101 |
+
"\n",
|
| 102 |
+
" self.mix_dropout = nn.Dropout(dropout)\n",
|
| 103 |
+
"\n",
|
| 104 |
+
" self.ff = nn.Sequential(\n",
|
| 105 |
+
" nn.Linear(d_model, d_ff),\n",
|
| 106 |
+
" nn.GELU(),\n",
|
| 107 |
+
" nn.Dropout(dropout),\n",
|
| 108 |
+
" nn.Linear(d_ff, d_model),\n",
|
| 109 |
+
" nn.Dropout(dropout)\n",
|
| 110 |
+
" )\n",
|
| 111 |
+
"\n",
|
| 112 |
+
" def forward(self, x):\n",
|
| 113 |
+
" # 1. Fourier Mixing Branch\n",
|
| 114 |
+
" residual = x\n",
|
| 115 |
+
" x = self.norm_mix(x)\n",
|
| 116 |
+
"\n",
|
| 117 |
+
" # --- THE FIX ---\n",
|
| 118 |
+
" with torch.cuda.amp.autocast(enabled=False):\n",
|
| 119 |
+
" x = x.float()\n",
|
| 120 |
+
" # norm='ortho' makes the FFT energy-preserving.\n",
|
| 121 |
+
" # Output magnitude will match input magnitude (~1).\n",
|
| 122 |
+
" x = torch.fft.fftn(x, dim=(-2, -1), norm='ortho').real\n",
|
| 123 |
+
" x = x.to(dtype=residual.dtype)\n",
|
| 124 |
+
" # ---------------\n",
|
| 125 |
+
"\n",
|
| 126 |
+
" # Now 'x' and 'residual' have roughly same magnitude.\n",
|
| 127 |
+
" # The skip connection works again.\n",
|
| 128 |
+
" x = self.mix_dropout(x)\n",
|
| 129 |
+
" x = x + residual\n",
|
| 130 |
+
"\n",
|
| 131 |
+
" # 2. Feed Forward Branch\n",
|
| 132 |
+
" residual = x\n",
|
| 133 |
+
" x = self.norm_ff(x)\n",
|
| 134 |
+
" x = self.ff(x)\n",
|
| 135 |
+
" return x + residual\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"\n",
|
| 138 |
+
"class FNetEncoder(nn.Module):\n",
|
| 139 |
+
" def __init__(self, depth, d_model, d_ff, dropout):\n",
|
| 140 |
+
" super().__init__()\n",
|
| 141 |
+
" self.layers = nn.ModuleList([\n",
|
| 142 |
+
" FNetBlock(d_model, d_ff, dropout) for _ in range(depth)\n",
|
| 143 |
+
" ])\n",
|
| 144 |
+
" # [FIX] Use LayerNorm here to match the blocks\n",
|
| 145 |
+
" self.norm_out = nn.LayerNorm(d_model)\n",
|
| 146 |
+
"\n",
|
| 147 |
+
" def forward(self, x):\n",
|
| 148 |
+
" for layer in self.layers:\n",
|
| 149 |
+
" x = layer(x)\n",
|
| 150 |
+
" return self.norm_out(x)\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"\n",
|
| 153 |
+
"class HybridFNetMLM(nn.Module):\n",
|
| 154 |
+
" def __init__(self, vocab_size, d_model, seq_len, d_ff, dropout):\n",
|
| 155 |
+
" super().__init__()\n",
|
| 156 |
+
"\n",
|
| 157 |
+
" # 1. Standard Embeddings + Absolute Positions\n",
|
| 158 |
+
" # (FNet NEEDS these because FFT is position-blind)\n",
|
| 159 |
+
" self.token_emb = nn.Embedding(vocab_size, d_model)\n",
|
| 160 |
+
" self.pos_emb = nn.Parameter(torch.randn(1, seq_len, d_model) * 0.02)\n",
|
| 161 |
+
" self.dropout = nn.Dropout(dropout)\n",
|
| 162 |
+
"\n",
|
| 163 |
+
" self.fnet_encoder = FNetEncoder(\n",
|
| 164 |
+
" depth=6,\n",
|
| 165 |
+
" d_model=d_model,\n",
|
| 166 |
+
" d_ff=d_ff,\n",
|
| 167 |
+
" dropout=dropout\n",
|
| 168 |
+
" )\n",
|
| 169 |
+
"\n",
|
| 170 |
+
" # 3. The Attention Cap (1 Layer) -> YOUR CONFIGURATION\n",
|
| 171 |
+
" self.transformer_cap = Encoder(\n",
|
| 172 |
+
" dim=d_model,\n",
|
| 173 |
+
" depth=1, # Just 1 layer\n",
|
| 174 |
+
" heads=8,\n",
|
| 175 |
+
" rotary_pos_emb=True, # RoPE (Hybrid Positioning: Absolute for FNet, Rotary for Attn)\n",
|
| 176 |
+
" attn_flash=True,\n",
|
| 177 |
+
" attn_dropout=dropout,\n",
|
| 178 |
+
" ff_dropout=dropout\n",
|
| 179 |
+
" # Removed 'dim_head' (fixes your error)\n",
|
| 180 |
+
" # Removed 'use_rmsnorm' (matches your snippet)\n",
|
| 181 |
+
" # Removed 'ff_glu' (matches your snippet)\n",
|
| 182 |
+
" )\n",
|
| 183 |
+
"\n",
|
| 184 |
+
" # 4. MLM Head\n",
|
| 185 |
+
" self.final_norm = nn.LayerNorm(d_model)\n",
|
| 186 |
+
" self.to_logits = nn.Linear(d_model, vocab_size)\n",
|
| 187 |
+
"\n",
|
| 188 |
+
" # Weight Tying\n",
|
| 189 |
+
" self.to_logits.weight = self.token_emb.weight\n",
|
| 190 |
+
"\n",
|
| 191 |
+
" def forward(self, input_ids):\n",
|
| 192 |
+
" # A. Embedding\n",
|
| 193 |
+
" x = self.token_emb(input_ids)\n",
|
| 194 |
+
" b, n, d = x.shape\n",
|
| 195 |
+
"\n",
|
| 196 |
+
" # Add Absolute Positions (Crucial for FNet layers)\n",
|
| 197 |
+
" x = x + self.pos_emb[:, :n, :]\n",
|
| 198 |
+
" x = self.dropout(x)\n",
|
| 199 |
+
"\n",
|
| 200 |
+
" x = self.fnet_encoder(x)\n",
|
| 201 |
+
"\n",
|
| 202 |
+
" # C. Attention Refinement (1 Layer)\n",
|
| 203 |
+
" # Note: This layer will internally apply RoPE to Q/K\n",
|
| 204 |
+
" x = self.transformer_cap(x)\n",
|
| 205 |
+
"\n",
|
| 206 |
+
" # D. Output\n",
|
| 207 |
+
" x = self.final_norm(x)\n",
|
| 208 |
+
" return self.to_logits(x)\n",
|
| 209 |
+
"\n",
|
| 210 |
+
"# ==========================================\n",
|
| 211 |
+
"# INSTANTIATE MODEL\n",
|
| 212 |
+
"# ==========================================\n",
|
| 213 |
+
"print(\"🏗️ Constructing Hybrid FNet (6-Spectral + 1-Attention)...\")\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"def count_active_parameters(model):\n",
|
| 216 |
+
" print(f\"\\n{'='*60}\")\n",
|
| 217 |
+
" print(f\"🧩 DETAILED PARAMETER BREAKDOWN\")\n",
|
| 218 |
+
" print(f\"{'='*60}\")\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" # 1. Identify Parameter Groups\n",
|
| 221 |
+
" # ----------------------------\n",
|
| 222 |
+
" embedding_ids = set()\n",
|
| 223 |
+
" active_ids = set()\n",
|
| 224 |
+
" unique_params = set()\n",
|
| 225 |
+
"\n",
|
| 226 |
+
" # --- MEMORY (Embeddings & Encodings) ---\n",
|
| 227 |
+
" embedding_params = 0\n",
|
| 228 |
+
" for p in model.token_emb.parameters():\n",
|
| 229 |
+
" embedding_params += p.numel()\n",
|
| 230 |
+
" embedding_ids.add(id(p))\n",
|
| 231 |
+
" unique_params.add(id(p))\n",
|
| 232 |
+
"\n",
|
| 233 |
+
" pos_params = model.pos_emb.numel()\n",
|
| 234 |
+
" embedding_ids.add(id(model.pos_emb))\n",
|
| 235 |
+
" unique_params.add(id(model.pos_emb))\n",
|
| 236 |
+
"\n",
|
| 237 |
+
" total_memory = embedding_params + pos_params\n",
|
| 238 |
+
"\n",
|
| 239 |
+
" # --- LOGIC (Active Processing) ---\n",
|
| 240 |
+
" active_count = 0\n",
|
| 241 |
+
" for name, param in model.named_parameters():\n",
|
| 242 |
+
" if id(param) in embedding_ids:\n",
|
| 243 |
+
" continue\n",
|
| 244 |
+
" if id(param) not in active_ids:\n",
|
| 245 |
+
" active_count += param.numel()\n",
|
| 246 |
+
" active_ids.add(id(param))\n",
|
| 247 |
+
" unique_params.add(id(param))\n",
|
| 248 |
+
"\n",
|
| 249 |
+
" # 2. Calculate Totals\n",
|
| 250 |
+
" # -------------------\n",
|
| 251 |
+
" total_physical_params = total_memory + active_count\n",
|
| 252 |
+
"\n",
|
| 253 |
+
" # 3. Print Report (FIXED SYNTAX)\n",
|
| 254 |
+
" # -------------------\n",
|
| 255 |
+
" print(f\"{'Component':<25} | {'Count':<15} | {'% of Model':<10}\")\n",
|
| 256 |
+
" print(f\"{'-'*60}\")\n",
|
| 257 |
+
"\n",
|
| 258 |
+
" print(f\"{'Token Embeddings':<25} | {embedding_params:<15,} | {embedding_params/total_physical_params:.1%}\")\n",
|
| 259 |
+
" print(f\"{'Positional Encodings':<25} | {pos_params:<15,} | {pos_params/total_physical_params:.1%}\")\n",
|
| 260 |
+
" print(f\"{'[MEMORY TOTAL]':<25} | {total_memory:<15,} | {total_memory/total_physical_params:.1%}\")\n",
|
| 261 |
+
" print(f\"{'-'*60}\")\n",
|
| 262 |
+
"\n",
|
| 263 |
+
" fnet_params = sum(p.numel() for p in model.fnet_encoder.parameters())\n",
|
| 264 |
+
" cap_params = sum(p.numel() for p in model.transformer_cap.parameters())\n",
|
| 265 |
+
" misc_params = active_count - fnet_params - cap_params\n",
|
| 266 |
+
"\n",
|
| 267 |
+
" print(f\"{'FNet Encoder (6 Layers)':<25} | {fnet_params:<15,} | {fnet_params/total_physical_params:.1%}\")\n",
|
| 268 |
+
" print(f\"{'Transformer Cap (1 Layer)':<25}| {cap_params:<15,} | {cap_params/total_physical_params:.1%}\")\n",
|
| 269 |
+
" print(f\"{'Norms & Biases':<25} | {misc_params:<15,} | {misc_params/total_physical_params:.1%}\")\n",
|
| 270 |
+
" print(f\"{'[ACTIVE LOGIC TOTAL]':<25} | {active_count:<15,} | {active_count/total_physical_params:.1%}\")\n",
|
| 271 |
+
"\n",
|
| 272 |
+
" print(f\"{'='*60}\")\n",
|
| 273 |
+
" print(f\"📢 FINAL ACTIVE PARAMETERS: {active_count / 1_000_000:.2f} M\")\n",
|
| 274 |
+
" print(f\"{'='*60}\\n\")\n",
|
| 275 |
+
"\n",
|
| 276 |
+
" return active_count\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"\n"
|
| 279 |
+
],
|
| 280 |
+
"metadata": {
|
| 281 |
+
"id": "V7DOwmmUjyin"
|
| 282 |
+
},
|
| 283 |
+
"execution_count": null,
|
| 284 |
+
"outputs": []
|
| 285 |
+
},
|
| 286 |
+
{
|
| 287 |
+
"cell_type": "code",
|
| 288 |
+
"source": [
|
| 289 |
+
"# ==========================================\n",
|
| 290 |
+
"# 3. INITIALIZATION FUNCTION (FNet Specific)\n",
|
| 291 |
+
"# ==========================================\n",
|
| 292 |
+
"def init_fnet_weights(model):\n",
|
| 293 |
+
" print(\"✨ Applying BERT-Style Initialization (N(0, 0.02))...\")\n",
|
| 294 |
+
"\n",
|
| 295 |
+
" for name, module in model.named_modules():\n",
|
| 296 |
+
" # A. Linear Layers (Projections, FFNs)\n",
|
| 297 |
+
" if isinstance(module, nn.Linear):\n",
|
| 298 |
+
" module.weight.data.normal_(mean=0.0, std=0.02)\n",
|
| 299 |
+
" if module.bias is not None:\n",
|
| 300 |
+
" module.bias.data.zero_()\n",
|
| 301 |
+
"\n",
|
| 302 |
+
" # B. Embeddings (Tokens)\n",
|
| 303 |
+
" elif isinstance(module, nn.Embedding):\n",
|
| 304 |
+
" module.weight.data.normal_(mean=0.0, std=0.02)\n",
|
| 305 |
+
" if module.padding_idx is not None:\n",
|
| 306 |
+
" module.weight.data[module.padding_idx].zero_()\n",
|
| 307 |
+
"\n",
|
| 308 |
+
" # C. LayerNorms (Stability)\n",
|
| 309 |
+
" elif isinstance(module, nn.LayerNorm):\n",
|
| 310 |
+
" if module.bias is not None: # <--- FIX IS HERE\n",
|
| 311 |
+
" module.bias.data.zero_()\n",
|
| 312 |
+
" if module.weight is not None:\n",
|
| 313 |
+
" module.weight.data.fill_(1.0)\n",
|
| 314 |
+
"\n",
|
| 315 |
+
" # D. Positional Embeddings (Manually handle the nn.Parameter)\n",
|
| 316 |
+
" if hasattr(model, 'pos_emb') and model.pos_emb is not None:\n",
|
| 317 |
+
" model.pos_emb.data.normal_(mean=0.0, std=0.02)\n",
|
| 318 |
+
"\n",
|
| 319 |
+
" print(\"✅ Initialization Complete.\")\n",
|
| 320 |
+
"\n",
|
| 321 |
+
"\n",
|
| 322 |
+
"# ==========================================\n",
|
| 323 |
+
"# 4. LOGGING UTILITIES\n",
|
| 324 |
+
"# ==========================================\n",
|
| 325 |
+
"def generate_run_id():\n",
|
| 326 |
+
" raw = datetime.now().strftime(\"%Y%m%d%H%M%S%f\")\n",
|
| 327 |
+
" return hashlib.md5(raw.encode()).hexdigest()[:8]\n",
|
| 328 |
+
"\n",
|
| 329 |
+
"def log_full_environment(save_dir, run_id, config):\n",
|
| 330 |
+
" log_path = os.path.join(save_dir, f\"env_metadata_{run_id}.txt\")\n",
|
| 331 |
+
"\n",
|
| 332 |
+
" # 1. Gather System Info\n",
|
| 333 |
+
" sys_info = {\n",
|
| 334 |
+
" \"Python Version\": sys.version.split()[0],\n",
|
| 335 |
+
" \"OS\": platform.platform(),\n",
|
| 336 |
+
" \"PyTorch Version\": torch.__version__,\n",
|
| 337 |
+
" \"CUDA Available\": torch.cuda.is_available(),\n",
|
| 338 |
+
" \"CUDNN Version\": torch.backends.cudnn.version() if torch.cuda.is_available() else \"N/A\"\n",
|
| 339 |
+
" }\n",
|
| 340 |
+
"\n",
|
| 341 |
+
" # 2. Gather GPU Info\n",
|
| 342 |
+
" gpu_info = []\n",
|
| 343 |
+
" if torch.cuda.is_available():\n",
|
| 344 |
+
" for i in range(torch.cuda.device_count()):\n",
|
| 345 |
+
" props = torch.cuda.get_device_properties(i)\n",
|
| 346 |
+
" gpu_info.append(f\"GPU {i}: {props.name} | VRAM: {props.total_memory / 1e9:.2f} GB\")\n",
|
| 347 |
+
" else:\n",
|
| 348 |
+
" gpu_info.append(\"No GPU Detected\")\n",
|
| 349 |
+
"\n",
|
| 350 |
+
" # 3. Gather Pip Freeze\n",
|
| 351 |
+
" try:\n",
|
| 352 |
+
" pip_packages = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze']).decode('utf-8')\n",
|
| 353 |
+
" except Exception as e:\n",
|
| 354 |
+
" pip_packages = f\"Could not retrieve pip packages: {e}\"\n",
|
| 355 |
+
"\n",
|
| 356 |
+
" # 4. Write to File\n",
|
| 357 |
+
" with open(log_path, \"w\") as f:\n",
|
| 358 |
+
" f.write(f\"🧪 EXPERIMENT METADATA | Run ID: {run_id}\\n\")\n",
|
| 359 |
+
" f.write(f\"{'='*60}\\n\\n\")\n",
|
| 360 |
+
"\n",
|
| 361 |
+
" f.write(f\"--- [1] CONFIGURATION ---\\n\")\n",
|
| 362 |
+
" for k, v in config.items():\n",
|
| 363 |
+
" f.write(f\"{k}: {v}\\n\")\n",
|
| 364 |
+
" f.write(\"\\n\")\n",
|
| 365 |
+
"\n",
|
| 366 |
+
" f.write(f\"--- [2] SYSTEM HARDWARE ---\\n\")\n",
|
| 367 |
+
" for k, v in sys_info.items():\n",
|
| 368 |
+
" f.write(f\"{k}: {v}\\n\")\n",
|
| 369 |
+
" for g in gpu_info:\n",
|
| 370 |
+
" f.write(f\"{g}\\n\")\n",
|
| 371 |
+
" f.write(\"\\n\")\n",
|
| 372 |
+
"\n",
|
| 373 |
+
" f.write(f\"--- [3] INSTALLED PACKAGES (pip freeze) ---\\n\")\n",
|
| 374 |
+
" f.write(pip_packages)\n",
|
| 375 |
+
"\n",
|
| 376 |
+
" print(f\"📝 Full Environment Snapshot (GPU + Pip) saved to: {log_path}\")\n",
|
| 377 |
+
"\n",
|
| 378 |
+
"\n",
|
| 379 |
+
"def save_checkpoint(path, model, optimizer, scheduler, epoch, best_loss, config):\n",
|
| 380 |
+
" torch.save({\n",
|
| 381 |
+
" 'epoch': epoch,\n",
|
| 382 |
+
" 'model_state_dict': model.state_dict(),\n",
|
| 383 |
+
" 'optimizer_state_dict': optimizer.state_dict(),\n",
|
| 384 |
+
" 'scheduler_state_dict': scheduler.state_dict(),\n",
|
| 385 |
+
" 'best_val_loss': best_loss,\n",
|
| 386 |
+
" 'config': config\n",
|
| 387 |
+
" }, path)\n",
|
| 388 |
+
"\n",
|
| 389 |
+
"# ==========================================\n",
|
| 390 |
+
"# 5. TRAINING LOOP\n",
|
| 391 |
+
"# ==========================================\n",
|
| 392 |
+
"def run_wikitext_training(experiment_name=\"FNet_Encoder\"):\n",
|
| 393 |
+
" from google.colab import drive\n",
|
| 394 |
+
" if not os.path.exists('/content/drive'): drive.mount('/content/drive')\n",
|
| 395 |
+
"\n",
|
| 396 |
+
" # --- SETUP DIRS ---\n",
|
| 397 |
+
" if RESUME_PATH and os.path.exists(RESUME_PATH):\n",
|
| 398 |
+
" print(f\"🔄 RESUMING FROM: {RESUME_PATH}\")\n",
|
| 399 |
+
" checkpoint = torch.load(RESUME_PATH, map_location=DEVICE)\n",
|
| 400 |
+
" SAVE_DIR = os.path.dirname(RESUME_PATH)\n",
|
| 401 |
+
" run_id = checkpoint.get('config', {}).get('run_id', 'resumed')\n",
|
| 402 |
+
" else:\n",
|
| 403 |
+
" run_id = generate_run_id()\n",
|
| 404 |
+
" timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n",
|
| 405 |
+
" folder_name = f\"{experiment_name}_{timestamp}_{run_id}\"\n",
|
| 406 |
+
" SAVE_DIR = os.path.join(\"/content/drive/My Drive/PRISM_Experiments\", folder_name)\n",
|
| 407 |
+
" os.makedirs(SAVE_DIR, exist_ok=True)\n",
|
| 408 |
+
" print(f\"💾 Checkpoints: {SAVE_DIR}\")\n",
|
| 409 |
+
"\n",
|
| 410 |
+
" writer = SummaryWriter(log_dir=SAVE_DIR)\n",
|
| 411 |
+
" GRAD_ACCUM = 4\n",
|
| 412 |
+
"\n",
|
| 413 |
+
" # Load Data\n",
|
| 414 |
+
" lm_datasets, data_collator = prepare_data_from_hub()\n",
|
| 415 |
+
"\n",
|
| 416 |
+
" # Create Loaders\n",
|
| 417 |
+
" train_loader = DataLoader(\n",
|
| 418 |
+
" lm_datasets[\"train\"], batch_size=BATCH_SIZE, shuffle=True,\n",
|
| 419 |
+
" collate_fn=data_collator, num_workers=2, pin_memory=True,\n",
|
| 420 |
+
" prefetch_factor=2, persistent_workers=True\n",
|
| 421 |
+
" )\n",
|
| 422 |
+
" valid_loader = DataLoader(\n",
|
| 423 |
+
" lm_datasets[\"validation\"], batch_size=BATCH_SIZE,\n",
|
| 424 |
+
" collate_fn=data_collator, num_workers=2, pin_memory=True\n",
|
| 425 |
+
" )\n",
|
| 426 |
+
" test_loader = DataLoader(\n",
|
| 427 |
+
" lm_datasets[\"test\"], batch_size=BATCH_SIZE,\n",
|
| 428 |
+
" collate_fn=data_collator, num_workers=2, pin_memory=True\n",
|
| 429 |
+
" )\n",
|
| 430 |
+
"\n",
|
| 431 |
+
" print(\"\\n⚡ INITIALIZING HYBRID FNET MODEL...\")\n",
|
| 432 |
+
"\n",
|
| 433 |
+
" # INSTANTIATE\n",
|
| 434 |
+
" model = HybridFNetMLM(\n",
|
| 435 |
+
" vocab_size=VOCAB_SIZE,\n",
|
| 436 |
+
" d_model=D_MODEL,\n",
|
| 437 |
+
" seq_len=SEQ_LEN,\n",
|
| 438 |
+
" d_ff=D_MODEL * 4,\n",
|
| 439 |
+
" dropout=0.1\n",
|
| 440 |
+
" ).to(DEVICE)\n",
|
| 441 |
+
"\n",
|
| 442 |
+
" # OPTIMIZER\n",
|
| 443 |
+
" optimizer = optim.AdamW(model.parameters(), lr=LR, weight_decay=0.01)\n",
|
| 444 |
+
"\n",
|
| 445 |
+
" total_steps = (len(train_loader) // GRAD_ACCUM) * EPOCHS\n",
|
| 446 |
+
" scheduler = get_cosine_schedule_with_warmup(\n",
|
| 447 |
+
" optimizer, num_warmup_steps=int(0.05 * total_steps), num_training_steps=total_steps\n",
|
| 448 |
+
" )\n",
|
| 449 |
+
" criterion = nn.CrossEntropyLoss()\n",
|
| 450 |
+
"\n",
|
| 451 |
+
" start_epoch = 0\n",
|
| 452 |
+
" best_val_loss = float('inf')\n",
|
| 453 |
+
"\n",
|
| 454 |
+
" # RESUME OR INIT\n",
|
| 455 |
+
" if RESUME_PATH and os.path.exists(RESUME_PATH):\n",
|
| 456 |
+
" model.load_state_dict(checkpoint['model_state_dict'])\n",
|
| 457 |
+
" optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n",
|
| 458 |
+
" scheduler.load_state_dict(checkpoint['scheduler_state_dict'])\n",
|
| 459 |
+
" start_epoch = checkpoint['epoch'] + 1\n",
|
| 460 |
+
" best_val_loss = checkpoint['best_val_loss']\n",
|
| 461 |
+
" del checkpoint\n",
|
| 462 |
+
" torch.cuda.empty_cache()\n",
|
| 463 |
+
" else:\n",
|
| 464 |
+
" # [UPDATED] CALL THE FNET INITIALIZATION\n",
|
| 465 |
+
" init_fnet_weights(model)\n",
|
| 466 |
+
"\n",
|
| 467 |
+
" # METRICS\n",
|
| 468 |
+
" try:\n",
|
| 469 |
+
" active_params = count_active_parameters(model) # Uses function defined in prev step\n",
|
| 470 |
+
" except:\n",
|
| 471 |
+
" print(\"⚠️ Parameter counter not found, skipping detailed breakdown.\")\n",
|
| 472 |
+
"\n",
|
| 473 |
+
" total_params = sum(p.numel() for p in model.parameters())\n",
|
| 474 |
+
" print(f\"✅ Model Ready. Total Raw Params: {total_params/1e6:.2f}M\")\n",
|
| 475 |
+
"\n",
|
| 476 |
+
" log_full_environment(SAVE_DIR, run_id, {\n",
|
| 477 |
+
" \"model\": \"HybridFNetMLM\",\n",
|
| 478 |
+
" \"d_model\": D_MODEL,\n",
|
| 479 |
+
" \"depth\": \"6+1\",\n",
|
| 480 |
+
" \"vocab\": VOCAB_SIZE,\n",
|
| 481 |
+
" \"batch\": BATCH_SIZE,\n",
|
| 482 |
+
" \"lr\": LR,\n",
|
| 483 |
+
" \"active_params\": f\"{active_params/1e6:.2f}M\"\n",
|
| 484 |
+
" })\n",
|
| 485 |
+
"\n",
|
| 486 |
+
" print(f\"\\n🚀 STARTING (Ep {start_epoch+1} to {EPOCHS})\")\n",
|
| 487 |
+
" global_step = (len(train_loader) // GRAD_ACCUM) * start_epoch\n",
|
| 488 |
+
"\n",
|
| 489 |
+
" for epoch in range(start_epoch, EPOCHS):\n",
|
| 490 |
+
" model.train()\n",
|
| 491 |
+
" pbar = tqdm(train_loader, desc=f\"Ep {epoch+1}/{EPOCHS}\")\n",
|
| 492 |
+
"\n",
|
| 493 |
+
" for step, batch in enumerate(pbar):\n",
|
| 494 |
+
" x, y = batch['input_ids'].to(DEVICE), batch['labels'].to(DEVICE)\n",
|
| 495 |
+
"\n",
|
| 496 |
+
" # FNet Forward Pass\n",
|
| 497 |
+
" logits = model(x)\n",
|
| 498 |
+
"\n",
|
| 499 |
+
" # Loss Calculation\n",
|
| 500 |
+
" loss = criterion(logits.view(-1, VOCAB_SIZE), y.view(-1)) / GRAD_ACCUM\n",
|
| 501 |
+
" loss.backward()\n",
|
| 502 |
+
"\n",
|
| 503 |
+
" if (step + 1) % GRAD_ACCUM == 0:\n",
|
| 504 |
+
" # 1. Calc Norm\n",
|
| 505 |
+
" grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n",
|
| 506 |
+
"\n",
|
| 507 |
+
" # 2. Step\n",
|
| 508 |
+
" optimizer.step()\n",
|
| 509 |
+
" scheduler.step()\n",
|
| 510 |
+
" optimizer.zero_grad()\n",
|
| 511 |
+
" global_step += 1\n",
|
| 512 |
+
"\n",
|
| 513 |
+
" # 3. LOGGING\n",
|
| 514 |
+
" actual_loss = loss.item() * GRAD_ACCUM\n",
|
| 515 |
+
" writer.add_scalar('Train/Loss', actual_loss, global_step)\n",
|
| 516 |
+
" writer.add_scalar('Train/GradNorm', grad_norm.item(), global_step)\n",
|
| 517 |
+
" writer.add_scalar('Train/LR', scheduler.get_last_lr()[0], global_step)\n",
|
| 518 |
+
"\n",
|
| 519 |
+
" # 4. Progress Bar\n",
|
| 520 |
+
" pbar.set_postfix({\n",
|
| 521 |
+
" 'loss': f\"{actual_loss:.4f}\",\n",
|
| 522 |
+
" 'gnorm': f\"{grad_norm.item():.2f}\"\n",
|
| 523 |
+
" })\n",
|
| 524 |
+
"\n",
|
| 525 |
+
" # VALIDATION\n",
|
| 526 |
+
" model.eval()\n",
|
| 527 |
+
" val_loss = 0\n",
|
| 528 |
+
" with torch.no_grad():\n",
|
| 529 |
+
" for batch in valid_loader:\n",
|
| 530 |
+
" x, y = batch['input_ids'].to(DEVICE), batch['labels'].to(DEVICE)\n",
|
| 531 |
+
" val_loss += criterion(model(x).view(-1, VOCAB_SIZE), y.view(-1)).item()\n",
|
| 532 |
+
"\n",
|
| 533 |
+
" avg_val_loss = val_loss / len(valid_loader)\n",
|
| 534 |
+
" ppl = math.exp(avg_val_loss) if avg_val_loss < 100 else float('inf')\n",
|
| 535 |
+
"\n",
|
| 536 |
+
" print(f\"✨ Epoch {epoch+1} | Val Loss: {avg_val_loss:.4f} | PPL: {ppl:.2f}\")\n",
|
| 537 |
+
" writer.add_scalar('Val/PPL', ppl, epoch+1)\n",
|
| 538 |
+
" writer.add_scalar('Val/Loss', avg_val_loss, epoch+1)\n",
|
| 539 |
+
"\n",
|
| 540 |
+
" config_dump = {\"epoch\": epoch, \"run_id\": run_id}\n",
|
| 541 |
+
" save_checkpoint(os.path.join(SAVE_DIR, \"last.pt\"), model, optimizer, scheduler, epoch, best_val_loss, config_dump)\n",
|
| 542 |
+
"\n",
|
| 543 |
+
" if avg_val_loss < best_val_loss:\n",
|
| 544 |
+
" best_val_loss = avg_val_loss\n",
|
| 545 |
+
" torch.save(model.state_dict(), os.path.join(SAVE_DIR, \"best.pt\"))\n",
|
| 546 |
+
" print(\" 🏆 New Best Model Saved!\")\n",
|
| 547 |
+
"\n",
|
| 548 |
+
" # FINAL TEST\n",
|
| 549 |
+
" best_path = os.path.join(SAVE_DIR, \"best.pt\")\n",
|
| 550 |
+
" if os.path.exists(best_path):\n",
|
| 551 |
+
" model.load_state_dict(torch.load(best_path))\n",
|
| 552 |
+
" model.eval()\n",
|
| 553 |
+
" test_loss = 0\n",
|
| 554 |
+
" with torch.no_grad():\n",
|
| 555 |
+
" for batch in tqdm(test_loader, desc=\"Testing\"):\n",
|
| 556 |
+
" x, y = batch['input_ids'].to(DEVICE), batch['labels'].to(DEVICE)\n",
|
| 557 |
+
" test_loss += criterion(model(x).view(-1, VOCAB_SIZE), y.view(-1)).item()\n",
|
| 558 |
+
" print(f\"🏆 FINAL TEST PPL: {math.exp(test_loss/len(test_loader)):.2f}\")\n",
|
| 559 |
+
"\n",
|
| 560 |
+
" writer.close()\n",
|
| 561 |
+
" return model"
|
| 562 |
+
],
|
| 563 |
+
"metadata": {
|
| 564 |
+
"id": "-TNEv89gkS1k"
|
| 565 |
+
},
|
| 566 |
+
"execution_count": null,
|
| 567 |
+
"outputs": []
|
| 568 |
+
},
|
| 569 |
+
{
|
| 570 |
+
"cell_type": "code",
|
| 571 |
+
"source": [
|
| 572 |
+
"if __name__ == \"__main__\":\n",
|
| 573 |
+
"\n",
|
| 574 |
+
"\n",
|
| 575 |
+
" # 1. Run the Training Routine\n",
|
| 576 |
+
" # This handles Model Creation -> Analysis -> Training -> Saving\n",
|
| 577 |
+
" trained_prism = run_wikitext_training()\n",
|
| 578 |
+
"\n",
|
| 579 |
+
" # 2. Cleanup & Shutdown\n"
|
| 580 |
+
],
|
| 581 |
+
"metadata": {
|
| 582 |
+
"id": "KaiJU0tPkVp-"
|
| 583 |
+
},
|
| 584 |
+
"execution_count": null,
|
| 585 |
+
"outputs": []
|
| 586 |
+
},
|
| 587 |
+
{
|
| 588 |
+
"cell_type": "code",
|
| 589 |
+
"source": [
|
| 590 |
+
"from google.colab import runtime\n",
|
| 591 |
+
"runtime.unassign()"
|
| 592 |
+
],
|
| 593 |
+
"metadata": {
|
| 594 |
+
"id": "bxFTYWHVqcSI"
|
| 595 |
+
},
|
| 596 |
+
"execution_count": null,
|
| 597 |
+
"outputs": []
|
| 598 |
+
}
|
| 599 |
+
]
|
| 600 |
+
}
|
HSSM_Wikitext_Training.ipynb
ADDED
|
@@ -0,0 +1,951 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"nbformat": 4,
|
| 3 |
+
"nbformat_minor": 0,
|
| 4 |
+
"metadata": {
|
| 5 |
+
"colab": {
|
| 6 |
+
"provenance": [],
|
| 7 |
+
"gpuType": "A100"
|
| 8 |
+
},
|
| 9 |
+
"kernelspec": {
|
| 10 |
+
"name": "python3",
|
| 11 |
+
"display_name": "Python 3"
|
| 12 |
+
},
|
| 13 |
+
"language_info": {
|
| 14 |
+
"name": "python"
|
| 15 |
+
},
|
| 16 |
+
"accelerator": "GPU"
|
| 17 |
+
},
|
| 18 |
+
"cells": [
|
| 19 |
+
{
|
| 20 |
+
"cell_type": "code",
|
| 21 |
+
"source": [
|
| 22 |
+
"!pip install -q x-transformers\n",
|
| 23 |
+
"!pip install -q flash-attn --no-build-isolation"
|
| 24 |
+
],
|
| 25 |
+
"metadata": {
|
| 26 |
+
"id": "6q9RTvlf5IiS"
|
| 27 |
+
},
|
| 28 |
+
"execution_count": null,
|
| 29 |
+
"outputs": []
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"cell_type": "code",
|
| 33 |
+
"source": [
|
| 34 |
+
"import torch\n",
|
| 35 |
+
"import torch.nn as nn\n",
|
| 36 |
+
"import torch.nn.functional as F\n",
|
| 37 |
+
"import torch.optim as optim\n",
|
| 38 |
+
"import math\n",
|
| 39 |
+
"import os\n",
|
| 40 |
+
"import sys\n",
|
| 41 |
+
"import subprocess\n",
|
| 42 |
+
"import hashlib\n",
|
| 43 |
+
"import gc\n",
|
| 44 |
+
"from datetime import datetime\n",
|
| 45 |
+
"from tqdm.auto import tqdm\n",
|
| 46 |
+
"from torch.utils.data import DataLoader\n",
|
| 47 |
+
"from torch.utils.tensorboard import SummaryWriter\n",
|
| 48 |
+
"from transformers import RobertaTokenizerFast, get_cosine_schedule_with_warmup, DataCollatorForLanguageModeling\n",
|
| 49 |
+
"from datasets import load_dataset\n",
|
| 50 |
+
"from x_transformers import Encoder\n",
|
| 51 |
+
"\n",
|
| 52 |
+
"# ==========================================\n",
|
| 53 |
+
"# 1. CONFIGURATION\n",
|
| 54 |
+
"# ==========================================\n",
|
| 55 |
+
"# YOUR REPO ID (Created in previous step)\n",
|
| 56 |
+
"HF_ID = \"prism-lab/wikitext-103-prism-32k-seq4k\"\n",
|
| 57 |
+
"\n",
|
| 58 |
+
"# Hyperparameters\n",
|
| 59 |
+
"VOCAB_SIZE = 32768\n",
|
| 60 |
+
"SEQ_LEN = 4096\n",
|
| 61 |
+
"BATCH_SIZE = 8\n",
|
| 62 |
+
"EPOCHS = 40\n",
|
| 63 |
+
"LR = 1e-3\n",
|
| 64 |
+
"D_MODEL = 512\n",
|
| 65 |
+
"D_BRANCH = 256\n",
|
| 66 |
+
"DEPTH = 9\n",
|
| 67 |
+
"RESUME_PATH = None #\"/content/drive/MyDrive/PRISM_Experiments/PILLARS_SplitStream_8Layer_20260116_025321_8438ce62/last.pt\"\n",
|
| 68 |
+
"DEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 69 |
+
"torch.set_float32_matmul_precision(\"high\")\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"# ==========================================\n",
|
| 72 |
+
"# 2. DATA PIPELINE (The \"Pro\" Way)\n",
|
| 73 |
+
"# ==========================================\n",
|
| 74 |
+
"def prepare_data_from_hub():\n",
|
| 75 |
+
" print(f\"⬇️ Pulling Pre-Tokenized Data from {HF_ID}...\")\n",
|
| 76 |
+
"\n",
|
| 77 |
+
" # 1. Load Tokenizer (Instant)\n",
|
| 78 |
+
" # This pulls the exact tokenizer you uploaded\n",
|
| 79 |
+
" tokenizer = RobertaTokenizerFast.from_pretrained(HF_ID)\n",
|
| 80 |
+
"\n",
|
| 81 |
+
" # 2. Load Dataset (Instant)\n",
|
| 82 |
+
" # This pulls the already chunked/tokenized data\n",
|
| 83 |
+
" dataset = load_dataset(HF_ID)\n",
|
| 84 |
+
"\n",
|
| 85 |
+
" print(f\"✅ Loaded {len(dataset['train'])} training chunks.\")\n",
|
| 86 |
+
"\n",
|
| 87 |
+
" # 3. Collator\n",
|
| 88 |
+
" data_collator = DataCollatorForLanguageModeling(\n",
|
| 89 |
+
" tokenizer=tokenizer,\n",
|
| 90 |
+
" mlm=True,\n",
|
| 91 |
+
" mlm_probability=0.15\n",
|
| 92 |
+
" )\n",
|
| 93 |
+
"\n",
|
| 94 |
+
" return dataset, data_collator\n",
|
| 95 |
+
"# ==========================================\n",
|
| 96 |
+
"# 3. PRISM ARCHITECTURE (Complex-Valued)\n",
|
| 97 |
+
"# ==========================================\n",
|
| 98 |
+
"\n",
|
| 99 |
+
"class ComplexDropout(nn.Module):\n",
|
| 100 |
+
" def __init__(self, p=0.5):\n",
|
| 101 |
+
" super().__init__()\n",
|
| 102 |
+
" self.p = p\n",
|
| 103 |
+
" def forward(self, z):\n",
|
| 104 |
+
" if not self.training or self.p == 0.0: return z\n",
|
| 105 |
+
" mask = torch.ones_like(z.real)\n",
|
| 106 |
+
" mask = F.dropout(mask, self.p, self.training, inplace=False)\n",
|
| 107 |
+
" return z * mask\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"class RobustPhaseNorm(nn.Module):\n",
|
| 110 |
+
" def __init__(self, d_model, eps=1e-5):\n",
|
| 111 |
+
" super().__init__()\n",
|
| 112 |
+
" self.scale = nn.Parameter(torch.ones(d_model))\n",
|
| 113 |
+
" self.eps = eps\n",
|
| 114 |
+
" def forward(self, x):\n",
|
| 115 |
+
" mag = torch.abs(x)\n",
|
| 116 |
+
" rms = torch.sqrt(torch.mean(mag**2, dim=-1, keepdim=True) + self.eps)\n",
|
| 117 |
+
" return (x / rms) * self.scale\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"class ModReLU(nn.Module):\n",
|
| 120 |
+
" def __init__(self, features):\n",
|
| 121 |
+
" super().__init__()\n",
|
| 122 |
+
" self.b = nn.Parameter(torch.zeros(features))\n",
|
| 123 |
+
" def forward(self, z):\n",
|
| 124 |
+
" mag = torch.abs(z)\n",
|
| 125 |
+
" new_mag = F.relu(mag + self.b)\n",
|
| 126 |
+
" phase = z / (mag + 1e-6)\n",
|
| 127 |
+
" return new_mag * phase\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"class ComplexToRealBridge(nn.Module):\n",
|
| 130 |
+
" def __init__(self, d_model):\n",
|
| 131 |
+
" super().__init__()\n",
|
| 132 |
+
" self.proj = nn.Linear(d_model * 2, d_model)\n",
|
| 133 |
+
" self.norm = nn.LayerNorm(d_model)\n",
|
| 134 |
+
" def forward(self, x_complex):\n",
|
| 135 |
+
" cat = torch.cat([x_complex.real, x_complex.imag], dim=-1)\n",
|
| 136 |
+
" return self.norm(self.proj(cat))\n",
|
| 137 |
+
"\n",
|
| 138 |
+
"# ==========================================\n",
|
| 139 |
+
"# 4. DYNAMIC RoSE (Mamba-3 Engine)\n",
|
| 140 |
+
"# ==========================================\n",
|
| 141 |
+
"class DynamicRoSE(nn.Module):\n",
|
| 142 |
+
" def __init__(self, num_embeddings, embedding_dim, max_period=10000.0):\n",
|
| 143 |
+
" super().__init__()\n",
|
| 144 |
+
" self.embedding_dim = embedding_dim\n",
|
| 145 |
+
"\n",
|
| 146 |
+
" # 1. Master Real Embedding (The \"Particle\")\n",
|
| 147 |
+
" self.raw_embedding = nn.Embedding(num_embeddings, embedding_dim)\n",
|
| 148 |
+
"\n",
|
| 149 |
+
" # 2. Complex Adapter (The \"Wave\" Magnitude/Initial Phase)\n",
|
| 150 |
+
" self.adapter = nn.Linear(embedding_dim, embedding_dim * 2)\n",
|
| 151 |
+
"\n",
|
| 152 |
+
" # 3. Static Frequencies (Positional)\n",
|
| 153 |
+
" freqs = torch.exp(torch.arange(0, embedding_dim, dtype=torch.float32) * -(math.log(max_period) / embedding_dim))\n",
|
| 154 |
+
" self.register_buffer('freqs', freqs)\n",
|
| 155 |
+
"\n",
|
| 156 |
+
" self.rotation_predictor = nn.Linear(embedding_dim, embedding_dim * 2)\n",
|
| 157 |
+
"\n",
|
| 158 |
+
" def forward(self, input_ids):\n",
|
| 159 |
+
" # A. Raw Particle\n",
|
| 160 |
+
" real_base = self.raw_embedding(input_ids)\n",
|
| 161 |
+
" B, L, D = real_base.shape\n",
|
| 162 |
+
"\n",
|
| 163 |
+
" # B. Complex Wave Content\n",
|
| 164 |
+
" complex_params = self.adapter(real_base)\n",
|
| 165 |
+
" z_t = torch.complex(complex_params[..., :D], complex_params[..., D:])\n",
|
| 166 |
+
"\n",
|
| 167 |
+
" rot_raw = self.rotation_predictor(real_base)\n",
|
| 168 |
+
" rot_x, rot_y = rot_raw.chunk(2, dim=-1)\n",
|
| 169 |
+
"\n",
|
| 170 |
+
" rot_mag = torch.sqrt(rot_x**2 + rot_y**2 + 1e-6)\n",
|
| 171 |
+
" dynamic_rot = torch.complex(rot_x / rot_mag, rot_y / rot_mag)\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" # D. Static Positional Rotation\n",
|
| 174 |
+
" pos = torch.arange(L, device=input_ids.device).float()\n",
|
| 175 |
+
" static_angles = torch.outer(pos, self.freqs) # [L, D]\n",
|
| 176 |
+
" static_rot = torch.polar(torch.ones_like(static_angles), static_angles) # [L, D]\n",
|
| 177 |
+
"\n",
|
| 178 |
+
" z_final = z_t * static_rot.unsqueeze(0) * dynamic_rot\n",
|
| 179 |
+
"\n",
|
| 180 |
+
" return z_final, real_base\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"# ==========================================\n",
|
| 183 |
+
"# 5. HYENA FILTER\n",
|
| 184 |
+
"# ==========================================\n",
|
| 185 |
+
"class HyenaNeuralFilter(nn.Module):\n",
|
| 186 |
+
" def __init__(self, d_model, max_len=1024, hidden_dim=64):\n",
|
| 187 |
+
" super().__init__()\n",
|
| 188 |
+
" self.d_model = d_model\n",
|
| 189 |
+
" freqs = torch.exp(torch.arange(0, hidden_dim, 2, dtype=torch.float32) * -(math.log(10000.0) / hidden_dim))\n",
|
| 190 |
+
" self.register_buffer(\"freqs\", freqs)\n",
|
| 191 |
+
" self.mlp = nn.Sequential(\n",
|
| 192 |
+
" nn.Linear(hidden_dim, hidden_dim), nn.SiLU(),\n",
|
| 193 |
+
" nn.Linear(hidden_dim, hidden_dim), nn.SiLU(),\n",
|
| 194 |
+
" nn.Linear(hidden_dim, d_model * 2)\n",
|
| 195 |
+
" )\n",
|
| 196 |
+
" def forward(self, L, device):\n",
|
| 197 |
+
" t = torch.linspace(0, 1, steps=L, device=device).unsqueeze(-1)\n",
|
| 198 |
+
" emb = torch.cat([torch.sin(t * self.freqs), torch.cos(t * self.freqs)], dim=-1)\n",
|
| 199 |
+
" out = self.mlp(emb).view(L, self.d_model, 2)\n",
|
| 200 |
+
" return torch.complex(out[..., 0], out[..., 1])\n",
|
| 201 |
+
"\n",
|
| 202 |
+
"# ==========================================\n",
|
| 203 |
+
"# 6. GATED HARMONIC CONVOLUTION (Lean)\n",
|
| 204 |
+
"# ==========================================\n",
|
| 205 |
+
"class GatedHarmonicConvolution(nn.Module):\n",
|
| 206 |
+
" def __init__(self, d_model, max_len=1024, dropout=0.1):\n",
|
| 207 |
+
" super().__init__()\n",
|
| 208 |
+
" self.d_model = d_model\n",
|
| 209 |
+
" self.filter_len = max_len\n",
|
| 210 |
+
" self.neural_filter = HyenaNeuralFilter(d_model, max_len=max_len)\n",
|
| 211 |
+
" self.gate_proj = nn.Linear(d_model * 2, d_model * 2)\n",
|
| 212 |
+
" self.mix_real = nn.Linear(d_model, d_model)\n",
|
| 213 |
+
" self.mix_imag = nn.Linear(d_model, d_model)\n",
|
| 214 |
+
" self.out_real = nn.Linear(d_model, d_model)\n",
|
| 215 |
+
" self.out_imag = nn.Linear(d_model, d_model)\n",
|
| 216 |
+
" self.activation = ModReLU(d_model)\n",
|
| 217 |
+
" self.norm = RobustPhaseNorm(d_model)\n",
|
| 218 |
+
" self.dropout = ComplexDropout(dropout)\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" def forward(self, x, src_mask=None):\n",
|
| 221 |
+
" residual = x\n",
|
| 222 |
+
" x_norm = self.norm(x)\n",
|
| 223 |
+
" if src_mask is not None:\n",
|
| 224 |
+
" x_norm = x_norm.masked_fill(src_mask.unsqueeze(-1), 0.0)\n",
|
| 225 |
+
"\n",
|
| 226 |
+
" # 1. Global Beam (FFT + Hyena)\n",
|
| 227 |
+
" B, L, D = x_norm.shape\n",
|
| 228 |
+
" eff_L = min(L, self.filter_len)\n",
|
| 229 |
+
" x_freq = torch.fft.fft(x_norm, n=eff_L, dim=1, norm='ortho')\n",
|
| 230 |
+
" h = self.neural_filter(eff_L, x.device).unsqueeze(0)\n",
|
| 231 |
+
" x_filtered = x_freq * h\n",
|
| 232 |
+
" x_time = torch.fft.ifft(x_filtered, n=eff_L, dim=1, norm='ortho')\n",
|
| 233 |
+
" if L > eff_L: x_time = F.pad(x_time, (0,0,0,L-eff_L))\n",
|
| 234 |
+
" else: x_time = x_time[:, :L, :]\n",
|
| 235 |
+
"\n",
|
| 236 |
+
" # 2. Gating\n",
|
| 237 |
+
" gates = torch.sigmoid(self.gate_proj(torch.cat([x_norm.real, x_norm.imag], dim=-1)))\n",
|
| 238 |
+
" g_r, g_i = gates.chunk(2, dim=-1)\n",
|
| 239 |
+
" x_gated = torch.complex(x_time.real * g_r, x_time.imag * g_i)\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" # 3. Mixing & Out\n",
|
| 242 |
+
" mr, mi = self.mix_real, self.mix_imag\n",
|
| 243 |
+
" x_mixed = torch.complex(mr(x_gated.real) - mi(x_gated.imag), mr(x_gated.imag) + mi(x_gated.real))\n",
|
| 244 |
+
" x_act = self.activation(x_mixed)\n",
|
| 245 |
+
" or_, oi = self.out_real, self.out_imag\n",
|
| 246 |
+
" out = torch.complex(or_(x_act.real) - oi(x_act.imag), or_(x_act.imag) + oi(x_act.real))\n",
|
| 247 |
+
" return self.dropout(out) + residual\n",
|
| 248 |
+
"\n",
|
| 249 |
+
"# ==========================================\n",
|
| 250 |
+
"# 7. MODEL WRAPPERS\n",
|
| 251 |
+
"# ==========================================\n",
|
| 252 |
+
"class PRISMEncoder(nn.Module):\n",
|
| 253 |
+
" def __init__(self, num_layers, d_model, max_len, dropout=0.1):\n",
|
| 254 |
+
" super().__init__()\n",
|
| 255 |
+
" self.layers = nn.ModuleList([\n",
|
| 256 |
+
" GatedHarmonicConvolution(d_model, max_len, dropout)\n",
|
| 257 |
+
" for _ in range(num_layers)\n",
|
| 258 |
+
" ])\n",
|
| 259 |
+
" self.final_norm = RobustPhaseNorm(d_model)\n",
|
| 260 |
+
" def forward(self, x, src_mask=None):\n",
|
| 261 |
+
" for layer in self.layers:\n",
|
| 262 |
+
" if self.training: x = torch.utils.checkpoint.checkpoint(layer, x, src_mask, use_reentrant=False)\n",
|
| 263 |
+
" else: x = layer(x, src_mask)\n",
|
| 264 |
+
" return self.final_norm(x)\n",
|
| 265 |
+
"\n",
|
| 266 |
+
"class PRISM_WikiText_Model(nn.Module):\n",
|
| 267 |
+
" def __init__(self, vocab_size, d_model, max_len, prism_depth=5, trans_depth=1, dropout=0.1):\n",
|
| 268 |
+
" super().__init__()\n",
|
| 269 |
+
" self.d_model = d_model\n",
|
| 270 |
+
"\n",
|
| 271 |
+
" # 1. PRISM Core (The Optical/Passive Part)\n",
|
| 272 |
+
" self.rose = DynamicRoSE(vocab_size, d_model)\n",
|
| 273 |
+
" self.prism_encoder = PRISMEncoder(prism_depth, d_model, max_len=max_len, dropout=dropout)\n",
|
| 274 |
+
" self.bridge = ComplexToRealBridge(d_model)\n",
|
| 275 |
+
" self.periscope_proj = nn.Sequential(nn.Linear(d_model * 2, d_model), nn.LayerNorm(d_model), nn.GELU())\n",
|
| 276 |
+
"\n",
|
| 277 |
+
" # 2. Refiner (The Digital/Active Part)\n",
|
| 278 |
+
" # 🔄 SWAPPED: Replaced Standard Transformer with RoPE-Enabled Encoder\n",
|
| 279 |
+
" if trans_depth > 0:\n",
|
| 280 |
+
" self.refiner = Encoder(\n",
|
| 281 |
+
" dim=d_model,\n",
|
| 282 |
+
" depth=trans_depth,\n",
|
| 283 |
+
" heads=8,\n",
|
| 284 |
+
" rotary_pos_emb=True,\n",
|
| 285 |
+
" attn_flash=True,\n",
|
| 286 |
+
" attn_dropout=dropout,\n",
|
| 287 |
+
" ff_dropout=dropout,\n",
|
| 288 |
+
"\n",
|
| 289 |
+
" )\n",
|
| 290 |
+
" else:\n",
|
| 291 |
+
" self.refiner = None\n",
|
| 292 |
+
"\n",
|
| 293 |
+
" # 3. Output\n",
|
| 294 |
+
" self.lm_head = nn.Linear(d_model, vocab_size)\n",
|
| 295 |
+
" self.lm_head.weight = self.rose.raw_embedding.weight\n",
|
| 296 |
+
"\n",
|
| 297 |
+
" def forward(self, input_ids):\n",
|
| 298 |
+
" # A. Wave Physics\n",
|
| 299 |
+
" wave_src, particle_src = self.rose(input_ids)\n",
|
| 300 |
+
" wave_out = self.prism_encoder(wave_src)\n",
|
| 301 |
+
" wave_real = self.bridge(wave_out)\n",
|
| 302 |
+
"\n",
|
| 303 |
+
" # B. Interface\n",
|
| 304 |
+
" mixed_memory = self.periscope_proj(torch.cat([wave_real, particle_src], dim=-1))\n",
|
| 305 |
+
"\n",
|
| 306 |
+
" # C. Digital Refinement (Now with RoPE)\n",
|
| 307 |
+
" if self.refiner:\n",
|
| 308 |
+
" out = self.refiner(mixed_memory)\n",
|
| 309 |
+
" else:\n",
|
| 310 |
+
" out = mixed_memory\n",
|
| 311 |
+
"\n",
|
| 312 |
+
" return self.lm_head(out)\n",
|
| 313 |
+
"\n",
|
| 314 |
+
"class FNetBlock(nn.Module):\n",
|
| 315 |
+
" def __init__(self, d_model, d_ff, dropout):\n",
|
| 316 |
+
" super().__init__()\n",
|
| 317 |
+
" self.norm_mix = nn.LayerNorm(d_model) # LayerNorm is safer for FNet than RMSNorm\n",
|
| 318 |
+
" self.norm_ff = nn.LayerNorm(d_model)\n",
|
| 319 |
+
"\n",
|
| 320 |
+
" self.mix_dropout = nn.Dropout(dropout)\n",
|
| 321 |
+
"\n",
|
| 322 |
+
" self.ff = nn.Sequential(\n",
|
| 323 |
+
" nn.Linear(d_model, d_ff),\n",
|
| 324 |
+
" nn.GELU(),\n",
|
| 325 |
+
" nn.Dropout(dropout),\n",
|
| 326 |
+
" nn.Linear(d_ff, d_model),\n",
|
| 327 |
+
" nn.Dropout(dropout)\n",
|
| 328 |
+
" )\n",
|
| 329 |
+
"\n",
|
| 330 |
+
" def forward(self, x):\n",
|
| 331 |
+
" # 1. Fourier Mixing Branch\n",
|
| 332 |
+
" residual = x\n",
|
| 333 |
+
" x = self.norm_mix(x)\n",
|
| 334 |
+
"\n",
|
| 335 |
+
" # --- THE FIX ---\n",
|
| 336 |
+
" with torch.cuda.amp.autocast(enabled=False):\n",
|
| 337 |
+
" x = x.float()\n",
|
| 338 |
+
" # norm='ortho' makes the FFT energy-preserving.\n",
|
| 339 |
+
" # Output magnitude will match input magnitude (~1).\n",
|
| 340 |
+
" x = torch.fft.fftn(x, dim=(-2, -1), norm='ortho').real\n",
|
| 341 |
+
" x = x.to(dtype=residual.dtype)\n",
|
| 342 |
+
" # ---------------\n",
|
| 343 |
+
"\n",
|
| 344 |
+
" # Now 'x' and 'residual' have roughly same magnitude.\n",
|
| 345 |
+
" # The skip connection works again.\n",
|
| 346 |
+
" x = self.mix_dropout(x)\n",
|
| 347 |
+
" x = x + residual\n",
|
| 348 |
+
"\n",
|
| 349 |
+
" # 2. Feed Forward Branch\n",
|
| 350 |
+
" residual = x\n",
|
| 351 |
+
" x = self.norm_ff(x)\n",
|
| 352 |
+
" x = self.ff(x)\n",
|
| 353 |
+
" return x + residual\n",
|
| 354 |
+
"\n",
|
| 355 |
+
"\n",
|
| 356 |
+
"class FNetEncoder(nn.Module):\n",
|
| 357 |
+
" def __init__(self, depth, d_model, d_ff, dropout):\n",
|
| 358 |
+
" super().__init__()\n",
|
| 359 |
+
" self.layers = nn.ModuleList([\n",
|
| 360 |
+
" FNetBlock(d_model, d_ff, dropout) for _ in range(depth)\n",
|
| 361 |
+
" ])\n",
|
| 362 |
+
" # [FIX] Use LayerNorm here to match the blocks\n",
|
| 363 |
+
" self.norm_out = nn.LayerNorm(d_model)\n",
|
| 364 |
+
"\n",
|
| 365 |
+
" def forward(self, x):\n",
|
| 366 |
+
" for layer in self.layers:\n",
|
| 367 |
+
" x = layer(x)\n",
|
| 368 |
+
" return self.norm_out(x)\n",
|
| 369 |
+
"\n",
|
| 370 |
+
"class Pillars_DualStream(nn.Module):\n",
|
| 371 |
+
" def __init__(self, vocab_size, d_model=512, d_branch=384, seq_len=4096, depth=4):\n",
|
| 372 |
+
" super().__init__()\n",
|
| 373 |
+
" self.d_branch = d_branch\n",
|
| 374 |
+
" self.d_refiner = d_model\n",
|
| 375 |
+
"\n",
|
| 376 |
+
" # --- A. Rate Stream (FNet) ---\n",
|
| 377 |
+
" self.fnet_emb = nn.Embedding(vocab_size, d_branch)\n",
|
| 378 |
+
" self.fnet_pos = nn.Embedding(seq_len, d_branch)\n",
|
| 379 |
+
" self.stream_rate = FNetEncoder(depth=depth, d_model=d_branch, d_ff=d_branch*4, dropout=0.1)\n",
|
| 380 |
+
"\n",
|
| 381 |
+
" # --- B. Phase Stream (PRISM) ---\n",
|
| 382 |
+
" self.stream_phase_emb = DynamicRoSE(vocab_size, d_branch)\n",
|
| 383 |
+
" self.stream_phase = PRISMEncoder(num_layers=depth, d_model=d_branch, max_len=seq_len, dropout=0.1)\n",
|
| 384 |
+
" self.phase_bridge = ComplexToRealBridge(d_branch)\n",
|
| 385 |
+
"\n",
|
| 386 |
+
" # --- C. Fusion (The Funnel) ---\n",
|
| 387 |
+
" self.fusion_proj = nn.Linear(d_branch * 2, d_model)\n",
|
| 388 |
+
" self.fusion_norm = nn.LayerNorm(d_model)\n",
|
| 389 |
+
"\n",
|
| 390 |
+
" # --- D. Refiner ---\n",
|
| 391 |
+
" self.refiner = Encoder(\n",
|
| 392 |
+
" dim=d_model, depth=1, heads=8, attn_flash=True,\n",
|
| 393 |
+
" rotary_pos_emb=True, attn_dropout=0.1, ff_dropout=0.1\n",
|
| 394 |
+
" )\n",
|
| 395 |
+
" self.lm_head = nn.Linear(d_model, vocab_size)\n",
|
| 396 |
+
"\n",
|
| 397 |
+
" def forward(self, x):\n",
|
| 398 |
+
" # 1. Rate Path\n",
|
| 399 |
+
" f_emb = self.fnet_emb(x) + self.fnet_pos(torch.arange(x.shape[1], device=x.device))\n",
|
| 400 |
+
" rate_out = self.stream_rate(f_emb)\n",
|
| 401 |
+
"\n",
|
| 402 |
+
" # 2. Phase Path\n",
|
| 403 |
+
" p_src, _ = self.stream_phase_emb(x)\n",
|
| 404 |
+
" phase_out = self.phase_bridge(self.stream_phase(p_src))\n",
|
| 405 |
+
"\n",
|
| 406 |
+
" # 3. Fusion\n",
|
| 407 |
+
" fused = self.fusion_norm(self.fusion_proj(torch.cat([rate_out, phase_out], dim=-1)))\n",
|
| 408 |
+
"\n",
|
| 409 |
+
" # 4. Refine & Output\n",
|
| 410 |
+
" return self.lm_head(self.refiner(fused))\n",
|
| 411 |
+
"\n",
|
| 412 |
+
"\n",
|
| 413 |
+
"class Pillars_Compact(nn.Module):\n",
|
| 414 |
+
" def __init__(self, vocab_size, d_model=512, d_branch=384, seq_len=4096, depth=4):\n",
|
| 415 |
+
" super().__init__()\n",
|
| 416 |
+
" self.d_model = d_model\n",
|
| 417 |
+
" self.d_branch = d_branch\n",
|
| 418 |
+
"\n",
|
| 419 |
+
" # 1. SHARED ROOT\n",
|
| 420 |
+
" self.rose = DynamicRoSE(vocab_size, d_model)\n",
|
| 421 |
+
"\n",
|
| 422 |
+
" # 2. DOWNSAMPLE (512 -> 384)\n",
|
| 423 |
+
" self.particle_down = nn.Linear(d_model, d_branch)\n",
|
| 424 |
+
" self.wave_down = nn.Linear(d_model * 2, d_branch * 2)\n",
|
| 425 |
+
"\n",
|
| 426 |
+
" # 3. RATE STREAM (FNet, Depth 4)\n",
|
| 427 |
+
" self.fnet_pos = nn.Embedding(seq_len, d_branch)\n",
|
| 428 |
+
" self.stream_rate = FNetEncoder(depth=depth, d_model=d_branch, d_ff=d_branch*4, dropout=0.1)\n",
|
| 429 |
+
"\n",
|
| 430 |
+
" # 4. PHASE STREAM (PRISM, Depth 4)\n",
|
| 431 |
+
" self.stream_phase = PRISMEncoder(num_layers=depth, d_model=d_branch, max_len=seq_len, dropout=0.1)\n",
|
| 432 |
+
" self.phase_bridge = ComplexToRealBridge(d_branch)\n",
|
| 433 |
+
"\n",
|
| 434 |
+
" # 5. FUSION (Clean Projection)\n",
|
| 435 |
+
" # Input: 384 (Rate) + 384 (Phase) = 768\n",
|
| 436 |
+
" # Output: 512 (Refiner Dim)\n",
|
| 437 |
+
" self.fusion_proj = nn.Linear(d_branch * 2, d_model)\n",
|
| 438 |
+
" self.fusion_norm = nn.LayerNorm(d_model)\n",
|
| 439 |
+
"\n",
|
| 440 |
+
" # 6. REFINER (The Brain)\n",
|
| 441 |
+
" self.refiner = Encoder(\n",
|
| 442 |
+
" dim=d_model, depth=1, heads=8, attn_flash=True,\n",
|
| 443 |
+
" rotary_pos_emb=True, attn_dropout=0.1, ff_dropout=0.1\n",
|
| 444 |
+
" )\n",
|
| 445 |
+
"\n",
|
| 446 |
+
" # 7. TIED HEAD\n",
|
| 447 |
+
" self.head_bias = nn.Parameter(torch.zeros(vocab_size))\n",
|
| 448 |
+
"\n",
|
| 449 |
+
" def forward(self, input_ids):\n",
|
| 450 |
+
" # A. Shared Root\n",
|
| 451 |
+
" wave_src, particle_src = self.rose(input_ids)\n",
|
| 452 |
+
"\n",
|
| 453 |
+
" # B. Downsample\n",
|
| 454 |
+
" p_small = self.particle_down(particle_src)\n",
|
| 455 |
+
" w_flat = torch.cat([wave_src.real, wave_src.imag], dim=-1)\n",
|
| 456 |
+
" w_small_flat = self.wave_down(w_flat)\n",
|
| 457 |
+
" w_small = torch.complex(w_small_flat[..., :self.d_branch], w_small_flat[..., self.d_branch:])\n",
|
| 458 |
+
"\n",
|
| 459 |
+
" # C. Branches\n",
|
| 460 |
+
" pos_emb = self.fnet_pos(torch.arange(input_ids.shape[1], device=input_ids.device))\n",
|
| 461 |
+
" rate_out = self.stream_rate(p_small + pos_emb)\n",
|
| 462 |
+
" phase_out = self.phase_bridge(self.stream_phase(w_small))\n",
|
| 463 |
+
"\n",
|
| 464 |
+
" # D. Fusion (Concat -> Project)\n",
|
| 465 |
+
" # We rely on the Transformer Refiner to attend to the right parts.\n",
|
| 466 |
+
" stacked = torch.cat([rate_out, phase_out], dim=-1)\n",
|
| 467 |
+
" context = self.fusion_norm(self.fusion_proj(stacked))\n",
|
| 468 |
+
"\n",
|
| 469 |
+
" # E. Refiner\n",
|
| 470 |
+
" refined = self.refiner(context)\n",
|
| 471 |
+
"\n",
|
| 472 |
+
" # F. Output\n",
|
| 473 |
+
" logits = F.linear(refined, self.rose.raw_embedding.weight, self.head_bias)\n",
|
| 474 |
+
"\n",
|
| 475 |
+
" return logits\n",
|
| 476 |
+
"\n",
|
| 477 |
+
"import torch\n",
|
| 478 |
+
"import torch.nn as nn\n",
|
| 479 |
+
"from prettytable import PrettyTable # Optional, but makes tables nice.\n",
|
| 480 |
+
"# If you don't have prettytable, the code below uses standard f-strings.\n",
|
| 481 |
+
"\n",
|
| 482 |
+
"import torch\n",
|
| 483 |
+
"import torch.nn as nn\n",
|
| 484 |
+
"\n",
|
| 485 |
+
"import torch\n",
|
| 486 |
+
"import torch.nn as nn\n",
|
| 487 |
+
"\n",
|
| 488 |
+
"def deep_analyze_pillars(model):\n",
|
| 489 |
+
" def get_p(obj):\n",
|
| 490 |
+
" \"\"\"Safely returns parameter count for Modules OR raw Parameters.\"\"\"\n",
|
| 491 |
+
" if isinstance(obj, nn.Parameter):\n",
|
| 492 |
+
" return obj.numel()\n",
|
| 493 |
+
" return sum(p.numel() for p in obj.parameters() if p.requires_grad)\n",
|
| 494 |
+
"\n",
|
| 495 |
+
" def format_num(n):\n",
|
| 496 |
+
" if n > 1e6: return f\"{n/1e6:.2f}M\"\n",
|
| 497 |
+
" if n > 1e3: return f\"{n/1e3:.2f}K\"\n",
|
| 498 |
+
" return str(n)\n",
|
| 499 |
+
"\n",
|
| 500 |
+
" print(\"\\n\" + \"=\"*80)\n",
|
| 501 |
+
" print(f\"🏗️ PILLARS (COMPACT) - DEEP LAYER ANALYSIS\")\n",
|
| 502 |
+
" print(\"=\"*80)\n",
|
| 503 |
+
" print(f\"{'MODULE / LAYER':<40} | {'PARAMS':<15} | {'TYPE'}\")\n",
|
| 504 |
+
" print(\"-\" * 80)\n",
|
| 505 |
+
"\n",
|
| 506 |
+
" total_params = get_p(model)\n",
|
| 507 |
+
"\n",
|
| 508 |
+
" # -----------------------------------------------\n",
|
| 509 |
+
" # 1. STATIC MEMORY (Embeddings)\n",
|
| 510 |
+
" # -----------------------------------------------\n",
|
| 511 |
+
" vocab_emb = get_p(model.rose.raw_embedding)\n",
|
| 512 |
+
" fnet_pos = get_p(model.fnet_pos)\n",
|
| 513 |
+
"\n",
|
| 514 |
+
" print(f\"{'Shared Vocab Embedding':<40} | {format_num(vocab_emb):<15} | 💾 STORAGE\")\n",
|
| 515 |
+
" print(f\"{'FNet Positional Embedding':<40} | {format_num(fnet_pos):<15} | 💾 STORAGE\")\n",
|
| 516 |
+
"\n",
|
| 517 |
+
" # -----------------------------------------------\n",
|
| 518 |
+
" # 2. INPUT LOGIC (RoSE & Downsampling)\n",
|
| 519 |
+
" # -----------------------------------------------\n",
|
| 520 |
+
" rose_total = get_p(model.rose)\n",
|
| 521 |
+
" rose_logic = rose_total - vocab_emb # Subtract the embedding matrix we already counted\n",
|
| 522 |
+
"\n",
|
| 523 |
+
" print(\"-\" * 80)\n",
|
| 524 |
+
" print(f\"{'Dynamic RoSE (Adapters)':<40} | {format_num(rose_logic):<15} | 🌊 PHASE INIT\")\n",
|
| 525 |
+
" print(f\"{'Particle Downsample (512->384)':<40} | {format_num(get_p(model.particle_down)):<15} | 📉 PROJ\")\n",
|
| 526 |
+
" print(f\"{'Wave Downsample (1024->768)':<40} | {format_num(get_p(model.wave_down)):<15} | 📉 PROJ\")\n",
|
| 527 |
+
"\n",
|
| 528 |
+
" # -----------------------------------------------\n",
|
| 529 |
+
" # 3. STREAM A: RATE (FNet)\n",
|
| 530 |
+
" # -----------------------------------------------\n",
|
| 531 |
+
" print(\"-\" * 80)\n",
|
| 532 |
+
" print(f\"TRACK A: RATE STREAM (FNet) - Depth {len(model.stream_rate.layers)}\")\n",
|
| 533 |
+
"\n",
|
| 534 |
+
" fnet_encoder_total = 0\n",
|
| 535 |
+
" for i, layer in enumerate(model.stream_rate.layers):\n",
|
| 536 |
+
" p = get_p(layer)\n",
|
| 537 |
+
" fnet_encoder_total += p\n",
|
| 538 |
+
" print(f\" ├─ FNet Block {i:<24} | {format_num(p):<15} | ⚡ RATE\")\n",
|
| 539 |
+
"\n",
|
| 540 |
+
" fnet_norm = get_p(model.stream_rate.norm_out)\n",
|
| 541 |
+
" fnet_encoder_total += fnet_norm\n",
|
| 542 |
+
" print(f\" └─ Final Norm {i:<24} | {format_num(fnet_norm):<15} | ⚡ RATE\")\n",
|
| 543 |
+
"\n",
|
| 544 |
+
" # -----------------------------------------------\n",
|
| 545 |
+
" # 4. STREAM B: PHASE (PRISM)\n",
|
| 546 |
+
" # -----------------------------------------------\n",
|
| 547 |
+
" print(\"-\" * 80)\n",
|
| 548 |
+
" print(f\"TRACK B: PHASE STREAM (PRISM) - Depth {len(model.stream_phase.layers)}\")\n",
|
| 549 |
+
"\n",
|
| 550 |
+
" prism_encoder_total = 0\n",
|
| 551 |
+
" for i, layer in enumerate(model.stream_phase.layers):\n",
|
| 552 |
+
" p = get_p(layer)\n",
|
| 553 |
+
" prism_encoder_total += p\n",
|
| 554 |
+
" print(f\" ├─ PRISM Block {i:<23} | {format_num(p):<15} | 🌊 PHASE\")\n",
|
| 555 |
+
"\n",
|
| 556 |
+
" prism_norm = get_p(model.stream_phase.final_norm)\n",
|
| 557 |
+
" prism_encoder_total += prism_norm\n",
|
| 558 |
+
" print(f\" └─ Final Norm {i:<24} | {format_num(prism_norm):<15} | 🌊 PHASE\")\n",
|
| 559 |
+
"\n",
|
| 560 |
+
" bridge_p = get_p(model.phase_bridge)\n",
|
| 561 |
+
" print(f\"{'Phase Bridge (Complex->Real)':<40} | {format_num(bridge_p):<15} | 🌉 BRIDGE\")\n",
|
| 562 |
+
"\n",
|
| 563 |
+
" # -----------------------------------------------\n",
|
| 564 |
+
" # 5. THE BRAIN (Fusion & Refiner)\n",
|
| 565 |
+
" # -----------------------------------------------\n",
|
| 566 |
+
" print(\"-\" * 80)\n",
|
| 567 |
+
" fusion_p = get_p(model.fusion_proj) + get_p(model.fusion_norm)\n",
|
| 568 |
+
" print(f\"{'Fusion (Concat -> Proj -> Norm)':<40} | {format_num(fusion_p):<15} | 🧠 FUSION\")\n",
|
| 569 |
+
"\n",
|
| 570 |
+
" refiner_p = get_p(model.refiner)\n",
|
| 571 |
+
" print(f\"{'Transformer Refiner (1 Layer)':<40} | {format_num(refiner_p):<15} | 🧠 ATTENTION\")\n",
|
| 572 |
+
"\n",
|
| 573 |
+
" # [FIX] Handle nn.Parameter directly\n",
|
| 574 |
+
" head_bias_p = get_p(model.head_bias)\n",
|
| 575 |
+
" print(f\"{'Output Head Bias':<40} | {format_num(head_bias_p):<15} | 🎯 OUTPUT\")\n",
|
| 576 |
+
"\n",
|
| 577 |
+
" # -----------------------------------------------\n",
|
| 578 |
+
" # 6. SUMMARY\n",
|
| 579 |
+
" # -----------------------------------------------\n",
|
| 580 |
+
" print(\"=\"*80)\n",
|
| 581 |
+
"\n",
|
| 582 |
+
" storage = vocab_emb + fnet_pos + head_bias_p\n",
|
| 583 |
+
" active = total_params - storage\n",
|
| 584 |
+
"\n",
|
| 585 |
+
" print(f\"TOTAL PARAMETERS: {total_params/1e6:.2f} M\")\n",
|
| 586 |
+
" print(f\" ├─ 💾 Storage: {storage/1e6:.2f} M (Embeddings)\")\n",
|
| 587 |
+
" print(f\" └─ 🧠 Compute: {active/1e6:.2f} M (Logic/Weights)\")\n",
|
| 588 |
+
" print(\"-\" * 80)\n",
|
| 589 |
+
" print(f\"STREAM BREAKDOWN:\")\n",
|
| 590 |
+
" print(f\" ├─ ⚡ Rate Stream: {fnet_encoder_total/1e6:.2f} M\")\n",
|
| 591 |
+
" print(f\" └─ 🌊 Phase Stream: {prism_encoder_total/1e6:.2f} M\")\n",
|
| 592 |
+
" print(\"=\"*80 + \"\\n\")\n",
|
| 593 |
+
"\n",
|
| 594 |
+
" return total_params\n",
|
| 595 |
+
"\n",
|
| 596 |
+
"model = Pillars_Compact(\n",
|
| 597 |
+
" vocab_size=VOCAB_SIZE,\n",
|
| 598 |
+
" d_model=D_MODEL,\n",
|
| 599 |
+
" d_branch=D_BRANCH,\n",
|
| 600 |
+
" seq_len=SEQ_LEN,\n",
|
| 601 |
+
" depth=DEPTH\n",
|
| 602 |
+
").to(DEVICE)\n",
|
| 603 |
+
"deep_analyze_pillars(model)"
|
| 604 |
+
],
|
| 605 |
+
"metadata": {
|
| 606 |
+
"id": "V7DOwmmUjyin"
|
| 607 |
+
},
|
| 608 |
+
"execution_count": null,
|
| 609 |
+
"outputs": []
|
| 610 |
+
},
|
| 611 |
+
{
|
| 612 |
+
"cell_type": "code",
|
| 613 |
+
"source": [
|
| 614 |
+
"\n",
|
| 615 |
+
"# Run the parameter analysis to confirm strict adherence to budget\n",
|
| 616 |
+
"def analyze_pillars_compact(model):\n",
|
| 617 |
+
" print(\"\\n\" + \"=\"*70)\n",
|
| 618 |
+
" print(\"🏛️ PILLARS COMPACT: ARCHITECTURAL COST ANALYSIS\")\n",
|
| 619 |
+
" print(\"=\"*70)\n",
|
| 620 |
+
"\n",
|
| 621 |
+
" stats = {\n",
|
| 622 |
+
" \"Shared Memory (Storage)\": 0,\n",
|
| 623 |
+
" \"Rate Stream (FNet)\": 0,\n",
|
| 624 |
+
" \"Phase Stream (PRISM)\": 0,\n",
|
| 625 |
+
" \"Fusion & Refiner\": 0,\n",
|
| 626 |
+
" \"Tied Head Bias\": 0\n",
|
| 627 |
+
" }\n",
|
| 628 |
+
"\n",
|
| 629 |
+
" total_params = 0\n",
|
| 630 |
+
"\n",
|
| 631 |
+
" for name, param in model.named_parameters():\n",
|
| 632 |
+
" if not param.requires_grad: continue\n",
|
| 633 |
+
" n = param.numel()\n",
|
| 634 |
+
" total_params += n\n",
|
| 635 |
+
"\n",
|
| 636 |
+
" if \"rose.raw_embedding\" in name:\n",
|
| 637 |
+
" stats[\"Shared Memory (Storage)\"] += n\n",
|
| 638 |
+
" elif \"rose.adapter\" in name or \"rose.rotation\" in name or \"stream_phase\" in name or \"phase_bridge\" in name:\n",
|
| 639 |
+
" stats[\"Phase Stream (PRISM)\"] += n\n",
|
| 640 |
+
" elif \"fnet_pos\" in name or \"stream_rate\" in name:\n",
|
| 641 |
+
" stats[\"Rate Stream (FNet)\"] += n\n",
|
| 642 |
+
" elif \"gate\" in name or \"mix\" in name or \"refiner\" in name or \"down\" in name or \"proj\" in name or \"norm\" in name:\n",
|
| 643 |
+
" stats[\"Fusion & Refiner\"] += n\n",
|
| 644 |
+
" elif \"head_bias\" in name:\n",
|
| 645 |
+
" stats[\"Tied Head Bias\"] += n\n",
|
| 646 |
+
" else:\n",
|
| 647 |
+
" print(f\"⚠️ Uncategorized: {name} ({n})\")\n",
|
| 648 |
+
"\n",
|
| 649 |
+
" print(f\"{'COMPONENT':<30} | {'PARAMS':<12} | {'% TOTAL':<8}\")\n",
|
| 650 |
+
" print(\"-\" * 60)\n",
|
| 651 |
+
"\n",
|
| 652 |
+
" for category, count in stats.items():\n",
|
| 653 |
+
" if count > 0:\n",
|
| 654 |
+
" pct = (count / total_params) * 100\n",
|
| 655 |
+
" print(f\"{category:<30} | {count:12,} | {pct:6.1f}%\")\n",
|
| 656 |
+
"\n",
|
| 657 |
+
" print(\"-\" * 60)\n",
|
| 658 |
+
" print(f\"{'TOTAL PARAMETERS':<30} | {total_params:12,} | 100.0%\")\n",
|
| 659 |
+
" print(\"=\" * 70)\n",
|
| 660 |
+
"\n",
|
| 661 |
+
"\n",
|
| 662 |
+
" active_params = total_params - stats[\"Shared Memory (Storage)\"] - stats[\"Tied Head Bias\"]\n",
|
| 663 |
+
" print(f\" 1. Total Model Size: {total_params/1e6:.1f}M\")\n",
|
| 664 |
+
" print(f\" 2. Baseline Target: ~32.5M\")\n",
|
| 665 |
+
" print(f\" 3. Active Reasoning Params: {active_params/1e6:.1f}M (The actual brain)\")\n",
|
| 666 |
+
" print(\"=\"*70 + \"\\n\")\n",
|
| 667 |
+
"\n",
|
| 668 |
+
"\n"
|
| 669 |
+
],
|
| 670 |
+
"metadata": {
|
| 671 |
+
"id": "ke4fYT8UX5zH"
|
| 672 |
+
},
|
| 673 |
+
"execution_count": null,
|
| 674 |
+
"outputs": []
|
| 675 |
+
},
|
| 676 |
+
{
|
| 677 |
+
"cell_type": "code",
|
| 678 |
+
"source": [
|
| 679 |
+
"# ==========================================\n",
|
| 680 |
+
"# 4. LOGGING UTILITIES\n",
|
| 681 |
+
"# ==========================================\n",
|
| 682 |
+
"def generate_run_id():\n",
|
| 683 |
+
" raw = datetime.now().strftime(\"%Y%m%d%H%M%S%f\")\n",
|
| 684 |
+
" return hashlib.md5(raw.encode()).hexdigest()[:8]\n",
|
| 685 |
+
"\n",
|
| 686 |
+
"def log_environment(save_dir, run_id, config):\n",
|
| 687 |
+
" log_path = os.path.join(save_dir, f\"env_metadata_{run_id}.txt\")\n",
|
| 688 |
+
" with open(log_path, \"w\") as f:\n",
|
| 689 |
+
" f.write(f\"PRISM EXPERIMENT METADATA | Run ID: {run_id}\\n{'='*50}\\n\")\n",
|
| 690 |
+
" for k, v in config.items(): f.write(f\"{k}: {v}\\n\")\n",
|
| 691 |
+
" print(f\"📝 Environment Snapshot saved to: {log_path}\")\n",
|
| 692 |
+
"\n",
|
| 693 |
+
"def log_metrics(save_dir, run_id, epoch, train_loss, val_loss, ppl):\n",
|
| 694 |
+
" log_path = os.path.join(save_dir, f\"metrics_log_{run_id}.csv\")\n",
|
| 695 |
+
" if not os.path.exists(log_path):\n",
|
| 696 |
+
" with open(log_path, \"w\") as f: f.write(\"Timestamp,Epoch,Train_Loss,Val_Loss,Perplexity\\n\")\n",
|
| 697 |
+
" with open(log_path, \"a\") as f:\n",
|
| 698 |
+
" ts = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n",
|
| 699 |
+
" f.write(f\"{ts},{epoch},{train_loss:.6f},{val_loss:.6f},{ppl:.6f}\\n\")\n",
|
| 700 |
+
"\n",
|
| 701 |
+
"\n",
|
| 702 |
+
"def save_checkpoint(path, model, optimizer, scheduler, epoch, best_loss, config):\n",
|
| 703 |
+
" torch.save({\n",
|
| 704 |
+
" 'epoch': epoch,\n",
|
| 705 |
+
" 'model_state_dict': model.state_dict(),\n",
|
| 706 |
+
" 'optimizer_state_dict': optimizer.state_dict(),\n",
|
| 707 |
+
" 'scheduler_state_dict': scheduler.state_dict(),\n",
|
| 708 |
+
" 'best_val_loss': best_loss,\n",
|
| 709 |
+
" 'config': config\n",
|
| 710 |
+
" }, path)\n",
|
| 711 |
+
"\n",
|
| 712 |
+
"def init_pillars_weights(model):\n",
|
| 713 |
+
" print(\"✨ APPLYING PILLARS INITIALIZATION PROTOCOL...\")\n",
|
| 714 |
+
"\n",
|
| 715 |
+
" # 1. SHARED ROOT (RoSE) - MATCHING YOUR ORIGINAL LOGIC\n",
|
| 716 |
+
" # Standard embedding init\n",
|
| 717 |
+
" nn.init.normal_(model.rose.raw_embedding.weight, std=model.d_model ** -0.5)\n",
|
| 718 |
+
"\n",
|
| 719 |
+
" # Adapter: Orthogonal ensures clean entry to complex plane\n",
|
| 720 |
+
" nn.init.orthogonal_(model.rose.adapter.weight)\n",
|
| 721 |
+
"\n",
|
| 722 |
+
" # --- THE ROSE IDENTITY TRICK (From your original code) ---\n",
|
| 723 |
+
" # Start with almost zero rotation influence from content\n",
|
| 724 |
+
" nn.init.normal_(model.rose.rotation_predictor.weight, std=0.01)\n",
|
| 725 |
+
" with torch.no_grad():\n",
|
| 726 |
+
" # Force initial vector to (1, 0) -> Angle 0, Mag 1\n",
|
| 727 |
+
" # This allows the model to start with \"Safe\" static physics\n",
|
| 728 |
+
" model.rose.rotation_predictor.bias[:model.d_model].fill_(1.0)\n",
|
| 729 |
+
" model.rose.rotation_predictor.bias[model.d_model:].fill_(0.0)\n",
|
| 730 |
+
" # -------------------------------------------------------\n",
|
| 731 |
+
"\n",
|
| 732 |
+
" # 2. DOWNSAMPLERS (The Split)\n",
|
| 733 |
+
" # Scale gain by 1.414 (sqrt 2) to preserve energy when halving dimensions\n",
|
| 734 |
+
" nn.init.orthogonal_(model.particle_down.weight, gain=1.414)\n",
|
| 735 |
+
" nn.init.orthogonal_(model.wave_down.weight, gain=1.414)\n",
|
| 736 |
+
"\n",
|
| 737 |
+
" # 3. FNET BRANCH (Rate Stream)\n",
|
| 738 |
+
" # Kaiming Normal (Good for GELU)\n",
|
| 739 |
+
" for name, m in model.stream_rate.named_modules():\n",
|
| 740 |
+
" if isinstance(m, nn.Linear):\n",
|
| 741 |
+
" nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n",
|
| 742 |
+
" if m.bias is not None: nn.init.zeros_(m.bias)\n",
|
| 743 |
+
"\n",
|
| 744 |
+
" # 4. PRISM BRANCH (Phase Stream)\n",
|
| 745 |
+
" # Xavier Uniform (Good for Complex/Linear)\n",
|
| 746 |
+
" for name, m in model.stream_phase.named_modules():\n",
|
| 747 |
+
" if isinstance(m, nn.Linear):\n",
|
| 748 |
+
" nn.init.xavier_uniform_(m.weight, gain=1.0)\n",
|
| 749 |
+
" if m.bias is not None: nn.init.zeros_(m.bias)\n",
|
| 750 |
+
" # Initialize ModReLU bias slightly positive to avoid dead neurons\n",
|
| 751 |
+
" if isinstance(m, ModReLU):\n",
|
| 752 |
+
" nn.init.constant_(m.b, 0.01)\n",
|
| 753 |
+
"\n",
|
| 754 |
+
" # 5. FUSION & REFINER\n",
|
| 755 |
+
" # Start neutral\n",
|
| 756 |
+
" nn.init.xavier_uniform_(model.fusion_proj.weight, gain=1.0)\n",
|
| 757 |
+
"\n",
|
| 758 |
+
" for p in model.refiner.parameters():\n",
|
| 759 |
+
" if p.dim() > 1:\n",
|
| 760 |
+
" nn.init.xavier_uniform_(p)\n",
|
| 761 |
+
"\n",
|
| 762 |
+
" # 6. TIED HEAD BIAS\n",
|
| 763 |
+
" nn.init.zeros_(model.head_bias)\n",
|
| 764 |
+
"\n",
|
| 765 |
+
" print(\"✅ INITIALIZATION COMPLETE.\")\n",
|
| 766 |
+
"\n",
|
| 767 |
+
"def run_wikitext_training(experiment_name=\"PILLARS_SplitStream_9Layer\"):\n",
|
| 768 |
+
" from google.colab import drive\n",
|
| 769 |
+
" if not os.path.exists('/content/drive'): drive.mount('/content/drive')\n",
|
| 770 |
+
"\n",
|
| 771 |
+
" # --- SETUP DIRS ---\n",
|
| 772 |
+
" if RESUME_PATH and os.path.exists(RESUME_PATH):\n",
|
| 773 |
+
" print(f\"🔄 RESUMING FROM: {RESUME_PATH}\")\n",
|
| 774 |
+
" checkpoint = torch.load(RESUME_PATH, map_location=DEVICE)\n",
|
| 775 |
+
" SAVE_DIR = os.path.dirname(RESUME_PATH)\n",
|
| 776 |
+
" run_id = checkpoint.get('config', {}).get('run_id', 'resumed')\n",
|
| 777 |
+
" else:\n",
|
| 778 |
+
" run_id = hashlib.md5(datetime.now().strftime(\"%Y%m%d%H%M%S%f\").encode()).hexdigest()[:8]\n",
|
| 779 |
+
" timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n",
|
| 780 |
+
" folder_name = f\"{experiment_name}_{timestamp}_{run_id}\"\n",
|
| 781 |
+
" SAVE_DIR = os.path.join(\"/content/drive/My Drive/PRISM_Experiments\", folder_name)\n",
|
| 782 |
+
" os.makedirs(SAVE_DIR, exist_ok=True)\n",
|
| 783 |
+
" print(f\"💾 Checkpoints: {SAVE_DIR}\")\n",
|
| 784 |
+
"\n",
|
| 785 |
+
" writer = SummaryWriter(log_dir=SAVE_DIR)\n",
|
| 786 |
+
" GRAD_ACCUM = 4\n",
|
| 787 |
+
"\n",
|
| 788 |
+
" lm_datasets, data_collator = prepare_data_from_hub()\n",
|
| 789 |
+
"\n",
|
| 790 |
+
" train_loader = DataLoader(\n",
|
| 791 |
+
" lm_datasets[\"train\"], batch_size=BATCH_SIZE, shuffle=True,\n",
|
| 792 |
+
" collate_fn=data_collator, num_workers=2, pin_memory=True,\n",
|
| 793 |
+
" prefetch_factor=2, persistent_workers=True\n",
|
| 794 |
+
" )\n",
|
| 795 |
+
" valid_loader = DataLoader(\n",
|
| 796 |
+
" lm_datasets[\"validation\"], batch_size=BATCH_SIZE,\n",
|
| 797 |
+
" collate_fn=data_collator, num_workers=2, pin_memory=True\n",
|
| 798 |
+
" )\n",
|
| 799 |
+
" test_loader = DataLoader(\n",
|
| 800 |
+
" lm_datasets[\"test\"], batch_size=BATCH_SIZE,\n",
|
| 801 |
+
" collate_fn=data_collator, num_workers=2, pin_memory=True\n",
|
| 802 |
+
" )\n",
|
| 803 |
+
"\n",
|
| 804 |
+
" print(\"\\n⚡ INITIALIZING PILLARS MODEL...\")\n",
|
| 805 |
+
"\n",
|
| 806 |
+
" # INSTANTIATE THE NEW MODEL\n",
|
| 807 |
+
" model = Pillars_Compact(\n",
|
| 808 |
+
" vocab_size=VOCAB_SIZE,\n",
|
| 809 |
+
" d_model=D_MODEL,\n",
|
| 810 |
+
" d_branch=D_BRANCH,\n",
|
| 811 |
+
" seq_len=SEQ_LEN,\n",
|
| 812 |
+
" depth=DEPTH\n",
|
| 813 |
+
" ).to(DEVICE)\n",
|
| 814 |
+
"\n",
|
| 815 |
+
" optimizer = optim.AdamW(model.parameters(), lr=LR, weight_decay=0.01) # Added decay for stabilization\n",
|
| 816 |
+
" total_steps = (len(train_loader) // GRAD_ACCUM) * EPOCHS\n",
|
| 817 |
+
" scheduler = get_cosine_schedule_with_warmup(\n",
|
| 818 |
+
" optimizer, num_warmup_steps=int(0.05 * total_steps), num_training_steps=total_steps\n",
|
| 819 |
+
" )\n",
|
| 820 |
+
" criterion = nn.CrossEntropyLoss()\n",
|
| 821 |
+
"\n",
|
| 822 |
+
" start_epoch = 0\n",
|
| 823 |
+
" best_val_loss = float('inf')\n",
|
| 824 |
+
"\n",
|
| 825 |
+
" if RESUME_PATH and os.path.exists(RESUME_PATH):\n",
|
| 826 |
+
" model.load_state_dict(checkpoint['model_state_dict'])\n",
|
| 827 |
+
" optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n",
|
| 828 |
+
" scheduler.load_state_dict(checkpoint['scheduler_state_dict'])\n",
|
| 829 |
+
" start_epoch = checkpoint['epoch'] + 1\n",
|
| 830 |
+
" best_val_loss = checkpoint['best_val_loss']\n",
|
| 831 |
+
" del checkpoint\n",
|
| 832 |
+
" torch.cuda.empty_cache()\n",
|
| 833 |
+
" else:\n",
|
| 834 |
+
" # APPLY THE NEW INIT LOGIC\n",
|
| 835 |
+
" init_pillars_weights(model)\n",
|
| 836 |
+
" print(model)\n",
|
| 837 |
+
" analyze_pillars_compact(model)\n",
|
| 838 |
+
" print(f\"\\n🚀 STARTING (Ep {start_epoch+1} to {EPOCHS})\")\n",
|
| 839 |
+
" global_step = (len(train_loader) // GRAD_ACCUM) * start_epoch\n",
|
| 840 |
+
"\n",
|
| 841 |
+
" for epoch in range(start_epoch, EPOCHS):\n",
|
| 842 |
+
" model.train()\n",
|
| 843 |
+
" pbar = tqdm(train_loader, desc=f\"Ep {epoch+1}/{EPOCHS}\")\n",
|
| 844 |
+
"\n",
|
| 845 |
+
" for step, batch in enumerate(pbar):\n",
|
| 846 |
+
" x, y = batch['input_ids'].to(DEVICE), batch['labels'].to(DEVICE)\n",
|
| 847 |
+
"\n",
|
| 848 |
+
" loss = criterion(model(x).view(-1, VOCAB_SIZE), y.view(-1)) / GRAD_ACCUM\n",
|
| 849 |
+
" loss.backward()\n",
|
| 850 |
+
"\n",
|
| 851 |
+
" if (step + 1) % GRAD_ACCUM == 0:\n",
|
| 852 |
+
" # 1. Calc Norm\n",
|
| 853 |
+
" grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n",
|
| 854 |
+
"\n",
|
| 855 |
+
" # 2. Step\n",
|
| 856 |
+
" optimizer.step()\n",
|
| 857 |
+
" scheduler.step()\n",
|
| 858 |
+
" optimizer.zero_grad()\n",
|
| 859 |
+
" global_step += 1\n",
|
| 860 |
+
"\n",
|
| 861 |
+
" # 3. LOGGING\n",
|
| 862 |
+
" actual_loss = loss.item() * GRAD_ACCUM\n",
|
| 863 |
+
"\n",
|
| 864 |
+
" # [FIX] Log Grad Norm to TensorBoard now\n",
|
| 865 |
+
" writer.add_scalar('Train/Loss', actual_loss, global_step)\n",
|
| 866 |
+
" writer.add_scalar('Train/GradNorm', grad_norm.item(), global_step)\n",
|
| 867 |
+
"\n",
|
| 868 |
+
" # 4. Progress Bar\n",
|
| 869 |
+
" pbar.set_postfix({\n",
|
| 870 |
+
" 'loss': f\"{actual_loss:.4f}\",\n",
|
| 871 |
+
" 'gnorm': f\"{grad_norm.item():.2f}\"\n",
|
| 872 |
+
" })\n",
|
| 873 |
+
"\n",
|
| 874 |
+
" # VALIDATION\n",
|
| 875 |
+
" model.eval()\n",
|
| 876 |
+
" val_loss = 0\n",
|
| 877 |
+
" with torch.no_grad():\n",
|
| 878 |
+
" for batch in valid_loader:\n",
|
| 879 |
+
" x, y = batch['input_ids'].to(DEVICE), batch['labels'].to(DEVICE)\n",
|
| 880 |
+
" val_loss += criterion(model(x).view(-1, VOCAB_SIZE), y.view(-1)).item()\n",
|
| 881 |
+
"\n",
|
| 882 |
+
" avg_val_loss = val_loss / len(valid_loader)\n",
|
| 883 |
+
" ppl = math.exp(avg_val_loss) if avg_val_loss < 100 else float('inf')\n",
|
| 884 |
+
"\n",
|
| 885 |
+
" print(f\"✨ Epoch {epoch+1} | Val Loss: {avg_val_loss:.4f} | PPL: {ppl:.2f}\")\n",
|
| 886 |
+
" writer.add_scalar('Val/PPL', ppl, epoch+1)\n",
|
| 887 |
+
"\n",
|
| 888 |
+
" config_dump = {\"epoch\": epoch, \"run_id\": run_id}\n",
|
| 889 |
+
" save_checkpoint(os.path.join(SAVE_DIR, \"last.pt\"), model, optimizer, scheduler, epoch, best_val_loss, config_dump)\n",
|
| 890 |
+
"\n",
|
| 891 |
+
" if avg_val_loss < best_val_loss:\n",
|
| 892 |
+
" best_val_loss = avg_val_loss\n",
|
| 893 |
+
" torch.save(model.state_dict(), os.path.join(SAVE_DIR, \"best.pt\"))\n",
|
| 894 |
+
" print(\" 🏆 New Best Model Saved!\")\n",
|
| 895 |
+
"\n",
|
| 896 |
+
" best_path = os.path.join(SAVE_DIR, \"best.pt\")\n",
|
| 897 |
+
" if os.path.exists(best_path):\n",
|
| 898 |
+
" model.load_state_dict(torch.load(best_path))\n",
|
| 899 |
+
" model.eval()\n",
|
| 900 |
+
" test_loss = 0\n",
|
| 901 |
+
" with torch.no_grad():\n",
|
| 902 |
+
" for batch in tqdm(test_loader, desc=\"Testing\"):\n",
|
| 903 |
+
" x, y = batch['input_ids'].to(DEVICE), batch['labels'].to(DEVICE)\n",
|
| 904 |
+
" test_loss += criterion(model(x).view(-1, VOCAB_SIZE), y.view(-1)).item()\n",
|
| 905 |
+
" print(f\"🏆 FINAL PPL: {math.exp(test_loss/len(test_loader)):.2f}\")\n",
|
| 906 |
+
"\n",
|
| 907 |
+
" writer.close()\n",
|
| 908 |
+
" return model"
|
| 909 |
+
],
|
| 910 |
+
"metadata": {
|
| 911 |
+
"id": "-TNEv89gkS1k"
|
| 912 |
+
},
|
| 913 |
+
"execution_count": null,
|
| 914 |
+
"outputs": []
|
| 915 |
+
},
|
| 916 |
+
{
|
| 917 |
+
"cell_type": "code",
|
| 918 |
+
"source": [
|
| 919 |
+
"if __name__ == \"__main__\":\n",
|
| 920 |
+
"\n",
|
| 921 |
+
" print(\"🔥 IGNITING PILLARS TRAINING PIPELINE...\")\n",
|
| 922 |
+
"\n",
|
| 923 |
+
" # 1. Run the Training Routine\n",
|
| 924 |
+
" # This handles Model Creation -> Analysis -> Training -> Saving\n",
|
| 925 |
+
" trained_prism = run_wikitext_training()\n",
|
| 926 |
+
"\n",
|
| 927 |
+
" # 2. Cleanup & Shutdown\n",
|
| 928 |
+
" print(\"✅ Experiment Complete. Shutting down runtime...\")\n",
|
| 929 |
+
" from google.colab import runtime\n",
|
| 930 |
+
" runtime.unassign()"
|
| 931 |
+
],
|
| 932 |
+
"metadata": {
|
| 933 |
+
"id": "KaiJU0tPkVp-"
|
| 934 |
+
},
|
| 935 |
+
"execution_count": null,
|
| 936 |
+
"outputs": []
|
| 937 |
+
},
|
| 938 |
+
{
|
| 939 |
+
"cell_type": "code",
|
| 940 |
+
"source": [
|
| 941 |
+
"from google.colab import runtime\n",
|
| 942 |
+
"runtime.unassign()"
|
| 943 |
+
],
|
| 944 |
+
"metadata": {
|
| 945 |
+
"id": "bxFTYWHVqcSI"
|
| 946 |
+
},
|
| 947 |
+
"execution_count": null,
|
| 948 |
+
"outputs": []
|
| 949 |
+
}
|
| 950 |
+
]
|
| 951 |
+
}
|
PRISM_wikitext_103_last.ipynb
ADDED
|
@@ -0,0 +1,589 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"nbformat": 4,
|
| 3 |
+
"nbformat_minor": 0,
|
| 4 |
+
"metadata": {
|
| 5 |
+
"colab": {
|
| 6 |
+
"provenance": [],
|
| 7 |
+
"gpuType": "A100"
|
| 8 |
+
},
|
| 9 |
+
"kernelspec": {
|
| 10 |
+
"name": "python3",
|
| 11 |
+
"display_name": "Python 3"
|
| 12 |
+
},
|
| 13 |
+
"language_info": {
|
| 14 |
+
"name": "python"
|
| 15 |
+
},
|
| 16 |
+
"accelerator": "GPU"
|
| 17 |
+
},
|
| 18 |
+
"cells": [
|
| 19 |
+
{
|
| 20 |
+
"cell_type": "code",
|
| 21 |
+
"source": [
|
| 22 |
+
"!pip install -q x-transformers"
|
| 23 |
+
],
|
| 24 |
+
"metadata": {
|
| 25 |
+
"id": "6q9RTvlf5IiS"
|
| 26 |
+
},
|
| 27 |
+
"execution_count": null,
|
| 28 |
+
"outputs": []
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"cell_type": "code",
|
| 32 |
+
"source": [
|
| 33 |
+
"import torch\n",
|
| 34 |
+
"import torch.nn as nn\n",
|
| 35 |
+
"import torch.nn.functional as F\n",
|
| 36 |
+
"import torch.optim as optim\n",
|
| 37 |
+
"import math\n",
|
| 38 |
+
"import os\n",
|
| 39 |
+
"import sys\n",
|
| 40 |
+
"import subprocess\n",
|
| 41 |
+
"import hashlib\n",
|
| 42 |
+
"import gc\n",
|
| 43 |
+
"from datetime import datetime\n",
|
| 44 |
+
"from tqdm.auto import tqdm\n",
|
| 45 |
+
"from torch.utils.data import DataLoader\n",
|
| 46 |
+
"from torch.utils.tensorboard import SummaryWriter\n",
|
| 47 |
+
"from transformers import RobertaTokenizerFast, get_cosine_schedule_with_warmup, DataCollatorForLanguageModeling\n",
|
| 48 |
+
"from datasets import load_dataset\n",
|
| 49 |
+
"from x_transformers import Encoder\n",
|
| 50 |
+
"\n",
|
| 51 |
+
"# ==========================================\n",
|
| 52 |
+
"# 1. CONFIGURATION\n",
|
| 53 |
+
"# ==========================================\n",
|
| 54 |
+
"# YOUR REPO ID (Created in previous step)\n",
|
| 55 |
+
"HF_ID = \"prism-lab/wikitext-103-prism-32k-seq4k\"\n",
|
| 56 |
+
"\n",
|
| 57 |
+
"# Hyperparameters\n",
|
| 58 |
+
"VOCAB_SIZE = 32768\n",
|
| 59 |
+
"SEQ_LEN = 4096\n",
|
| 60 |
+
"BATCH_SIZE = 8\n",
|
| 61 |
+
"EPOCHS = 40\n",
|
| 62 |
+
"LR = 1e-3\n",
|
| 63 |
+
"D_MODEL = 512\n",
|
| 64 |
+
"DEPTH = 6\n",
|
| 65 |
+
"DROPOUT = 0.1\n",
|
| 66 |
+
"RESUME_PATH = None\n",
|
| 67 |
+
"DEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 68 |
+
"torch.set_float32_matmul_precision(\"high\")\n",
|
| 69 |
+
"\n",
|
| 70 |
+
"# ==========================================\n",
|
| 71 |
+
"# 2. DATA PIPELINE (The \"Pro\" Way)\n",
|
| 72 |
+
"# ==========================================\n",
|
| 73 |
+
"def prepare_data_from_hub():\n",
|
| 74 |
+
" print(f\"⬇️ Pulling Pre-Tokenized Data from {HF_ID}...\")\n",
|
| 75 |
+
"\n",
|
| 76 |
+
" # 1. Load Tokenizer (Instant)\n",
|
| 77 |
+
" # This pulls the exact tokenizer you uploaded\n",
|
| 78 |
+
" tokenizer = RobertaTokenizerFast.from_pretrained(HF_ID)\n",
|
| 79 |
+
"\n",
|
| 80 |
+
" # 2. Load Dataset (Instant)\n",
|
| 81 |
+
" # This pulls the already chunked/tokenized data\n",
|
| 82 |
+
" dataset = load_dataset(HF_ID)\n",
|
| 83 |
+
"\n",
|
| 84 |
+
" print(f\"✅ Loaded {len(dataset['train'])} training chunks.\")\n",
|
| 85 |
+
"\n",
|
| 86 |
+
" # 3. Collator\n",
|
| 87 |
+
" data_collator = DataCollatorForLanguageModeling(\n",
|
| 88 |
+
" tokenizer=tokenizer,\n",
|
| 89 |
+
" mlm=True,\n",
|
| 90 |
+
" mlm_probability=0.15\n",
|
| 91 |
+
" )\n",
|
| 92 |
+
"\n",
|
| 93 |
+
" return dataset, data_collator\n",
|
| 94 |
+
"# ==========================================\n",
|
| 95 |
+
"# 3. PRISM ARCHITECTURE (Complex-Valued)\n",
|
| 96 |
+
"# ==========================================\n",
|
| 97 |
+
"\n",
|
| 98 |
+
"class ComplexDropout(nn.Module):\n",
|
| 99 |
+
" def __init__(self, p=0.5):\n",
|
| 100 |
+
" super().__init__()\n",
|
| 101 |
+
" self.p = p\n",
|
| 102 |
+
" def forward(self, z):\n",
|
| 103 |
+
" if not self.training or self.p == 0.0: return z\n",
|
| 104 |
+
" mask = torch.ones_like(z.real)\n",
|
| 105 |
+
" mask = F.dropout(mask, self.p, self.training, inplace=False)\n",
|
| 106 |
+
" return z * mask\n",
|
| 107 |
+
"\n",
|
| 108 |
+
"class RobustPhaseNorm(nn.Module):\n",
|
| 109 |
+
" def __init__(self, d_model, eps=1e-5):\n",
|
| 110 |
+
" super().__init__()\n",
|
| 111 |
+
" self.scale = nn.Parameter(torch.ones(d_model))\n",
|
| 112 |
+
" self.eps = eps\n",
|
| 113 |
+
" def forward(self, x):\n",
|
| 114 |
+
" mag = torch.abs(x)\n",
|
| 115 |
+
" rms = torch.sqrt(torch.mean(mag**2, dim=-1, keepdim=True) + self.eps)\n",
|
| 116 |
+
" return (x / rms) * self.scale\n",
|
| 117 |
+
"\n",
|
| 118 |
+
"class ModReLU(nn.Module):\n",
|
| 119 |
+
" def __init__(self, features):\n",
|
| 120 |
+
" super().__init__()\n",
|
| 121 |
+
" self.b = nn.Parameter(torch.zeros(features))\n",
|
| 122 |
+
" def forward(self, z):\n",
|
| 123 |
+
" mag = torch.abs(z)\n",
|
| 124 |
+
" new_mag = F.relu(mag + self.b)\n",
|
| 125 |
+
" phase = z / (mag + 1e-6)\n",
|
| 126 |
+
" return new_mag * phase\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"class ComplexToRealBridge(nn.Module):\n",
|
| 129 |
+
" def __init__(self, d_model):\n",
|
| 130 |
+
" super().__init__()\n",
|
| 131 |
+
" self.proj = nn.Linear(d_model * 2, d_model)\n",
|
| 132 |
+
" self.norm = nn.LayerNorm(d_model)\n",
|
| 133 |
+
" def forward(self, x_complex):\n",
|
| 134 |
+
" cat = torch.cat([x_complex.real, x_complex.imag], dim=-1)\n",
|
| 135 |
+
" return self.norm(self.proj(cat))\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"# ==========================================\n",
|
| 138 |
+
"# 4. DYNAMIC RoSE (Mamba-3 Engine)\n",
|
| 139 |
+
"# ==========================================\n",
|
| 140 |
+
"class DynamicRoSE(nn.Module):\n",
|
| 141 |
+
" def __init__(self, num_embeddings, embedding_dim, max_period=10000.0):\n",
|
| 142 |
+
" super().__init__()\n",
|
| 143 |
+
" self.embedding_dim = embedding_dim\n",
|
| 144 |
+
"\n",
|
| 145 |
+
" # 1. Master Real Embedding (The \"Particle\")\n",
|
| 146 |
+
" self.raw_embedding = nn.Embedding(num_embeddings, embedding_dim)\n",
|
| 147 |
+
"\n",
|
| 148 |
+
" # 2. Complex Adapter (The \"Wave\" Magnitude/Initial Phase)\n",
|
| 149 |
+
" self.adapter = nn.Linear(embedding_dim, embedding_dim * 2)\n",
|
| 150 |
+
"\n",
|
| 151 |
+
" # 3. Static Frequencies (Positional)\n",
|
| 152 |
+
" freqs = torch.exp(torch.arange(0, embedding_dim, dtype=torch.float32) * -(math.log(max_period) / embedding_dim))\n",
|
| 153 |
+
" self.register_buffer('freqs', freqs)\n",
|
| 154 |
+
"\n",
|
| 155 |
+
" self.rotation_predictor = nn.Linear(embedding_dim, embedding_dim * 2)\n",
|
| 156 |
+
"\n",
|
| 157 |
+
" def forward(self, input_ids):\n",
|
| 158 |
+
" # A. Raw Particle\n",
|
| 159 |
+
" real_base = self.raw_embedding(input_ids)\n",
|
| 160 |
+
" B, L, D = real_base.shape\n",
|
| 161 |
+
"\n",
|
| 162 |
+
" # B. Complex Wave Content\n",
|
| 163 |
+
" complex_params = self.adapter(real_base)\n",
|
| 164 |
+
" z_t = torch.complex(complex_params[..., :D], complex_params[..., D:])\n",
|
| 165 |
+
"\n",
|
| 166 |
+
" rot_raw = self.rotation_predictor(real_base)\n",
|
| 167 |
+
" rot_x, rot_y = rot_raw.chunk(2, dim=-1)\n",
|
| 168 |
+
"\n",
|
| 169 |
+
" rot_mag = torch.sqrt(rot_x**2 + rot_y**2 + 1e-6)\n",
|
| 170 |
+
" dynamic_rot = torch.complex(rot_x / rot_mag, rot_y / rot_mag)\n",
|
| 171 |
+
"\n",
|
| 172 |
+
" # D. Static Positional Rotation\n",
|
| 173 |
+
" pos = torch.arange(L, device=input_ids.device).float()\n",
|
| 174 |
+
" static_angles = torch.outer(pos, self.freqs) # [L, D]\n",
|
| 175 |
+
" static_rot = torch.polar(torch.ones_like(static_angles), static_angles) # [L, D]\n",
|
| 176 |
+
"\n",
|
| 177 |
+
" z_final = z_t * static_rot.unsqueeze(0) * dynamic_rot\n",
|
| 178 |
+
"\n",
|
| 179 |
+
" return z_final, real_base\n",
|
| 180 |
+
"\n",
|
| 181 |
+
"# ==========================================\n",
|
| 182 |
+
"# 5. HYENA FILTER\n",
|
| 183 |
+
"# ==========================================\n",
|
| 184 |
+
"class HyenaNeuralFilter(nn.Module):\n",
|
| 185 |
+
" def __init__(self, d_model, max_len=1024, hidden_dim=64):\n",
|
| 186 |
+
" super().__init__()\n",
|
| 187 |
+
" self.d_model = d_model\n",
|
| 188 |
+
" freqs = torch.exp(torch.arange(0, hidden_dim, 2, dtype=torch.float32) * -(math.log(10000.0) / hidden_dim))\n",
|
| 189 |
+
" self.register_buffer(\"freqs\", freqs)\n",
|
| 190 |
+
" self.mlp = nn.Sequential(\n",
|
| 191 |
+
" nn.Linear(hidden_dim, hidden_dim), nn.SiLU(),\n",
|
| 192 |
+
" nn.Linear(hidden_dim, hidden_dim), nn.SiLU(),\n",
|
| 193 |
+
" nn.Linear(hidden_dim, d_model * 2)\n",
|
| 194 |
+
" )\n",
|
| 195 |
+
" def forward(self, L, device):\n",
|
| 196 |
+
" t = torch.linspace(0, 1, steps=L, device=device).unsqueeze(-1)\n",
|
| 197 |
+
" emb = torch.cat([torch.sin(t * self.freqs), torch.cos(t * self.freqs)], dim=-1)\n",
|
| 198 |
+
" out = self.mlp(emb).view(L, self.d_model, 2)\n",
|
| 199 |
+
" return torch.complex(out[..., 0], out[..., 1])\n",
|
| 200 |
+
"\n",
|
| 201 |
+
"# ==========================================\n",
|
| 202 |
+
"# 6. GATED HARMONIC CONVOLUTION (Lean)\n",
|
| 203 |
+
"# ==========================================\n",
|
| 204 |
+
"class GatedHarmonicConvolution(nn.Module):\n",
|
| 205 |
+
" def __init__(self, d_model, max_len=1024, dropout=0.1):\n",
|
| 206 |
+
" super().__init__()\n",
|
| 207 |
+
" self.d_model = d_model\n",
|
| 208 |
+
" self.filter_len = max_len\n",
|
| 209 |
+
" self.neural_filter = HyenaNeuralFilter(d_model, max_len=max_len)\n",
|
| 210 |
+
" self.gate_proj = nn.Linear(d_model * 2, d_model * 2)\n",
|
| 211 |
+
" self.mix_real = nn.Linear(d_model, d_model)\n",
|
| 212 |
+
" self.mix_imag = nn.Linear(d_model, d_model)\n",
|
| 213 |
+
" self.out_real = nn.Linear(d_model, d_model)\n",
|
| 214 |
+
" self.out_imag = nn.Linear(d_model, d_model)\n",
|
| 215 |
+
" self.activation = ModReLU(d_model)\n",
|
| 216 |
+
" self.norm = RobustPhaseNorm(d_model)\n",
|
| 217 |
+
" self.dropout = ComplexDropout(dropout)\n",
|
| 218 |
+
"\n",
|
| 219 |
+
" def forward(self, x, src_mask=None):\n",
|
| 220 |
+
" residual = x\n",
|
| 221 |
+
" x_norm = self.norm(x)\n",
|
| 222 |
+
" if src_mask is not None:\n",
|
| 223 |
+
" x_norm = x_norm.masked_fill(src_mask.unsqueeze(-1), 0.0)\n",
|
| 224 |
+
"\n",
|
| 225 |
+
" # 1. Global Beam (FFT + Hyena)\n",
|
| 226 |
+
" B, L, D = x_norm.shape\n",
|
| 227 |
+
" eff_L = min(L, self.filter_len)\n",
|
| 228 |
+
" x_freq = torch.fft.fft(x_norm, n=eff_L, dim=1, norm='ortho')\n",
|
| 229 |
+
" h = self.neural_filter(eff_L, x.device).unsqueeze(0)\n",
|
| 230 |
+
" x_filtered = x_freq * h\n",
|
| 231 |
+
" x_time = torch.fft.ifft(x_filtered, n=eff_L, dim=1, norm='ortho')\n",
|
| 232 |
+
" if L > eff_L: x_time = F.pad(x_time, (0,0,0,L-eff_L))\n",
|
| 233 |
+
" else: x_time = x_time[:, :L, :]\n",
|
| 234 |
+
"\n",
|
| 235 |
+
" # 2. Gating\n",
|
| 236 |
+
" gates = torch.sigmoid(self.gate_proj(torch.cat([x_norm.real, x_norm.imag], dim=-1)))\n",
|
| 237 |
+
" g_r, g_i = gates.chunk(2, dim=-1)\n",
|
| 238 |
+
" x_gated = torch.complex(x_time.real * g_r, x_time.imag * g_i)\n",
|
| 239 |
+
"\n",
|
| 240 |
+
" # 3. Mixing & Out\n",
|
| 241 |
+
" mr, mi = self.mix_real, self.mix_imag\n",
|
| 242 |
+
" x_mixed = torch.complex(mr(x_gated.real) - mi(x_gated.imag), mr(x_gated.imag) + mi(x_gated.real))\n",
|
| 243 |
+
" x_act = self.activation(x_mixed)\n",
|
| 244 |
+
" or_, oi = self.out_real, self.out_imag\n",
|
| 245 |
+
" out = torch.complex(or_(x_act.real) - oi(x_act.imag), or_(x_act.imag) + oi(x_act.real))\n",
|
| 246 |
+
" return self.dropout(out) + residual\n",
|
| 247 |
+
"\n",
|
| 248 |
+
"# ==========================================\n",
|
| 249 |
+
"# 7. MODEL WRAPPERS\n",
|
| 250 |
+
"# ==========================================\n",
|
| 251 |
+
"class PRISMEncoder(nn.Module):\n",
|
| 252 |
+
" def __init__(self, num_layers, d_model, max_len, dropout=0.1):\n",
|
| 253 |
+
" super().__init__()\n",
|
| 254 |
+
" self.layers = nn.ModuleList([\n",
|
| 255 |
+
" GatedHarmonicConvolution(d_model, max_len, dropout)\n",
|
| 256 |
+
" for _ in range(num_layers)\n",
|
| 257 |
+
" ])\n",
|
| 258 |
+
" self.final_norm = RobustPhaseNorm(d_model)\n",
|
| 259 |
+
" def forward(self, x, src_mask=None):\n",
|
| 260 |
+
" for layer in self.layers:\n",
|
| 261 |
+
" if self.training: x = torch.utils.checkpoint.checkpoint(layer, x, src_mask, use_reentrant=False)\n",
|
| 262 |
+
" else: x = layer(x, src_mask)\n",
|
| 263 |
+
" return self.final_norm(x)\n",
|
| 264 |
+
"\n",
|
| 265 |
+
"class PRISM_WikiText_Model(nn.Module):\n",
|
| 266 |
+
" def __init__(self, vocab_size, d_model, max_len, prism_depth=5, trans_depth=1, dropout=0.1):\n",
|
| 267 |
+
" super().__init__()\n",
|
| 268 |
+
" self.d_model = d_model\n",
|
| 269 |
+
"\n",
|
| 270 |
+
" # 1. PRISM Core (The Optical/Passive Part)\n",
|
| 271 |
+
" self.rose = DynamicRoSE(vocab_size, d_model)\n",
|
| 272 |
+
" self.prism_encoder = PRISMEncoder(prism_depth, d_model, max_len=max_len, dropout=dropout)\n",
|
| 273 |
+
" self.bridge = ComplexToRealBridge(d_model)\n",
|
| 274 |
+
" self.periscope_proj = nn.Sequential(nn.Linear(d_model * 2, d_model), nn.LayerNorm(d_model), nn.GELU())\n",
|
| 275 |
+
"\n",
|
| 276 |
+
" # 2. Refiner (The Digital/Active Part)\n",
|
| 277 |
+
" # 🔄 SWAPPED: Replaced Standard Transformer with RoPE-Enabled Encoder\n",
|
| 278 |
+
" if trans_depth > 0:\n",
|
| 279 |
+
" self.refiner = Encoder(\n",
|
| 280 |
+
" dim=d_model,\n",
|
| 281 |
+
" depth=trans_depth,\n",
|
| 282 |
+
" heads=8,\n",
|
| 283 |
+
" rotary_pos_emb=True,\n",
|
| 284 |
+
" attn_flash=True,\n",
|
| 285 |
+
" attn_dropout=dropout,\n",
|
| 286 |
+
" ff_dropout=dropout,\n",
|
| 287 |
+
"\n",
|
| 288 |
+
" )\n",
|
| 289 |
+
" else:\n",
|
| 290 |
+
" self.refiner = None\n",
|
| 291 |
+
"\n",
|
| 292 |
+
" # 3. Output\n",
|
| 293 |
+
" self.lm_head = nn.Linear(d_model, vocab_size)\n",
|
| 294 |
+
" self.lm_head.weight = self.rose.raw_embedding.weight\n",
|
| 295 |
+
"\n",
|
| 296 |
+
" def forward(self, input_ids):\n",
|
| 297 |
+
" # A. Wave Physics\n",
|
| 298 |
+
" wave_src, particle_src = self.rose(input_ids)\n",
|
| 299 |
+
" wave_out = self.prism_encoder(wave_src)\n",
|
| 300 |
+
" wave_real = self.bridge(wave_out)\n",
|
| 301 |
+
"\n",
|
| 302 |
+
" # B. Interface\n",
|
| 303 |
+
" mixed_memory = self.periscope_proj(torch.cat([wave_real, particle_src], dim=-1))\n",
|
| 304 |
+
"\n",
|
| 305 |
+
" # C. Digital Refinement (Now with RoPE)\n",
|
| 306 |
+
" if self.refiner:\n",
|
| 307 |
+
" out = self.refiner(mixed_memory)\n",
|
| 308 |
+
" else:\n",
|
| 309 |
+
" out = mixed_memory\n",
|
| 310 |
+
"\n",
|
| 311 |
+
" return self.lm_head(out)"
|
| 312 |
+
],
|
| 313 |
+
"metadata": {
|
| 314 |
+
"id": "V7DOwmmUjyin"
|
| 315 |
+
},
|
| 316 |
+
"execution_count": null,
|
| 317 |
+
"outputs": []
|
| 318 |
+
},
|
| 319 |
+
{
|
| 320 |
+
"cell_type": "code",
|
| 321 |
+
"source": [
|
| 322 |
+
"# ==========================================\n",
|
| 323 |
+
"# 4. LOGGING UTILITIES\n",
|
| 324 |
+
"# ==========================================\n",
|
| 325 |
+
"def generate_run_id():\n",
|
| 326 |
+
" raw = datetime.now().strftime(\"%Y%m%d%H%M%S%f\")\n",
|
| 327 |
+
" return hashlib.md5(raw.encode()).hexdigest()[:8]\n",
|
| 328 |
+
"\n",
|
| 329 |
+
"def log_environment(save_dir, run_id, config):\n",
|
| 330 |
+
" log_path = os.path.join(save_dir, f\"env_metadata_{run_id}.txt\")\n",
|
| 331 |
+
" with open(log_path, \"w\") as f:\n",
|
| 332 |
+
" f.write(f\"PRISM EXPERIMENT METADATA | Run ID: {run_id}\\n{'='*50}\\n\")\n",
|
| 333 |
+
" for k, v in config.items(): f.write(f\"{k}: {v}\\n\")\n",
|
| 334 |
+
" print(f\"📝 Environment Snapshot saved to: {log_path}\")\n",
|
| 335 |
+
"\n",
|
| 336 |
+
"def log_metrics(save_dir, run_id, epoch, train_loss, val_loss, ppl):\n",
|
| 337 |
+
" log_path = os.path.join(save_dir, f\"metrics_log_{run_id}.csv\")\n",
|
| 338 |
+
" if not os.path.exists(log_path):\n",
|
| 339 |
+
" with open(log_path, \"w\") as f: f.write(\"Timestamp,Epoch,Train_Loss,Val_Loss,Perplexity\\n\")\n",
|
| 340 |
+
" with open(log_path, \"a\") as f:\n",
|
| 341 |
+
" ts = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n",
|
| 342 |
+
" f.write(f\"{ts},{epoch},{train_loss:.6f},{val_loss:.6f},{ppl:.6f}\\n\")\n",
|
| 343 |
+
"\n",
|
| 344 |
+
"\n",
|
| 345 |
+
"def save_checkpoint(path, model, optimizer, scheduler, epoch, best_loss, config):\n",
|
| 346 |
+
" torch.save({\n",
|
| 347 |
+
" 'epoch': epoch,\n",
|
| 348 |
+
" 'model_state_dict': model.state_dict(),\n",
|
| 349 |
+
" 'optimizer_state_dict': optimizer.state_dict(),\n",
|
| 350 |
+
" 'scheduler_state_dict': scheduler.state_dict(),\n",
|
| 351 |
+
" 'best_val_loss': best_loss,\n",
|
| 352 |
+
" 'config': config\n",
|
| 353 |
+
" }, path)\n",
|
| 354 |
+
"\n",
|
| 355 |
+
"\n",
|
| 356 |
+
"def run_wikitext_training(experiment_name=\"PRISM2_WT103_40epochs\"):\n",
|
| 357 |
+
" from google.colab import drive\n",
|
| 358 |
+
" if not os.path.exists('/content/drive'): drive.mount('/content/drive')\n",
|
| 359 |
+
"\n",
|
| 360 |
+
" # --- SETUP DIRS ---\n",
|
| 361 |
+
" if RESUME_PATH and os.path.exists(RESUME_PATH):\n",
|
| 362 |
+
" print(f\"🔄 RESUMING FROM: {RESUME_PATH}\")\n",
|
| 363 |
+
" checkpoint = torch.load(RESUME_PATH, map_location=DEVICE)\n",
|
| 364 |
+
" SAVE_DIR = os.path.dirname(RESUME_PATH)\n",
|
| 365 |
+
" run_id = checkpoint.get('config', {}).get('run_id', 'resumed')\n",
|
| 366 |
+
" else:\n",
|
| 367 |
+
" run_id = hashlib.md5(datetime.now().strftime(\"%Y%m%d%H%M%S%f\").encode()).hexdigest()[:8]\n",
|
| 368 |
+
" timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n",
|
| 369 |
+
" folder_name = f\"{experiment_name}_{timestamp}_{run_id}\"\n",
|
| 370 |
+
" SAVE_DIR = os.path.join(\"/content/drive/My Drive/PRISM_Experiments\", folder_name)\n",
|
| 371 |
+
" os.makedirs(SAVE_DIR, exist_ok=True)\n",
|
| 372 |
+
" print(f\"💾 Checkpoints: {SAVE_DIR}\")\n",
|
| 373 |
+
"\n",
|
| 374 |
+
" writer = SummaryWriter(log_dir=SAVE_DIR)\n",
|
| 375 |
+
" GRAD_ACCUM = 4\n",
|
| 376 |
+
"\n",
|
| 377 |
+
" lm_datasets, data_collator = prepare_data_from_hub()\n",
|
| 378 |
+
"\n",
|
| 379 |
+
" # WORKERS=2 (Safe for Colab)\n",
|
| 380 |
+
" train_loader = DataLoader(\n",
|
| 381 |
+
" lm_datasets[\"train\"], batch_size=BATCH_SIZE, shuffle=True,\n",
|
| 382 |
+
" collate_fn=data_collator, num_workers=2, pin_memory=True,\n",
|
| 383 |
+
" prefetch_factor=2, persistent_workers=True\n",
|
| 384 |
+
" )\n",
|
| 385 |
+
" valid_loader = DataLoader(\n",
|
| 386 |
+
" lm_datasets[\"validation\"], batch_size=BATCH_SIZE,\n",
|
| 387 |
+
" collate_fn=data_collator, num_workers=2, pin_memory=True\n",
|
| 388 |
+
" )\n",
|
| 389 |
+
" test_loader = DataLoader(\n",
|
| 390 |
+
" lm_datasets[\"test\"], batch_size=BATCH_SIZE,\n",
|
| 391 |
+
" collate_fn=data_collator, num_workers=2, pin_memory=True\n",
|
| 392 |
+
" )\n",
|
| 393 |
+
"\n",
|
| 394 |
+
" print(\"\\n⚡ INITIALIZING MODEL...\")\n",
|
| 395 |
+
" model = PRISM_WikiText_Model(\n",
|
| 396 |
+
" vocab_size=VOCAB_SIZE, d_model=D_MODEL, max_len=SEQ_LEN,\n",
|
| 397 |
+
" prism_depth=DEPTH-1, trans_depth=1, dropout=DROPOUT\n",
|
| 398 |
+
" ).to(DEVICE)\n",
|
| 399 |
+
"\n",
|
| 400 |
+
" optimizer = optim.AdamW(model.parameters(), lr=LR, weight_decay=0.0)\n",
|
| 401 |
+
" total_steps = (len(train_loader) // GRAD_ACCUM) * EPOCHS\n",
|
| 402 |
+
" scheduler = get_cosine_schedule_with_warmup(\n",
|
| 403 |
+
" optimizer, num_warmup_steps=int(0.1 * total_steps), num_training_steps=total_steps\n",
|
| 404 |
+
" )\n",
|
| 405 |
+
" criterion = nn.CrossEntropyLoss()\n",
|
| 406 |
+
"\n",
|
| 407 |
+
" start_epoch = 0\n",
|
| 408 |
+
" best_val_loss = float('inf')\n",
|
| 409 |
+
"\n",
|
| 410 |
+
" if RESUME_PATH and os.path.exists(RESUME_PATH):\n",
|
| 411 |
+
" model.load_state_dict(checkpoint['model_state_dict'])\n",
|
| 412 |
+
" optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n",
|
| 413 |
+
" scheduler.load_state_dict(checkpoint['scheduler_state_dict'])\n",
|
| 414 |
+
" start_epoch = checkpoint['epoch'] + 1\n",
|
| 415 |
+
" best_val_loss = checkpoint['best_val_loss']\n",
|
| 416 |
+
" del checkpoint\n",
|
| 417 |
+
" torch.cuda.empty_cache()\n",
|
| 418 |
+
" else:\n",
|
| 419 |
+
" def init_weights_PRISM(m):\n",
|
| 420 |
+
" if isinstance(m, nn.Linear):\n",
|
| 421 |
+
" nn.init.xavier_uniform_(m.weight)\n",
|
| 422 |
+
" if m.bias is not None: nn.init.zeros_(m.bias)\n",
|
| 423 |
+
" elif isinstance(m, nn.Embedding):\n",
|
| 424 |
+
" nn.init.normal_(m.weight, std=D_MODEL**-0.5)\n",
|
| 425 |
+
" model.apply(init_weights_PRISM)\n",
|
| 426 |
+
" nn.init.normal_(model.rose.rotation_predictor.weight, std=0.01)\n",
|
| 427 |
+
" with torch.no_grad():\n",
|
| 428 |
+
" model.rose.rotation_predictor.bias[:D_MODEL].fill_(1.0)\n",
|
| 429 |
+
" model.rose.rotation_predictor.bias[D_MODEL:].fill_(0.0)\n",
|
| 430 |
+
"\n",
|
| 431 |
+
" print(f\"\\n🚀 STARTING (Ep {start_epoch+1} to {EPOCHS})\")\n",
|
| 432 |
+
" global_step = (len(train_loader) // GRAD_ACCUM) * start_epoch\n",
|
| 433 |
+
"\n",
|
| 434 |
+
" for epoch in range(start_epoch, EPOCHS):\n",
|
| 435 |
+
" model.train()\n",
|
| 436 |
+
" pbar = tqdm(train_loader, desc=f\"Ep {epoch+1}/{EPOCHS}\")\n",
|
| 437 |
+
"\n",
|
| 438 |
+
" for step, batch in enumerate(pbar):\n",
|
| 439 |
+
" x, y = batch['input_ids'].to(DEVICE), batch['labels'].to(DEVICE)\n",
|
| 440 |
+
"\n",
|
| 441 |
+
" # Forward\n",
|
| 442 |
+
" loss = criterion(model(x).view(-1, VOCAB_SIZE), y.view(-1)) / GRAD_ACCUM\n",
|
| 443 |
+
" loss.backward()\n",
|
| 444 |
+
"\n",
|
| 445 |
+
" # Step (Every 4 batches)\n",
|
| 446 |
+
" if (step + 1) % GRAD_ACCUM == 0:\n",
|
| 447 |
+
" # 1. Calc Norm\n",
|
| 448 |
+
" grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n",
|
| 449 |
+
"\n",
|
| 450 |
+
" # 2. Step\n",
|
| 451 |
+
" optimizer.step()\n",
|
| 452 |
+
" scheduler.step()\n",
|
| 453 |
+
" optimizer.zero_grad()\n",
|
| 454 |
+
" global_step += 1\n",
|
| 455 |
+
"\n",
|
| 456 |
+
" # 3. UPDATE BAR WITH GNORM\n",
|
| 457 |
+
" actual_loss = loss.item() * GRAD_ACCUM\n",
|
| 458 |
+
" writer.add_scalar('Train/Loss', actual_loss, global_step)\n",
|
| 459 |
+
"\n",
|
| 460 |
+
" # <--- FIXED LINE HERE:\n",
|
| 461 |
+
" pbar.set_postfix({\n",
|
| 462 |
+
" 'loss': f\"{actual_loss:.4f}\",\n",
|
| 463 |
+
" 'gnorm': f\"{grad_norm.item():.2f}\"\n",
|
| 464 |
+
" })\n",
|
| 465 |
+
"\n",
|
| 466 |
+
" # VALIDATION\n",
|
| 467 |
+
" model.eval()\n",
|
| 468 |
+
" val_loss = 0\n",
|
| 469 |
+
" with torch.no_grad():\n",
|
| 470 |
+
" for batch in valid_loader:\n",
|
| 471 |
+
" x, y = batch['input_ids'].to(DEVICE), batch['labels'].to(DEVICE)\n",
|
| 472 |
+
" val_loss += criterion(model(x).view(-1, VOCAB_SIZE), y.view(-1)).item()\n",
|
| 473 |
+
"\n",
|
| 474 |
+
" avg_val_loss = val_loss / len(valid_loader)\n",
|
| 475 |
+
" ppl = math.exp(avg_val_loss) if avg_val_loss < 100 else float('inf')\n",
|
| 476 |
+
"\n",
|
| 477 |
+
" print(f\"✨ Epoch {epoch+1} | Val Loss: {avg_val_loss:.4f} | PPL: {ppl:.2f}\")\n",
|
| 478 |
+
" writer.add_scalar('Val/PPL', ppl, epoch+1)\n",
|
| 479 |
+
"\n",
|
| 480 |
+
" config_dump = {\"epoch\": epoch, \"run_id\": run_id}\n",
|
| 481 |
+
" save_checkpoint(os.path.join(SAVE_DIR, \"last.pt\"), model, optimizer, scheduler, epoch, best_val_loss, config_dump)\n",
|
| 482 |
+
"\n",
|
| 483 |
+
" if avg_val_loss < best_val_loss:\n",
|
| 484 |
+
" best_val_loss = avg_val_loss\n",
|
| 485 |
+
" torch.save(model.state_dict(), os.path.join(SAVE_DIR, \"best.pt\"))\n",
|
| 486 |
+
" print(\" 🏆 New Best Model Saved!\")\n",
|
| 487 |
+
"\n",
|
| 488 |
+
" # TEST\n",
|
| 489 |
+
" best_path = os.path.join(SAVE_DIR, \"best.pt\")\n",
|
| 490 |
+
" if os.path.exists(best_path):\n",
|
| 491 |
+
" model.load_state_dict(torch.load(best_path))\n",
|
| 492 |
+
" model.eval()\n",
|
| 493 |
+
" test_loss = 0\n",
|
| 494 |
+
" with torch.no_grad():\n",
|
| 495 |
+
" for batch in tqdm(test_loader, desc=\"Testing\"):\n",
|
| 496 |
+
" x, y = batch['input_ids'].to(DEVICE), batch['labels'].to(DEVICE)\n",
|
| 497 |
+
" test_loss += criterion(model(x).view(-1, VOCAB_SIZE), y.view(-1)).item()\n",
|
| 498 |
+
" print(f\"🏆 FINAL PPL: {math.exp(test_loss/len(test_loader)):.2f}\")\n",
|
| 499 |
+
"\n",
|
| 500 |
+
" writer.close()\n",
|
| 501 |
+
" return model"
|
| 502 |
+
],
|
| 503 |
+
"metadata": {
|
| 504 |
+
"id": "-TNEv89gkS1k"
|
| 505 |
+
},
|
| 506 |
+
"execution_count": null,
|
| 507 |
+
"outputs": []
|
| 508 |
+
},
|
| 509 |
+
{
|
| 510 |
+
"cell_type": "code",
|
| 511 |
+
"source": [
|
| 512 |
+
"def analyze_prism_params(model):\n",
|
| 513 |
+
" print(\"=\"*80)\n",
|
| 514 |
+
" print(f\"📊 LEAN PRISM-2 PARAMETER ANALYSIS\")\n",
|
| 515 |
+
" print(\"=\"*80)\n",
|
| 516 |
+
" total_params = sum(p.numel() for p in model.parameters())\n",
|
| 517 |
+
" # Embeddings (Shared)\n",
|
| 518 |
+
" vocab_params = model.rose.raw_embedding.weight.numel()\n",
|
| 519 |
+
" # Wave Engine\n",
|
| 520 |
+
" enc_params = sum(p.numel() for p in model.prism_encoder.parameters())\n",
|
| 521 |
+
" # Transformer Refiner\n",
|
| 522 |
+
" ref_params = sum(p.numel() for p in model.refiner.parameters()) if model.refiner else 0\n",
|
| 523 |
+
" # Other\n",
|
| 524 |
+
" other_params = total_params - vocab_params - enc_params - ref_params\n",
|
| 525 |
+
"\n",
|
| 526 |
+
" print(f\"{'Shared Embeddings (Particle)':<35} | {vocab_params:<15,} | {vocab_params/total_params:.1%} | Tied\")\n",
|
| 527 |
+
" print(f\"{'PRISM Optical Engine':<35} | {enc_params:<15,} | {enc_params/total_params:.1%} | 5 Layers\")\n",
|
| 528 |
+
" print(f\"{'Digital Refiner':<35} | {ref_params:<15,} | {ref_params/total_params:.1%} | 1 Layer\")\n",
|
| 529 |
+
" print(\"=\"*80)\n",
|
| 530 |
+
" print(f\"{'TOTAL PARAMETERS':<35} | {total_params:<15,} | 100.0%\")\n",
|
| 531 |
+
" print(\"=\"*80)\n",
|
| 532 |
+
"\n",
|
| 533 |
+
"\n",
|
| 534 |
+
"if __name__ == \"__main__\":\n",
|
| 535 |
+
"\n",
|
| 536 |
+
" print(\"🏗️ INSTANTIATING MODEL FOR INSPECTION...\")\n",
|
| 537 |
+
" # Initialize a temporary model just for counting\n",
|
| 538 |
+
" dummy_model = PRISM_WikiText_Model(\n",
|
| 539 |
+
" vocab_size=VOCAB_SIZE,\n",
|
| 540 |
+
" d_model=D_MODEL,\n",
|
| 541 |
+
" max_len=SEQ_LEN,\n",
|
| 542 |
+
" prism_depth=DEPTH-1,\n",
|
| 543 |
+
" trans_depth=1,\n",
|
| 544 |
+
" dropout=DROPOUT\n",
|
| 545 |
+
" )\n",
|
| 546 |
+
"\n",
|
| 547 |
+
" # 2. Run Analysis\n",
|
| 548 |
+
" analyze_prism_params(dummy_model)\n",
|
| 549 |
+
"\n",
|
| 550 |
+
" # 3. Clean up to free RAM for actual training\n",
|
| 551 |
+
" del dummy_model\n",
|
| 552 |
+
" gc.collect()\n",
|
| 553 |
+
" torch.cuda.empty_cache()\n",
|
| 554 |
+
"\n",
|
| 555 |
+
" # 4. Ask for confirmation (Optional, or just proceed)\n",
|
| 556 |
+
" print(\"\\n✅ Analysis Complete. Starting Training Routine in 5 seconds...\")\n",
|
| 557 |
+
" import time\n",
|
| 558 |
+
" time.sleep(5)\n",
|
| 559 |
+
"\n",
|
| 560 |
+
" # 5. Start Training\n",
|
| 561 |
+
" trained_prism = run_wikitext_training()\n",
|
| 562 |
+
"\n",
|
| 563 |
+
" # 6. Final Analysis (Post-training check)\n",
|
| 564 |
+
" analyze_prism_params(trained_prism)\n",
|
| 565 |
+
"\n",
|
| 566 |
+
" # 7. Kill Runtime (Colab specific)\n",
|
| 567 |
+
" from google.colab import runtime\n",
|
| 568 |
+
" runtime.unassign()"
|
| 569 |
+
],
|
| 570 |
+
"metadata": {
|
| 571 |
+
"id": "KaiJU0tPkVp-"
|
| 572 |
+
},
|
| 573 |
+
"execution_count": null,
|
| 574 |
+
"outputs": []
|
| 575 |
+
},
|
| 576 |
+
{
|
| 577 |
+
"cell_type": "code",
|
| 578 |
+
"source": [
|
| 579 |
+
"from google.colab import runtime\n",
|
| 580 |
+
"runtime.unassign()"
|
| 581 |
+
],
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"nbformat": 4,
|
| 3 |
+
"nbformat_minor": 0,
|
| 4 |
+
"metadata": {
|
| 5 |
+
"colab": {
|
| 6 |
+
"provenance": [],
|
| 7 |
+
"gpuType": "A100"
|
| 8 |
+
},
|
| 9 |
+
"kernelspec": {
|
| 10 |
+
"name": "python3",
|
| 11 |
+
"display_name": "Python 3"
|
| 12 |
+
},
|
| 13 |
+
"language_info": {
|
| 14 |
+
"name": "python"
|
| 15 |
+
},
|
| 16 |
+
"accelerator": "GPU"
|
| 17 |
+
},
|
| 18 |
+
"cells": [
|
| 19 |
+
{
|
| 20 |
+
"cell_type": "code",
|
| 21 |
+
"source": [
|
| 22 |
+
"!pip install -q x-transformers\n",
|
| 23 |
+
"!pip install -q flash-attn --no-build-isolation"
|
| 24 |
+
],
|
| 25 |
+
"metadata": {
|
| 26 |
+
"id": "6q9RTvlf5IiS"
|
| 27 |
+
},
|
| 28 |
+
"execution_count": null,
|
| 29 |
+
"outputs": []
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"cell_type": "code",
|
| 33 |
+
"source": [
|
| 34 |
+
"import torch\n",
|
| 35 |
+
"import torch.nn as nn\n",
|
| 36 |
+
"import torch.nn.functional as F\n",
|
| 37 |
+
"import torch.optim as optim\n",
|
| 38 |
+
"import math\n",
|
| 39 |
+
"import os\n",
|
| 40 |
+
"import sys\n",
|
| 41 |
+
"import subprocess\n",
|
| 42 |
+
"import hashlib\n",
|
| 43 |
+
"import gc\n",
|
| 44 |
+
"from datetime import datetime\n",
|
| 45 |
+
"from tqdm.auto import tqdm\n",
|
| 46 |
+
"from torch.utils.data import DataLoader\n",
|
| 47 |
+
"from torch.utils.tensorboard import SummaryWriter\n",
|
| 48 |
+
"from transformers import RobertaTokenizerFast, get_cosine_schedule_with_warmup, DataCollatorForLanguageModeling\n",
|
| 49 |
+
"from datasets import load_dataset\n",
|
| 50 |
+
"from x_transformers import Encoder\n",
|
| 51 |
+
"\n",
|
| 52 |
+
"# ==========================================\n",
|
| 53 |
+
"# 1. CONFIGURATION\n",
|
| 54 |
+
"# ==========================================\n",
|
| 55 |
+
"# YOUR REPO ID (Created in previous step)\n",
|
| 56 |
+
"HF_ID = \"prism-lab/wikitext-103-prism-32k-seq4k\"\n",
|
| 57 |
+
"\n",
|
| 58 |
+
"# Hyperparameters\n",
|
| 59 |
+
"VOCAB_SIZE = 32768\n",
|
| 60 |
+
"SEQ_LEN = 4096\n",
|
| 61 |
+
"BATCH_SIZE = 8\n",
|
| 62 |
+
"EPOCHS = 40\n",
|
| 63 |
+
"LR = 1e-3\n",
|
| 64 |
+
"D_MODEL = 512\n",
|
| 65 |
+
"D_BRANCH = 256\n",
|
| 66 |
+
"DEPTH = 6\n",
|
| 67 |
+
"RESUME_PATH = None #\"/content/drive/MyDrive/PRISM_Experiments/PILLARS_SplitStream_8Layer_20260116_025321_8438ce62/last.pt\"\n",
|
| 68 |
+
"DEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 69 |
+
"torch.set_float32_matmul_precision(\"high\")\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"# ==========================================\n",
|
| 72 |
+
"# 2. DATA PIPELINE (The \"Pro\" Way)\n",
|
| 73 |
+
"# ==========================================\n",
|
| 74 |
+
"def prepare_data_from_hub():\n",
|
| 75 |
+
" print(f\"⬇️ Pulling Pre-Tokenized Data from {HF_ID}...\")\n",
|
| 76 |
+
"\n",
|
| 77 |
+
" # 1. Load Tokenizer (Instant)\n",
|
| 78 |
+
" # This pulls the exact tokenizer you uploaded\n",
|
| 79 |
+
" tokenizer = RobertaTokenizerFast.from_pretrained(HF_ID)\n",
|
| 80 |
+
"\n",
|
| 81 |
+
" # 2. Load Dataset (Instant)\n",
|
| 82 |
+
" # This pulls the already chunked/tokenized data\n",
|
| 83 |
+
" dataset = load_dataset(HF_ID)\n",
|
| 84 |
+
"\n",
|
| 85 |
+
" print(f\"✅ Loaded {len(dataset['train'])} training chunks.\")\n",
|
| 86 |
+
"\n",
|
| 87 |
+
" # 3. Collator\n",
|
| 88 |
+
" data_collator = DataCollatorForLanguageModeling(\n",
|
| 89 |
+
" tokenizer=tokenizer,\n",
|
| 90 |
+
" mlm=True,\n",
|
| 91 |
+
" mlm_probability=0.15\n",
|
| 92 |
+
" )\n",
|
| 93 |
+
"\n",
|
| 94 |
+
" return dataset, data_collator\n",
|
| 95 |
+
"# ==========================================\n",
|
| 96 |
+
"# 3. PRISM ARCHITECTURE (Complex-Valued)\n",
|
| 97 |
+
"# ==========================================\n",
|
| 98 |
+
"\n",
|
| 99 |
+
"class ComplexDropout(nn.Module):\n",
|
| 100 |
+
" def __init__(self, p=0.5):\n",
|
| 101 |
+
" super().__init__()\n",
|
| 102 |
+
" self.p = p\n",
|
| 103 |
+
" def forward(self, z):\n",
|
| 104 |
+
" if not self.training or self.p == 0.0: return z\n",
|
| 105 |
+
" mask = torch.ones_like(z.real)\n",
|
| 106 |
+
" mask = F.dropout(mask, self.p, self.training, inplace=False)\n",
|
| 107 |
+
" return z * mask\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"class RobustPhaseNorm(nn.Module):\n",
|
| 110 |
+
" def __init__(self, d_model, eps=1e-5):\n",
|
| 111 |
+
" super().__init__()\n",
|
| 112 |
+
" self.scale = nn.Parameter(torch.ones(d_model))\n",
|
| 113 |
+
" self.eps = eps\n",
|
| 114 |
+
" def forward(self, x):\n",
|
| 115 |
+
" mag = torch.abs(x)\n",
|
| 116 |
+
" rms = torch.sqrt(torch.mean(mag**2, dim=-1, keepdim=True) + self.eps)\n",
|
| 117 |
+
" return (x / rms) * self.scale\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"class ModReLU(nn.Module):\n",
|
| 120 |
+
" def __init__(self, features):\n",
|
| 121 |
+
" super().__init__()\n",
|
| 122 |
+
" self.b = nn.Parameter(torch.zeros(features))\n",
|
| 123 |
+
"\n",
|
| 124 |
+
" def forward(self, z):\n",
|
| 125 |
+
" # 1. FORCE FLOAT32 FOR GEOMETRY\n",
|
| 126 |
+
" # We must calculate magnitude in high precision to prevent\n",
|
| 127 |
+
" # square-law overflow (Re^2 + Im^2) from killing the gradients.\n",
|
| 128 |
+
" z_32 = z.to(torch.complex64)\n",
|
| 129 |
+
"\n",
|
| 130 |
+
" # 2. Calculate Magnitude (Safe)\n",
|
| 131 |
+
" mag = torch.abs(z_32)\n",
|
| 132 |
+
"\n",
|
| 133 |
+
" # 3. Activation Logic (Still FP32)\n",
|
| 134 |
+
" new_mag = F.relu(mag + self.b.float())\n",
|
| 135 |
+
"\n",
|
| 136 |
+
" # 4. Reconstruct Phase (Safe Division)\n",
|
| 137 |
+
" # (z / mag) is the unit vector (phase)\n",
|
| 138 |
+
" phase = z_32 / (mag + 1e-6)\n",
|
| 139 |
+
"\n",
|
| 140 |
+
" # 5. Result\n",
|
| 141 |
+
" out = new_mag * phase\n",
|
| 142 |
+
"\n",
|
| 143 |
+
" # 6. Cast back to network dtype (BF16/FP16)\n",
|
| 144 |
+
" return out.to(z.dtype)\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"class ComplexToRealBridge(nn.Module):\n",
|
| 147 |
+
" def __init__(self, d_model):\n",
|
| 148 |
+
" super().__init__()\n",
|
| 149 |
+
" self.proj = nn.Linear(d_model * 2, d_model)\n",
|
| 150 |
+
" self.norm = nn.LayerNorm(d_model)\n",
|
| 151 |
+
" def forward(self, x_complex):\n",
|
| 152 |
+
" cat = torch.cat([x_complex.real, x_complex.imag], dim=-1)\n",
|
| 153 |
+
" return self.norm(self.proj(cat))\n",
|
| 154 |
+
"\n",
|
| 155 |
+
"# ==========================================\n",
|
| 156 |
+
"# 4. DYNAMIC RoSE (Mamba-3 Engine)\n",
|
| 157 |
+
"# ==========================================\n",
|
| 158 |
+
"class DynamicRoSE(nn.Module):\n",
|
| 159 |
+
" def __init__(self, num_embeddings, embedding_dim, max_period=10000.0):\n",
|
| 160 |
+
" super().__init__()\n",
|
| 161 |
+
" self.embedding_dim = embedding_dim\n",
|
| 162 |
+
"\n",
|
| 163 |
+
" # 1. Master Real Embedding (The \"Particle\")\n",
|
| 164 |
+
" self.raw_embedding = nn.Embedding(num_embeddings, embedding_dim)\n",
|
| 165 |
+
"\n",
|
| 166 |
+
" # 2. Complex Adapter (The \"Wave\" Magnitude/Initial Phase)\n",
|
| 167 |
+
" self.adapter = nn.Linear(embedding_dim, embedding_dim * 2)\n",
|
| 168 |
+
"\n",
|
| 169 |
+
" # 3. Static Frequencies (Positional)\n",
|
| 170 |
+
" freqs = torch.exp(torch.arange(0, embedding_dim, dtype=torch.float32) * -(math.log(max_period) / embedding_dim))\n",
|
| 171 |
+
" self.register_buffer('freqs', freqs)\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" self.rotation_predictor = nn.Linear(embedding_dim, embedding_dim * 2)\n",
|
| 174 |
+
"\n",
|
| 175 |
+
" def forward(self, input_ids):\n",
|
| 176 |
+
" # A. Raw Particle\n",
|
| 177 |
+
" real_base = self.raw_embedding(input_ids)\n",
|
| 178 |
+
" B, L, D = real_base.shape\n",
|
| 179 |
+
"\n",
|
| 180 |
+
" # B. Complex Wave Content\n",
|
| 181 |
+
" complex_params = self.adapter(real_base)\n",
|
| 182 |
+
" z_t = torch.complex(complex_params[..., :D], complex_params[..., D:])\n",
|
| 183 |
+
"\n",
|
| 184 |
+
" rot_raw = self.rotation_predictor(real_base)\n",
|
| 185 |
+
" rot_x, rot_y = rot_raw.chunk(2, dim=-1)\n",
|
| 186 |
+
"\n",
|
| 187 |
+
" rot_mag = torch.sqrt(rot_x**2 + rot_y**2 + 1e-6)\n",
|
| 188 |
+
" dynamic_rot = torch.complex(rot_x / rot_mag, rot_y / rot_mag)\n",
|
| 189 |
+
"\n",
|
| 190 |
+
" # D. Static Positional Rotation\n",
|
| 191 |
+
" pos = torch.arange(L, device=input_ids.device).float()\n",
|
| 192 |
+
" static_angles = torch.outer(pos, self.freqs) # [L, D]\n",
|
| 193 |
+
" static_rot = torch.polar(torch.ones_like(static_angles), static_angles) # [L, D]\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" z_final = z_t * static_rot.unsqueeze(0) * dynamic_rot\n",
|
| 196 |
+
"\n",
|
| 197 |
+
" return z_final, real_base\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"# ==========================================\n",
|
| 200 |
+
"# 5. HYENA FILTER\n",
|
| 201 |
+
"# ==========================================\n",
|
| 202 |
+
"class HyenaNeuralFilter(nn.Module):\n",
|
| 203 |
+
" def __init__(self, d_model, max_len=1024, hidden_dim=64):\n",
|
| 204 |
+
" super().__init__()\n",
|
| 205 |
+
" self.d_model = d_model\n",
|
| 206 |
+
" freqs = torch.exp(torch.arange(0, hidden_dim, 2, dtype=torch.float32) * -(math.log(10000.0) / hidden_dim))\n",
|
| 207 |
+
" self.register_buffer(\"freqs\", freqs)\n",
|
| 208 |
+
" self.mlp = nn.Sequential(\n",
|
| 209 |
+
" nn.Linear(hidden_dim, hidden_dim), nn.SiLU(),\n",
|
| 210 |
+
" nn.Linear(hidden_dim, hidden_dim), nn.SiLU(),\n",
|
| 211 |
+
" nn.Linear(hidden_dim, d_model * 2)\n",
|
| 212 |
+
" )\n",
|
| 213 |
+
" def forward(self, L, device):\n",
|
| 214 |
+
" t = torch.linspace(0, 1, steps=L, device=device).unsqueeze(-1)\n",
|
| 215 |
+
" emb = torch.cat([torch.sin(t * self.freqs), torch.cos(t * self.freqs)], dim=-1)\n",
|
| 216 |
+
" out = self.mlp(emb).view(L, self.d_model, 2)\n",
|
| 217 |
+
" return torch.complex(out[..., 0], out[..., 1])\n",
|
| 218 |
+
"\n",
|
| 219 |
+
"# ==========================================\n",
|
| 220 |
+
"# 6. GATED HARMONIC CONVOLUTION (Lean)\n",
|
| 221 |
+
"# ==========================================\n",
|
| 222 |
+
"# @title 🛠️ Fixed PRISM Layer (Precision-Gated)\n",
|
| 223 |
+
"\n",
|
| 224 |
+
"# @title 🛠️ Fixed PRISM Layer (Type-Safe)\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"class GatedHarmonicConvolution(nn.Module):\n",
|
| 227 |
+
" def __init__(self, d_model, max_len=1024, dropout=0.1):\n",
|
| 228 |
+
" super().__init__()\n",
|
| 229 |
+
" self.d_model = d_model\n",
|
| 230 |
+
" self.filter_len = max_len\n",
|
| 231 |
+
" self.neural_filter = HyenaNeuralFilter(d_model, max_len=max_len)\n",
|
| 232 |
+
" self.gate_proj = nn.Linear(d_model * 2, d_model * 2)\n",
|
| 233 |
+
"\n",
|
| 234 |
+
" self.mix_real = nn.Linear(d_model, d_model)\n",
|
| 235 |
+
" self.mix_imag = nn.Linear(d_model, d_model)\n",
|
| 236 |
+
" self.out_real = nn.Linear(d_model, d_model)\n",
|
| 237 |
+
" self.out_imag = nn.Linear(d_model, d_model)\n",
|
| 238 |
+
"\n",
|
| 239 |
+
" self.activation = ModReLU(d_model)\n",
|
| 240 |
+
" self.norm = RobustPhaseNorm(d_model)\n",
|
| 241 |
+
" self.dropout = ComplexDropout(dropout)\n",
|
| 242 |
+
"\n",
|
| 243 |
+
" def forward(self, x, src_mask=None):\n",
|
| 244 |
+
" residual = x\n",
|
| 245 |
+
" x_norm = self.norm(x)\n",
|
| 246 |
+
" if src_mask is not None:\n",
|
| 247 |
+
" x_norm = x_norm.masked_fill(src_mask.unsqueeze(-1), 0.0)\n",
|
| 248 |
+
"\n",
|
| 249 |
+
" # 🛑 PRECISION GATE 🛑\n",
|
| 250 |
+
" # Force operations to Float32 Complex to preserve Phase Physics\n",
|
| 251 |
+
" with torch.amp.autocast('cuda', enabled=False):\n",
|
| 252 |
+
"\n",
|
| 253 |
+
" # --- THE FIX IS HERE ---\n",
|
| 254 |
+
" # Old: x_32 = x_norm.float() <-- This stripped the imaginary part\n",
|
| 255 |
+
" # New: Explicit cast to Complex64\n",
|
| 256 |
+
" x_32 = x_norm.to(torch.complex64)\n",
|
| 257 |
+
" # -----------------------\n",
|
| 258 |
+
"\n",
|
| 259 |
+
" B, L, D = x_32.shape\n",
|
| 260 |
+
" eff_L = min(L, self.filter_len)\n",
|
| 261 |
+
"\n",
|
| 262 |
+
" # 1. FFT (Now safe because x_32 is definitely complex)\n",
|
| 263 |
+
" x_freq = torch.fft.fft(x_32, n=eff_L, dim=1, norm='ortho')\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" # 2. Filter (Ensure filter is also complex64)\n",
|
| 266 |
+
" h = self.neural_filter(eff_L, x.device).unsqueeze(0).to(torch.complex64)\n",
|
| 267 |
+
" x_filtered = x_freq * h\n",
|
| 268 |
+
"\n",
|
| 269 |
+
" # 3. IFFT\n",
|
| 270 |
+
" x_time = torch.fft.ifft(x_filtered, n=eff_L, dim=1, norm='ortho')\n",
|
| 271 |
+
"\n",
|
| 272 |
+
" if L > eff_L: x_time = F.pad(x_time, (0,0,0,L-eff_L))\n",
|
| 273 |
+
" else: x_time = x_time[:, :L, :]\n",
|
| 274 |
+
"\n",
|
| 275 |
+
" # 4. Gating (Sigmoid logic)\n",
|
| 276 |
+
" # Safe concatenation because x_32 is complex64\n",
|
| 277 |
+
" x_cat = torch.cat([x_32.real, x_32.imag], dim=-1)\n",
|
| 278 |
+
"\n",
|
| 279 |
+
" # Cast weights to Float32 for the calculation\n",
|
| 280 |
+
" gate_w = self.gate_proj.weight.to(torch.float32)\n",
|
| 281 |
+
" gate_b = self.gate_proj.bias.to(torch.float32)\n",
|
| 282 |
+
"\n",
|
| 283 |
+
" gate_out = F.linear(x_cat, gate_w, gate_b)\n",
|
| 284 |
+
" gates = torch.sigmoid(gate_out)\n",
|
| 285 |
+
"\n",
|
| 286 |
+
" g_r, g_i = gates.chunk(2, dim=-1)\n",
|
| 287 |
+
" x_gated_32 = torch.complex(x_time.real * g_r, x_time.imag * g_i)\n",
|
| 288 |
+
"\n",
|
| 289 |
+
" # 🏁 EXIT GATE: Cast back to original dtype (likely BFloat16 from autocast)\n",
|
| 290 |
+
" # We cast real/imag separately to be safe\n",
|
| 291 |
+
" target_dtype = x.dtype\n",
|
| 292 |
+
" # If x was complex, target is complex. If x was real, we have an issue.\n",
|
| 293 |
+
" # Assuming x comes from autocast, it might be complex16.\n",
|
| 294 |
+
"\n",
|
| 295 |
+
" x_gated = x_gated_32.to(target_dtype)\n",
|
| 296 |
+
"\n",
|
| 297 |
+
" # 5. Mixing (Back in mixed precision)\n",
|
| 298 |
+
" mr, mi = self.mix_real, self.mix_imag\n",
|
| 299 |
+
" x_mixed = torch.complex(mr(x_gated.real) - mi(x_gated.imag), mr(x_gated.imag) + mi(x_gated.real))\n",
|
| 300 |
+
"\n",
|
| 301 |
+
" x_act = self.activation(x_mixed)\n",
|
| 302 |
+
"\n",
|
| 303 |
+
" or_, oi = self.out_real, self.out_imag\n",
|
| 304 |
+
" out = torch.complex(or_(x_act.real) - oi(x_act.imag), or_(x_act.imag) + oi(x_act.real))\n",
|
| 305 |
+
"\n",
|
| 306 |
+
" return self.dropout(out) + residual\n",
|
| 307 |
+
"# ==========================================\n",
|
| 308 |
+
"# 7. MODEL WRAPPERS\n",
|
| 309 |
+
"# ==========================================\n",
|
| 310 |
+
"class PRISMEncoder(nn.Module):\n",
|
| 311 |
+
" def __init__(self, num_layers, d_model, max_len, dropout=0.1):\n",
|
| 312 |
+
" super().__init__()\n",
|
| 313 |
+
" self.layers = nn.ModuleList([\n",
|
| 314 |
+
" GatedHarmonicConvolution(d_model, max_len, dropout)\n",
|
| 315 |
+
" for _ in range(num_layers)\n",
|
| 316 |
+
" ])\n",
|
| 317 |
+
" self.final_norm = RobustPhaseNorm(d_model)\n",
|
| 318 |
+
" def forward(self, x, src_mask=None):\n",
|
| 319 |
+
" for layer in self.layers:\n",
|
| 320 |
+
" if self.training: x = torch.utils.checkpoint.checkpoint(layer, x, src_mask, use_reentrant=False)\n",
|
| 321 |
+
" else: x = layer(x, src_mask)\n",
|
| 322 |
+
" return self.final_norm(x)\n",
|
| 323 |
+
"\n",
|
| 324 |
+
"class PRISM_WikiText_Model(nn.Module):\n",
|
| 325 |
+
" def __init__(self, vocab_size, d_model, max_len, prism_depth=5, trans_depth=1, dropout=0.1):\n",
|
| 326 |
+
" super().__init__()\n",
|
| 327 |
+
" self.d_model = d_model\n",
|
| 328 |
+
"\n",
|
| 329 |
+
" # 1. PRISM Core (The Optical/Passive Part)\n",
|
| 330 |
+
" self.rose = DynamicRoSE(vocab_size, d_model)\n",
|
| 331 |
+
" self.prism_encoder = PRISMEncoder(prism_depth, d_model, max_len=max_len, dropout=dropout)\n",
|
| 332 |
+
" self.bridge = ComplexToRealBridge(d_model)\n",
|
| 333 |
+
" self.periscope_proj = nn.Sequential(nn.Linear(d_model * 2, d_model), nn.LayerNorm(d_model), nn.GELU())\n",
|
| 334 |
+
"\n",
|
| 335 |
+
" # 2. Refiner (The Digital/Active Part)\n",
|
| 336 |
+
" # 🔄 SWAPPED: Replaced Standard Transformer with RoPE-Enabled Encoder\n",
|
| 337 |
+
" if trans_depth > 0:\n",
|
| 338 |
+
" self.refiner = Encoder(\n",
|
| 339 |
+
" dim=d_model,\n",
|
| 340 |
+
" depth=trans_depth,\n",
|
| 341 |
+
" heads=8,\n",
|
| 342 |
+
" rotary_pos_emb=True,\n",
|
| 343 |
+
" attn_flash=True,\n",
|
| 344 |
+
" attn_dropout=dropout,\n",
|
| 345 |
+
" ff_dropout=dropout,\n",
|
| 346 |
+
"\n",
|
| 347 |
+
" )\n",
|
| 348 |
+
" else:\n",
|
| 349 |
+
" self.refiner = None\n",
|
| 350 |
+
"\n",
|
| 351 |
+
" # 3. Output\n",
|
| 352 |
+
" self.lm_head = nn.Linear(d_model, vocab_size)\n",
|
| 353 |
+
" self.lm_head.weight = self.rose.raw_embedding.weight\n",
|
| 354 |
+
"\n",
|
| 355 |
+
" def forward(self, input_ids):\n",
|
| 356 |
+
" # A. Wave Physics\n",
|
| 357 |
+
" wave_src, particle_src = self.rose(input_ids)\n",
|
| 358 |
+
" wave_out = self.prism_encoder(wave_src)\n",
|
| 359 |
+
" wave_real = self.bridge(wave_out)\n",
|
| 360 |
+
"\n",
|
| 361 |
+
" # B. Interface\n",
|
| 362 |
+
" mixed_memory = self.periscope_proj(torch.cat([wave_real, particle_src], dim=-1))\n",
|
| 363 |
+
"\n",
|
| 364 |
+
" # C. Digital Refinement (Now with RoPE)\n",
|
| 365 |
+
" if self.refiner:\n",
|
| 366 |
+
" out = self.refiner(mixed_memory)\n",
|
| 367 |
+
" else:\n",
|
| 368 |
+
" out = mixed_memory\n",
|
| 369 |
+
"\n",
|
| 370 |
+
" return self.lm_head(out)\n",
|
| 371 |
+
"\n",
|
| 372 |
+
"# ==========================================\n",
|
| 373 |
+
"# 1. SENSORY STREAM (Transformer + RoPE)\n",
|
| 374 |
+
"# ==========================================\n",
|
| 375 |
+
"class SensoryStream(nn.Module):\n",
|
| 376 |
+
" def __init__(self, depth, d_model, dropout=0.1):\n",
|
| 377 |
+
" super().__init__()\n",
|
| 378 |
+
" self.encoder = Encoder(\n",
|
| 379 |
+
" dim=d_model,\n",
|
| 380 |
+
" depth=depth,\n",
|
| 381 |
+
" heads=4, # 256 dim / 64 head_dim = 4 heads\n",
|
| 382 |
+
" attn_flash=True, # Flash Attention\n",
|
| 383 |
+
" rotary_pos_emb=True, # <--- CRITICAL: RoPE Enabled\n",
|
| 384 |
+
" attn_dropout=dropout,\n",
|
| 385 |
+
" ff_dropout=dropout,\n",
|
| 386 |
+
" use_rmsnorm=True, # RMSNorm (Llama style)\n",
|
| 387 |
+
" ff_glu=True # SwiGLU (Llama style)\n",
|
| 388 |
+
" )\n",
|
| 389 |
+
"\n",
|
| 390 |
+
" def forward(self, x):\n",
|
| 391 |
+
" return self.encoder(x)\n",
|
| 392 |
+
"\n",
|
| 393 |
+
"# ==========================================\n",
|
| 394 |
+
"# 2. PILLARS-DAT (Dual Attention with RoPE)\n",
|
| 395 |
+
"# ==========================================\n",
|
| 396 |
+
"class Pillars_DAT(nn.Module):\n",
|
| 397 |
+
" def __init__(self, vocab_size, d_model=512, d_branch=256, seq_len=4096, depth=4):\n",
|
| 398 |
+
" super().__init__()\n",
|
| 399 |
+
" self.d_model = d_model\n",
|
| 400 |
+
" self.d_branch = d_branch\n",
|
| 401 |
+
"\n",
|
| 402 |
+
" # --- A. SHARED ROOT ---\n",
|
| 403 |
+
" self.rose = DynamicRoSE(vocab_size, d_model)\n",
|
| 404 |
+
"\n",
|
| 405 |
+
" # --- B. DOWNSAMPLE ---\n",
|
| 406 |
+
" self.particle_down = nn.Linear(d_model, d_branch)\n",
|
| 407 |
+
" self.wave_down = nn.Linear(d_model * 2, d_branch * 2)\n",
|
| 408 |
+
"\n",
|
| 409 |
+
" # --- C. STREAM 1: SENSORY (Object Attributes) ---\n",
|
| 410 |
+
" # REPLACED: FNet -> Transformer with RoPE\n",
|
| 411 |
+
" # NOTE: No self.sensory_pos anymore! RoPE handles it.\n",
|
| 412 |
+
" self.stream_sensory = SensoryStream(depth=depth, d_model=d_branch, dropout=0.1)\n",
|
| 413 |
+
"\n",
|
| 414 |
+
" # --- D. STREAM 2: RELATIONAL (Structure / Phase) ---\n",
|
| 415 |
+
" # PRISM handles positions internally via RoSE frequencies\n",
|
| 416 |
+
" self.stream_relational = PRISMEncoder(num_layers=depth, d_model=d_branch, max_len=seq_len, dropout=0.1)\n",
|
| 417 |
+
" self.relational_bridge = ComplexToRealBridge(d_branch)\n",
|
| 418 |
+
"\n",
|
| 419 |
+
" # --- E. FUSION ---\n",
|
| 420 |
+
" self.fusion_proj = nn.Linear(d_branch * 2, d_model)\n",
|
| 421 |
+
" self.fusion_norm = nn.LayerNorm(d_model)\n",
|
| 422 |
+
"\n",
|
| 423 |
+
" # --- F. REFINER ---\n",
|
| 424 |
+
" self.refiner = Encoder(\n",
|
| 425 |
+
" dim=d_model, depth=1, heads=8, attn_flash=True,\n",
|
| 426 |
+
" rotary_pos_emb=True, attn_dropout=0.1, ff_dropout=0.1\n",
|
| 427 |
+
" )\n",
|
| 428 |
+
"\n",
|
| 429 |
+
" # --- G. OUTPUT ---\n",
|
| 430 |
+
" self.head_bias = nn.Parameter(torch.zeros(vocab_size))\n",
|
| 431 |
+
"\n",
|
| 432 |
+
" def forward(self, input_ids):\n",
|
| 433 |
+
" # 1. Root Physics\n",
|
| 434 |
+
" wave_src, particle_src = self.rose(input_ids)\n",
|
| 435 |
+
"\n",
|
| 436 |
+
" # 2. Downsample\n",
|
| 437 |
+
" p_small = self.particle_down(particle_src)\n",
|
| 438 |
+
"\n",
|
| 439 |
+
" # Prepare complex wave input\n",
|
| 440 |
+
" w_flat = torch.cat([wave_src.real, wave_src.imag], dim=-1)\n",
|
| 441 |
+
" w_small_flat = self.wave_down(w_flat)\n",
|
| 442 |
+
" w_small = torch.complex(w_small_flat[..., :self.d_branch], w_small_flat[..., self.d_branch:])\n",
|
| 443 |
+
"\n",
|
| 444 |
+
" # 3. Parallel Processing\n",
|
| 445 |
+
"\n",
|
| 446 |
+
" # --- Stream A: Sensory (Transformer + RoPE) ---\n",
|
| 447 |
+
" # Pass pure features. RoPE adds position info inside the attention layer.\n",
|
| 448 |
+
" sensory_out = self.stream_sensory(p_small)\n",
|
| 449 |
+
"\n",
|
| 450 |
+
" # --- Stream B: Relational (PRISM) ---\n",
|
| 451 |
+
" relational_out_complex = self.stream_relational(w_small)\n",
|
| 452 |
+
" relational_out = self.relational_bridge(relational_out_complex)\n",
|
| 453 |
+
"\n",
|
| 454 |
+
" # 4. Integration\n",
|
| 455 |
+
" stacked = torch.cat([sensory_out, relational_out], dim=-1)\n",
|
| 456 |
+
" context = self.fusion_norm(self.fusion_proj(stacked))\n",
|
| 457 |
+
"\n",
|
| 458 |
+
" # 5. Refinement\n",
|
| 459 |
+
" refined = self.refiner(context)\n",
|
| 460 |
+
"\n",
|
| 461 |
+
" # 6. Output\n",
|
| 462 |
+
" logits = F.linear(refined, self.rose.raw_embedding.weight, self.head_bias)\n",
|
| 463 |
+
"\n",
|
| 464 |
+
" return logits\n",
|
| 465 |
+
"\n",
|
| 466 |
+
"import torch\n",
|
| 467 |
+
"import torch.nn as nn\n",
|
| 468 |
+
"from prettytable import PrettyTable # Optional, but makes tables nice.\n",
|
| 469 |
+
"# If you don't have prettytable, the code below uses standard f-strings.\n",
|
| 470 |
+
"\n",
|
| 471 |
+
"import torch\n",
|
| 472 |
+
"import torch.nn as nn\n",
|
| 473 |
+
"\n",
|
| 474 |
+
"import torch\n",
|
| 475 |
+
"import torch.nn as nn\n",
|
| 476 |
+
"\n",
|
| 477 |
+
"def deep_analyze_pillars(model):\n",
|
| 478 |
+
" def get_p(obj):\n",
|
| 479 |
+
" \"\"\"Safely returns parameter count for Modules OR raw Parameters.\"\"\"\n",
|
| 480 |
+
" if isinstance(obj, nn.Parameter):\n",
|
| 481 |
+
" return obj.numel()\n",
|
| 482 |
+
" return sum(p.numel() for p in obj.parameters() if p.requires_grad)\n",
|
| 483 |
+
"\n",
|
| 484 |
+
" def format_num(n):\n",
|
| 485 |
+
" if n > 1e6: return f\"{n/1e6:.2f}M\"\n",
|
| 486 |
+
" if n > 1e3: return f\"{n/1e3:.2f}K\"\n",
|
| 487 |
+
" return str(n)\n",
|
| 488 |
+
"\n",
|
| 489 |
+
" print(\"\\n\" + \"=\"*80)\n",
|
| 490 |
+
" print(f\"🏗️ PILLARS (COMPACT) - DEEP LAYER ANALYSIS\")\n",
|
| 491 |
+
" print(\"=\"*80)\n",
|
| 492 |
+
" print(f\"{'MODULE / LAYER':<40} | {'PARAMS':<15} | {'TYPE'}\")\n",
|
| 493 |
+
" print(\"-\" * 80)\n",
|
| 494 |
+
"\n",
|
| 495 |
+
" total_params = get_p(model)\n",
|
| 496 |
+
"\n",
|
| 497 |
+
" # -----------------------------------------------\n",
|
| 498 |
+
" # 1. STATIC MEMORY (Embeddings)\n",
|
| 499 |
+
" # -----------------------------------------------\n",
|
| 500 |
+
" vocab_emb = get_p(model.rose.raw_embedding)\n",
|
| 501 |
+
" fnet_pos = get_p(model.fnet_pos)\n",
|
| 502 |
+
"\n",
|
| 503 |
+
" print(f\"{'Shared Vocab Embedding':<40} | {format_num(vocab_emb):<15} | 💾 STORAGE\")\n",
|
| 504 |
+
" print(f\"{'FNet Positional Embedding':<40} | {format_num(fnet_pos):<15} | 💾 STORAGE\")\n",
|
| 505 |
+
"\n",
|
| 506 |
+
" # -----------------------------------------------\n",
|
| 507 |
+
" # 2. INPUT LOGIC (RoSE & Downsampling)\n",
|
| 508 |
+
" # -----------------------------------------------\n",
|
| 509 |
+
" rose_total = get_p(model.rose)\n",
|
| 510 |
+
" rose_logic = rose_total - vocab_emb # Subtract the embedding matrix we already counted\n",
|
| 511 |
+
"\n",
|
| 512 |
+
" print(\"-\" * 80)\n",
|
| 513 |
+
" print(f\"{'Dynamic RoSE (Adapters)':<40} | {format_num(rose_logic):<15} | 🌊 PHASE INIT\")\n",
|
| 514 |
+
" print(f\"{'Particle Downsample (512->384)':<40} | {format_num(get_p(model.particle_down)):<15} | 📉 PROJ\")\n",
|
| 515 |
+
" print(f\"{'Wave Downsample (1024->768)':<40} | {format_num(get_p(model.wave_down)):<15} | 📉 PROJ\")\n",
|
| 516 |
+
"\n",
|
| 517 |
+
" # -----------------------------------------------\n",
|
| 518 |
+
" # 3. STREAM A: RATE (FNet)\n",
|
| 519 |
+
" # -----------------------------------------------\n",
|
| 520 |
+
" print(\"-\" * 80)\n",
|
| 521 |
+
" print(f\"TRACK A: RATE STREAM (FNet) - Depth {len(model.stream_rate.layers)}\")\n",
|
| 522 |
+
"\n",
|
| 523 |
+
" fnet_encoder_total = 0\n",
|
| 524 |
+
" for i, layer in enumerate(model.stream_rate.layers):\n",
|
| 525 |
+
" p = get_p(layer)\n",
|
| 526 |
+
" fnet_encoder_total += p\n",
|
| 527 |
+
" print(f\" ├─ FNet Block {i:<24} | {format_num(p):<15} | ⚡ RATE\")\n",
|
| 528 |
+
"\n",
|
| 529 |
+
" fnet_norm = get_p(model.stream_rate.norm_out)\n",
|
| 530 |
+
" fnet_encoder_total += fnet_norm\n",
|
| 531 |
+
" print(f\" └─ Final Norm {i:<24} | {format_num(fnet_norm):<15} | ⚡ RATE\")\n",
|
| 532 |
+
"\n",
|
| 533 |
+
" # -----------------------------------------------\n",
|
| 534 |
+
" # 4. STREAM B: PHASE (PRISM)\n",
|
| 535 |
+
" # -----------------------------------------------\n",
|
| 536 |
+
" print(\"-\" * 80)\n",
|
| 537 |
+
" print(f\"TRACK B: PHASE STREAM (PRISM) - Depth {len(model.stream_phase.layers)}\")\n",
|
| 538 |
+
"\n",
|
| 539 |
+
" prism_encoder_total = 0\n",
|
| 540 |
+
" for i, layer in enumerate(model.stream_phase.layers):\n",
|
| 541 |
+
" p = get_p(layer)\n",
|
| 542 |
+
" prism_encoder_total += p\n",
|
| 543 |
+
" print(f\" ├─ PRISM Block {i:<23} | {format_num(p):<15} | 🌊 PHASE\")\n",
|
| 544 |
+
"\n",
|
| 545 |
+
" prism_norm = get_p(model.stream_phase.final_norm)\n",
|
| 546 |
+
" prism_encoder_total += prism_norm\n",
|
| 547 |
+
" print(f\" └─ Final Norm {i:<24} | {format_num(prism_norm):<15} | 🌊 PHASE\")\n",
|
| 548 |
+
"\n",
|
| 549 |
+
" bridge_p = get_p(model.phase_bridge)\n",
|
| 550 |
+
" print(f\"{'Phase Bridge (Complex->Real)':<40} | {format_num(bridge_p):<15} | 🌉 BRIDGE\")\n",
|
| 551 |
+
"\n",
|
| 552 |
+
" # -----------------------------------------------\n",
|
| 553 |
+
" # 5. THE BRAIN (Fusion & Refiner)\n",
|
| 554 |
+
" # -----------------------------------------------\n",
|
| 555 |
+
" print(\"-\" * 80)\n",
|
| 556 |
+
" fusion_p = get_p(model.fusion_proj) + get_p(model.fusion_norm)\n",
|
| 557 |
+
" print(f\"{'Fusion (Concat -> Proj -> Norm)':<40} | {format_num(fusion_p):<15} | 🧠 FUSION\")\n",
|
| 558 |
+
"\n",
|
| 559 |
+
" refiner_p = get_p(model.refiner)\n",
|
| 560 |
+
" print(f\"{'Transformer Refiner (1 Layer)':<40} | {format_num(refiner_p):<15} | 🧠 ATTENTION\")\n",
|
| 561 |
+
"\n",
|
| 562 |
+
" # [FIX] Handle nn.Parameter directly\n",
|
| 563 |
+
" head_bias_p = get_p(model.head_bias)\n",
|
| 564 |
+
" print(f\"{'Output Head Bias':<40} | {format_num(head_bias_p):<15} | 🎯 OUTPUT\")\n",
|
| 565 |
+
"\n",
|
| 566 |
+
" # -----------------------------------------------\n",
|
| 567 |
+
" # 6. SUMMARY\n",
|
| 568 |
+
" # -----------------------------------------------\n",
|
| 569 |
+
" print(\"=\"*80)\n",
|
| 570 |
+
"\n",
|
| 571 |
+
" storage = vocab_emb + fnet_pos + head_bias_p\n",
|
| 572 |
+
" active = total_params - storage\n",
|
| 573 |
+
"\n",
|
| 574 |
+
" print(f\"TOTAL PARAMETERS: {total_params/1e6:.2f} M\")\n",
|
| 575 |
+
" print(f\" ├─ 💾 Storage: {storage/1e6:.2f} M (Embeddings)\")\n",
|
| 576 |
+
" print(f\" └─ 🧠 Compute: {active/1e6:.2f} M (Logic/Weights)\")\n",
|
| 577 |
+
" print(\"-\" * 80)\n",
|
| 578 |
+
" print(f\"STREAM BREAKDOWN:\")\n",
|
| 579 |
+
" print(f\" ├─ ⚡ Rate Stream: {fnet_encoder_total/1e6:.2f} M\")\n",
|
| 580 |
+
" print(f\" └─ 🌊 Phase Stream: {prism_encoder_total/1e6:.2f} M\")\n",
|
| 581 |
+
" print(\"=\"*80 + \"\\n\")\n",
|
| 582 |
+
"\n",
|
| 583 |
+
" return total_params\n"
|
| 584 |
+
],
|
| 585 |
+
"metadata": {
|
| 586 |
+
"id": "V7DOwmmUjyin"
|
| 587 |
+
},
|
| 588 |
+
"execution_count": null,
|
| 589 |
+
"outputs": []
|
| 590 |
+
},
|
| 591 |
+
{
|
| 592 |
+
"cell_type": "code",
|
| 593 |
+
"source": [
|
| 594 |
+
"\n",
|
| 595 |
+
"# Run the parameter analysis to confirm strict adherence to budget\n",
|
| 596 |
+
"def deep_analyze_pillars_dat(model):\n",
|
| 597 |
+
" def get_p(obj):\n",
|
| 598 |
+
" if isinstance(obj, nn.Parameter): return obj.numel()\n",
|
| 599 |
+
" return sum(p.numel() for p in obj.parameters() if p.requires_grad)\n",
|
| 600 |
+
"\n",
|
| 601 |
+
" def format_num(n):\n",
|
| 602 |
+
" if n > 1e6: return f\"{n/1e6:.2f}M\"\n",
|
| 603 |
+
" if n > 1e3: return f\"{n/1e3:.2f}K\"\n",
|
| 604 |
+
" return str(n)\n",
|
| 605 |
+
"\n",
|
| 606 |
+
" print(\"\\n\" + \"=\"*80)\n",
|
| 607 |
+
" print(f\"🏛️ PILLARS-DAT (Hybrid Transformer-PRISM) - ANALYSIS\")\n",
|
| 608 |
+
" print(\"=\"*80)\n",
|
| 609 |
+
" print(f\"{'MODULE / LAYER':<40} | {'PARAMS':<12} | {'TYPE'}\")\n",
|
| 610 |
+
" print(\"-\" * 80)\n",
|
| 611 |
+
"\n",
|
| 612 |
+
" total_params = get_p(model)\n",
|
| 613 |
+
"\n",
|
| 614 |
+
" # --- 1. MEMORY ---\n",
|
| 615 |
+
" vocab_emb = get_p(model.rose.raw_embedding)\n",
|
| 616 |
+
" print(f\"{'Shared Vocab Embedding':<40} | {format_num(vocab_emb):<12} | 💾 STORAGE\")\n",
|
| 617 |
+
"\n",
|
| 618 |
+
" # --- 2. INPUT PHYSICS ---\n",
|
| 619 |
+
" rose_logic = get_p(model.rose) - vocab_emb\n",
|
| 620 |
+
" print(f\"{'Dynamic RoSE (Adapters)':<40} | {format_num(rose_logic):<12} | 🌊 PHYSICS\")\n",
|
| 621 |
+
"\n",
|
| 622 |
+
" down_p = get_p(model.particle_down) + get_p(model.wave_down)\n",
|
| 623 |
+
" print(f\"{'Stream Splitters (Downsample)':<40} | {format_num(down_p):<12} | 📉 PROJ\")\n",
|
| 624 |
+
"\n",
|
| 625 |
+
" # --- 3. STREAM A: SENSORY (TRANSFORMER) ---\n",
|
| 626 |
+
" print(\"-\" * 80)\n",
|
| 627 |
+
" print(f\"STREAM A: SENSORY (Identity/Magnitude)\")\n",
|
| 628 |
+
" sensory_p = get_p(model.stream_sensory)\n",
|
| 629 |
+
" # Attempt to count depth if accessible, else generic\n",
|
| 630 |
+
" try:\n",
|
| 631 |
+
" depth_s = len(model.stream_sensory.encoder.layers)\n",
|
| 632 |
+
" print(f\" ├─ Transformer Encoder (Depth {depth_s}) | {format_num(sensory_p):<12} | ⚡ ATTENTION\")\n",
|
| 633 |
+
" except:\n",
|
| 634 |
+
" print(f\" ├─ Transformer Encoder (Fused) | {format_num(sensory_p):<12} | ⚡ ATTENTION\")\n",
|
| 635 |
+
"\n",
|
| 636 |
+
" # --- 4. STREAM B: RELATIONAL (PRISM) ---\n",
|
| 637 |
+
" print(\"-\" * 80)\n",
|
| 638 |
+
" print(f\"STREAM B: RELATIONAL (Structure/Phase)\")\n",
|
| 639 |
+
" relational_core = get_p(model.stream_relational)\n",
|
| 640 |
+
" relational_bridge = get_p(model.relational_bridge)\n",
|
| 641 |
+
"\n",
|
| 642 |
+
" try:\n",
|
| 643 |
+
" depth_r = len(model.stream_relational.layers)\n",
|
| 644 |
+
" print(f\" ├─ PRISM Encoder (Depth {depth_r}) | {format_num(relational_core):<12} | 🌊 SPECTRAL\")\n",
|
| 645 |
+
" except:\n",
|
| 646 |
+
" print(f\" ├─ PRISM Encoder (Fused) | {format_num(relational_core):<12} | 🌊 SPECTRAL\")\n",
|
| 647 |
+
"\n",
|
| 648 |
+
" print(f\" └─ Bridge (Complex->Real) | {format_num(relational_bridge):<12} | 🌉 PROJ\")\n",
|
| 649 |
+
"\n",
|
| 650 |
+
" # --- 5. FUSION & OUTPUT ---\n",
|
| 651 |
+
" print(\"-\" * 80)\n",
|
| 652 |
+
" fusion_p = get_p(model.fusion_proj) + get_p(model.fusion_norm)\n",
|
| 653 |
+
" print(f\"{'Fusion (Concat -> Proj)':<40} | {format_num(fusion_p):<12} | 🧠 MIX\")\n",
|
| 654 |
+
"\n",
|
| 655 |
+
" refiner_p = get_p(model.refiner)\n",
|
| 656 |
+
" print(f\"{'Refiner (1-Layer Transformer)':<40} | {format_num(refiner_p):<12} | 🧠 REASONING\")\n",
|
| 657 |
+
"\n",
|
| 658 |
+
" bias_p = get_p(model.head_bias)\n",
|
| 659 |
+
" print(f\"{'Output Head Bias':<40} | {format_num(bias_p):<12} | 🎯 OUT\")\n",
|
| 660 |
+
"\n",
|
| 661 |
+
" # --- SUMMARY ---\n",
|
| 662 |
+
" print(\"=\"*80)\n",
|
| 663 |
+
" storage = vocab_emb + bias_p\n",
|
| 664 |
+
" active = total_params - storage\n",
|
| 665 |
+
"\n",
|
| 666 |
+
" print(f\"TOTAL PARAMETERS: {total_params/1e6:.2f} M\")\n",
|
| 667 |
+
" print(f\" ├─ 💾 Storage: {storage/1e6:.2f} M (Embeddings)\")\n",
|
| 668 |
+
" print(f\" └─ 🧠 Compute: {active/1e6:.2f} M (Active Weights)\")\n",
|
| 669 |
+
" print(\"-\" * 80)\n",
|
| 670 |
+
" print(f\"RATIO CHECK:\")\n",
|
| 671 |
+
" print(f\" ⚡ Sensory (Transf): {sensory_p/1e6:.2f} M\")\n",
|
| 672 |
+
" print(f\" 🌊 Relation (PRISM): {(relational_core + relational_bridge)/1e6:.2f} M\")\n",
|
| 673 |
+
" print(\"=\"*80 + \"\\n\")\n"
|
| 674 |
+
],
|
| 675 |
+
"metadata": {
|
| 676 |
+
"id": "ke4fYT8UX5zH"
|
| 677 |
+
},
|
| 678 |
+
"execution_count": null,
|
| 679 |
+
"outputs": []
|
| 680 |
+
},
|
| 681 |
+
{
|
| 682 |
+
"cell_type": "code",
|
| 683 |
+
"source": [
|
| 684 |
+
"# ==========================================\n",
|
| 685 |
+
"# 4. LOGGING & ANALYSIS UTILITIES\n",
|
| 686 |
+
"# ==========================================\n",
|
| 687 |
+
"def deep_analyze_pillars_dat(model):\n",
|
| 688 |
+
" def get_p(obj):\n",
|
| 689 |
+
" if isinstance(obj, nn.Parameter): return obj.numel()\n",
|
| 690 |
+
" return sum(p.numel() for p in obj.parameters() if p.requires_grad)\n",
|
| 691 |
+
"\n",
|
| 692 |
+
" def format_num(n):\n",
|
| 693 |
+
" if n > 1e6: return f\"{n/1e6:.2f}M\"\n",
|
| 694 |
+
" if n > 1e3: return f\"{n/1e3:.2f}K\"\n",
|
| 695 |
+
" return str(n)\n",
|
| 696 |
+
"\n",
|
| 697 |
+
" print(\"\\n\" + \"=\"*80)\n",
|
| 698 |
+
" print(f\"🏛️ PILLARS-DAT (Hybrid Transformer-PRISM) - ANALYSIS\")\n",
|
| 699 |
+
" print(\"=\"*80)\n",
|
| 700 |
+
" print(f\"{'MODULE / LAYER':<40} | {'PARAMS':<12} | {'TYPE'}\")\n",
|
| 701 |
+
" print(\"-\" * 80)\n",
|
| 702 |
+
"\n",
|
| 703 |
+
" total_params = get_p(model)\n",
|
| 704 |
+
"\n",
|
| 705 |
+
" # --- 1. MEMORY ---\n",
|
| 706 |
+
" vocab_emb = get_p(model.rose.raw_embedding)\n",
|
| 707 |
+
" print(f\"{'Shared Vocab Embedding':<40} | {format_num(vocab_emb):<12} | 💾 STORAGE\")\n",
|
| 708 |
+
"\n",
|
| 709 |
+
" # --- 2. INPUT PHYSICS ---\n",
|
| 710 |
+
" rose_logic = get_p(model.rose) - vocab_emb\n",
|
| 711 |
+
" print(f\"{'Dynamic RoSE (Adapters)':<40} | {format_num(rose_logic):<12} | 🌊 PHYSICS\")\n",
|
| 712 |
+
"\n",
|
| 713 |
+
" down_p = get_p(model.particle_down) + get_p(model.wave_down)\n",
|
| 714 |
+
" print(f\"{'Stream Splitters (Downsample)':<40} | {format_num(down_p):<12} | 📉 PROJ\")\n",
|
| 715 |
+
"\n",
|
| 716 |
+
" # --- 3. STREAM A: SENSORY (TRANSFORMER) ---\n",
|
| 717 |
+
" print(\"-\" * 80)\n",
|
| 718 |
+
" print(f\"STREAM A: SENSORY (Identity/Magnitude)\")\n",
|
| 719 |
+
" sensory_p = get_p(model.stream_sensory)\n",
|
| 720 |
+
" try:\n",
|
| 721 |
+
" depth_s = len(model.stream_sensory.encoder.layers)\n",
|
| 722 |
+
" print(f\" ├─ Transformer Encoder (Depth {depth_s}) | {format_num(sensory_p):<12} | ⚡ ATTENTION\")\n",
|
| 723 |
+
" except:\n",
|
| 724 |
+
" print(f\" ├─ Transformer Encoder (Fused) | {format_num(sensory_p):<12} | ⚡ ATTENTION\")\n",
|
| 725 |
+
"\n",
|
| 726 |
+
" # --- 4. STREAM B: RELATIONAL (PRISM) ---\n",
|
| 727 |
+
" print(\"-\" * 80)\n",
|
| 728 |
+
" print(f\"STREAM B: RELATIONAL (Structure/Phase)\")\n",
|
| 729 |
+
" relational_core = get_p(model.stream_relational)\n",
|
| 730 |
+
" relational_bridge = get_p(model.relational_bridge)\n",
|
| 731 |
+
"\n",
|
| 732 |
+
" try:\n",
|
| 733 |
+
" depth_r = len(model.stream_relational.layers)\n",
|
| 734 |
+
" print(f\" ├─ PRISM Encoder (Depth {depth_r}) | {format_num(relational_core):<12} | 🌊 SPECTRAL\")\n",
|
| 735 |
+
" except:\n",
|
| 736 |
+
" print(f\" ├─ PRISM Encoder (Fused) | {format_num(relational_core):<12} | 🌊 SPECTRAL\")\n",
|
| 737 |
+
"\n",
|
| 738 |
+
" print(f\" └─ Bridge (Complex->Real) | {format_num(relational_bridge):<12} | 🌉 PROJ\")\n",
|
| 739 |
+
"\n",
|
| 740 |
+
" # --- 5. FUSION & OUTPUT ---\n",
|
| 741 |
+
" print(\"-\" * 80)\n",
|
| 742 |
+
" fusion_p = get_p(model.fusion_proj) + get_p(model.fusion_norm)\n",
|
| 743 |
+
" print(f\"{'Fusion (Concat -> Proj)':<40} | {format_num(fusion_p):<12} | 🧠 MIX\")\n",
|
| 744 |
+
"\n",
|
| 745 |
+
" refiner_p = get_p(model.refiner)\n",
|
| 746 |
+
" print(f\"{'Refiner (1-Layer Transformer)':<40} | {format_num(refiner_p):<12} | 🧠 REASONING\")\n",
|
| 747 |
+
"\n",
|
| 748 |
+
" bias_p = get_p(model.head_bias)\n",
|
| 749 |
+
" print(f\"{'Output Head Bias':<40} | {format_num(bias_p):<12} | 🎯 OUT\")\n",
|
| 750 |
+
"\n",
|
| 751 |
+
" # --- SUMMARY ---\n",
|
| 752 |
+
" print(\"=\"*80)\n",
|
| 753 |
+
" storage = vocab_emb + bias_p\n",
|
| 754 |
+
" active = total_params - storage\n",
|
| 755 |
+
"\n",
|
| 756 |
+
" print(f\"TOTAL PARAMETERS: {total_params/1e6:.2f} M\")\n",
|
| 757 |
+
" print(f\" ├─ 💾 Storage: {storage/1e6:.2f} M (Embeddings)\")\n",
|
| 758 |
+
" print(f\" └─ 🧠 Compute: {active/1e6:.2f} M (Active Weights)\")\n",
|
| 759 |
+
" print(\"-\" * 80)\n",
|
| 760 |
+
" print(f\"RATIO CHECK:\")\n",
|
| 761 |
+
" print(f\" ⚡ Sensory (Transf): {sensory_p/1e6:.2f} M\")\n",
|
| 762 |
+
" print(f\" 🌊 Relation (PRISM): {(relational_core + relational_bridge)/1e6:.2f} M\")\n",
|
| 763 |
+
" print(\"=\"*80 + \"\\n\")\n",
|
| 764 |
+
"\n",
|
| 765 |
+
"def generate_run_id():\n",
|
| 766 |
+
" raw = datetime.now().strftime(\"%Y%m%d%H%M%S%f\")\n",
|
| 767 |
+
" return hashlib.md5(raw.encode()).hexdigest()[:8]\n",
|
| 768 |
+
"\n",
|
| 769 |
+
"def log_environment(save_dir, run_id, config):\n",
|
| 770 |
+
" log_path = os.path.join(save_dir, f\"env_metadata_{run_id}.txt\")\n",
|
| 771 |
+
" with open(log_path, \"w\") as f:\n",
|
| 772 |
+
" f.write(f\"PRISM EXPERIMENT METADATA | Run ID: {run_id}\\n{'='*50}\\n\")\n",
|
| 773 |
+
" for k, v in config.items(): f.write(f\"{k}: {v}\\n\")\n",
|
| 774 |
+
" print(f\"📝 Environment Snapshot saved to: {log_path}\")\n",
|
| 775 |
+
"\n",
|
| 776 |
+
"def log_metrics(save_dir, run_id, epoch, train_loss, val_loss, ppl):\n",
|
| 777 |
+
" log_path = os.path.join(save_dir, f\"metrics_log_{run_id}.csv\")\n",
|
| 778 |
+
" if not os.path.exists(log_path):\n",
|
| 779 |
+
" with open(log_path, \"w\") as f: f.write(\"Timestamp,Epoch,Train_Loss,Val_Loss,Perplexity\\n\")\n",
|
| 780 |
+
" with open(log_path, \"a\") as f:\n",
|
| 781 |
+
" ts = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n",
|
| 782 |
+
" f.write(f\"{ts},{epoch},{train_loss:.6f},{val_loss:.6f},{ppl:.6f}\\n\")\n",
|
| 783 |
+
"\n",
|
| 784 |
+
"def save_checkpoint(path, model, optimizer, scheduler, scaler, epoch, best_loss, config):\n",
|
| 785 |
+
" torch.save({\n",
|
| 786 |
+
" 'epoch': epoch,\n",
|
| 787 |
+
" 'model_state_dict': model.state_dict(),\n",
|
| 788 |
+
" 'optimizer_state_dict': optimizer.state_dict(),\n",
|
| 789 |
+
" 'scheduler_state_dict': scheduler.state_dict(),\n",
|
| 790 |
+
" 'scaler_state_dict': scaler.state_dict(), # <--- IMPORTANT FOR AMP\n",
|
| 791 |
+
" 'best_val_loss': best_loss,\n",
|
| 792 |
+
" 'config': config\n",
|
| 793 |
+
" }, path)\n",
|
| 794 |
+
"\n",
|
| 795 |
+
"# ==========================================\n",
|
| 796 |
+
"# 5. A100 TRAINING LOOP (WITH LOGGING)\n",
|
| 797 |
+
"# ==========================================\n",
|
| 798 |
+
"# ==========================================\n",
|
| 799 |
+
"# 4. LOGGING & ANALYSIS UTILITIES\n",
|
| 800 |
+
"# ==========================================\n",
|
| 801 |
+
"def deep_analyze_pillars_dat(model):\n",
|
| 802 |
+
" def get_p(obj):\n",
|
| 803 |
+
" if isinstance(obj, nn.Parameter): return obj.numel()\n",
|
| 804 |
+
" return sum(p.numel() for p in obj.parameters() if p.requires_grad)\n",
|
| 805 |
+
"\n",
|
| 806 |
+
" def format_num(n):\n",
|
| 807 |
+
" if n > 1e6: return f\"{n/1e6:.2f}M\"\n",
|
| 808 |
+
" if n > 1e3: return f\"{n/1e3:.2f}K\"\n",
|
| 809 |
+
" return str(n)\n",
|
| 810 |
+
"\n",
|
| 811 |
+
" print(\"\\n\" + \"=\"*80)\n",
|
| 812 |
+
" print(f\"🏛️ PILLARS-DAT (Hybrid Transformer-PRISM) - ANALYSIS\")\n",
|
| 813 |
+
" print(\"=\"*80)\n",
|
| 814 |
+
" print(f\"{'MODULE / LAYER':<40} | {'PARAMS':<12} | {'TYPE'}\")\n",
|
| 815 |
+
" print(\"-\" * 80)\n",
|
| 816 |
+
"\n",
|
| 817 |
+
" total_params = get_p(model)\n",
|
| 818 |
+
"\n",
|
| 819 |
+
" # --- 1. MEMORY ---\n",
|
| 820 |
+
" vocab_emb = get_p(model.rose.raw_embedding)\n",
|
| 821 |
+
" print(f\"{'Shared Vocab Embedding':<40} | {format_num(vocab_emb):<12} | 💾 STORAGE\")\n",
|
| 822 |
+
"\n",
|
| 823 |
+
" # --- 2. INPUT PHYSICS ---\n",
|
| 824 |
+
" rose_logic = get_p(model.rose) - vocab_emb\n",
|
| 825 |
+
" print(f\"{'Dynamic RoSE (Adapters)':<40} | {format_num(rose_logic):<12} | 🌊 PHYSICS\")\n",
|
| 826 |
+
"\n",
|
| 827 |
+
" down_p = get_p(model.particle_down) + get_p(model.wave_down)\n",
|
| 828 |
+
" print(f\"{'Stream Splitters (Downsample)':<40} | {format_num(down_p):<12} | 📉 PROJ\")\n",
|
| 829 |
+
"\n",
|
| 830 |
+
" # --- 3. STREAM A: SENSORY (TRANSFORMER) ---\n",
|
| 831 |
+
" print(\"-\" * 80)\n",
|
| 832 |
+
" print(f\"STREAM A: SENSORY (Identity/Magnitude)\")\n",
|
| 833 |
+
" sensory_p = get_p(model.stream_sensory)\n",
|
| 834 |
+
" try:\n",
|
| 835 |
+
" depth_s = len(model.stream_sensory.encoder.layers)\n",
|
| 836 |
+
" print(f\" ├─ Transformer Encoder (Depth {depth_s}) | {format_num(sensory_p):<12} | ⚡ ATTENTION\")\n",
|
| 837 |
+
" except:\n",
|
| 838 |
+
" print(f\" ├─ Transformer Encoder (Fused) | {format_num(sensory_p):<12} | ⚡ ATTENTION\")\n",
|
| 839 |
+
"\n",
|
| 840 |
+
" # --- 4. STREAM B: RELATIONAL (PRISM) ---\n",
|
| 841 |
+
" print(\"-\" * 80)\n",
|
| 842 |
+
" print(f\"STREAM B: RELATIONAL (Structure/Phase)\")\n",
|
| 843 |
+
" relational_core = get_p(model.stream_relational)\n",
|
| 844 |
+
" relational_bridge = get_p(model.relational_bridge)\n",
|
| 845 |
+
"\n",
|
| 846 |
+
" try:\n",
|
| 847 |
+
" depth_r = len(model.stream_relational.layers)\n",
|
| 848 |
+
" print(f\" ├─ PRISM Encoder (Depth {depth_r}) | {format_num(relational_core):<12} | 🌊 SPECTRAL\")\n",
|
| 849 |
+
" except:\n",
|
| 850 |
+
" print(f\" ├─ PRISM Encoder (Fused) | {format_num(relational_core):<12} | 🌊 SPECTRAL\")\n",
|
| 851 |
+
"\n",
|
| 852 |
+
" print(f\" └─ Bridge (Complex->Real) | {format_num(relational_bridge):<12} | 🌉 PROJ\")\n",
|
| 853 |
+
"\n",
|
| 854 |
+
" # --- 5. FUSION & OUTPUT ---\n",
|
| 855 |
+
" print(\"-\" * 80)\n",
|
| 856 |
+
" fusion_p = get_p(model.fusion_proj) + get_p(model.fusion_norm)\n",
|
| 857 |
+
" print(f\"{'Fusion (Concat -> Proj)':<40} | {format_num(fusion_p):<12} | 🧠 MIX\")\n",
|
| 858 |
+
"\n",
|
| 859 |
+
" refiner_p = get_p(model.refiner)\n",
|
| 860 |
+
" print(f\"{'Refiner (1-Layer Transformer)':<40} | {format_num(refiner_p):<12} | 🧠 REASONING\")\n",
|
| 861 |
+
"\n",
|
| 862 |
+
" bias_p = get_p(model.head_bias)\n",
|
| 863 |
+
" print(f\"{'Output Head Bias':<40} | {format_num(bias_p):<12} | 🎯 OUT\")\n",
|
| 864 |
+
"\n",
|
| 865 |
+
" # --- SUMMARY ---\n",
|
| 866 |
+
" print(\"=\"*80)\n",
|
| 867 |
+
" storage = vocab_emb + bias_p\n",
|
| 868 |
+
" active = total_params - storage\n",
|
| 869 |
+
"\n",
|
| 870 |
+
" print(f\"TOTAL PARAMETERS: {total_params/1e6:.2f} M\")\n",
|
| 871 |
+
" print(f\" ├─ 💾 Storage: {storage/1e6:.2f} M (Embeddings)\")\n",
|
| 872 |
+
" print(f\" └─ 🧠 Compute: {active/1e6:.2f} M (Active Weights)\")\n",
|
| 873 |
+
" print(\"-\" * 80)\n",
|
| 874 |
+
" print(f\"RATIO CHECK:\")\n",
|
| 875 |
+
" print(f\" ⚡ Sensory (Transf): {sensory_p/1e6:.2f} M\")\n",
|
| 876 |
+
" print(f\" 🌊 Relation (PRISM): {(relational_core + relational_bridge)/1e6:.2f} M\")\n",
|
| 877 |
+
" print(\"=\"*80 + \"\\n\")\n",
|
| 878 |
+
"\n",
|
| 879 |
+
"def init_pillars_dat_weights(model):\n",
|
| 880 |
+
" print(\"✨ APPLYING PILLARS-DAT INITIALIZATION PROTOCOL...\")\n",
|
| 881 |
+
" # 1. SHARED ROOT (RoSE)\n",
|
| 882 |
+
" nn.init.normal_(model.rose.raw_embedding.weight, std=model.d_model ** -0.5)\n",
|
| 883 |
+
" nn.init.orthogonal_(model.rose.adapter.weight)\n",
|
| 884 |
+
"\n",
|
| 885 |
+
" # --- ROSE IDENTITY TRICK ---\n",
|
| 886 |
+
" nn.init.normal_(model.rose.rotation_predictor.weight, std=0.01)\n",
|
| 887 |
+
" with torch.no_grad():\n",
|
| 888 |
+
" model.rose.rotation_predictor.bias[:model.d_model].fill_(1.0) # Real=1\n",
|
| 889 |
+
" model.rose.rotation_predictor.bias[model.d_model:].fill_(0.0) # Imag=0\n",
|
| 890 |
+
"\n",
|
| 891 |
+
" # 2. DOWNSAMPLERS\n",
|
| 892 |
+
" nn.init.orthogonal_(model.particle_down.weight, gain=1.414)\n",
|
| 893 |
+
" nn.init.orthogonal_(model.wave_down.weight, gain=1.414)\n",
|
| 894 |
+
"\n",
|
| 895 |
+
" # 3. SENSORY STREAM (Transformer + RoPE)\n",
|
| 896 |
+
" print(\" ├─ Initializing Sensory Stream (Transformer)...\")\n",
|
| 897 |
+
" for name, p in model.stream_sensory.named_parameters():\n",
|
| 898 |
+
" if p.dim() > 1:\n",
|
| 899 |
+
" nn.init.xavier_uniform_(p)\n",
|
| 900 |
+
" elif \"norm\" in name.lower() and p.dim() == 1:\n",
|
| 901 |
+
" if \"weight\" in name: nn.init.ones_(p)\n",
|
| 902 |
+
" if \"bias\" in name: nn.init.zeros_(p)\n",
|
| 903 |
+
"\n",
|
| 904 |
+
" # 4. RELATIONAL STREAM (PRISM)\n",
|
| 905 |
+
" print(\" ├─ Initializing Relational Stream (PRISM)...\")\n",
|
| 906 |
+
" for name, m in model.stream_relational.named_modules():\n",
|
| 907 |
+
" if isinstance(m, nn.Linear):\n",
|
| 908 |
+
" nn.init.xavier_uniform_(m.weight, gain=1.0)\n",
|
| 909 |
+
" if m.bias is not None: nn.init.zeros_(m.bias)\n",
|
| 910 |
+
" if isinstance(m, ModReLU):\n",
|
| 911 |
+
" nn.init.constant_(m.b, 0.01)\n",
|
| 912 |
+
"\n",
|
| 913 |
+
" # 5. FUSION & REFINER\n",
|
| 914 |
+
" nn.init.xavier_uniform_(model.fusion_proj.weight, gain=1.0)\n",
|
| 915 |
+
" for p in model.refiner.parameters():\n",
|
| 916 |
+
" if p.dim() > 1: nn.init.xavier_uniform_(p)\n",
|
| 917 |
+
"\n",
|
| 918 |
+
" # 6. TIED HEAD BIAS\n",
|
| 919 |
+
" nn.init.zeros_(model.head_bias)\n",
|
| 920 |
+
" print(\"✅ DAT INITIALIZATION COMPLETE.\")\n",
|
| 921 |
+
"\n",
|
| 922 |
+
"# ==========================================\n",
|
| 923 |
+
"# 5. A100 TRAINING LOOP (WITH LOGGING)\n",
|
| 924 |
+
"# ==========================================\n",
|
| 925 |
+
"def run_a100_training(experiment_name=\"PILLARS_DAT_A100_Final\"):\n",
|
| 926 |
+
" from torch.cuda.amp import autocast, GradScaler\n",
|
| 927 |
+
" from torch.utils.tensorboard import SummaryWriter\n",
|
| 928 |
+
"\n",
|
| 929 |
+
" # --- 1. SETUP DRIVE & LOGGING ---\n",
|
| 930 |
+
" from google.colab import drive\n",
|
| 931 |
+
" if not os.path.exists('/content/drive'): drive.mount('/content/drive')\n",
|
| 932 |
+
"\n",
|
| 933 |
+
" run_id = generate_run_id()\n",
|
| 934 |
+
" timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n",
|
| 935 |
+
" SAVE_DIR = os.path.join(\"/content/drive/My Drive/PRISM_Experiments\", f\"{experiment_name}_{timestamp}_{run_id}\")\n",
|
| 936 |
+
" os.makedirs(SAVE_DIR, exist_ok=True)\n",
|
| 937 |
+
"\n",
|
| 938 |
+
" writer = SummaryWriter(log_dir=SAVE_DIR)\n",
|
| 939 |
+
"\n",
|
| 940 |
+
" # Config for Logs\n",
|
| 941 |
+
" config_dump = {\n",
|
| 942 |
+
" \"run_id\": run_id, \"batch_size\": 6, \"accum\": 8, \"d_model\": D_MODEL, \"depth\": DEPTH, \"seq_len\": SEQ_LEN\n",
|
| 943 |
+
" }\n",
|
| 944 |
+
" log_environment(SAVE_DIR, run_id, config_dump)\n",
|
| 945 |
+
"\n",
|
| 946 |
+
" # --- 2. MODEL & DATA ---\n",
|
| 947 |
+
" SAFE_BATCH_SIZE = BATCH_SIZE\n",
|
| 948 |
+
" GRAD_ACCUM = 4\n",
|
| 949 |
+
" print(f\"\\n⚡ A100 DETECTED. CONFIGURING FLASH ATTENTION PIPELINE...\")\n",
|
| 950 |
+
"\n",
|
| 951 |
+
" lm_datasets, data_collator = prepare_data_from_hub()\n",
|
| 952 |
+
" train_loader = DataLoader(lm_datasets[\"train\"], batch_size=SAFE_BATCH_SIZE, shuffle=True, collate_fn=data_collator, num_workers=4, pin_memory=True)\n",
|
| 953 |
+
" valid_loader = DataLoader(lm_datasets[\"validation\"], batch_size=SAFE_BATCH_SIZE, collate_fn=data_collator, num_workers=2)\n",
|
| 954 |
+
"\n",
|
| 955 |
+
" model = Pillars_DAT(vocab_size=VOCAB_SIZE, d_model=D_MODEL, d_branch=D_BRANCH, seq_len=SEQ_LEN, depth=DEPTH).to(DEVICE)\n",
|
| 956 |
+
" init_pillars_dat_weights(model)\n",
|
| 957 |
+
" print(model)\n",
|
| 958 |
+
" deep_analyze_pillars_dat(model) # <--- Parameter Analysis\n",
|
| 959 |
+
"\n",
|
| 960 |
+
" optimizer = optim.AdamW(model.parameters(), lr=LR, weight_decay=0.01)\n",
|
| 961 |
+
" total_steps = (len(train_loader) // GRAD_ACCUM) * EPOCHS\n",
|
| 962 |
+
" warmup_steps = int(total_steps * 0.1)\n",
|
| 963 |
+
" scheduler = get_cosine_schedule_with_warmup(optimizer, warmup_steps, total_steps)\n",
|
| 964 |
+
" criterion = nn.CrossEntropyLoss()\n",
|
| 965 |
+
" scaler = GradScaler() # For AMP\n",
|
| 966 |
+
"\n",
|
| 967 |
+
" print(f\"\\n🚀 IGNITING FUSION DRIVE... Saving to: {SAVE_DIR}\")\n",
|
| 968 |
+
"\n",
|
| 969 |
+
" global_step = 0\n",
|
| 970 |
+
" best_val_loss = float('inf')\n",
|
| 971 |
+
"\n",
|
| 972 |
+
" for epoch in range(EPOCHS):\n",
|
| 973 |
+
" model.train()\n",
|
| 974 |
+
" pbar = tqdm(train_loader, desc=f\"Ep {epoch+1}\")\n",
|
| 975 |
+
"\n",
|
| 976 |
+
" for step, batch in enumerate(pbar):\n",
|
| 977 |
+
" x, y = batch['input_ids'].to(DEVICE), batch['labels'].to(DEVICE)\n",
|
| 978 |
+
"\n",
|
| 979 |
+
" # ⚡ AMP CONTEXT\n",
|
| 980 |
+
" with autocast(dtype=torch.float16):\n",
|
| 981 |
+
" logits = model(x).view(-1, VOCAB_SIZE)\n",
|
| 982 |
+
" loss = criterion(logits, y.view(-1)) / GRAD_ACCUM\n",
|
| 983 |
+
"\n",
|
| 984 |
+
" scaler.scale(loss).backward()\n",
|
| 985 |
+
"\n",
|
| 986 |
+
" if (step + 1) % GRAD_ACCUM == 0:\n",
|
| 987 |
+
" scaler.unscale_(optimizer)\n",
|
| 988 |
+
" # 🛑 CALC GRAD NORM HERE FOR PBAR 🛑\n",
|
| 989 |
+
" grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n",
|
| 990 |
+
"\n",
|
| 991 |
+
" scaler.step(optimizer)\n",
|
| 992 |
+
" scaler.update()\n",
|
| 993 |
+
" scheduler.step()\n",
|
| 994 |
+
" optimizer.zero_grad()\n",
|
| 995 |
+
" global_step += 1\n",
|
| 996 |
+
"\n",
|
| 997 |
+
" # 📝 STEP LOGGING\n",
|
| 998 |
+
" actual_loss = loss.item() * GRAD_ACCUM\n",
|
| 999 |
+
" writer.add_scalar('Train/Loss', actual_loss, global_step)\n",
|
| 1000 |
+
" writer.add_scalar('Train/GradNorm', grad_norm.item(), global_step)\n",
|
| 1001 |
+
" writer.add_scalar('Train/LR', scheduler.get_last_lr()[0], global_step)\n",
|
| 1002 |
+
"\n",
|
| 1003 |
+
" # ✨ UPDATE PBAR WITH GNORM ✨\n",
|
| 1004 |
+
" pbar.set_postfix({\n",
|
| 1005 |
+
" 'loss': f\"{actual_loss:.4f}\",\n",
|
| 1006 |
+
" 'gnorm': f\"{grad_norm.item():.2f}\"\n",
|
| 1007 |
+
" })\n",
|
| 1008 |
+
"\n",
|
| 1009 |
+
" # --- VALIDATION ---\n",
|
| 1010 |
+
" model.eval()\n",
|
| 1011 |
+
" val_loss = 0\n",
|
| 1012 |
+
" with torch.no_grad(), autocast():\n",
|
| 1013 |
+
" for batch in valid_loader:\n",
|
| 1014 |
+
" x, y = batch['input_ids'].to(DEVICE), batch['labels'].to(DEVICE)\n",
|
| 1015 |
+
" val_loss += criterion(model(x).view(-1, VOCAB_SIZE), y.view(-1)).item()\n",
|
| 1016 |
+
"\n",
|
| 1017 |
+
" avg_val_loss = val_loss / len(valid_loader)\n",
|
| 1018 |
+
" # Prevent overflow if loss is exploding\n",
|
| 1019 |
+
" ppl = math.exp(avg_val_loss) if avg_val_loss < 20 else float('inf')\n",
|
| 1020 |
+
"\n",
|
| 1021 |
+
" print(f\"✨ Ep {epoch+1} | Val Loss: {avg_val_loss:.4f} | PPL: {ppl:.2f}\")\n",
|
| 1022 |
+
"\n",
|
| 1023 |
+
" # 📝 EPOCH LOGGING\n",
|
| 1024 |
+
" writer.add_scalar('Val/Loss', avg_val_loss, epoch+1)\n",
|
| 1025 |
+
" writer.add_scalar('Val/PPL', ppl, epoch+1)\n",
|
| 1026 |
+
" log_metrics(SAVE_DIR, run_id, epoch+1, 0.0, avg_val_loss, ppl)\n",
|
| 1027 |
+
"\n",
|
| 1028 |
+
" # 💾 SAVE CHECKPOINTS (Includes Scaler/Optim/Sched)\n",
|
| 1029 |
+
" save_checkpoint(os.path.join(SAVE_DIR, \"last.pt\"), model, optimizer, scheduler, scaler, epoch, best_val_loss, config_dump)\n",
|
| 1030 |
+
"\n",
|
| 1031 |
+
" if avg_val_loss < best_val_loss:\n",
|
| 1032 |
+
" best_val_loss = avg_val_loss\n",
|
| 1033 |
+
" print(f\" 🏆 New Best Model! Saving best.pt...\")\n",
|
| 1034 |
+
" save_checkpoint(os.path.join(SAVE_DIR, \"best.pt\"), model, optimizer, scheduler, scaler, epoch, best_val_loss, config_dump)\n",
|
| 1035 |
+
"\n",
|
| 1036 |
+
" writer.close()\n",
|
| 1037 |
+
" return model\n",
|
| 1038 |
+
"\n",
|
| 1039 |
+
"if __name__ == \"__main__\":\n",
|
| 1040 |
+
" run_a100_training()"
|
| 1041 |
+
],
|
| 1042 |
+
"metadata": {
|
| 1043 |
+
"id": "-TNEv89gkS1k"
|
| 1044 |
+
},
|
| 1045 |
+
"execution_count": null,
|
| 1046 |
+
"outputs": []
|
| 1047 |
+
},
|
| 1048 |
+
{
|
| 1049 |
+
"cell_type": "code",
|
| 1050 |
+
"source": [
|
| 1051 |
+
"from google.colab import runtime\n",
|
| 1052 |
+
"runtime.unassign()"
|
| 1053 |
+
],
|
| 1054 |
+
"metadata": {
|
| 1055 |
+
"id": "bxFTYWHVqcSI"
|
| 1056 |
+
},
|
| 1057 |
+
"execution_count": null,
|
| 1058 |
+
"outputs": []
|
| 1059 |
+
}
|
| 1060 |
+
]
|
| 1061 |
+
}
|
WT103_Transformer_Baseline.ipynb
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"nbformat": 4,
|
| 3 |
+
"nbformat_minor": 0,
|
| 4 |
+
"metadata": {
|
| 5 |
+
"colab": {
|
| 6 |
+
"provenance": [],
|
| 7 |
+
"gpuType": "A100"
|
| 8 |
+
},
|
| 9 |
+
"kernelspec": {
|
| 10 |
+
"name": "python3",
|
| 11 |
+
"display_name": "Python 3"
|
| 12 |
+
},
|
| 13 |
+
"language_info": {
|
| 14 |
+
"name": "python"
|
| 15 |
+
},
|
| 16 |
+
"accelerator": "GPU"
|
| 17 |
+
},
|
| 18 |
+
"cells": [
|
| 19 |
+
{
|
| 20 |
+
"cell_type": "code",
|
| 21 |
+
"source": [
|
| 22 |
+
"!pip install -q x-transformers\n",
|
| 23 |
+
"!pip install -q flash-attn --no-build-isolation\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"import torch\n",
|
| 26 |
+
"import torch.nn as nn\n",
|
| 27 |
+
"import torch.optim as optim\n",
|
| 28 |
+
"import math\n",
|
| 29 |
+
"import os\n",
|
| 30 |
+
"import hashlib\n",
|
| 31 |
+
"from datetime import datetime\n",
|
| 32 |
+
"from tqdm.auto import tqdm\n",
|
| 33 |
+
"from torch.utils.data import DataLoader\n",
|
| 34 |
+
"from torch.utils.tensorboard import SummaryWriter\n",
|
| 35 |
+
"from transformers import RobertaTokenizerFast, get_cosine_schedule_with_warmup, DataCollatorForLanguageModeling\n",
|
| 36 |
+
"from datasets import load_dataset\n",
|
| 37 |
+
"from x_transformers import TransformerWrapper, Encoder\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"# ==========================================\n",
|
| 40 |
+
"# 1. CONFIGURATION\n",
|
| 41 |
+
"# ==========================================\n",
|
| 42 |
+
"HF_ID = \"prism-lab/wikitext-103-prism-32k-seq4k\"\n",
|
| 43 |
+
"EXPERIMENT_NAME = \"BASELINE_Pure_XTransformers\"\n",
|
| 44 |
+
"\n",
|
| 45 |
+
"VOCAB_SIZE = 32768\n",
|
| 46 |
+
"SEQ_LEN = 4096\n",
|
| 47 |
+
"BATCH_SIZE = 8\n",
|
| 48 |
+
"GRAD_ACCUM = 4\n",
|
| 49 |
+
"EPOCHS = 40\n",
|
| 50 |
+
"LR = 1e-3\n",
|
| 51 |
+
"D_MODEL = 512\n",
|
| 52 |
+
"DEPTH = 5\n",
|
| 53 |
+
"HEADS = 8\n",
|
| 54 |
+
"DROPOUT = 0.1\n",
|
| 55 |
+
"WEIGHT_DECAY = 0.01\n",
|
| 56 |
+
"\n",
|
| 57 |
+
"DEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 58 |
+
"torch.set_float32_matmul_precision(\"high\")\n",
|
| 59 |
+
"def print_detailed_param_count(model):\n",
|
| 60 |
+
" \"\"\"\n",
|
| 61 |
+
" Detailed parameter breakdown for x_transformers models.\n",
|
| 62 |
+
" \"\"\"\n",
|
| 63 |
+
" total_params = 0\n",
|
| 64 |
+
" categories = {\n",
|
| 65 |
+
" \"Embeddings\": 0,\n",
|
| 66 |
+
" \"Attention\": 0,\n",
|
| 67 |
+
" \"FeedForward\": 0,\n",
|
| 68 |
+
" \"Norms\": 0,\n",
|
| 69 |
+
" \"Head/Other\": 0\n",
|
| 70 |
+
" }\n",
|
| 71 |
+
"\n",
|
| 72 |
+
" # Track distinct tensors to handle tied weights correctly\n",
|
| 73 |
+
" seen_pointers = set()\n",
|
| 74 |
+
"\n",
|
| 75 |
+
" for name, param in model.named_parameters():\n",
|
| 76 |
+
" if param.requires_grad:\n",
|
| 77 |
+
" # Check for shared weights (tied embeddings)\n",
|
| 78 |
+
" if param.data_ptr() in seen_pointers:\n",
|
| 79 |
+
" continue\n",
|
| 80 |
+
" seen_pointers.add(param.data_ptr())\n",
|
| 81 |
+
"\n",
|
| 82 |
+
" num_params = param.numel()\n",
|
| 83 |
+
" total_params += num_params\n",
|
| 84 |
+
"\n",
|
| 85 |
+
" # Logic for x_transformers naming conventions\n",
|
| 86 |
+
" if \"token_emb\" in name or \"pos_emb\" in name:\n",
|
| 87 |
+
" categories[\"Embeddings\"] += num_params\n",
|
| 88 |
+
" elif \"attn\" in name or \"to_q\" in name or \"to_k\" in name or \"to_v\" in name:\n",
|
| 89 |
+
" categories[\"Attention\"] += num_params\n",
|
| 90 |
+
" elif \"ff\" in name:\n",
|
| 91 |
+
" categories[\"FeedForward\"] += num_params\n",
|
| 92 |
+
" elif \"norm\" in name:\n",
|
| 93 |
+
" categories[\"Norms\"] += num_params\n",
|
| 94 |
+
" else:\n",
|
| 95 |
+
" categories[\"Head/Other\"] += num_params\n",
|
| 96 |
+
"\n",
|
| 97 |
+
" print(f\"\\n{'='*60}\")\n",
|
| 98 |
+
" print(f\"{'COMPONENT':<25} | {'PARAMS':<12} | {'%':<6}\")\n",
|
| 99 |
+
" print(f\"{'-'*60}\")\n",
|
| 100 |
+
"\n",
|
| 101 |
+
" for cat, count in categories.items():\n",
|
| 102 |
+
" if count > 0:\n",
|
| 103 |
+
" percentage = (count / total_params) * 100\n",
|
| 104 |
+
" print(f\"{cat:<25} | {count:12,} | {percentage:5.1f}%\")\n",
|
| 105 |
+
"\n",
|
| 106 |
+
" print(f\"{'='*60}\")\n",
|
| 107 |
+
" print(f\"{'TOTAL':<25} | {total_params:12,} | 100.0%\")\n",
|
| 108 |
+
" print(f\"{'='*60}\\n\")\n",
|
| 109 |
+
"\n",
|
| 110 |
+
" return total_params\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"# ==========================================\n",
|
| 113 |
+
"# 2. TRAINING ROUTINE\n",
|
| 114 |
+
"# ==========================================\n",
|
| 115 |
+
"def run_baseline_training():\n",
|
| 116 |
+
" from google.colab import drive\n",
|
| 117 |
+
" if not os.path.exists('/content/drive'): drive.mount('/content/drive')\n",
|
| 118 |
+
"\n",
|
| 119 |
+
" # Setup Logging\n",
|
| 120 |
+
" timestamp = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n",
|
| 121 |
+
" run_id = hashlib.md5(timestamp.encode()).hexdigest()[:8]\n",
|
| 122 |
+
" SAVE_DIR = os.path.join(\"/content/drive/My Drive/PRISM_Experiments\", f\"{EXPERIMENT_NAME}_{timestamp}_{run_id}\")\n",
|
| 123 |
+
" os.makedirs(SAVE_DIR, exist_ok=True)\n",
|
| 124 |
+
" writer = SummaryWriter(log_dir=SAVE_DIR)\n",
|
| 125 |
+
"\n",
|
| 126 |
+
" # Data\n",
|
| 127 |
+
" print(\"⬇️ Loading Data...\")\n",
|
| 128 |
+
" tokenizer = RobertaTokenizerFast.from_pretrained(HF_ID)\n",
|
| 129 |
+
" dataset = load_dataset(HF_ID)\n",
|
| 130 |
+
" pad_id = tokenizer.pad_token_id # We need this for the mask\n",
|
| 131 |
+
"\n",
|
| 132 |
+
" data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=True, mlm_probability=0.15)\n",
|
| 133 |
+
"\n",
|
| 134 |
+
" train_loader = DataLoader(dataset[\"train\"], batch_size=BATCH_SIZE, shuffle=True, collate_fn=data_collator, num_workers=2, pin_memory=True, persistent_workers=True)\n",
|
| 135 |
+
" valid_loader = DataLoader(dataset[\"validation\"], batch_size=BATCH_SIZE, collate_fn=data_collator, num_workers=2, pin_memory=True)\n",
|
| 136 |
+
" test_loader = DataLoader(dataset[\"test\"], batch_size=BATCH_SIZE, collate_fn=data_collator, num_workers=2, pin_memory=True)\n",
|
| 137 |
+
"\n",
|
| 138 |
+
" # ======================================================\n",
|
| 139 |
+
" # 3. MODEL: DIRECTLY USING THE LIBRARY\n",
|
| 140 |
+
" # ======================================================\n",
|
| 141 |
+
" print(\"\\n⚡ INITIALIZING x_transformers LIBRARY MODEL...\")\n",
|
| 142 |
+
"\n",
|
| 143 |
+
" model = TransformerWrapper(\n",
|
| 144 |
+
" num_tokens=VOCAB_SIZE,\n",
|
| 145 |
+
" max_seq_len=SEQ_LEN,\n",
|
| 146 |
+
" use_abs_pos_emb=False, # FALSE because we use RoPE\n",
|
| 147 |
+
" tie_embedding=True, # Match PRISM (if PRISM tied embeddings)\n",
|
| 148 |
+
" attn_layers=Encoder(\n",
|
| 149 |
+
" dim=D_MODEL,\n",
|
| 150 |
+
" depth=DEPTH,\n",
|
| 151 |
+
" heads=HEADS,\n",
|
| 152 |
+
" layer_dropout=DROPOUT,\n",
|
| 153 |
+
" attn_dropout=DROPOUT,\n",
|
| 154 |
+
" ff_dropout=DROPOUT,\n",
|
| 155 |
+
" rotary_pos_emb=True, # Match PRISM Refiner\n",
|
| 156 |
+
" attn_flash=True, # Match PRISM Refiner\n",
|
| 157 |
+
" use_scalenorm=False # <--- CHANGE THIS TO FALSE (Or remove it)\n",
|
| 158 |
+
" )\n",
|
| 159 |
+
" ).to(DEVICE)\n",
|
| 160 |
+
" print(model)\n",
|
| 161 |
+
" print_detailed_param_count(model)\n",
|
| 162 |
+
" # Simple Parameter Count\n",
|
| 163 |
+
" print(f\"📊 Parameters: {sum(p.numel() for p in model.parameters()):,}\")\n",
|
| 164 |
+
"\n",
|
| 165 |
+
" # ======================================================\n",
|
| 166 |
+
"\n",
|
| 167 |
+
" optimizer = optim.AdamW(model.parameters(), lr=LR, weight_decay=WEIGHT_DECAY)\n",
|
| 168 |
+
" total_steps = (len(train_loader) // GRAD_ACCUM) * EPOCHS\n",
|
| 169 |
+
" scheduler = get_cosine_schedule_with_warmup(optimizer, num_warmup_steps=int(0.1*total_steps), num_training_steps=total_steps)\n",
|
| 170 |
+
" criterion = nn.CrossEntropyLoss()\n",
|
| 171 |
+
" scaler = torch.cuda.amp.GradScaler()\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" print(f\"\\n🚀 STARTING TRAINING (Ep 1 to {EPOCHS})\")\n",
|
| 174 |
+
"\n",
|
| 175 |
+
" best_val_loss = float('inf')\n",
|
| 176 |
+
" global_step = 0\n",
|
| 177 |
+
"\n",
|
| 178 |
+
" for epoch in range(EPOCHS):\n",
|
| 179 |
+
" model.train()\n",
|
| 180 |
+
" pbar = tqdm(train_loader, desc=f\"Ep {epoch+1}/{EPOCHS}\", dynamic_ncols=True)\n",
|
| 181 |
+
"\n",
|
| 182 |
+
" for step, batch in enumerate(pbar):\n",
|
| 183 |
+
" x, y = batch['input_ids'].to(DEVICE), batch['labels'].to(DEVICE)\n",
|
| 184 |
+
"\n",
|
| 185 |
+
" # --- CRITICAL CHANGE: PASS MASK MANUALLY ---\n",
|
| 186 |
+
" # x_transformers requires 'mask' to know what is padding\n",
|
| 187 |
+
" mask = (x != pad_id)\n",
|
| 188 |
+
"\n",
|
| 189 |
+
" with torch.cuda.amp.autocast():\n",
|
| 190 |
+
" # We pass the mask directly here\n",
|
| 191 |
+
" outputs = model(x, mask=mask)\n",
|
| 192 |
+
" loss = criterion(outputs.view(-1, VOCAB_SIZE), y.view(-1)) / GRAD_ACCUM\n",
|
| 193 |
+
"\n",
|
| 194 |
+
" scaler.scale(loss).backward()\n",
|
| 195 |
+
"\n",
|
| 196 |
+
" if (step + 1) % GRAD_ACCUM == 0:\n",
|
| 197 |
+
" scaler.unscale_(optimizer)\n",
|
| 198 |
+
" torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n",
|
| 199 |
+
" scaler.step(optimizer)\n",
|
| 200 |
+
" scaler.update()\n",
|
| 201 |
+
" scheduler.step()\n",
|
| 202 |
+
" optimizer.zero_grad()\n",
|
| 203 |
+
" global_step += 1\n",
|
| 204 |
+
"\n",
|
| 205 |
+
" loss_val = loss.item() * GRAD_ACCUM\n",
|
| 206 |
+
" pbar.set_postfix({'loss': f\"{loss_val:.4f}\", 'lr': f\"{scheduler.get_last_lr()[0]:.2e}\"})\n",
|
| 207 |
+
" writer.add_scalar('Train/Loss', loss_val, global_step)\n",
|
| 208 |
+
"\n",
|
| 209 |
+
" # Validation\n",
|
| 210 |
+
" model.eval()\n",
|
| 211 |
+
" val_loss = 0\n",
|
| 212 |
+
" total_batches = 0\n",
|
| 213 |
+
" with torch.no_grad():\n",
|
| 214 |
+
" for batch in valid_loader:\n",
|
| 215 |
+
" x, y = batch['input_ids'].to(DEVICE), batch['labels'].to(DEVICE)\n",
|
| 216 |
+
" mask = (x != pad_id)\n",
|
| 217 |
+
"\n",
|
| 218 |
+
" with torch.cuda.amp.autocast():\n",
|
| 219 |
+
" outputs = model(x, mask=mask)\n",
|
| 220 |
+
" val_loss += criterion(outputs.view(-1, VOCAB_SIZE), y.view(-1)).item()\n",
|
| 221 |
+
" total_batches += 1\n",
|
| 222 |
+
"\n",
|
| 223 |
+
" avg_val_loss = val_loss / total_batches\n",
|
| 224 |
+
" ppl = math.exp(avg_val_loss) if avg_val_loss < 100 else float('inf')\n",
|
| 225 |
+
" print(f\"✨ Epoch {epoch+1} | Val Loss: {avg_val_loss:.4f} | PPL: {ppl:.2f}\")\n",
|
| 226 |
+
" writer.add_scalar('Val/PPL', ppl, epoch+1)\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" # Save Best\n",
|
| 229 |
+
" if avg_val_loss < best_val_loss:\n",
|
| 230 |
+
" best_val_loss = avg_val_loss\n",
|
| 231 |
+
" torch.save(model.state_dict(), os.path.join(SAVE_DIR, \"best.pt\"))\n",
|
| 232 |
+
" print(\" 🏆 New Best Model Saved!\")\n",
|
| 233 |
+
"\n",
|
| 234 |
+
" # Save Last State (Optimizer, Scheduler, Scaler)\n",
|
| 235 |
+
" state = {\n",
|
| 236 |
+
" 'epoch': epoch,\n",
|
| 237 |
+
" 'model': model.state_dict(),\n",
|
| 238 |
+
" 'optimizer': optimizer.state_dict(),\n",
|
| 239 |
+
" 'scheduler': scheduler.state_dict(),\n",
|
| 240 |
+
" 'scaler': scaler.state_dict(),\n",
|
| 241 |
+
" 'best_loss': best_val_loss\n",
|
| 242 |
+
" }\n",
|
| 243 |
+
" torch.save(state, os.path.join(SAVE_DIR, \"last.pt\"))\n",
|
| 244 |
+
"\n",
|
| 245 |
+
" # Test\n",
|
| 246 |
+
" print(f\"\\n🧪 Testing Best Model...\")\n",
|
| 247 |
+
" if os.path.exists(os.path.join(SAVE_DIR, \"best.pt\")):\n",
|
| 248 |
+
" model.load_state_dict(torch.load(os.path.join(SAVE_DIR, \"best.pt\")))\n",
|
| 249 |
+
"\n",
|
| 250 |
+
" model.eval()\n",
|
| 251 |
+
" test_loss = 0\n",
|
| 252 |
+
" total_batches = 0\n",
|
| 253 |
+
" with torch.no_grad():\n",
|
| 254 |
+
" for batch in tqdm(test_loader, desc=\"Testing\"):\n",
|
| 255 |
+
" x, y = batch['input_ids'].to(DEVICE), batch['labels'].to(DEVICE)\n",
|
| 256 |
+
" mask = (x != pad_id)\n",
|
| 257 |
+
" with torch.cuda.amp.autocast():\n",
|
| 258 |
+
" outputs = model(x, mask=mask)\n",
|
| 259 |
+
" test_loss += criterion(outputs.view(-1, VOCAB_SIZE), y.view(-1)).item()\n",
|
| 260 |
+
" total_batches += 1\n",
|
| 261 |
+
"\n",
|
| 262 |
+
" final_ppl = math.exp(test_loss / total_batches)\n",
|
| 263 |
+
" print(f\"🏆 FINAL BASELINE PPL: {final_ppl:.2f}\")\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" writer.close()\n",
|
| 266 |
+
" return model\n",
|
| 267 |
+
"\n",
|
| 268 |
+
"if __name__ == \"__main__\":\n",
|
| 269 |
+
" run_baseline_training()"
|
| 270 |
+
],
|
| 271 |
+
"metadata": {
|
| 272 |
+
"id": "FnQHarBgVBnU"
|
| 273 |
+
},
|
| 274 |
+
"execution_count": null,
|
| 275 |
+
"outputs": []
|
| 276 |
+
},
|
| 277 |
+
{
|
| 278 |
+
"cell_type": "code",
|
| 279 |
+
"source": [
|
| 280 |
+
"!pip freeze"
|
| 281 |
+
],
|
| 282 |
+
"metadata": {
|
| 283 |
+
"id": "3YRhdCC-O2tW"
|
| 284 |
+
},
|
| 285 |
+
"execution_count": null,
|
| 286 |
+
"outputs": []
|
| 287 |
+
},
|
| 288 |
+
{
|
| 289 |
+
"cell_type": "code",
|
| 290 |
+
"source": [
|
| 291 |
+
"import sys\n",
|
| 292 |
+
"import torch\n",
|
| 293 |
+
"import platform\n",
|
| 294 |
+
"import os\n",
|
| 295 |
+
"\n",
|
| 296 |
+
"# Define output file\n",
|
| 297 |
+
"log_file = \"environment_snapshot.txt\"\n",
|
| 298 |
+
"\n",
|
| 299 |
+
"print(f\"📝 Generating {log_file}...\")\n",
|
| 300 |
+
"\n",
|
| 301 |
+
"with open(log_file, \"w\") as f:\n",
|
| 302 |
+
" # 1. PYTHON & SYSTEM INFO\n",
|
| 303 |
+
" f.write(\"=\"*40 + \"\\n\")\n",
|
| 304 |
+
" f.write(\"SYSTEM INFORMATION\\n\")\n",
|
| 305 |
+
" f.write(\"=\"*40 + \"\\n\")\n",
|
| 306 |
+
" f.write(f\"Python Version: {sys.version}\\n\")\n",
|
| 307 |
+
" f.write(f\"Platform: {platform.platform()}\\n\")\n",
|
| 308 |
+
" f.write(f\"Architecture: {platform.machine()}\\n\")\n",
|
| 309 |
+
" f.write(f\"Processor: {platform.processor()}\\n\")\n",
|
| 310 |
+
"\n",
|
| 311 |
+
" # 2. GPU & CUDA INFO\n",
|
| 312 |
+
" f.write(\"\\n\" + \"=\"*40 + \"\\n\")\n",
|
| 313 |
+
" f.write(\"GPU / CUDA INFORMATION\\n\")\n",
|
| 314 |
+
" f.write(\"=\"*40 + \"\\n\")\n",
|
| 315 |
+
" f.write(f\"PyTorch Version: {torch.__version__}\\n\")\n",
|
| 316 |
+
" f.write(f\"CUDA Available: {torch.cuda.is_available()}\\n\")\n",
|
| 317 |
+
"\n",
|
| 318 |
+
" if torch.cuda.is_available():\n",
|
| 319 |
+
" f.write(f\"CUDA Version: {torch.version.cuda}\\n\")\n",
|
| 320 |
+
" f.write(f\"CUDNN Version: {torch.backends.cudnn.version()}\\n\")\n",
|
| 321 |
+
" f.write(f\"Device Name: {torch.cuda.get_device_name(0)}\\n\")\n",
|
| 322 |
+
" f.write(f\"Device Count: {torch.cuda.device_count()}\\n\")\n",
|
| 323 |
+
" else:\n",
|
| 324 |
+
" f.write(\"NO GPU DETECTED\\n\")\n",
|
| 325 |
+
"\n",
|
| 326 |
+
" # 3. COLAB SPECIFICS (If applicable)\n",
|
| 327 |
+
" f.write(\"\\n\" + \"=\"*40 + \"\\n\")\n",
|
| 328 |
+
" f.write(\"ENV VARIABLES (FILTERED)\\n\")\n",
|
| 329 |
+
" f.write(\"=\"*40 + \"\\n\")\n",
|
| 330 |
+
" # Capturing useful Colab/Jupyter env vars without exposing secrets\n",
|
| 331 |
+
" keys_to_log = ['COLAB_GPU', 'CUDA_VERSION', 'TBE_RUNTIME_ADDR']\n",
|
| 332 |
+
" for k, v in os.environ.items():\n",
|
| 333 |
+
" if any(x in k for x in ['COLAB', 'CUDA', 'LD_LIBRARY_PATH']):\n",
|
| 334 |
+
" f.write(f\"{k}: {v}\\n\")\n",
|
| 335 |
+
"\n",
|
| 336 |
+
" # 4. INSTALLED PACKAGES (Pip Freeze)\n",
|
| 337 |
+
" f.write(\"\\n\" + \"=\"*40 + \"\\n\")\n",
|
| 338 |
+
" f.write(\"PIP FREEZE (FULL LIBRARY LIST)\\n\")\n",
|
| 339 |
+
" f.write(\"=\"*40 + \"\\n\")\n",
|
| 340 |
+
"\n",
|
| 341 |
+
"# Append pip freeze output directly to the file\n",
|
| 342 |
+
"os.system(f\"pip freeze >> {log_file}\")\n",
|
| 343 |
+
"\n",
|
| 344 |
+
"print(f\"✅ Log saved to {log_file}\")\n",
|
| 345 |
+
"print(\" (Check the Files tab on the left to download it)\")\n",
|
| 346 |
+
"\n",
|
| 347 |
+
"# Optional: Print head of file to verify\n",
|
| 348 |
+
"!head -n 20 environment_snapshot.txt"
|
| 349 |
+
],
|
| 350 |
+
"metadata": {
|
| 351 |
+
"id": "63cDp0cJL2c2"
|
| 352 |
+
},
|
| 353 |
+
"execution_count": null,
|
| 354 |
+
"outputs": []
|
| 355 |
+
}
|
| 356 |
+
]
|
| 357 |
+
}
|