Skip to main content
Milestone #14Not StartedPhase 8Research · Capstone25–40 hours15 required tasks

Research Reproduction

Select a foundational LLM architecture or optimization paper, design a parameter- and FLOP-matched multi-seed experiment from scratch, and publish a reproducible technical report

PythonPyTorchControlled Experimental DesignMulti-Seed Statistical AnalysisMatplotlib / Publication FiguresReproducible Research Shell Scripts
Build Progress0 / 15 tasks (0%)
0%(0/15 steps)Not Started
Project Specification & Architecture

What You Will Build

The final milestone of the AI Roadmap transitions you from an AI builder to an independent AI researcher. You will select a foundational Transformer architecture, positional encoding, normalization, or optimization paper (for example: RoPE vs. Learned/ALiBi Positional Embeddings; SwiGLU vs. GELU Feed-Forward Networks; Grouped-Query Attention vs. Multi-Head Attention; RMSNorm + QK-Norm vs. LayerNorm; or Muon/Lion vs. AdamW), translate its mathematical formulation into your own clean PyTorch implementation, design a strictly controlled experiment holding dataset order, tokenizer, parameter count, and FLOP budget constant, run both baseline and experimental variants across at least 3 random seeds (`seed=42, 43, 44`), execute a multi-row ablation table, and publish a transparent, one-command reproducible research repository and technical report.

Why This Project Matters in the AI/LLM Stack

Reading papers passively creates an illusion of understanding; reproducing a paper's claims at a scaled-down compute budget—discovering which hyperparameters actually drive the improvement, measuring seed variance ($\mu \pm \sigma$), and reporting negative or boundary regimes honestly—is the exact skill practiced at frontier AI research labs.

Learning Objectives

  • Deconstruct a primary LLM research paper into its exact mathematical delta over a standard baseline.
  • Design a confound-free experimental protocol matching parameter count, token budget, batch ordering, and FLOPs.
  • Execute multi-seed runs (`seed=42, 43, 44`) to separate genuine architectural/ algorithmic improvements from random initialization noise.
  • Design and run a systematic ablation table isolating sub-component contributions and boundary failure modes.
  • Author a publication-grade technical report and a single-command `reproduce.sh` pipeline.

Prerequisites

  • Phase 5 Project: Mini GPT Architecture (`milestone-10-mini-gpt-architecture`)
  • Phase 6 Project: Pretrained Mini LLM (`milestone-11-pretrained-mini-llm`)
  • Phase 8 Modules 8.3 & 8.5: Advanced Architectures and Research & Experimentation

Required Mathematical Concepts

  • Parameter-matched architectural scaling (e.g., d_ff = (8/3) d_model for SwiGLU 3-matrix FFN vs 4 d_model for 2-matrix GELU FFN)
  • Iso-FLOP training budget calculation: C ≈ 6 N D
  • Multi-seed sample mean and standard deviation: mu ± sigma across K >= 3 random seeds
  • Signal-to-noise ratio: |mu_exp - mu_base| / sqrt(sigma_exp^2 + sigma_base^2)
Interactive Engineering Checklist

Step-by-Step Implementation Tasks (15 Steps)

Check off each engineering task as your code passes its acceptance criteria. Progress is saved automatically in your browser.

Stage 1 of 40/3 tasks complete

Paper Selection, Mathematical Deconstruction & Hypothesis Formulation

Select a concrete paper, isolate its exact mathematical equations, and write a falsifiable pre-registered experimental hypothesis.

Core

A great reproduction study chooses a clear, focused paper claim that can be tested cleanly on a 5M–25M parameter Transformer.

Implementation: Choose one paper topic (e.g., RoPE vs. Learned PosEmbed + length extrapolation; SwiGLU vs. GELU FFN; GQA vs. MHA KV-bandwidth vs. perplexity; QK-Norm stability at high learning rates; or Muon vs. AdamW) and document the citation and core claim in `PROPOSAL.md`.
Expected Outcome: Focused research topic and scaled proxy specification.
Acceptance Check: `PROPOSAL.md` states the paper title, authors, year, equations under test, and target proxy scale.
Core

Scientific rigor requires specifying what outcome would confirm or refute the hypothesis *before* looking at final test curves.

Implementation: Write a quantitative hypothesis (e.g., 'Parameter-matched SwiGLU achieves lower validation perplexity than GELU across 3 seeds at equal FLOPs, with effect size > 2 standard deviations') and list primary (`val_ppl`) and secondary (`tokens_per_sec`, `peak_vram_mb`) metrics.
Expected Outcome: Pre-registered hypothesis and metric definitions.
Acceptance Check: Hypothesis specifies the independent variable, dependent metrics, and falsification threshold.
Intermediate

