Implement the following plan:
Plan: Implement all 01-foundations scripts (team develop)
Context
Implementing the 6 remaining scripts in 01-foundations/. microtokenizer.py (Phase 1) is complete and committed. The user directed "start with microgpt.py" and provided Karpathy's reference gist. This plan covers all scripts from microgpt through microvae, using the Build topology: plan → approve → execute with team.
Reference materials:
- Karpathy's gist:
https://gist.github.com/karpathy/8627fe009c40f57531cb18360106ce95
- Engineering spec:
docs/implementation.md
- Canonical autograd:
docs/autograd-interface.md
- Commenting standard:
CONTRIBUTING.md
- Pattern reference:
01-foundations/microtokenizer.py (established conventions)
Task Breakdown
| # | Script | Complexity | ~Lines | Runtime | Depends On |
|---|
| 1 | microgpt.py | complex | 450-550 | < 7 min | none |
| 2 | micrornn.py | complex | 350-400 | < 9 min | Task 1 (autograd pattern) |
| 3 | microembedding.py | moderate | 200-250 | < 5 min | none |
| 4 | microrag.py | complex | 350-400 | < 6 min | none |
| 5 | microdiffusion.py | moderate | 250-300 | < 5 min | none |
| 6 | microvae.py | moderate | 200-250 | < 4 min | none |
Task Details
Task 1: microgpt.py — Autoregressive Language Model (complex)
Owner: Sonnet agent (Wave 1 — priority start)
Reference: Karpathy's gist (architecture + algorithm). NOT a copy — rewritten from scratch with the project's commenting standard and pedagogical goals. Full attribution in header.
Architecture (from spec): GPT-2 variant — RMSNorm (not LayerNorm), no biases, ReLU (not GELU)
Hyperparameters: n_embd=16, n_head=4, n_layer=1, block_size=16, lr=0.01, ~4,200 params
Sections:
- File thesis + attribution (Karpathy reference)
- Imports +
random.seed(42) — os, math, random, urllib.request
- Constants/hyperparameters
- Data loading —
names.txt, character-level tokenization with BOS token
- Value class — canonical autograd interface from
docs/autograd-interface.md:
- Arithmetic:
__add__, __radd__, __mul__, __rmul__, __neg__, __sub__, __rsub__, __truediv__, __rtruediv__, __pow__
- Activations:
tanh(), exp(), relu(), log()
backward() with topological sort
- Autograd callout block (no extensions for microgpt)
- Weight initialization —
state_dict with wte, wpe, lm_head, per-layer attn_wq/wk/wv/wo, mlp_fc1/fc2
- Helper functions —
linear(), softmax() (stable: subtract max), rmsnorm()
- GPT forward pass — token/position embeddings, RMSNorm, multi-head self-attention (incremental KV), residual connections, MLP block, logits
- Training loop — 1000 steps, Adam with bias correction + linear LR decay, cross-entropy loss with clipped log-probs
- Inference — temperature-scaled autoregressive sampling, generate 20 names
Key "why" comments:
- Why RMSNorm over LayerNorm (modern architectures, fewer ops)
- Why incremental KV construction provides causal masking without an explicit mask
- Why softmax needs max-subtraction (overflow prevention)
- Why clipped log-probs (gradient safety at near-zero probabilities)
- Why Adam needs bias correction (early steps have biased moment estimates)
Success criteria:
- Final loss < 2.5
- ≥50% pronounceable generated names
- Runtime < 7 minutes (expected ~3-5 min)
- All canonical autograd test vectors pass
- Stable softmax, clipped log-probs, Adam epsilon patterns present
Critical constraint: The Value class established here becomes the pattern for micrornn, microlora, microdpo, microppo, micromoe. It must match the canonical spec exactly.
Task 2: micrornn.py — Recurrent Sequence Modeling (complex)
Owner: Sonnet agent (Wave 2)
Architecture: Vanilla RNN + GRU side by side. Same dataset, same hyperparameters — only architecture differs.
Hyperparameters: n_hidden=32, seq_len=16, lr=0.01, steps=500 per model, ~800 params each
Sections:
- File thesis + historical context (RNNs → GRUs/LSTMs → Transformers)
- Imports + seed
- Constants
- Data loading — same
names.txt, character-level
- Value class — canonical interface +
sigmoid() extension
- Autograd callout: documents sigmoid addition for GRU gating
- Vanilla RNN:
h_t = tanh(W_xh @ x_t + W_hh @ h_{t-1} + b_h)
y_t = W_hy @ h_t + b_y
- BPTT through unrolled sequence
- Train, print loss, track gradient norms per timestep
- GRU:
- Update gate:
z_t = sigmoid(W_xz @ x_t + W_hz @ h_{t-1})
- Reset gate:
r_t = sigmoid(W_xr @ x_t + W_hr @ h_{t-1})
- Candidate:
h_candidate = tanh(W_xh @ x_t + W_hh @ (r_t * h_{t-1}))
- Hidden:
h_t = (1 - z_t) * h_{t-1} + z_t * h_candidate
- Train, print loss, track gradient norms
- Comparison table: architecture, final loss, gradient norm ratio, sample outputs
- Inference: generate names from both models side by side
Key "why" comments:
- Why gradient norms decay exponentially in vanilla RNN (repeated matrix multiplication)
- Why update gate creates "gradient highways" (h_t = h_{t-1} when z_t ≈ 1)
- Why GRU over LSTM (fewer gates, same principle, easier to follow in scalar autograd)
Success criteria:
- Vanilla RNN gradient norm ratio (last/first): < 0.01
- GRU gradient norm ratio: 0.1–10.0
- GRU final loss < vanilla RNN final loss
- Runtime < 9 minutes
Task 3: microembedding.py — Contrastive Embedding Learning (moderate)
Owner: Sonnet agent (Wave 2)
No autograd needed. Character n-gram features → linear projection → contrastive loss.
Sections:
- File thesis
- Imports + seed —
os, math, random, urllib.request, collections, string
- Constants
- Data loading —
names.txt
- Feature extraction — character n-gram bag (bigrams/trigrams → sparse vector)
- Encoder — matrix multiply + L2 normalize (plain floats, manual gradients)
- Augmentation — random character deletion/swap for positive pairs
- InfoNCE/NT-Xent loss — cosine similarity, temperature scaling
- Training loop — SGD or manual Adam on encoder weights
- Inference — embed new names, find nearest neighbors by cosine similarity
Success criteria:
- Nearest neighbors have low edit distance
- Positive pair cosine similarity > 0.8
- Random pair cosine similarity < 0.3
- Runtime < 5 minutes
Task 4: microrag.py — Retrieval-Augmented Generation (complex)
Owner: Sonnet agent (Wave 2)
Two subsystems: BM25 retrieval index + character-level MLP generator.
Dataset: 100 synthetic factual paragraphs generated programmatically (no download needed).
Sections:
- File thesis
- Imports + seed
- Constants
- Synthetic knowledge base construction (cities, countries, facts)
- Tokenization — simple word splitting
- BM25 index — term frequency saturation, document length normalization, IDF weighting
- Retrieval — score and rank documents against query, return top-k
- Character-level MLP — concatenated
embed(query) + embed(retrieved_context) as input
- Training loop — train MLP on knowledge base
- Inference — same query with and without retrieval, compare output quality
Success criteria:
- BM25 returns relevant docs for ≥80% of test queries
- Generation with retrieval measurably better than without
- Runtime < 6 minutes
Task 5: microdiffusion.py — Denoising Diffusion (moderate)
Owner: Sonnet agent (Wave 2)
Dataset: Synthetic 2D spiral point cloud (generated programmatically, no download).
Sections:
- File thesis + 2D-to-image mapping explanation
- Imports + seed —
math, random
- Constants — T timesteps, beta schedule, learning rate
- Synthetic data generation — spiral/Swiss roll in 2D
- Noise schedule — linear beta schedule, precompute alpha_bar_t
- Timestep embedding — sinusoidal encoding (manual implementation)
- Denoising MLP —
[x_noisy, t_embedding] → predicted_noise, ~1000 params
- Forward process — add noise at arbitrary timestep t using alpha_bar_t
- Training loop — sample t, noise data, predict noise, MSE loss
- Sampling — start from random noise, iteratively denoise for T steps
- Output — statistics of generated points (mean, variance) vs training distribution
Key comments: Explicit 2D-to-image mapping (2D coords → pixels, MLP → U-Net, same algorithm at any dimensionality)
Success criteria:
- Generated point stats within 20% of training distribution
- Runtime < 5 minutes
Task 6: microvae.py — Variational Autoencoder (moderate)
Owner: Sonnet agent (Wave 2)
Dataset: Synthetic 2D distributions (generated programmatically, no download).
Sections:
- File thesis
- Imports + seed —
math, random
- Constants — latent dim, learning rate, beta weight
- Synthetic data generation — 2D point distributions
- Encoder MLP — input → (mean, log_variance)
- Reparameterization trick —
z = mu + exp(0.5 * log_var) * epsilon, epsilon ~ N(0,1)
- This is the entire pedagogical point — must be crystal clear
- Decoder MLP — z → reconstructed output
- ELBO loss — reconstruction loss + beta * KL divergence
- KL closed form:
0.5 * sum(1 + log_var - mean^2 - exp(log_var))
- KL clamping per canonical spec
- Training loop — Adam on encoder + decoder weights
- Inference — latent interpolation between points, sample from prior z ~ N(0,1)
Success criteria:
- Reconstruction loss decreases over training
- KL divergence positive and bounded (not collapsed or exploded)
- Latent interpolation produces smooth transitions
- Runtime < 4 minutes
Execution Strategy
Wave 1: microgpt (1 Sonnet agent)
- Priority start per user request
- Establishes canonical autograd pattern
- Validate: run script, check loss < 2.5, verify generated name quality
- After validation, microgpt serves as reference for micrornn
Wave 2: remaining 5 scripts (5 Sonnet agents, parallel)
- Each agent owns exactly one script file (file ownership is sacred)
- All agents receive: the canonical autograd spec, the CONTRIBUTING.md commenting standard, the microtokenizer.py as a pattern reference for section headers/comment density, and microgpt.py as the autograd reference (for micrornn specifically)
- Each agent runs its script and validates against success criteria
Verification (Lead)
After all agents complete:
- Run each script:
python 01-foundations/<script>.py — verify exit 0
- Check runtime < specified limit
- Verify success criteria per spec
- Check comment density (30-40%)
- Check no external imports
- Ensure consistent
random.seed(42) pattern
Team Composition
| Role | Model | Assignment | Mode |
|---|
| Lead | Opus (me) | Coordination, validation | delegate |
| Engineer-GPT | Sonnet | microgpt.py | Wave 1, full autonomy |
| Engineer-RNN | Sonnet | micrornn.py | Wave 2, full autonomy |
| Engineer-Embed | Sonnet | microembedding.py | Wave 2, full autonomy |
| Engineer-RAG | Sonnet | microrag.py | Wave 2, full autonomy |
| Engineer-Diff | Sonnet | microdiffusion.py | Wave 2, full autonomy |
| Engineer-VAE | Sonnet | microvae.py | Wave 2, full autonomy |
Cost class: moderate (7 agents total including lead, each producing 200-550 lines)
Conventions (all scripts must follow)
from __future__ import annotations as first import
random.seed(42) after imports
- Section headers:
# === SECTION NAME ===
- File thesis as top docstring
- Data auto-download via
urllib + local cache
if __name__ == "__main__": guard for execution
- Print training progress (step, loss) and inference results
- 30-40% comment/blank line density
- Stable softmax, clipped log-probs, Adam epsilon (where applicable)
- 100 char max line length, 4-space indent, f-strings
If you need specific details from before exiting plan mode (like exact code snippets, error messages, or content you generated), read the full transcript at: /Users/druk/.REDACTED.jsonl
If this plan can be broken down into multiple independent tasks, consider using the TeamCreate tool to create a team and parallelize the work.