Best for
- Implementing autograd / backprop from scratch (micrograd-style)
- Building makemore (bigram, MLP, WaveNet-style character LMs)
- Implementing self-attention, multi-head attention, causal masking
vasilyu1983/AI-Agents-public/frameworks/shared-skills/skills/ai-pretraining/SKILL.md
Builds a transformer/GPT and BPE tokenizer from scratch. Use when implementing autograd, self-attention, a nanoGPT-style pretraining loop, or a byte-level tokenizer.
Decision brief
Domain: building a transformer/GPT and a BPE tokenizer from first principles — the from-first-principles training-layer competency. Does NOT cover applications-layer fine-tuning, RLHF, or inference optimization; those belong to sibling skills.
Compatibility matrix
| Platform | Status | Evidence | What to check |
|---|---|---|---|
| Codex | Declared | Source record | Install path and trigger |
| Claude Code | Declared | Source record | Install path and trigger |
| Cursor | Not declared | No explicit evidence | Portability before use |
| Gemini CLI | Not declared | No explicit evidence | Portability before use |
Installation
The source command is displayed only when detected. A safe inspection prompt is always available so your agent can explain every action before execution.
npx skills add https://github.com/vasilyu1983/AI-Agents-public --skill "frameworks/shared-skills/skills/ai-pretraining"Inspect the Agent Skill "ai-pretraining" from https://github.com/vasilyu1983/AI-Agents-public/blob/53f6cb73ea53a2646e3e7d4665062ad66f3683ac/frameworks/shared-skills/skills/ai-pretraining/SKILL.md at commit 53f6cb73ea53a2646e3e7d4665062ad66f3683ac. List every install step, command, network request, credential, file read/write, external action, and rollback step. Explain whether it fits my task. Do not install or execute anything until I approve.
Workflow
1. Autograd first: implement Value class with backward(), build MLP, verify gradients against PyTorch. 2. Character LM ladder: bigram table - MLP (makemore) - verify loss convergence and sampling. 3. Attention module: single-head self-attention with causal mask; verify attention…
Review the “ASCII Flow” section in the pinned source before continuing.
Activate when the user asks about:
LLM lifecycle, fine-tuning, provider selection, deployment - ai-llm
Build GPT-2 first to understand the mechanics, then apply the deltas — the pre-norm residual skeleton is unchanged; you swap sublayers, not the architecture.
Permission review
No configured static risk pattern was detected
This is not proof of safety. Runtime behavior, indirect dependencies, and hidden external systems are outside the static scan.
Evidence record
| Signal | Value | Evidence type | Meaning |
|---|---|---|---|
| Quality score | 92/100 | Computed | Documentation, specificity, maintenance, and trust rules |
| Repository stars | 82 | Source | Repository attention, not individual Skill quality |
| Compatibility | 2 platforms | Source | Declared in the catalog source record |
| Usage guide | automated source guide | Editorial | Generated or reviewed according to the visible evidence level |
Pinned source
Domain: building a transformer/GPT and a BPE tokenizer from first principles — the from-first-principles training-layer competency. Does NOT cover applications-layer fine-tuning, RLHF, or inference optimization; those belong to sibling skills.
Canonical teachers: Karpathy "Neural Networks: Zero to Hero" (micrograd → makemore → "Let's build GPT" → "Let's build the GPT Tokenizer" → "Let's reproduce GPT-2"), Karpathy nanochat (full-stack from-scratch successor to nanoGPT, 2025), Raschka "Build a Large Language Model From Scratch", nanoGPT, minbpe, "Attention Is All You Need".
GPT-2 is the pedagogical spine here — the right thing to build first. The 2026 from-scratch baseline then swaps four components onto that spine (RoPE, RMSNorm, SwiGLU, GQA) and runs attention through FlashAttention/SDPA; see Modern Architecture Deltas.
Raw text corpus
|
v
BPE Tokenizer (byte-level merges, vocab, encode/decode)
|
v
Token IDs -> Embedding table (vocab_size x n_embd)
|
v
+ Positional Embedding (learned, shape: block_size x n_embd)
|
v
Transformer Block x N
├── LayerNorm (pre-norm placement in GPT-2 style)
├── Multi-Head Self-Attention (causal mask, k/q/v projections)
├── Residual connection
├── LayerNorm
├── FFN (Linear -> GELU -> Linear, 4x expansion)
└── Residual connection
|
v
Final LayerNorm
|
v
LM Head (Linear, n_embd -> vocab_size, weight-tied to embedding)
|
v
Cross-entropy loss -> Pretraining loop
(bf16/autocast, grad accumulation, cosine LR + warmup, checkpoint)
Activate when the user asks about:
nn.MultiheadAttention output exactly.torch.autocast(bf16), gradient accumulation, cosine LR, checkpoint.wpe, RMSNorm for LayerNorm, SwiGLU for the GELU-MLP, GQA, and F.scaled_dot_product_attention; optionally train with Muon. See Modern Architecture Deltas.Build GPT-2 first to understand the mechanics, then apply the deltas — the pre-norm residual skeleton is unchanged; you swap sublayers, not the architecture.
| GPT-2 (2019) | 2026 baseline | Why |
|---|---|---|
Learned absolute pos embed (wpe) | RoPE (rotary, in attention) | Relative position; better length extrapolation; no block_size ceiling |
| LayerNorm | RMSNorm | Cheaper, no centering/bias, stable at depth |
| GELU-MLP (4×) | SwiGLU (~8/3×) | Gated FFN improves quality per param |
| MHA (KV heads = query heads) | GQA (fewer KV heads) | Shrinks KV cache for inference |
| Hand-rolled softmax attention | F.scaled_dot_product_attention | FlashAttention kernel — O(T) memory, much faster |
| AdamW for all params | Muon (2D matrices) + AdamW (embed/head/norms) | Newton-Schulz orthogonalized updates; large per-step speedup |
Frontier reference: the modded-nanoGPT speedrun stacks Muon, QK-Norm, ReLU², logit softcap, and embedding-skip connections to drive GPT-2-grade FineWeb val loss to ~3.28 far below the original wall-clock on 8×H100 (record still ~3.28-target as of mid-2026, per the repo README). The record is a moving target — verify the current repo README, don't quote a fixed time. For the full from-scratch pipeline (tokenizer → pretrain → SFT → RL → serve), Karpathy's nanochat is the 2025 successor to nanoGPT; its headline benchmark shifted in 2026 to "time to GPT-2" (wall-clock to beat GPT-2 1.6B on DCLM CORE, 8×H100) — check the repo, not this doc, for the current number.
| Component | Key Detail | Common Mistake |
|---|---|---|
| Autograd | Value.backward() accumulates += into .grad, not = | Forgetting to zero grads before .backward() |
| Embedding | nn.Embedding(vocab_size, n_embd) — random init, learned | Confusing token embed with positional embed shape |
| Causal mask | torch.tril(torch.ones(T,T)) before softmax; fill -inf not 0 | Using 0 fill — attention leaks future tokens |
| Attention math | softmax(QK^T / sqrt(d_k)) * V | Forgetting /sqrt(d_k) — variance explodes |
| LayerNorm placement | Pre-norm (before attention/FFN) in GPT-2; original paper was post-norm | Post-norm makes deep stacks hard to train |
| FFN expansion | 4x hidden dim, GELU activation | Using ReLU — slight quality difference, matters at scale |
| Weight tying | LM head matrix = transpose of embedding matrix | Forgetting tying doubles params and degrades loss |
| Init scaling | std=0.02 for most; residual projections: std=0.02/sqrt(2*n_layer) | Flat 0.02 everywhere — residual stream variance grows |
| Gradient accumulation | accumulate N micro-batches, divide loss by N, step once | Forgetting to divide loss — effective LR N× too large |
| bf16 autocast | torch.autocast('cuda', dtype=torch.bfloat16) | Using fp16 without loss scaling — NaN on older GPUs |
| BPE merges | greedy highest-frequency pair; merge in-place, repeat | Not updating pair counts after each merge — wrong vocab |
| Cosine LR | warmup linearly for ~1% of steps, then cosine decay to ~10% of peak | Skipping warmup — loss spike at start |
| Temperature | logits / temperature before softmax; T<1 sharpens (more deterministic), T>1 flattens (more random) | Applying temperature after softmax — has no effect on the distribution |
| Top-k sampling | zero out all logits except the top-k before softmax; draw from the remaining distribution | Top-k=1 is greedy decoding; top-k=vocab_size is pure sampling |
| KV-cache | at inference, cache K and V tensors for all past positions; on each new token only compute Q/K/V for the single new position and append to cache | Re-computing all K/V at each generation step — O(T²) cost; cache turns it O(T) |
optimizer.zero_grad() before the forward pass (or set_to_none=True for speed), not after .step().-float('inf') or float('-inf'), not a large negative constant like -1e9 — softmax on -inf gives exact 0, large negatives can give small nonzero values.worker_init_fn.torch.compile interaction: torch.compile + gradient checkpointing can conflict in some PyTorch versions — test before enabling both.attn_weights.sum(dim=-1) is all-ones (no causal leak check).torch.nn. equivalent before stacking.ln(V) loss; check this at step 0.betas=(0.9, 0.999) — GPT-2 paper used betas=(0.9, 0.95) for stability at scale.nn.MultiheadAttention on identical inputs before moving on.ln(vocab_size) by >10%, stop and debug — don't train through bad initialization.torch.compile flags, DataLoader args) against current PyTorch docs before recommending.Before applying this skill on a non-trivial task, read learnings.consolidated.md in this directory (and learnings.md if present).
After applying it, if you encountered a pattern worth remembering, a mistake worth preventing, or a domain fact that surprised you, append one dated bullet to learnings.md via agents-skills-feedback-loop/scripts/append_learning.py. Do not modify SKILL.md itself.
Frequently asked questions
Domain: building a transformer/GPT and a BPE tokenizer from first principles — the from-first-principles training-layer competency. Does NOT cover applications-layer fine-tuning, RLHF, or inference optimization; those belong to sibling skills.
The source record exposes this install command: npx skills add https://github.com/vasilyu1983/AI-Agents-public --skill "frameworks/shared-skills/skills/ai-pretraining". Inspect the command and pinned source before running it.
The pinned source record declares support for: codex, claude code.
Alternatives
vasilyu1983/AI-Agents-public
Configures Claude Code hooks and Codex hooks.json/notify callbacks. Use when adding guardrails, preflight, audit trails, worktree automation, or budget enforcement.
vasilyu1983/AI-Agents-public
Guides iOS testing with XCTest, XCUITest, Swift Testing, simctl, and xcresult. Use when choosing destinations, controlling flakes, or parsing test artifacts for native apps.
vasilyu1983/AI-Agents-public
Guides multi-GPU pre-training: DDP, FSDP2, ZeRO, tensor/pipeline/expert parallelism, fp8/Muon. Use when scaling a run, training MoE, or reproducing GPT-2 on rented GPUs.
vasilyu1983/AI-Agents-public
Sizes models and token budgets using Kaplan/Chinchilla scaling laws. Use when reasoning about compute-optimal N and D, tokens-per-parameter ratios, or over-training tradeoffs.