A naive SwiGLU layer with $d_{\text{ff}} = 4 d_{\text{model}}$ has 3 matrices instead of 2 (50% more FFN parameters than GELU!). Fair comparisons must scale $d_{\text{ff}} = \frac{2}{3}(4 d_{\text{model}})$ rounded to a multiple of 64.

Implementation: Write `experiments/verify_parity.py` that instantiates both baseline and experimental models and verifies parameter counts match within `< 0.5%` and batch data iterators yield identical token sequences for a given seed.
Expected Outcome: Automated parity audit script.
Acceptance Check: `verify_parity.py` asserts parameter parity (`< 0.5%` delta) and identical batch token IDs across baseline and experimental configs.
Stage 2 of 40/4 tasks complete

Iso-Parameter & Iso-FLOP Baseline vs. Experimental Implementation

Implement the baseline and paper variant in a unified codebase, enforcing identical parameter counts, data ordering, and unit tests.

Core

Your baseline must be well-tuned and bug-free so the proposed method does not win simply because the baseline was misconfigured.

Implementation: Implement the baseline variant in `src/models.py` with clean configuration flags and verify its step-0 loss and training stability.
Expected Outcome: Verified baseline implementation.
Acceptance Check: Baseline passes all shape, gradient, and initial loss (`≈ ln(V)`) checks.
Advanced

Translate the paper's mathematical equations directly into modular PyTorch code within the same repository.

Implementation: Implement the paper's mechanism (e.g., `RotaryEmbedding`, `SwiGLUFFN`, `GroupedQueryAttention`, or `QKNorm`) and expose a single config switch (`method: 'baseline' | 'proposed'`).
Expected Outcome: Clean toggleable implementation of the paper's method.
Acceptance Check: Switching from `baseline` to `proposed` changes only the targeted module while keeping everything else identical.
Intermediate

For example, RoPE dot products must depend only on relative distance $m - n$; GQA with $G = H$ must equal MHA exactly.

Implementation: Create `tests/test_paper_mechanism.py` testing the mathematical invariants of your implemented method.
Expected Outcome: Automated unit test suite for the research mechanism.
Acceptance Check: All mathematical invariant tests pass under `pytest`.
Core

Every run must log its git commit hash, config JSON, random seed, hardware device, step-by-step loss/throughput telemetry, and wall-clock time.

Implementation: Build `src/experiment_runner.py` that pins `random`, `numpy`, and `torch` seeds and writes structured logs to `results/<exp_name>_seed<seed>.jsonl`.
Expected Outcome: Reproducible experiment harness.
Acceptance Check: Running the same config with `seed=42` twice produces identical step-by-step training losses.
Stage 3 of 40/4 tasks complete

Multi-Seed Experiments, Ablation Study & Stress Testing

Run 3 random seeds for baseline and proposed methods, execute component ablations, and test an extreme stress regime.

Intermediate

Running 3 independent seeds establishes the mean and standard deviation ($\mu_{\text{base}} \pm \sigma_{\text{base}}$) of the baseline.

Implementation: Run the baseline configuration across seeds `42`, `43`, and `44` for your full token budget and record all validation checkpoints.
Expected Outcome: Three complete baseline telemetry logs.
Acceptance Check: `results/` contains complete JSONL logs for `baseline_seed42`, `baseline_seed43`, and `baseline_seed44`.
Intermediate

Using the exact same 3 seeds guarantees that each seed pair (`baseline_seed42` vs `proposed_seed42`) sees the exact same mini-batch sequence.

Implementation: Run the proposed configuration across seeds `42`, `43`, and `44` and record validation loss, perplexity, throughput, and peak memory.
Expected Outcome: Three complete proposed-method telemetry logs.
Acceptance Check: `results/` contains complete JSONL logs for `proposed_seed42`, `proposed_seed43`, and `proposed_seed44`.
Advanced

Ablations isolate *why* the method works (e.g., in SwiGLU: testing SiLU activation alone vs. gating alone vs. full SwiGLU; in GQA: testing `kv_heads = 8, 4, 2, 1`).

Implementation: Run at least 2–3 ablation variants isolating intermediate design choices or hyperparameter sensitivities.
Expected Outcome: Complete ablation experiment logs and comparison table.
Acceptance Check: Ablation table compares Baseline, intermediate ablations, and Full Proposed method across identical token budgets.
Advanced

