File size: 21,124 Bytes
f90f02b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 | {
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# ANLP Assignment 2: Mixture of Experts, Pretraining Optimizers, and Decoding Strategies\n",
"### Complete Self-Contained GPU Runner for Google Colab Pro (T4 / V100 / A100)\n",
"\n",
"[](https://colab.research.google.com/github/Chiranjeevi-2020/ANLP_assignment2/blob/main/colab/ANLP_Assignment2_Colab_Runner.ipynb)\n",
"\n",
"Welcome! This notebook executes all three core sections of **Assignment 2 (Monsoon 2026, IIIT Hyderabad)**:\n",
"1. **Part 1: Mixture of Experts (MoE) (40 marks)** \u2014 5 FFN variants, parameter parity matching, Switch auxiliary loss, and language specialization heatmaps on `belumind/en-vi-ja-curated-500k-triplets`.\n",
"2. **Part 2: Custom Optimizers from Scratch (30 marks)** \u2014 Category 1 (AdamW), Category 2 (Adan), Category 3 (Lion), Category 4 (Muon), and Bonus (Sophia) pretraining dynamics on `browndw/human-ai-parallel-corpus`.\n",
"3. **Part 3: Decoding Strategies from Scratch (30 marks)** \u2014 Greedy, Top-k, Top-p, and Beam Search ($B \\in \\{1, 2, 4\\}$) on `EleutherAI/Pythia-160M` evaluated on `hamishivi/ROCStories` (1,000 samples) using strictly `model.forward()`.\n",
"\n",
"---\n",
"### \ud83d\udc76 Explain Like I'm 5 (ELI5): What Are We Doing in This Notebook?\n",
"Imagine you are building a team of smart robots to read and write stories:\n",
"- **Part 1 (Mixture of Experts)**: Instead of asking one big robot to know every language, we have a smart receptionist that sends Vietnamese words to one expert robot and Japanese words to another expert robot! They share the work so each robot does what it's best at.\n",
"- **Part 2 (Optimizers)**: How do robots learn from their mistakes? An optimizer is like a coach telling the robot how big of a step to take. We test 5 different coaches from scratch (like Muon, which uses matrix geometry, and Lion, which saves half the memory) to see who trains the robot fastest!\n",
"- **Part 3 (Decoding Strategies)**: When the robot writes the next word of a story, how does it choose? Greedy always takes the highest score; Top-k and Top-p pick from the best fun choices so the story isn't boring; Beam search looks ahead like a chess master to find the best storyline!\n",
"\n",
"---\n",
"### \u23f1\ufe0f Expected Runtimes on Google Colab Pro\n",
"| Pipeline Stage | Fast Verification / Smoke Test | Full Dataset Training (Colab Pro A100/V100) |\n",
"| :--- | :--- | :--- |\n",
"| **Environment & Git Setup** | ~30 seconds | ~30 seconds |\n",
"| **Part 1: 5 MoE Ablations** | ~2 minutes (dummy tensors) | ~45-60 minutes (A100) / ~90 minutes (T4) |\n",
"| **Part 2: 5 Optimizers Dynamics** | ~1 minute (warmup) | ~30-40 minutes (A100) / ~60 minutes (T4) |\n",
"| **Part 3: Decoding Benchmark (1,000 samples)** | ~30 seconds (10 samples) | ~10-15 minutes (1,000 samples on A100) |\n",
"| **Total End-to-End Execution** | **~5 minutes** | **~1.5 to 2.5 hours** |\n",
"\n",
"---\n",
"### \ud83d\udcc1 Where Are Files & Checkpoints Generated?\n",
"- Trained Model Checkpoints: `checkpoints/part1/` and `checkpoints/part2/`\n",
"- Heatmaps & Plots: `assets/expert_heatmap.png`, `assets/optimizer_dynamics.png`, `assets/beam_search_runtime.png`\n",
"- Numerical Results & Logs: `assets/part2/optimizer_benchmark_results.json`, `assets/part3/decoding_summary.json`\n",
"- At the end of this notebook, a single cell zips all outputs into `submission_artifacts.zip` for instant local download."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step 1: Clone Repository & Set Working Directory (ELI5: Put our project on the computer)\n",
"\n",
"Google Colab starts with an empty `/content` folder. This cell automatically:\n",
"1. Checks Colab Secrets for a `GH_TOKEN` (needed if your repo is **private**).\n",
"2. Clones your GitHub repository `ANLP_assignment2` into `/content/ANLP_assignment2`.\n",
"3. Changes the active working directory into the repository root.\n",
"4. Pulls the latest commits from branch `main`.\n",
"\n",
"**If your repo is private**, add a secret named `GH_TOKEN` in the \ud83d\udd11 Secrets tab with a [GitHub Personal Access Token](https://github.com/settings/tokens) (Classic, with `repo` scope). Toggle **Notebook access** ON.\n",
"\n",
"**If your repo is public**, no token is needed \u2014 it just works!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os, sys, subprocess\n",
"\n",
"REPO_DIR = \"/content/ANLP_assignment2\"\n",
"\n",
"# --- Fetch GitHub token from Colab Secrets Vault for private repo access ---\n",
"gh_token = None\n",
"try:\n",
" from google.colab import userdata\n",
" for name in ['GH_TOKEN', 'GITHUB_TOKEN', 'github_token', 'gh_token']:\n",
" try:\n",
" gh_token = userdata.get(name)\n",
" if gh_token:\n",
" print(f'\\U0001f513 Found GitHub token in Colab Secrets (key: {name})')\n",
" break\n",
" except Exception:\n",
" pass\n",
"except ImportError:\n",
" pass # Not running in Colab\n",
"\n",
"# --- Build clone URL (with or without token) ---\n",
"if gh_token:\n",
" clone_url = f'https://{gh_token}@github.com/Chiranjeevi-2020/ANLP_assignment2.git'\n",
"else:\n",
" clone_url = 'https://github.com/Chiranjeevi-2020/ANLP_assignment2.git'\n",
" print('\\u26a0\\ufe0f No GitHub token found in Colab Secrets.')\n",
" print(' If your repo is PRIVATE, add a secret named GH_TOKEN with a GitHub Personal Access Token.')\n",
" print(' If your repo is PUBLIC, this will work without a token.')\n",
"\n",
"# --- Clone if not already present ---\n",
"if not os.path.exists(REPO_DIR):\n",
" result = subprocess.run(['git', 'clone', clone_url, REPO_DIR], capture_output=True, text=True)\n",
" if result.returncode != 0:\n",
" print(f'\\u274c Clone failed: {result.stderr.strip()}')\n",
" print('\\n\\U0001f527 FIX: Your repo is likely PRIVATE. Do ONE of these:')\n",
" print(' Option A (Easiest): Go to https://github.com/Chiranjeevi-2020/ANLP_assignment2/settings')\n",
" print(' Scroll to \"Danger Zone\" -> \"Change visibility\" -> Make it Public')\n",
" print(' Option B: Create a GitHub Personal Access Token at https://github.com/settings/tokens')\n",
" print(' Add it to Colab Secrets (\\U0001f511 icon) as GH_TOKEN with Notebook access ON')\n",
" raise RuntimeError('Repository clone failed. See instructions above.')\n",
" else:\n",
" print(f'\\u2705 Successfully cloned repository!')\n",
"\n",
"# --- Navigate into repository root ---\n",
"%cd {REPO_DIR}\n",
"\n",
"# --- Pull latest changes ---\n",
"!git pull origin main --ff-only 2>/dev/null || true\n",
"\n",
"# --- Add to Python path ---\n",
"if REPO_DIR not in sys.path:\n",
" sys.path.insert(0, REPO_DIR)\n",
"\n",
"print(f'\\n\\u2705 Project Root: {os.getcwd()}')\n",
"print(f'\\u2705 Files: {sorted([f for f in os.listdir(\".\") if not f.startswith(\".\")][:15])}')\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step 2: GPU Diagnostics & Setup (ELI5: Check that the supercomputer is awake)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 1. Verify GPU assignment\n",
"!nvidia-smi\n",
"import torch\n",
"print(f\"CUDA Available: {torch.cuda.is_available()}\")\n",
"if torch.cuda.is_available():\n",
" print(f\"Allocated GPU: {torch.cuda.get_device_name(0)}\")\n",
" print(f\"Device Memory: {torch.cuda.get_device_properties(0).total_memory / 1e9:.2f} GB\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step 3: Install Required Libraries (ELI5: Download the tools our robot needs)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Install core NLP, model evaluation, and dashboard packages\n",
"!pip install -q pytest accelerate torch transformers datasets tokenizers sacrebleu evaluate wandb matplotlib seaborn einops huggingface_hub"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step 4: Authenticate WandB & Hugging Face via Colab Secrets Vault (ELI5: Safe Login)\n",
"\n",
"This cell securely fetches your API tokens from Google Colab's **Secrets Vault** without exposing them in code:\n",
"\n",
"### \ud83d\udd11 How to set up your secrets in Colab (One-Time Setup):\n",
"1. Click the **Key icon (\ud83d\udd11)** on Google Colab's left sidebar (Secrets panel).\n",
"2. Click **+ Add new secret**.\n",
"3. Secret 1: Name = `WANDB_API_KEY`, Value = *(your WandB API key from [wandb.ai/authorize](https://wandb.ai/authorize))*\n",
"4. Secret 2: Name = `HF_TOKEN`, Value = *(your Hugging Face token from [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens))*\n",
"5. \u26a0\ufe0f **CRITICAL**: Toggle **Notebook access** to **ON** for both secrets!\n",
"\n",
"*If secrets are not added, the notebook will operate in safe offline mode with zero crashes.*"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"\n",
"# 1. Fetch WandB Secret from Colab Secrets Vault\n",
"wandb_key = None\n",
"try:\n",
" from google.colab import userdata\n",
" for name in ['WANDB_API_KEY', 'wandb_api_key', 'WANDB', 'wandb']:\n",
" try:\n",
" wandb_key = userdata.get(name)\n",
" if wandb_key:\n",
" print(f\"[OK] Found WandB secret under key: '{name}'\")\n",
" break\n",
" except Exception as e:\n",
" err_msg = str(e).lower()\n",
" if \"notebook access\" in err_msg or \"notebookaccesserror\" in type(e).__name__.lower():\n",
" print(f\"[WARNING] Secret '{name}' exists in Colab Secrets Vault, but 'Notebook access' toggle is OFF! Please turn ON the toggle switch next to '{name}' in the Colab Secrets (\ud83d\udd11) tab.\")\n",
"except Exception:\n",
" pass\n",
"\n",
"if wandb_key:\n",
" os.environ['WANDB_API_KEY'] = wandb_key\n",
" try:\n",
" import wandb\n",
" wandb.login(key=wandb_key)\n",
" print(\"[SUCCESS] Successfully authenticated WandB via Colab Secrets!\")\n",
" except Exception as e:\n",
" print(f\"[NOTE] WandB login notice: {e}\")\n",
"else:\n",
" print(\"[INFO] WandB secret not found in Secrets Vault. Operating in safe offline mode (wandb disabled).\")\n",
" os.environ['WANDB_MODE'] = 'offline'\n",
"\n",
"# 2. Fetch Hugging Face Secret from Colab Secrets Vault\n",
"hf_token = None\n",
"try:\n",
" from google.colab import userdata\n",
" for name in ['HF_TOKEN', 'hf_token', 'HUGGINGFACE_TOKEN', 'huggingface_token', 'HF', 'huggingface']:\n",
" try:\n",
" hf_token = userdata.get(name)\n",
" if hf_token:\n",
" print(f\"[OK] Found Hugging Face secret under key: '{name}'\")\n",
" break\n",
" except Exception as e:\n",
" err_msg = str(e).lower()\n",
" if \"notebook access\" in err_msg or \"notebookaccesserror\" in type(e).__name__.lower():\n",
" print(f\"[WARNING] Secret '{name}' exists in Colab Secrets Vault, but 'Notebook access' toggle is OFF! Please turn ON the toggle switch next to '{name}' in the Colab Secrets (\ud83d\udd11) tab.\")\n",
"except Exception:\n",
" pass\n",
"\n",
"if hf_token:\n",
" os.environ['HF_TOKEN'] = hf_token\n",
" os.environ['HUGGING_FACE_HUB_TOKEN'] = hf_token\n",
" try:\n",
" from huggingface_hub import login\n",
" login(token=hf_token, add_to_git_credential=True)\n",
" print(\"[SUCCESS] Successfully authenticated Hugging Face via Colab Secrets!\")\n",
" except Exception as e:\n",
" print(f\"[NOTE] Hugging Face login notice: {e}\")\n",
"else:\n",
" print(\"[INFO] HF secret not found in Secrets Vault. Public datasets and models will download normally.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step 5: Verify Mathematical Integrity & Test Suite (ELI5: Double check all formulas and code tests)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Runs comprehensive pytest suite across all 22 mathematical tests and main verify\n",
"!python -m pytest tests/ -v\n",
"!python main.py verify"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step 6: Part 1 \u2014 Mixture of Experts (MoE) Execution\n",
"### ELI5:\n",
"We test 5 designs:\n",
"1. **Dense**: 1 big standard feedforward brain.\n",
"2. **Top-1 MoE**: 4 experts, 1 chosen per token.\n",
"3. **Top-2 MoE**: 4 experts, 2 chosen per token.\n",
"4. **Shared + Routed**: 1 expert always stays on, plus 1 routed expert chosen from 3.\n",
"5. **Matched Active**: 4 experts with doubled width so active parameters match the dense baseline exactly.\n",
"\n",
"We train on `belumind/en-vi-ja-curated-500k-triplets` to translate Vietnamese & Japanese to English, track routing with Switch auxiliary loss, and extract language heatmaps."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Run Part 1 training across all 5 architectural ablations\n",
"# To run a quick smoke run, keep samples=2000, epochs=1.\n",
"# For full training, increase samples=10000, epochs=3.\n",
"\n",
"ablations = [\"dense\", \"top1\", \"top2\", \"shared_routed\", \"matched_active\"]\n",
"for abl in ablations:\n",
" print(f\"\\n{'='*25} RUNNING PART 1 ABLATION: {abl.upper()} {'='*25}\")\n",
" !python main.py part1 --ablation {abl} --train --samples 2000 --epochs 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step 7: Part 2 \u2014 Custom Optimizers Pretraining Dynamics\n",
"### ELI5:\n",
"We pretrain our dense model on `browndw/human-ai-parallel-corpus` using 5 scratch optimizers:\n",
"1. **AdamW**: Standard baseline with decoupled weight decay.\n",
"2. **Adan**: Looks at gradient differences to smooth out bumpy steps.\n",
"3. **Lion**: Uses only `+1` or `-1` signs, cutting memory in half!\n",
"4. **Muon**: Uses Newton-Schulz polynomial iterations to rotate matrices without distortion.\n",
"5. **Sophia**: Uses second-order diagonal curvature and clipping to handle steep hills.\n",
"\n",
"We log validation loss and test BLEU at $0.1\\times$ intervals to replicate Figure 2 of *Fantastic Pretraining Optimizers*."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Run Part 2 Pretraining Dynamics benchmark for all 5 optimizers\n",
"# tokens=100000 provides quick validation; tokens=500000 gives full Chinchilla curve.\n",
"!python main.py part2 --optimizer all --train --tokens 100000"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step 8: Part 3 \u2014 Decoding Strategies on ROCStories\n",
"### ELI5:\n",
"Using `EleutherAI/Pythia-160M` without calling `model.generate()`, we generate story endings for 1,000 ROCStories samples using:\n",
"- **Greedy**: Always pick top token.\n",
"- **Top-k ($k=40, T=0.8$)**: Pick from top 40 words.\n",
"- **Top-p ($p=0.9, T=0.8$)**: Pick from the top 90% probability mass.\n",
"- **Beam Search ($B=1, 2, 4$)**: Keep the best $B$ candidate story paths.\n",
"\n",
"We measure perplexity, accuracy, and confirm linear latency scaling with respect to beam width $B$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Run Part 3 Decoding Benchmark on 1000 samples\n",
"!python main.py part3 --model_name EleutherAI/Pythia-160M --samples 1000 --output_dir assets/part3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step 9: View Visualizations (ELI5: Look at the pretty pictures our robots made!)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"from IPython.display import Image, display\n",
"\n",
"figs = [\n",
" (\"MoE Language Specialization Heatmap\", \"assets/expert_heatmap.png\"),\n",
" (\"Optimizer Pretraining Dynamics (Fig 2)\", \"assets/optimizer_dynamics.png\"),\n",
" (\"Beam Search Latency vs Beam Width\", \"assets/beam_search_runtime.png\")\n",
"]\n",
"\n",
"for title, path in figs:\n",
" if os.path.exists(path):\n",
" print(f\"\\n=== {title} ({path}) ===\")\n",
" display(Image(path))\n",
" else:\n",
" print(f\"Note: {path} not yet generated.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step 10: Download All Artifacts Locally (ELI5: Pack all homework into a neat zip bag to submit)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Zips all assets, figures, configs, and json results for submission\n",
"!zip -r submission_artifacts.zip assets/ report.pdf configs/\n",
"\n",
"try:\n",
" from google.colab import files\n",
" files.download('submission_artifacts.zip')\n",
" print(\"Downloaded submission_artifacts.zip!\")\n",
"except Exception as e:\n",
" print(f\"Running outside Google Colab environment. File saved as submission_artifacts.zip in current directory ({e}).\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Step 11: Syncing Your Executed Notebook & Results to GitHub (ELI5: Save your work online)\n",
"\n",
"There are two easy ways to get your executed notebook and results on GitHub:\n",
"\n",
"### Option A: Save Executed Notebook Directly via Colab Menu (Recommended & Fastest \ud83d\ude80)\n",
"To save this completed notebook with all its live execution outputs, logs, and plots:\n",
"1. Click **File** (top left menu of Colab) $\\to$ **Save a copy in GitHub**.\n",
"2. Select Repository: `Chiranjeevi-2020/ANLP_assignment2`.\n",
"3. Select Branch: `main`.\n",
"4. File path: `colab/ANLP_Assignment2_Colab_Runner.ipynb`.\n",
"5. Click **OK**. Google Colab commits the executed notebook directly to your GitHub repo!\n",
"\n",
"### Option B: Push Generated Assets Directly from this Colab Cell (Optional)\n",
"If you have a GitHub Personal Access Token saved in Colab Secrets as `GH_TOKEN` or `GITHUB_TOKEN`:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Optional: Push generated figures and results directly from Colab VM\n",
"try:\n",
" from google.colab import userdata\n",
" gh_token = None\n",
" for name in ['GH_TOKEN', 'GITHUB_TOKEN', 'github_token']:\n",
" try:\n",
" gh_token = userdata.get(name)\n",
" if gh_token: break\n",
" except Exception: pass\n",
" \n",
" if gh_token:\n",
" !git config user.email \"chiranjeevi.kumaravadivel@gmail.com\"\n",
" !git config user.name \"Chiranjeevi-2020\"\n",
" !git add assets/ configs/ report.pdf\n",
" !git commit -m \"Colab GPU execution: update high-res training dynamics and assets\"\n",
" !git push https://{gh_token}@github.com/Chiranjeevi-2020/ANLP_assignment2.git main\n",
" print(\"Successfully pushed Colab training assets to GitHub!\")\n",
" else:\n",
" print(\"No GH_TOKEN found in Colab Secrets. Use Option A (File -> Save a copy in GitHub) or download submission_artifacts.zip from Step 10.\")\n",
"except Exception as e:\n",
" print(f\"Git push notice: {e}\")"
]
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"provenance": []
},
"language_info": {
"name": "python",
"version": "3.12"
}
},
"nbformat": 4,
"nbformat_minor": 2
} |