Every architectural choice has tradeoffs—for example, testing length extrapolation at $2\times$ training context length, or testing stability at $3\times$ higher learning rate.

Implementation: Run one targeted stress test evaluating both baseline and proposed models outside the standard training regime and document the result honestly (including negative results if the method fails).
Expected Outcome: Boundary/stress-test empirical measurement.
Acceptance Check: Stress test results are logged and analyzed without cherry-picking.
Stage 4 of 40/4 tasks complete

Statistical Analysis, Publication Figures & Technical Report

Compute mean ± std metrics, generate publication-quality plots, package `reproduce.sh`, and write the final research paper.

Core

Reporting `21.42 ± 0.18` across 3 seeds shows whether an observed improvement exceeds random seed variance.

Implementation: Write `scripts/analyze_results.py` that reads all `results/*.jsonl` files and generates Markdown tables with `mean ± std`, relative delta `%`, and paired seed comparisons.
Expected Outcome: Automated statistical summary script and Markdown results table.
Acceptance Check: Script outputs formatted tables with mean, standard deviation, and per-seed breakdown.
Core

Visualizing mean validation loss curves with $\pm 1\sigma$ shaded error bands communicates convergence speed and stability immediately.

Implementation: Write `scripts/plot_figures.py` to generate high-resolution PNG/SVG plots showing (1) multi-seed validation loss curves with shaded error bands, and (2) the ablation / stress-test comparison bar or line chart.
Expected Outcome: Saved publication figures in `figures/`.
Acceptance Check: Figures have clear axis labels, legends, units, and multi-seed error bands.
Core

True reproducible research allows any engineer to run one script that prepares data, runs tests, executes experiments, and regenerates all tables and figures.

Implementation: Write `reproduce.sh` (with a `--quick` flag for fast verification and `--full` for full 3-seed reproduction) and pin dependencies in `requirements.txt` / `pyproject.toml`.
Expected Outcome: End-to-end executable reproduction script.
Acceptance Check: `bash reproduce.sh --quick` runs cleanly from a fresh state and outputs summary tables.
Core

Structure your report like a clean ML conference workshop paper: Abstract, Paper Summary & Equations, Experimental Setup & Parity Controls, Multi-Seed Results, Ablation Study, Stress-Test & Limitations, and Reproducibility Guide.

Implementation: Write `PAPER_REPORT.md` embedding your statistical tables, generated figures, and candid discussion of where your scaled-down findings agreed with or diverged from the original paper.
Expected Outcome: Publication-grade technical research report.
Acceptance Check: `PAPER_REPORT.md` contains all 6 sections, multi-seed `mean ± std` tables, embedded figures, and limitations analysis.
Reference Architecture & Verification Code

Starter & Verification Code Examples

Iso-Parameter SwiGLU vs. GELU FFN & Multi-Seed Statistical Aggregator

Example showing how to match parameter counts between a 2-matrix GELU FFN and a 3-matrix SwiGLU FFN and compute multi-seed confidence intervals.

import numpy as np
import torch.nn as nn
import torch.nn.functional as F

class GELUFFN(nn.Module):
    def __init__(self, d_model: int):
        super().__init__()
        d_ff = 4 * d_model
        self.fc1 = nn.Linear(d_model, d_ff, bias=False)
        self.fc2 = nn.Linear(d_ff, d_model, bias=False)

    def forward(self, x):
        return self.fc2(F.gelu(self.fc1(x)))

class IsoParamSwiGLUFFN(nn.Module):
    def __init__(self, d_model: int, multiple_of: int = 32):
        super().__init__()
        # 2/3 of 4*d_model keeps 3-matrix parameter count equal to 2-matrix 4*d_model
        hidden = int(2 * (4 * d_model) / 3)
        d_ff = multiple_of * ((hidden + multiple_of - 1) // multiple_of)
        self.w_gate = nn.Linear(d_model, d_ff, bias=False)
        self.w_up = nn.Linear(d_model, d_ff, bias=False)
        self.w_down = nn.Linear(d_ff, d_model, bias=False)

    def forward(self, x):
        return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))

def summarize_seeds(values: list[float]) -> str:
    arr = np.asarray(values, dtype=np.float64)
    return f"{arr.mean():.4f} ± {arr.std(ddof=1):.4f} (n={len(arr)})"
Verification & Acceptance Suite

How to Test Your Implementation

Verify parameter and data-order parity, mathematical invariants of the reproduced mechanism, and deterministic seed reproducibility.

$ pytest tests/test_paper_mechanism.py tests/test_parity.py -vTest Runner

Iso-Parameter & Data-Order Parity Test

Ensure experimental differences cannot be caused by accidental parameter bloat or different batch ordering.

Steps: Run `pytest tests/test_parity.py` comparing parameter counts and first-10-batch token IDs of baseline vs. proposed configs at `seed=42`.

Pass Criteria: Parameter delta `< 0.5%` and batch token IDs match 100%.

Deterministic Seed Reproducibility Test

Confirm that two runs with `seed=42` produce identical loss trajectories.

Steps: Run 20 training steps twice with `seed=42` on the same device and compare logged losses.

Pass Criteria: Step losses match within `1e-6`.

Statistical Aggregator Verification

Ensure `analyze_results.py` computes sample mean and standard deviation accurately.

Steps: Run `python scripts/analyze_results.py` on synthetic seed logs and verify computed `mean ± std`.

Pass Criteria: Exact match with `numpy.mean` and `numpy.std(ddof=1)`.

Overall Project Acceptance Criteria

  • `verify_parity.py` confirms baseline and experimental models match parameter counts within `< 0.5%` and receive identical mini-batch sequences per seed.
  • Both baseline and proposed methods are evaluated across at least 3 random seeds (`seed=42, 43, 44`) with reported `mean ± std` metrics.
  • Repository includes a multi-row ablation study and a stress-regime test.
  • `PAPER_REPORT.md` and `reproduce.sh` provide a complete, self-contained, reproducible research package.
Progressive Spoiler-Free Guidance

Expandable Hints & Debugging Tips

Try implementing each stage on your own first. Expand a hint below if you want to verify tensor shapes, mathematical identities, or common edge cases.

Optional Bonus Extensions

Optional Stretch Challenges

Optional · Does Not Block Completion

Compute-Optimal Scaling Curve Comparison (3 Compute Budgets)

Compare the baseline and proposed method across 3 token budgets (e.g., 10M, 25M, 50M tokens) to measure the compute multiplier ($C_{\text{base}} / C_{\text{proposed}}$ to reach equal validation loss).

What You Learn: How frontier labs measure architectural efficiency in 'effective compute multipliers' rather than single-point loss deltas.

LaTeX Technical Report Compilation

Typeset your `PAPER_REPORT.md` into a 4–6 page NeurIPS/ICLR-style PDF paper with vector matplotlib figures and BibTeX references.

What You Learn: Academic and industrial AI research communication standards.

Expected Deliverable

What Your Completed Repository Should Contain

A complete, one-command reproducible AI research repository (`reproduce.sh`) and publication-grade technical report (`PAPER_REPORT.md`) validating an empirical LLM hypothesis across multiple random seeds.

Deliverable Artifacts

  • `PROPOSAL.md` with mathematical paper deconstruction and pre-registered hypothesis
  • `src/models.py` & `experiments/verify_parity.py` enforcing iso-parameter and data-order parity
  • Multi-seed (`seed=42, 43, 44`) experiment logs for baseline, proposed method, and ablations
  • `scripts/analyze_results.py`, `scripts/plot_figures.py`, and `reproduce.sh`
  • Publication-grade technical report (`PAPER_REPORT.md`) with `mean ± std` tables and figures

After Completing This Project, You Should Be Able To...

  • Translate mathematical formulations from ML research papers directly into PyTorch code.
  • Design rigorous iso-parameter and iso-FLOP controlled experiments free of confounding variables.
  • Evaluate deep learning hypotheses statistically across multiple random seeds and ablation matrices.
  • Publish transparent, reproducible AI research with candid analysis of limitations and negative results.
Portfolio & Repository Tracking

GitHub Repository Submission

Link your public or private GitHub repository URL to keep a structured portfolio of your from-scratch AI builds. Stored locally in your browser (self-reported; no GitHub tokens or remote code execution).

Status: Not Linked

Suggested Repository: llm-research-reproduction-study

Recommended Directory Layout:

PROPOSAL.md
PAPER_REPORT.md
reproduce.sh
src/models.py
src/experiment_runner.py
experiments/verify_parity.py
scripts/analyze_results.py
scripts/plot_figures.py
figures/
tests/test_paper_mechanism.py
tests/test_parity.py
README.md

Recommended README Documentation Checklist

  • State the reproduced paper citation and the exact hypothesis tested.
  • Embed the primary multi-seed validation loss figure (`mean ± std`).
  • Include the multi-row ablation and parity verification table.
  • Provide the single-command `bash reproduce.sh` instructions.
Local Engineering Notebook

Personal Implementation Notes