← Frontier Lab Interview Curriculum·Study guide 04 of 13
Senior-staff study guide · 04

ML coding from scratch and debugging

ML coding rounds ask you to write core model pieces (attention, a KV-cached decode loop, a sampler, a backward pass, an optimizer, or a classic algorithm) from a blank file in NumPy or PyTorch, or to find planted bugs in a small transformer. Frontier labs use it to check that you can turn ideas into correct tensor code fast; OpenAI reports a miniGPT debug plus add-a-KV-cache round and Anthropic a MHA + KV cache + GQA hour. At senior staff the code is table stakes: you are also expected to prove it correct, explain the numerics and memory costs, and say how the same bug or design would behave at scale.

72resources7courses8with video32from 2025–2647%advanced52/52question groups covered4%of interview evidence (0% at staff+)
Intro 7Core 31Advanced 34

The senior-staff bar

What L7-level depth looks like in this topic, the follow-up an interviewer would push on, and the resources that prepare you for it.

From the interview reportsNo staff-level evidence either way. Meta MSL loops at E6 include 'AI coding' (NumPy/PyTorch components); a Microsoft principal prepared for it with CS336 alone.

Start here

The best resources for a time-poor senior engineer, newest first.

2026Practice

LLMs-from-scratch (code for 'Build a Large Language Model (From Scratch)')

Sebastian Raschka · Oct 2026 · ~25 h

Chapter notebooks implement causal multi-head attention, GPT blocks, pretraining, sampling with temperature/top-k, and bonus folders for KV cache, GQA, RoPE-based architectures (Llama, Qwen, Gemma 3) and LoRA (appendix E). Actively maintained in 2026.

2026Course

CS336: Language Modeling from Scratch (Spring 2026)

Tatsunori Hashimoto, Percy Liang (Stanford) · Apr 2026 · ~120 h

Assignment 1 has you write a byte-level BPE tokenizer, a pre-norm transformer with RoPE and SwiGLU, cross-entropy, AdamW, a cosine schedule and a training loop against unit tests; it is the curriculum's end-to-end capstone and the single best rehearsal for the from-scratch rounds.

2026Course

CS231n: Deep Learning for Computer Vision (Spring 2026)

Stanford (Fei-Fei Li, Ehsan Adeli et al.) · Apr 2026 · ~40 h

Assignment 1 is kNN with no-loop vectorized L2 distances, a softmax classifier and a two-layer net with hand-written backward passes checked numerically; A2 adds batchnorm/dropout backward, A3 a captioning transformer. The no-loop kNN is almost exactly the reported OpenAI 1-NN question.

2025Practice

nanoGPT

Andrej Karpathy · Nov 2025 · ~8 h

~300-line GPT model and training loop that is the de facto template for 'miniGPT' interview code; reading model.py closely is preparation for debugging someone else's version of it.

2024Course

Neural Networks: Zero to Hero

Andrej Karpathy · Jun 2024 · ~30 h

Code-along series from micrograd (scalar autograd) through manual backprop of an MLP with batchnorm ('becoming a backprop ninja'), to building GPT, the GPT tokenizer and reproducing GPT-2. The fastest way to make attention-from-a-blank-file muscle memory.

2022Practice

Autodiff-Puzzles

Sasha Rush · Oct 2022 · ~3 h

Write the backward (VJP) for a series of tensor functions, checked automatically; directly drills matmul, sum, broadcasting and indexing gradients.

2022Practice

Tensor-Puzzles

Sasha Rush · Apr 2022 · ~4 h

21 puzzles reimplementing NumPy/PyTorch functions using only broadcasting and arange, one line each.

2019Blog post

A Recipe for Training Neural Networks

Andrej Karpathy · Apr 2019 · ~1 h

The canonical checklist: inspect data, fix seeds, verify init loss (~ln(vocab)), overfit one batch, visualize just before the net, add complexity one step at a time.

Learning path

Work through the stages in order. The last stage is the senior-staff layer: production case studies, papers to critique and large-scale trade-offs. Each resource's L7 line says what it adds at your level.

  1. 1

    Attention from a blank file

    Write causal multi-head attention, RoPE and a KV-cached decode loop with shapes in comments, tested against SDPA · Week 1 (10–12 h)

    • 2022
      Sasha Rush · Apr 2022 · Practice · Core · ~4 h
      21 puzzles reimplementing NumPy/PyTorch functions using only broadcasting and arange, one line each.
      L7Builds the broadcasting fluency that makes loop-free kNN distances and batched attention masks trivial under time pressure.
    • 2026
      NumPy developers · 2026 · Reference · Core · ~1 h
      The exact broadcasting rules, with the pairwise-distance example that underlies loop-free kNN, k-means assignment and closest-center problems.
      L7Baseline; know the rules well enough to spot a 'silently working' broadcast bug, a staple of planted-bug rounds.
    • 2018
      Tim Rocktäschel · Apr 2018 · Blog post · Core · ~1 h
      Worked einsum examples from transpose to batched matmul and bilinear attention; makes multi-head attention a few readable einsum lines.
      L7Baseline; the senior signal is choosing index names that make the head/batch layout and GQA broadcast obvious to the interviewer.
    • 2024
      Andrej Karpathy · Jun 2024 · Course · Core · ~30 h · video
      Code-along series from micrograd (scalar autograd) through manual backprop of an MLP with batchnorm ('becoming a backprop ninja'), to building GPT, the GPT tokenizer and reproducing GPT-2. The fastest way to make attention-from-a-blank-file muscle memory.
      L7Baseline for implementation fluency; the 'backprop ninja' and 'build GPT' episodes are the ones to redo without the video.
    • 2025
      Andrej Karpathy · Nov 2025 · Practice · Core · ~8 h
      ~300-line GPT model and training loop that is the de facto template for 'miniGPT' interview code; reading model.py closely is preparation for debugging someone else's version of it.
      L7Baseline; the value is knowing this file so well that a planted bug in a look-alike stands out.
    • 2026
      PyTorch · 2026 · Reference · Core · ~1 h
      Includes a reference Python implementation of SDPA with is_causal, attn_mask, scale and enable_gqa semantics, plus backend selection (Flash, memory-efficient, math).
      L7Use as the oracle to unit-test your from-scratch attention, and know its mask conventions (bool True = attend) which are a common bug source.
    • 2021
      EleutherAI (Stella Biderman, Sid Black et al.) · Apr 2021 · Blog post · Core · ~1.5 h
      Derivation of RoPE with short PyTorch and JAX implementations; the clearest route from 'rotate pairs of dims' to working code.
      L7Baseline for implementing RoPE correctly in a KV-cached decode loop, where the position offset is the classic bug.
    • 2025
      Sebastian Raschka · Jun 2025 · Tutorial · Core · ~2 h
      Walks through adding a KV cache to a from-scratch GPT: cache buffers, position tracking, reset, and a side-by-side script with and without the cache.
      L7Baseline for the OpenAI 'add a KV cache' round; then extend it yourself to GQA and a pre-allocated cache.
    • 2025
      Hugging Face (Aritra Roy Gosthipaty, Kashif Rasul, Luis Wiedmann, Andres Marafioti, Pedro Cuenca) · Jun 2025 · Blog post · Core · ~1.5 h
      Second worked KV-cache implementation in a small real codebase, separating prefill from decode and handling the position bookkeeping.
      L7Baseline; reading two different KV-cache designs helps you explain the prefill/decode split and where cache bugs come from.
    • 2026
      duoan · Mar 2026 · Practice · Core · ~10 h
      Self-hosted Jupyter 'LeetCode for PyTorch': ~40 problems (softmax, LayerNorm, MHA, GQA, RoPE, KV cache, sampling, transformer block) with an auto-judge that also checks gradients.
      L7Baseline drill set; good for timing yourself on the 'MHA + KV cache + GQA in an hour' target.
  2. 2

    Backprop by hand and classic ML

    Matmul/softmax-CE/layernorm backward in NumPy checked with finite differences; AdamW; loop-free kNN, k-means, logistic regression · Week 2 (10 h)

    • 2026
      Stanford (Fei-Fei Li, Ehsan Adeli et al.) · Apr 2026 · Course · Core · ~40 h · video
      Assignment 1 is kNN with no-loop vectorized L2 distances, a softmax classifier and a two-layer net with hand-written backward passes checked numerically; A2 adds batchnorm/dropout backward, A3 a captioning transformer. The no-loop kNN is almost exactly the reported OpenAI 1-NN question.
      L7Baseline for a staff-level ML engineer; do A1 and the BN-backward part of A2 cold to make hand backprop and vectorization automatic under time pressure.
    • 2016
      Eli Bendersky · Oct 2016 · Blog post · Core · ~1 h
      Step-by-step Jacobian of softmax, the stable max-subtraction trick, and the combined softmax + cross-entropy gradient (p − y).
      L7Baseline; rehearse the derivation until you can do it on a whiteboard in under five minutes and explain why the fused form is numerically safer.
    • 2024
      Andrej Karpathy (llm.c) · Apr 2024 · Tutorial · Core · ~1 h
      Derives and implements LayerNorm forward and backward in PyTorch, checked against autograd, then ports it to C; the companion to the softmax/layernorm-from-scratch question.
      L7Baseline-to-core; know the compact backward formula and why mean/variance are cached.
    • 2022
      Sasha Rush · Oct 2022 · Practice · Advanced · ~3 h
      Write the backward (VJP) for a series of tensor functions, checked automatically; directly drills matmul, sum, broadcasting and indexing gradients.
      L7Trains exactly the 'matmul forward and backward from a skeleton' question and its harder follow-ups.
    • 2007
      Mark Harris, Shubhabrata Sengupta, John D. Owens (NVIDIA) · 2007 · Reference · Advanced · ~2 h
      Explains the naive Hillis–Steele scan (O(n log n) work) and the work-efficient Blelloch up-sweep/down-sweep, with diagrams; the scan pattern OpenAI's prefix-matmul question builds on.
      L7Lets you write a scan over an associative op (matrix products) and reason about its backward pass and depth/work trade-off, which is the senior follow-up to 'matmul backward'.
    • 2020
      Andrej Karpathy · Apr 2020 · Practice · Intro · ~3 h
      ~150-line scalar reverse-mode autograd engine with a tiny neural-net library on top.
      L7Baseline; rewrite it from memory in 30 minutes as a warmup for autograd questions.
    • 2026
      Alisa Liu (UW) · Jun 2026 · Reference · Core · ~4 h
      Personal notes by an LM researcher, written for interview prep: shapes and backprop for linear layers (including PyTorch's W-transpose convention and why bias gradients sum over the batch), activations, Jacobians.
      L7Baseline; good for checking that your whiteboard gradient derivations use the same shape conventions PyTorch does.
    • 2026
      Diyi Yang, Yejin Choi (Stanford) · Jan 2026 · Course · Core · ~30 h · video
      A2 drills tensor derivatives (the softmax + cross-entropy gradient that comes up on whiteboards); A3 is self-attention and transformers. Good targeted practice for the derivation-style questions.
      L7Baseline; use A2's written part to rehearse deriving gradients aloud cleanly, which is what a research-fundamentals round grades.
    • 2017
      Ilya Loshchilov, Frank Hutter · Nov 2017 · Paper · Advanced · ~1.5 h
      Shows that L2 regularization and weight decay differ under Adam and gives the decoupled update; Algorithm 2 is what you implement from scratch.
      L7Lets you explain precisely why Adam+L2 is not AdamW and what that means for which parameters get decayed, a frequent interviewer probe after you write the optimizer.
    • 2026
      Deep-ML · 2026 · Practice · Core · ~15 h
      1,200+ auto-graded NumPy/PyTorch problems: linear and logistic regression, k-means, kNN, PCA, softmax, attention, optimizers, plus an interview-prep track.
      L7Baseline drill platform; use it for timed classic-ML-from-scratch reps.
    • 2026
      PyTorch · 2026 · Reference · Core · ~2 h
      detect_anomaly/set_detect_anomaly to find the op that produced a NaN in backward, gradcheck/gradgradcheck for finite-difference checks of custom backward passes, hooks and the functional Jacobian API.
      L7Lets you verify a hand-written backward in one line and localize NaNs fast during a live debug session.
  3. 3

    Debug a broken miniGPT, then sampling

    Build a 15-bug zoo, narrate a bisection, find 5 planted bugs in 45 min; implement temperature/top-k/top-p/beam · Week 3 (8–10 h)

    • 2019
      Andrej Karpathy · Apr 2019 · Blog post · Core · ~1 h
      The canonical checklist: inspect data, fix seeds, verify init loss (~ln(vocab)), overfit one batch, visualize just before the net, add complexity one step at a time.
      L7Baseline, but rehearse narrating it — a structured bisection out loud is what separates candidates in the debug round.
    • 2021
      Josh Tobin (Full Stack Deep Learning) · Mar 2021 · Lecture · Core · ~1.5 h · video
      Decision-tree approach to DL debugging: start simple, implement and debug (shape mismatches, casting, OOM, numerical instability), compare to a known result, then bias-variance.
      L7Baseline; gives you a named bug taxonomy to organize a 15-bug zoo around.
    • 2026
      PracHub (candidate-reported) · Sep 2026 · Practice · Core · ~1.5 h
      Candidate-reported write-up of the OpenAI ML-coding round: find 4–5 planted bugs in a decoder-only transformer, then add a KV cache and check it matches full recompute.
      L7Use it to calibrate scope and timing for the real round; the content is the prompt, not a solution.
    • 2026
      PyTorch · 2026 · Tutorial · Intro · ~0.5 h
      Dataset/DataLoader contract, shuffling, batching and custom collate; pair with the torch.utils.data reference for samplers and workers.
      L7Baseline; enough to catch unshuffled loaders, label/feature misalignment and worker-seeding bugs in a data-pipeline debug round.
    • 2023
      Eugene Yan · Feb 2023 · Blog post · Core · ~0.5 h
      Practical test patterns for ML code: tiny real models instead of mocks, output-shape and range checks, loss-decreases and overfit-a-batch tests, and leakage checks.
      L7Baseline; lets you state what tests you would add after fixing a bug, which interviewers often ask as the wrap-up.
    • 2026
      PyTorch · 2026 · Reference · Advanced · ~1 h
      Where results legitimately differ: non-associative float sums, batched vs single computation, TF32 on Ampere+, reduced-precision reductions in fp16/bf16, and extremal values.
      L7Lets you tell a real bug from expected numerical noise when two implementations disagree, and explain tolerance choices in tests.
    • 2020
      Patrick von Platen (Hugging Face) · Mar 2020 · Blog post · Core · ~1 h
      Greedy, beam search, top-k, top-p and temperature explained with examples; enough to implement each from logits.
      L7Baseline; skim if known.
    • 2019
      Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes, Yejin Choi · Apr 2019 · Paper · Advanced · ~1.5 h
      Introduces nucleus (top-p) sampling and shows why beam search and pure sampling degenerate.
      L7Lets you justify sampler choices with evidence rather than defaults, and explain the failure modes of beam search for open-ended text.
    • 2021
      Edward J. Hu et al. (Microsoft) · Jun 2021 · Paper · Advanced · ~1.5 h
      Low-rank update W + BA with B zero-initialized and an alpha/r scale; short enough to implement from the paper in 20 minutes.
      L7Lets you defend init, scaling and merge-at-inference choices and say which matrices to adapt.
  4. 4

    CS336 Assignment 1 end to end

    BPE tokenizer, transformer LM, AdamW, schedule and training loop passing the official tests, trained on TinyStories · Weeks 4–5 (25–40 h)

  5. 5

    Senior-staff depth

    Argue KV-cache budgets, attention variants, stability fixes and nondeterminism with numbers and primary sources · Week 6+ (12–15 h, selective)

    • 2019
      Noam Shazeer (Google) · Nov 2019 · Paper · Advanced · ~1.5 h
      Introduces multi-query attention and analyses incremental decoding as memory-bandwidth bound, with the KV-cache arithmetic that motivates it.
      L7Lets you argue from bytes moved per token why decode is bandwidth-bound and why sharing K/V heads helps, instead of just naming MQA.
    • 2023
      Joshua Ainslie et al. (Google Research) · May 2023 · Paper · Advanced · ~1 h
      Grouped-query attention and uptraining from MHA checkpoints; the variant Anthropic reportedly asked for alongside a KV cache in one hour.
      L7Lets you implement GQA via head repetition/broadcast and quantify the cache saving versus quality loss.
    • 2024
      DeepSeek-AI · May 2024 · Paper · Advanced · ~2 h
      Introduces Multi-head Latent Attention (MLA), which caches a low-rank latent instead of full K/V, and explains the decoupled-RoPE trick it needs.
      L7Lets you compare MHA/GQA/MLA cache sizes per token and explain why RoPE complicates low-rank K/V, a typical senior follow-up.
    • 2022
      Tri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra, Christopher Ré · May 2022 · Paper · Advanced · ~3 h
      Tiled attention with online softmax that never materializes the N×N score matrix; the algorithm CS336 A2 has you implement in Triton.
      L7Lets you write the online-softmax recurrence by hand and explain why attention is memory-bound, which turns a 'write attention' question into a systems discussion.
    • 2018
      Maxim Milakov, Natalia Gimelshein (NVIDIA) · May 2018 · Paper · Advanced · ~1 h
      Four-page paper deriving the single-pass running-max/running-sum softmax that FlashAttention and streaming log-sum-exp computations use.
      L7Lets you derive streaming softmax, entropy or attention over chunks on the spot and prove it equals the two-pass result.
    • 2022
      kipply (Carol Chen) · Mar 2022 · Blog post · Advanced · ~1.5 h
      Back-of-envelope formulas for KV-cache size, FLOPs versus memory bandwidth, and latency for prefill and decode.
      L7Lets you defend a KV-cache memory budget with numbers in the same interview where you implement it.
    • 2025
      Horace He and Thinking Machines Lab · Sep 2025 · Blog post · Advanced · ~1.5 h
      Shows that temperature-0 nondeterminism in serving comes mainly from batch-size-dependent kernels (lack of batch invariance) rather than 'GPU concurrency', and builds batch-invariant RMSNorm, matmul and attention kernels.
      L7Lets you diagnose 'KV-cached output differs from full recompute' and 'greedy decode isn't reproducible' correctly, with the kernel-level reason.
    • 2023
      Mitchell Wortsman et al. (Google DeepMind) · Sep 2023 · Paper · Advanced · ~2 h
      Reproduces large-model instabilities (attention-logit growth, output-logit divergence) in small models and shows the fixes (qk-layernorm, z-loss) and LR sensitivity analysis.
      L7Lets you debug at the level of 'why does this diverge at scale' and propose cheap small-scale experiments before spending compute, which is L7 judgment.
    • 2024
      Team OLMo (Allen Institute for AI) · Dec 2024 · Paper · Advanced · ~3 h
      Open lab's account of the stability fixes they needed (loss spikes, initialization, QK-norm, z-loss, weight-decay exclusions, data issues) with ablations.
      L7Gives you a concrete, published playbook of training-stability interventions and their measured effects to cite when asked how you'd triage a spiking run.
    • 2024
      Zhihong Shao et al. (DeepSeek-AI) · Feb 2024 · Paper · Advanced · ~2 h
      Introduces Group Relative Policy Optimization: group-normalized advantages, clipped ratio and KL term without a value model; Section 4 is the exact objective you would debug.
      L7Lets you spot the classic GRPO bugs (advantage normalization over the wrong axis, ratio from the wrong logprobs, mask/padding leaks, KL sign) and argue why they matter.
    • 2025
      John Schulman and Thinking Machines Lab · Sep 2025 · Blog post · Advanced · ~1.5 h
      Frontier-lab experiments on when LoRA matches full fine-tuning (SFT and RL), the LR ratio versus full FT, and why applying it to all layers including MLPs matters.
      L7Gives you current, numbers-backed positions on LoRA rank, LR and capacity limits that most candidates only know from the 2021 paper.
    • 2025
      Andrej Karpathy · Oct 2025 · Practice · Advanced · ~15 h
      Full-stack ChatGPT-like pipeline in one hackable repo: tokenizer training in Rust, pretraining, midtraining, SFT, RL, KV-cached inference engine and a chat UI, sized to run for about $100 on an 8×H100 node.
      L7Shows how the from-scratch pieces fit into a modern end-to-end recipe (Muon + AdamW, KV-cache engine, eval harness), so you can discuss the whole stack and its cost.
    • 2026
      Keller Jordan and contributors · Sep 2026 · Practice · Advanced · ~6 h
      Record log of the community speedrun to train a 124M GPT to a target loss fastest; each record is a small, reasoned change (Muon optimizer, QK-norm, ReLU², FP8 head, sliding windows, data loading).
      L7Gives you a catalogue of measured training-efficiency changes with their effect sizes, the kind of evidence a senior candidate cites when asked what they would change and why.

What the interviews ask

Problems that recur in this track across 30 reports (16 firsthand), with the resources that prepare you for each.

Question coverage

Every question group collected for this topic from candidate reports, mapped to the resources that prepare you for it. 52 of 52 groups are covered, which is 100% of all report mentions. Hover an example to see the full question.

ReportsQuestion group and examplePrepare with
2transformer debuggingOpenAI 2ML coding: debug a transformer implementationnanoGPTA Recipe for Training Neural NetworksOpenAI: Debug a Transformer Implementation and Implement a KV Cache for DecodingKnow nanoGPT model.py cold; Karpathy's checklist structures the bug hunt
2transformer bug huntOpenAI 2Transformer Bug Hunt: The file tiny_gpt.py below implements a small decoder-only Transformer in PyTorch and trains it to reverse a string of…A Recipe for Training Neural NetworksLecture 7: Troubleshooting Deep Neural NetworksnanoGPTOverfit-one-batch and init-loss checks find non-converging tiny GPT bugs
1numpy backward passUnspecified frontier 1Write the backward pass from scratch using only numpyCS231n: Deep Learning for Computer Vision (Spring 2026)Autodiff-Puzzlesllm.cCS231n A1/A2 hand-written NumPy backward passes with numeric gradient checks
1transformer implement and debugUnspecified frontier 1Implement / debug a transformer from scratch (reported as coming up very often in ML coding)CS336: Language Modeling from Scratch (Spring 2026)Neural Networks: Zero to HeroCS336 A1 and 'Let's build GPT' rebuild a transformer end to end
1decoding strategyUnspecified frontier 1ML coding: implement a given decoding strategyHow to generate text: using different decoding methods for language generation with TransformersThe Curious Case of Neural Text DegenerationUnderstanding Deep Learning (book + Colab notebooks)Greedy, beam, top-k, top-p implementations; UDL Ch.12 decoding notebook
1classic ML algorithmUnspecified frontier 1ML coding: implement a traditional ML algorithm from scratchCS231n: Deep Learning for Computer Vision (Spring 2026)Deep-MLStanford CS229: Machine Learning (Spring 2022 lectures)kNN/softmax from scratch; Deep-ML classic algorithm problems; CS229 derivations
1LLM inference step notebookAnthropic 155-minute Google Colab exercise: complete/debug part of an LLM inference step from ~20-30 lines of skeleton Python, without using an LLMUnderstanding and Coding the KV Cache in LLMs from ScratchKV Cache from scratch in nanoVLMnanoGPTPrefill/decode inference step code with KV cache in small codebases
1miniGPT debug + KV cacheOpenAI 1Debug a transformer so a miniGPT produces correct text, then implement a KV cache, in PyTorchOpenAI: Debug a Transformer Implementation and Implement a KV Cache for DecodingUnderstanding and Coding the KV Cache in LLMs from ScratchnanoGPTSame OpenAI round prompt; KV-cache add-on to a nanoGPT-style model
1matmul backprop + scanOpenAI 1Matrix multiplication forward and backprop in PyTorch from a skeleton; follow-up resembling backprop via the Hillis-Steele scan algorithmAutodiff-PuzzlesGPU Gems 3, Chapter 39: Parallel Prefix Sum (Scan) with CUDAGPU-PuzzlesMatmul VJP puzzles; Hillis-Steele scan chapter for the follow-up
11-nearest neighborOpenAI 11NN (nearest neighbor) questionCS231n: Deep Learning for Computer Vision (Spring 2026)NumPy BroadcastingCS231n A1 kNN with no-loop L2 distance via broadcasting
1matrix cumprod + gradientsOpenAI 1Matrix cumulative product of N DxD matrices: in-place version and why you can't take gradients that way; out-of-place forward and backward; …GPU Gems 3, Chapter 39: Parallel Prefix Sum (Scan) with CUDAAutodiff-PuzzlesPyTorch internals10-414/714: Deep Learning Systems — Algorithms and Implementation (Fall 2026)Scan over matrix products, VJPs, and why in-place ops break autograd
1transformer bugs + KV cacheOpenAI 1ML coding: debug 4-5 implanted bugs in transformer code and implement KV cache from scratchOpenAI: Debug a Transformer Implementation and Implement a KV Cache for DecodingUnderstanding and Coding the KV Cache in LLMs from Scratchtorch.nn.functional.scaled_dot_product_attentionPlanted-bug transformer prompt, KV-cache tutorial, SDPA as test oracle
1research fundamentals ML algoAnthropic 1Research fundamentals round: implement an ML algorithm and discuss research/mathematical aspects around itDecoupled Weight Decay Regularization (AdamW)LoRA: Low-Rank Adaptation of Large Language ModelsCS224N: Natural Language Processing with Deep Learning (Winter 2026)Implement-and-discuss: AdamW and LoRA papers, CS224N derivation practice
1vectorized 1-NN as Wx+bOpenAI 1ML coding (Colab, numpy/pytorch): implement vectorized 1-NN with L2 distance without for loops; express 1-NN as a neural network forward pas…CS231n: Deep Learning for Computer Vision (Spring 2026)Tensor-PuzzlesNo-loop L2 expands to ||x||^2-2xW+||w||^2, i.e. a linear layer
1MHA with KV cache and GQAAnthropic 1Implement multi-head attention from scratch (no torch.nn.MultiheadAttention) and handle KV cache plus grouped-query attention in the same ho…LLMs-from-scratch (code for 'Build a Large Language Model (From Scratch)')GQA: Training Generalized Multi-Query Transformer Models from Multi-Head CheckpointsTorchCodeRaschka MHA/GQA/KV-cache code; GQA paper; timed TorchCode MHA/GQA problems
1softmax cross-entropy gradientUnspecified frontier 1Derive the gradient of softmax + cross-entropy (backprop derivation on a whiteboard)The Softmax function and its derivativeCS224N: Natural Language Processing with Deep Learning (Winter 2026)Softmax Jacobian and p-minus-y derivation; CS224N A2 tensor derivatives
1PyTorch model debuggingUnspecified frontier 1ML coding: debug a PyTorch modelA Recipe for Training Neural Networkstorch.autograd reference: anomaly detection, gradcheck, functional APIAutomatic Differentiation with torch.autograd (PyTorch tutorial)Debug checklist, anomaly detection, zero_grad and accumulation semantics
1PyTorch training bugOpenAI 1Debug live PyTorch code mid-interview, a non-toy bug resembling a training run gone wrongSmall-scale proxies for large-scale Transformer training instabilitiesMachine Learning Engineering Open Book (debugging and training-instabilities chapters)The Smol Training Playbook: The Secrets to Building World-Class LLMsA Recipe for Training Neural NetworksRealistic training-run failures: divergence, NaNs, instabilities and their fixes
1NumPy debugging exerciseAnthropic 1Anthropic Fellows OA2: debugging exercise (6 parts) where the bug can be anywhere, with a high expectation of NumPy proficiencyNumPy BroadcastingTensor-PuzzlesNumerical accuracy (PyTorch notes)NumPy broadcasting rules, tensor puzzles, float tolerance for anywhere-bugs
1flash attention from scratchMistral 1Pair coding: implement flash attention from scratch, with the interviewer adding changes and asking to justify choicesFlashAttention: Fast and Memory-Efficient Exact Attention with IO-AwarenessOnline normalizer calculation for softmaxCS336: Language Modeling from Scratch (Spring 2026)FlashAttention tiling and online softmax; CS336 A2 FlashAttention-2 implementation
1flash attention in NumPyUnspecified frontier 1Implement single-head flash attention in NumPyOnline normalizer calculation for softmaxFlashAttention: Fast and Memory-Efficient Exact Attention with IO-AwarenessSingle-head tiled attention with running max and sum in NumPy
1transformer + flash attention codingMeta (org unspecified) 1Coding round: ML-based coding related to transformers and flash attentionFlashAttention: Fast and Memory-Efficient Exact Attention with IO-AwarenessCS336: Language Modeling from Scratch (Spring 2026)Making Deep Learning Go Brrrr From First PrinciplesFlashAttention algorithm, CS336 A2 implementation, memory-bound reasoning
1transformer + efficient attentionMeta (org unspecified) 1Implement a transformer and some computationally efficient variants of attentionThe Transformer Family Version 2.0Fast Transformer Decoding: One Write-Head is All You NeedDeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language ModelFlashAttention: Fast and Memory-Efficient Exact Attention with IO-AwarenessEfficient attention variants survey; MQA and FlashAttention as concrete implementations
1tokenizer bug fixAnthropic 1Bug fix: tokenize/detokenize code — read unfamiliar code and find logic errorsminbpeCS336: Language Modeling from Scratch (Spring 2026)Read and fix BPE encode/decode logic; CS336 A1 tokenizer tests
1nanoGPT planted bugsOpenAI 1Transformer debugging: nanoGPT-style model and training loop with 4 planted bugs (positional embedding init, causal mask not -inf before sof…nanoGPTRotary Embeddings: A Relative Revolutiontorch.nn.functional.scaled_dot_product_attentionPositional embeddings, -inf causal mask, projection dims, label shift in nanoGPT
Show the other 27 question groups
1vectorized 1-NN and forward passOpenAI 1ML coding: vectorized 1-nearest-neighbour and a neural network forward passCS231n: Deep Learning for Computer Vision (Spring 2026)microgradVectorized kNN plus hand-written MLP forward pass
1buggy extremely randomized treesAnthropic 1Anthropic Fellows OA2: debug a provided implementation of the Extremely Randomized Trees algorithm that crashes in some cases and gives poor…scikit-learn User Guide: Ensembles — Extremely Randomized TreesNumPy BroadcastingIntended Extra-Trees split rules to locate crash and accuracy bugs
1causal scaled dot-product attentionAnthropic 1, Google DeepMind 1Implement scaled dot-product attention with a causal mask, from scratch, in NumPy or PyTorch.torch.nn.functional.scaled_dot_product_attentionNeural Networks: Zero to HeroThe Annotated TransformerSDPA reference code and causal masking from 'Let's build GPT'
1multi-head to grouped-query attentionGoogle DeepMind 1, Mistral 1Implement multi-head attention, then convert it to grouped-query attention.GQA: Training Generalized Multi-Query Transformer Models from Multi-Head CheckpointsLLMs-from-scratch (code for 'Build a Large Language Model (From Scratch)')GQA paper and Raschka's MHA-to-GQA code with K/V head repetition
1top-k top-p temperature samplingGoogle DeepMind 1Implement top-k, top-p and temperature sampling over a logits vector.How to generate text: using different decoding methods for language generation with TransformersThe Curious Case of Neural Text DegenerationTemperature, top-k, top-p over logits; nucleus sampling definition
1RMSE functionGoogle DeepMind 1Write a function to compute root-mean-square error given y_pred and y_true lists.Classification: ROC and AUC (Machine Learning Crash Course)sklearn metrics guide defines RMSE; implement in plain Python
1causal multi-head attentionUnspecified frontier 1ML/research coding: implement causal multi-head attention from scratch.Neural Networks: Zero to HeroCS224N: Natural Language Processing with Deep Learning (Winter 2026)LLMs-from-scratch (code for 'Build a Large Language Model (From Scratch)')Causal MHA built line by line; CS224N A3 self-attention
1nucleus samplingUnspecified frontier 1ML/research coding: implement nucleus (top-p) sampling from scratch.The Curious Case of Neural Text DegenerationHow to generate text: using different decoding methods for language generation with TransformersNucleus sampling: sort, cumulative sum, cutoff, renormalize
1KV cache decode loopUnspecified frontier 1ML/research coding: implement a decode loop with a KV cache from scratch.Understanding and Coding the KV Cache in LLMs from ScratchTransformer Inference ArithmeticKV Cache from scratch in nanoVLMKV-cached decode loop code plus cache-size arithmetic
1BPE from scratchUnspecified frontier 1ML/research coding: implement byte pair encoding from scratch.minbpeNeural Networks: Zero to HeroMinimal byte-level BPE training and the tokenizer video
1layernorm and softmaxUnspecified frontier 1ML/research coding: implement layer norm and softmax from scratch.layernorm.md: LayerNorm forward and backward from scratchThe Softmax function and its derivativeLayerNorm forward/backward and numerically stable softmax derivation
1LoRA adapter from scratchUnspecified frontier 1ML/research coding: implement a LoRA adapter from scratch.LoRA: Low-Rank Adaptation of Large Language ModelsLoRA Without RegretLLMs-from-scratch (code for 'Build a Large Language Model (From Scratch)')LoRA math, init and scaling; appendix E from-scratch LoRA layer
1broken training loopUnspecified frontier 1Debug a training-run notebook that runs but does not learn: bugs such as a missing zero_grad, softmax on the wrong dimension, a double softm…A Recipe for Training Neural NetworksDatasets & DataLoaders (PyTorch tutorial)Automatic Differentiation with torch.autograd (PyTorch tutorial)zero_grad, softmax dim, double softmax, broadcast, shuffle checks
1transformer bug fix plus KV cacheOpenAI 1Given a ~300-line transformer implementation with four annotated buggy sections, find and fix the bugs, then implement KV caching.OpenAI: Debug a Transformer Implementation and Implement a KV Cache for DecodingnanoGPTUnderstanding and Coding the KV Cache in LLMs from ScratchFour-bug transformer prompt, nanoGPT reference, KV-cache implementation
1training data pipeline bugsAnthropic 1You're given a roughly 200-line Python script powering a model training data pipeline. At least two bugs are keeping it from running correct…Datasets & DataLoaders (PyTorch tutorial)Don't Mock Machine Learning Models In Unit TestsDataLoader/Dataset contract and tests that catch data-pipeline bugs
1multi-head attention from scratchUnspecified frontier 1Implement a Multi-Head Attention block or a full Transformer layer.The Annotated TransformerNeural Networks: Zero to HeroDive into Deep Learning, Ch. 11: Attention Mechanisms and TransformersFull transformer layer implementations to reproduce from memory
1notebook model not learningGoogle DeepMind 1Debug a Jupyter notebook model that runs but doesn't learn (flat/diverging loss): broadcasting errors, wrong softmax dim, softmax before Cro…A Recipe for Training Neural NetworksLecture 7: Troubleshooting Deep Neural NetworksNumPy BroadcastingFlat/diverging loss triage; broadcasting and softmax-before-CE bugs
1classic ML from scratchUnspecified frontier 1Implement K-means without sklearn / compute AUC in vanilla Python / neural net training loop in numpy.Deep-MLClassification: ROC and AUC (Machine Learning Crash Course)CS231n: Deep Learning for Computer Vision (Spring 2026)Deep-ML k-means problem, AUC as ranking probability, NumPy training loop
1prefix matmul autograd scanOpenAI 1Prefix Matmul: Autograd, Manual Backward, Hillis–Steele Scan (4 parts / 75 min)Autodiff-PuzzlesGPU Gems 3, Chapter 39: Parallel Prefix Sum (Scan) with CUDAtorch.autograd reference: anomaly detection, gradcheck, functional APIManual backward, Hillis-Steele scan, gradcheck to verify against autograd
1NumPy 1-NN vectorizedOpenAI 1NumPy 1-NN as an Affine Layer (2 parts / 60 min)CS231n: Deep Learning for Computer Vision (Spring 2026)Tensor-PuzzlesVectorized L2 1-NN rewritten as an affine layer plus argmax
1streaming softmax entropyOpenAI 1Streaming Entropy (4 parts / 60 min)Online normalizer calculation for softmaxThe Softmax function and its derivativeRunning max/sum log-sum-exp gives streaming softmax entropy
1attention KV cache online softmaxGoogle DeepMind 1Attention with a KV Cache and an Online Softmax (3 parts / 45–60 min)Online normalizer calculation for softmaxUnderstanding and Coding the KV Cache in LLMs from ScratchFlashAttention: Fast and Memory-Efficient Exact Attention with IO-AwarenessOnline softmax over cached K/V chunks during decode
1MLP backprop from scratchGoogle DeepMind 1Backpropagation from Scratch (3 parts / 45 min)CS231n: Deep Learning for Computer Vision (Spring 2026)microgradNeural Networks: Zero to HeroAlisa's book of LLMsMLP backprop by hand: CS231n two-layer net, micrograd, backprop ninja
1classifier not learning debugGoogle DeepMind 1Debugging a Classifier That Does Not Learn (3 parts / 45 min)A Recipe for Training Neural NetworksLecture 7: Troubleshooting Deep Neural NetworksDon't Mock Machine Learning Models In Unit TestsSystematic checks for a classifier stuck at chance
1GRPO training loop bugsAnthropic 1Debugging a GRPO Training Loop: The file grpo_train.py below trains a tiny policy with *Group Relative Policy Optimization* (GRPO) on a synt…DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models (GRPO, Sec. 4)Build a Reasoning Model (From Scratch)GRPO objective and group advantages; from-scratch GRPO code in Raschka's reasoning book
1multi-head attention einsumAnthropic 1Multi-Head Attention with einsum (3 parts / 55 min)Einsum is All you Need — Einstein Summation in Deep LearningLLMs-from-scratch (code for 'Build a Large Language Model (From Scratch)')Multi-head attention as einsum contractions over batch, head, sequence
1PyTorch closest center broadcastingMistral 1Given a PyTorch tensor representing coordinates of points and another representing coordinates of centers, write a function to compute the d…NumPy BroadcastingTensor-PuzzlesPairwise distances via broadcasting, then min/argmin over centers

All resources

Everything collected for this topic, newest first. 2026 items are marked green. ★ marks a top pick.

Type
Level
Subtopic

  • 2026
    Sebastian Raschka · Oct 2026 · Practice · Core · ~25 h
    Chapter notebooks implement causal multi-head attention, GPT blocks, pretraining, sampling with temperature/top-k, and bonus folders for KV cache, GQA, RoPE-based architectures (Llama, Qwen, Gemma 3) and LoRA (appendix E). Actively maintained in 2026.
    L7The bonus folders let you compare MHA/GQA/MLA-style variants side by side in readable code, which is what you need to discuss architecture trade-offs while coding.
  • 2026
    Stas Bekman · Oct 2026 · Book · Advanced · ~6 h
    Field notes from training BLOOM-176B and other large models: debugging hangs and NaNs, underflow/overflow detection in fp16/bf16, loss-spike case studies, and tooling.
    L7Gives you real large-run war stories and tools to draw on when the interviewer asks how this bug would show up at 1,000 GPUs.
    Continuously updated.
  • 2026
    Tianqi Chen, Tim Dettmers (CMU) · Sep 2026 · Course · Advanced · ~80 h · video
    You build 'needle', a small PyTorch-like library: reverse-mode autodiff, nn.Module abstractions, optimizers, an NDArray backend with CPU/CUDA kernels, then CNNs, RNNs and a transformer on top. Best resource for autograd-engine questions.
    L7Lets you explain how a framework's tape, graph and memory actually work, so you can reason about why a training bug happens, not just patch it.
    Videos are the 2022 public run; Fall 2026 slides and homeworks are current.
  • 2026
    Keller Jordan and contributors · Sep 2026 · Practice · Advanced · ~6 h
    Record log of the community speedrun to train a 124M GPT to a target loss fastest; each record is a small, reasoned change (Muon optimizer, QK-norm, ReLU², FP8 head, sliding windows, data loading).
    L7Gives you a catalogue of measured training-efficiency changes with their effect sizes, the kind of evidence a senior candidate cites when asked what they would change and why.
  • 2026
    PracHub (candidate-reported) · Sep 2026 · Practice · Core · ~1.5 h
    Candidate-reported write-up of the OpenAI ML-coding round: find 4–5 planted bugs in a decoder-only transformer, then add a KV cache and check it matches full recompute.
    L7Use it to calibrate scope and timing for the real round; the content is the prompt, not a solution.
    Third-party, candidate-submitted; some content may need an account.
  • 2026
    Sebastian Raschka (Manning) · Aug 2026 · Book · Advanced · ~25 h · paid
    Starts from a pretrained Qwen3-class model implemented from scratch, adds a KV-cached generation loop and evaluation, then inference-time scaling and RL (GRPO-style) for reasoning, all in PyTorch.
    L7Connects decoding-loop code to how reasoning models are trained and evaluated, so you can talk about inference-time compute and RL verifiers with code-level specifics.
    Paid book (440 pp., published Aug 2026 per retailer listings); code is free.
  • 2026
    Alisa Liu (UW) · Jun 2026 · Reference · Core · ~4 h
    Personal notes by an LM researcher, written for interview prep: shapes and backprop for linear layers (including PyTorch's W-transpose convention and why bias gradients sum over the batch), activations, Jacobians.
    L7Baseline; good for checking that your whiteboard gradient derivations use the same shape conventions PyTorch does.
    Notion page; content renders client-side.
  • 2026
    Tatsunori Hashimoto, Percy Liang (Stanford) · Apr 2026 · Course · Advanced · ~120 h · video
    Assignment 1 has you write a byte-level BPE tokenizer, a pre-norm transformer with RoPE and SwiGLU, cross-entropy, AdamW, a cosine schedule and a training loop against unit tests; it is the curriculum's end-to-end capstone and the single best rehearsal for the from-scratch rounds.
    L7Gives you first-hand numbers (tokens/s, memory, loss curves) from a model you built, so you can argue design choices from experience rather than recall; A2 adds FlashAttention-2 in Triton and DDP.
    A1 alone is ~25–40 h for a strong engineer; the full course is far more.
  • 2026
    Stanford (Fei-Fei Li, Ehsan Adeli et al.) · Apr 2026 · Course · Core · ~40 h · video
    Assignment 1 is kNN with no-loop vectorized L2 distances, a softmax classifier and a two-layer net with hand-written backward passes checked numerically; A2 adds batchnorm/dropout backward, A3 a captioning transformer. The no-loop kNN is almost exactly the reported OpenAI 1-NN question.
    L7Baseline for a staff-level ML engineer; do A1 and the BN-backward part of A2 cold to make hand backprop and vectorization automatic under time pressure.
    Latest public video playlist is the 2025 offering.
  • 2026
    duoan · Mar 2026 · Practice · Core · ~10 h
    Self-hosted Jupyter 'LeetCode for PyTorch': ~40 problems (softmax, LayerNorm, MHA, GQA, RoPE, KV cache, sampling, transformer block) with an auto-judge that also checks gradients.
    L7Baseline drill set; good for timing yourself on the 'MHA + KV cache + GQA in an hour' target.
  • 2026
    Diyi Yang, Yejin Choi (Stanford) · Jan 2026 · Course · Core · ~30 h · video
    A2 drills tensor derivatives (the softmax + cross-entropy gradient that comes up on whiteboards); A3 is self-attention and transformers. Good targeted practice for the derivation-style questions.
    L7Baseline; use A2's written part to rehearse deriving gradients aloud cleanly, which is what a research-fundamentals round grades.
    Winter 2026 lectures are Canvas-only; the public playlist is Spring 2024.
  • 2026
    Alexander Amini, Ava Amini (MIT) · Jan 2026 · Course · Intro · ~12 h · video
    One-week bootcamp with lectures and PyTorch/TensorFlow labs; the sequence-modeling lecture is a quick visual route to attention for someone coming from signal processing.
    L7Skim only — baseline vocabulary; skip if you already teach this material.
  • 2026
    PyTorch · 2026 · Reference · Core · ~2 h
    detect_anomaly/set_detect_anomaly to find the op that produced a NaN in backward, gradcheck/gradgradcheck for finite-difference checks of custom backward passes, hooks and the functional Jacobian API.
    L7Lets you verify a hand-written backward in one line and localize NaNs fast during a live debug session.
  • 2026
    PyTorch · 2026 · Reference · Advanced · ~1 h
    Where results legitimately differ: non-associative float sums, batched vs single computation, TF32 on Ampere+, reduced-precision reductions in fp16/bf16, and extremal values.
    L7Lets you tell a real bug from expected numerical noise when two implementations disagree, and explain tolerance choices in tests.
  • 2026
    PyTorch · 2026 · Tutorial · Intro · ~0.5 h
    Computation graphs, requires_grad, gradient accumulation, detach and no_grad in one short page.
    L7Baseline; skim if known — but zero_grad/accumulation bugs are on every planted-bug list.
  • 2026
    PyTorch · 2026 · Reference · Core · ~1 h
    Includes a reference Python implementation of SDPA with is_causal, attn_mask, scale and enable_gqa semantics, plus backend selection (Flash, memory-efficient, math).
    L7Use as the oracle to unit-test your from-scratch attention, and know its mask conventions (bool True = attend) which are a common bug source.
  • 2026
    PyTorch · 2026 · Tutorial · Advanced · ~2 h
    How Dynamo captures graphs, graph breaks, recompilation and Inductor codegen; pair with the troubleshooting guide for debugging compiled models.
    L7Lets you discuss why a compiled model diverges or recompiles and how you'd isolate it, a modern variant of the debug round.
  • 2026
    Google JAX team · 2026 · Tutorial · Core · ~4 h
    jit, grad, vmap and pytrees; the Autodiff Cookbook covers JVPs, VJPs and Hessian-vector products cleanly.
    L7Useful if the target team is JAX-first (Google DeepMind); VJP/JVP vocabulary also sharpens backprop-derivation answers.
  • 2026
    Deep-ML · 2026 · Practice · Core · ~15 h
    1,200+ auto-graded NumPy/PyTorch problems: linear and logistic regression, k-means, kNN, PCA, softmax, attention, optimizers, plus an interview-prep track.
    L7Baseline drill platform; use it for timed classic-ML-from-scratch reps.
    Free core with a premium tier.
  • 2026
    scikit-learn developers · 2026 · Reference · Core · ~1 h
    Describes how Extra-Trees differ from random forests (random split thresholds per feature, no bootstrap by default) and the key parameters, with a pointer to the original paper.
    L7Baseline; enough to know the intended algorithm so you can find where a buggy implementation deviates (split selection, empty nodes, constant features).
    Springer DOI page returns a bot challenge to curl.
  • 2026
    NumPy developers · 2026 · Reference · Core · ~1 h
    The exact broadcasting rules, with the pairwise-distance example that underlies loop-free kNN, k-means assignment and closest-center problems.
    L7Baseline; know the rules well enough to spot a 'silently working' broadcast bug, a staple of planted-bug rounds.
  • 2026
    PyTorch · 2026 · Tutorial · Intro · ~0.5 h
    Dataset/DataLoader contract, shuffling, batching and custom collate; pair with the torch.utils.data reference for samplers and workers.
    L7Baseline; enough to catch unshuffled loaders, label/feature misalignment and worker-seeding bugs in a data-pipeline debug round.
  • 2025
    Andrej Karpathy · Nov 2025 · Practice · Core · ~8 h
    ~300-line GPT model and training loop that is the de facto template for 'miniGPT' interview code; reading model.py closely is preparation for debugging someone else's version of it.
    L7Baseline; the value is knowing this file so well that a planted bug in a look-alike stands out.
    Karpathy now points new users to nanochat; nanoGPT remains the reference for small-GPT code.
  • 2025
    Andrej Karpathy · Oct 2025 · Practice · Advanced · ~15 h
    Full-stack ChatGPT-like pipeline in one hackable repo: tokenizer training in Rust, pretraining, midtraining, SFT, RL, KV-cached inference engine and a chat UI, sized to run for about $100 on an 8×H100 node.
    L7Shows how the from-scratch pieces fit into a modern end-to-end recipe (Muon + AdamW, KV-cache engine, eval harness), so you can discuss the whole stack and its cost.
    Still updated in Sept 2026.
  • 2025
    Hugging Face (SmolLM team) · Oct 2025 · Book · Advanced · ~8 h
    End-to-end account of training SmolLM3: ablation methodology, architecture choices, and the failures they hit mid-run (throughput drops, loss issues, bugs) and how they found them.
    L7Gives you a recent, lab-style narrative of debugging a real pretraining run to model your own war-story answers on.
  • 2025
    John Schulman and Thinking Machines Lab · Sep 2025 · Blog post · Advanced · ~1.5 h
    Frontier-lab experiments on when LoRA matches full fine-tuning (SFT and RL), the LR ratio versus full FT, and why applying it to all layers including MLPs matters.
    L7Gives you current, numbers-backed positions on LoRA rank, LR and capacity limits that most candidates only know from the 2021 paper.
  • 2025
    Horace He and Thinking Machines Lab · Sep 2025 · Blog post · Advanced · ~1.5 h
    Shows that temperature-0 nondeterminism in serving comes mainly from batch-size-dependent kernels (lack of batch invariance) rather than 'GPU concurrency', and builds batch-invariant RMSNorm, matmul and attention kernels.
    L7Lets you diagnose 'KV-cached output differs from full recompute' and 'greedy decode isn't reproducible' correctly, with the kernel-level reason.
  • 2025
    Sebastian Raschka · Jun 2025 · Tutorial · Core · ~2 h
    Walks through adding a KV cache to a from-scratch GPT: cache buffers, position tracking, reset, and a side-by-side script with and without the cache.
    L7Baseline for the OpenAI 'add a KV cache' round; then extend it yourself to GQA and a pre-allocated cache.
    Mirrored at sebastianraschka.com/blog (406 to curl).
  • 2025
    Hugging Face (Aritra Roy Gosthipaty, Kashif Rasul, Luis Wiedmann, Andres Marafioti, Pedro Cuenca) · Jun 2025 · Blog post · Core · ~1.5 h
    Second worked KV-cache implementation in a small real codebase, separating prefill from decode and handling the position bookkeeping.
    L7Baseline; reading two different KV-cache designs helps you explain the prefill/decode split and where cache bugs come from.
  • 2025
    Jacob Austin et al. (Google DeepMind) · Feb 2025 · Book · Advanced · ~15 h
    TPU/GPU roofline analysis, transformer FLOP and memory accounting, sharding for training and inference, and KV-cache-dominated serving maths, with worked problems.
    L7Gives you the arithmetic a DeepMind or OpenAI senior interviewer expects when the coding question turns into 'now run it at scale'.
  • 2025
    Hugging Face (Nouamane Tazi et al.) · Feb 2025 · Book · Advanced · ~10 h
    Interactive book on data, tensor, pipeline, context and expert parallelism plus ZeRO, with memory/throughput measurements from thousands of runs.
    L7Lets you extend a single-GPU training loop answer to multi-node, with memory numbers per parallelism choice.
  • 2025
    Google for Developers · 2025 · Tutorial · Intro · ~0.5 h
    Short refresher on ROC curves and AUC as a ranking probability, which is how you implement AUC in plain Python (sort by score, count concordant pairs).
    L7Baseline; skim if known — the bar is a correct, tie-aware O(n log n) implementation.
  • 2024
    Team OLMo (Allen Institute for AI) · Dec 2024 · Paper · Advanced · ~3 h
    Open lab's account of the stability fixes they needed (loss spikes, initialization, QK-norm, z-loss, weight-decay exclusions, data issues) with ablations.
    L7Gives you a concrete, published playbook of training-stability interventions and their measured effects to cite when asked how you'd triage a spiking run.
  • 2024
    Sebastian Raschka (Manning) · Sep 2024 · Book · Core · ~25 h · paid
    Book companion to the repo: tokenization, attention, GPT architecture, pretraining, classification and instruction fine-tuning, all in plain PyTorch.
    L7Baseline; read for the attention and pretraining chapters only, then work from the repo.
    Paid book; all code is free in the repo.
  • 2024
    Andrej Karpathy · Jun 2024 · Course · Core · ~30 h · video
    Code-along series from micrograd (scalar autograd) through manual backprop of an MLP with batchnorm ('becoming a backprop ninja'), to building GPT, the GPT tokenizer and reproducing GPT-2. The fastest way to make attention-from-a-blank-file muscle memory.
    L7Baseline for implementation fluency; the 'backprop ninja' and 'build GPT' episodes are the ones to redo without the video.
    Episodes released 2022-08 to 2024-06.
  • 2024
    DeepSeek-AI · May 2024 · Paper · Advanced · ~2 h
    Introduces Multi-head Latent Attention (MLA), which caches a low-rank latent instead of full K/V, and explains the decoupled-RoPE trick it needs.
    L7Lets you compare MHA/GQA/MLA cache sizes per token and explain why RoPE complicates low-rank K/V, a typical senior follow-up.
  • 2024
    Andrej Karpathy · Apr 2024 · Practice · Advanced · ~10 h
    GPT-2 training in raw C/CUDA with every forward and backward kernel written by hand (layernorm, attention, GELU, AdamW), validated against a PyTorch reference.
    L7Forces you to know the backward pass of every transformer op and how they are fused, which is the depth behind 'derive attention backward'.
    Last pushed mid-2025.
  • 2024
    Andrej Karpathy (llm.c) · Apr 2024 · Tutorial · Core · ~1 h
    Derives and implements LayerNorm forward and backward in PyTorch, checked against autograd, then ports it to C; the companion to the softmax/layernorm-from-scratch question.
    L7Baseline-to-core; know the compact backward formula and why mean/variance are cached.
  • 2024
    Andrej Karpathy · Feb 2024 · Practice · Core · ~4 h
    Minimal byte-level BPE training, encoding and decoding, plus a regex-split GPT-4-style tokenizer, with an exercise file.
    L7Baseline; implement BPE training yourself before CS336 A1, where efficiency of the merge loop matters.
  • 2024
    Zhihong Shao et al. (DeepSeek-AI) · Feb 2024 · Paper · Advanced · ~2 h
    Introduces Group Relative Policy Optimization: group-normalized advantages, clipped ratio and KL term without a value model; Section 4 is the exact objective you would debug.
    L7Lets you spot the classic GRPO bugs (advantage normalization over the wrong axis, ratio from the wrong logprobs, mask/padding leaks, KL sign) and argue why they matter.
  • 2023
    Simon J. D. Prince · Dec 2023 · Book · Core · ~12 h
    Free book with per-chapter notebooks; Ch. 7 notebooks implement backprop by hand on toy models, Ch. 12 notebooks implement self-attention, multi-head attention, tokenization and decoding strategies with fill-in-the-blank code.
    L7Baseline drill set; the Ch. 7 and Ch. 12 notebooks are short, self-checking warmups before timed practice.
    Book published 2023; repo still updated in 2026.
  • 2023
    Woosuk Kwon et al. (UC Berkeley, vLLM) · Sep 2023 · Paper · Advanced · ~2 h
    The vLLM paper: KV-cache fragmentation, block tables and copy-on-write sharing for beams and parallel sampling.
    L7Lets you take a toy KV cache to production questions (fragmentation, batching many sequences, beam sharing) and argue memory numbers.
  • 2023
    Mitchell Wortsman et al. (Google DeepMind) · Sep 2023 · Paper · Advanced · ~2 h
    Reproduces large-model instabilities (attention-logit growth, output-logit divergence) in small models and shows the fixes (qk-layernorm, z-loss) and LR sensitivity analysis.
    L7Lets you debug at the level of 'why does this diverge at scale' and propose cheap small-scale experiments before spending compute, which is L7 judgment.
  • 2023
    Joshua Ainslie et al. (Google Research) · May 2023 · Paper · Advanced · ~1 h
    Grouped-query attention and uptraining from MHA checkpoints; the variant Anthropic reportedly asked for alongside a KV cache in one hour.
    L7Lets you implement GQA via head repetition/broadcast and quantify the cache saving versus quality loss.
  • 2023
    Eugene Yan · Feb 2023 · Blog post · Core · ~0.5 h
    Practical test patterns for ML code: tiny real models instead of mocks, output-shape and range checks, loss-decreases and overfit-a-batch tests, and leakage checks.
    L7Baseline; lets you state what tests you would add after fixing a bug, which interviewers often ask as the wrap-up.
  • 2023
    Lilian Weng · Jan 2023 · Blog post · Advanced · ~3 h
    Dense survey of attention variants: positional encodings (incl. RoPE), long-context and sparse attention, memory/recurrence, efficient attention, adaptive computation.
    L7Lets you place any variant an interviewer names (sliding window, linear, sparse) and state its complexity and failure mode on the spot.
  • 2023
    Aston Zhang, Zachary Lipton, Mu Li, Alexander Smola · 2023 · Book · Intro · ~6 h
    Runnable PyTorch/JAX notebooks building attention scoring, masked softmax, multi-head attention and positional encodings step by step.
    L7Baseline; skim if known. Useful for its masked-softmax and shape-bookkeeping code.
  • 2022
    Yaniv Leviathan, Matan Kalman, Yossi Matias (Google) · Nov 2022 · Paper · Advanced · ~2 h
    Draft-then-verify decoding with a rejection-sampling rule that provably preserves the target distribution.
    L7Lets you implement and prove correctness of the acceptance rule, a common 'extend your sampler' follow-up.
  • 2022
    Sasha Rush · Oct 2022 · Practice · Advanced · ~3 h
    Write the backward (VJP) for a series of tensor functions, checked automatically; directly drills matmul, sum, broadcasting and indexing gradients.
    L7Trains exactly the 'matmul forward and backward from a skeleton' question and its harder follow-ups.
  • 2022
    Sasha Rush · Jul 2022 · Practice · Advanced · ~5 h
    CUDA programming puzzles in Python via Numba: map, zip, pooling, dot product, prefix sum, matmul with shared memory.
    L7The prefix-sum puzzle covers Hillis–Steele/Blelloch scans (a reported OpenAI follow-up) and builds intuition for why kernels are tiled.
  • 2022
    Tri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra, Christopher Ré · May 2022 · Paper · Advanced · ~3 h
    Tiled attention with online softmax that never materializes the N×N score matrix; the algorithm CS336 A2 has you implement in Triton.
    L7Lets you write the online-softmax recurrence by hand and explain why attention is memory-bound, which turns a 'write attention' question into a systems discussion.
  • 2022
    Stanford (Tengyu Ma, Chris Ré et al.) · Apr 2022 · Course · Core · ~8 h · video
    Pick the lectures on logistic regression/GLMs, k-means and EM to refresh the maths you need to derive and vectorize classic algorithms on a whiteboard.
    L7Baseline; skim if known — useful only for re-deriving logistic-regression gradients and k-means convergence quickly.
    cs229.stanford.edu timed out from here; the official YouTube playlist is linked instead.
  • 2022
    Sasha Rush · Apr 2022 · Practice · Core · ~4 h
    21 puzzles reimplementing NumPy/PyTorch functions using only broadcasting and arange, one line each.
    L7Builds the broadcasting fluency that makes loop-free kNN distances and batched attention masks trivial under time pressure.
  • 2022
    kipply (Carol Chen) · Mar 2022 · Blog post · Advanced · ~1.5 h
    Back-of-envelope formulas for KV-cache size, FLOPs versus memory bandwidth, and latency for prefill and decode.
    L7Lets you defend a KV-cache memory budget with numbers in the same interview where you implement it.
  • 2022
    Horace He · Mar 2022 · Blog post · Advanced · ~1 h
    Compute-bound vs memory-bandwidth-bound vs overhead-bound, with how to tell which regime you are in.
    L7Lets you explain why your naive attention is slow and what fusion or FlashAttention buys, rather than just that it is faster.
  • 2022
    Harvard NLP (Austin Huang, Suraj Subramanian, Jonathan Sum, Khalid Almubarak, Stella Biderman; original by Sasha Rush) · 2022 · Tutorial · Core · ~4 h
    Line-by-line PyTorch implementation of the original encoder-decoder transformer interleaved with the paper text, including masking, label smoothing and greedy decoding.
    L7Baseline; useful as a reference implementation to diff your own code against when hunting mask and shape bugs.
  • 2021
    Edward J. Hu et al. (Microsoft) · Jun 2021 · Paper · Advanced · ~1.5 h
    Low-rank update W + BA with B zero-initialized and an alpha/r scale; short enough to implement from the paper in 20 minutes.
    L7Lets you defend init, scaling and merge-at-inference choices and say which matrices to adapt.
  • 2021
    EleutherAI (Stella Biderman, Sid Black et al.) · Apr 2021 · Blog post · Core · ~1.5 h
    Derivation of RoPE with short PyTorch and JAX implementations; the clearest route from 'rotate pairs of dims' to working code.
    L7Baseline for implementing RoPE correctly in a KV-cached decode loop, where the position offset is the classic bug.
  • 2021
    Josh Tobin (Full Stack Deep Learning) · Mar 2021 · Lecture · Core · ~1.5 h · video
    Decision-tree approach to DL debugging: start simple, implement and debug (shape mismatches, casting, OOM, numerical instability), compare to a known result, then bias-variance.
    L7Baseline; gives you a named bug taxonomy to organize a 15-bug zoo around.
  • 2020
    Andrej Karpathy · Apr 2020 · Practice · Intro · ~3 h
    ~150-line scalar reverse-mode autograd engine with a tiny neural-net library on top.
    L7Baseline; rewrite it from memory in 30 minutes as a warmup for autograd questions.
  • 2020
    Patrick von Platen (Hugging Face) · Mar 2020 · Blog post · Core · ~1 h
    Greedy, beam search, top-k, top-p and temperature explained with examples; enough to implement each from logits.
    L7Baseline; skim if known.
  • 2019
    Noam Shazeer (Google) · Nov 2019 · Paper · Advanced · ~1.5 h
    Introduces multi-query attention and analyses incremental decoding as memory-bandwidth bound, with the KV-cache arithmetic that motivates it.
    L7Lets you argue from bytes moved per token why decode is bandwidth-bound and why sharing K/V heads helps, instead of just naming MQA.
  • 2019
    Edward Z. Yang · May 2019 · Blog post · Advanced · ~1.5 h
    Tensors as storage + strides + offsets, views versus copies, dispatch and how autograd is wired; written by a PyTorch core maintainer.
    L7Lets you explain non-contiguous tensors, in-place-op autograd errors and silent view aliasing — bugs that only show up under stride assumptions.
    Older but still the canonical explainer.
  • 2019
    Ari Holtzman, Jan Buys, Li Du, Maxwell Forbes, Yejin Choi · Apr 2019 · Paper · Advanced · ~1.5 h
    Introduces nucleus (top-p) sampling and shows why beam search and pure sampling degenerate.
    L7Lets you justify sampler choices with evidence rather than defaults, and explain the failure modes of beam search for open-ended text.
  • 2019
    Andrej Karpathy · Apr 2019 · Blog post · Core · ~1 h
    The canonical checklist: inspect data, fix seeds, verify init loss (~ln(vocab)), overfit one batch, visualize just before the net, add complexity one step at a time.
    L7Baseline, but rehearse narrating it — a structured bisection out loud is what separates candidates in the debug round.
  • 2018
    Jay Alammar · Jun 2018 · Blog post · Intro · ~1 h
    The standard visual walk-through of Q/K/V, multi-head attention and the encoder-decoder stack.
    L7Skim only — baseline vocabulary.
  • 2018
    Maxim Milakov, Natalia Gimelshein (NVIDIA) · May 2018 · Paper · Advanced · ~1 h
    Four-page paper deriving the single-pass running-max/running-sum softmax that FlashAttention and streaming log-sum-exp computations use.
    L7Lets you derive streaming softmax, entropy or attention over chunks on the spot and prove it equals the two-pass result.
  • 2018
    Tim Rocktäschel · Apr 2018 · Blog post · Core · ~1 h
    Worked einsum examples from transpose to batched matmul and bilinear attention; makes multi-head attention a few readable einsum lines.
    L7Baseline; the senior signal is choosing index names that make the head/batch layout and GQA broadcast obvious to the interviewer.
  • 2017
    Ilya Loshchilov, Frank Hutter · Nov 2017 · Paper · Advanced · ~1.5 h
    Shows that L2 regularization and weight decay differ under Adam and gives the decoupled update; Algorithm 2 is what you implement from scratch.
    L7Lets you explain precisely why Adam+L2 is not AdamW and what that means for which parameters get decayed, a frequent interviewer probe after you write the optimizer.
  • 2017
    Ashish Vaswani, Noam Shazeer et al. (Google) · Jun 2017 · Paper · Core · ~2 h
    Original transformer paper; read Section 3 for the exact attention, multi-head and scaling definitions interviewers expect.
    L7Baseline; know why scores are divided by sqrt(d_k) and what goes wrong without it.
  • 2016
    Eli Bendersky · Oct 2016 · Blog post · Core · ~1 h
    Step-by-step Jacobian of softmax, the stable max-subtraction trick, and the combined softmax + cross-entropy gradient (p − y).
    L7Baseline; rehearse the derivation until you can do it on a whiteboard in under five minutes and explain why the fused form is numerically safer.
  • 2007
    Mark Harris, Shubhabrata Sengupta, John D. Owens (NVIDIA) · 2007 · Reference · Advanced · ~2 h
    Explains the naive Hillis–Steele scan (O(n log n) work) and the work-efficient Blelloch up-sweep/down-sweep, with diagrams; the scan pattern OpenAI's prefix-matmul question builds on.
    L7Lets you write a scan over an associative op (matrix products) and reason about its backward pass and depth/work trade-off, which is the senior follow-up to 'matmul backward'.
    Old but canonical; the algorithms are unchanged.
Not found or not verified. TensorGym is retired (tensorgym.com now shows a farewell page), so it is not listed. cs229.stanford.edu timed out from here; only the 2022 YouTube lectures are linked. No public 2026 recording exists for CS224N (Canvas-only) or a 2026 CS231n playlist yet; the latest public playlists are older and are linked as such. CMU 10-414/714 videos are still the 2022 recordings. I could not find a maintained, public 'planted-bug zoo' for transformer code — the PracHub prompt describes the round but not a bug set, so the 15-bug zoo has to be built yourself (seed it from the Karpathy recipe, FSDL taxonomy and the SDPA mask conventions). No solid standalone tutorial on testing transformer code specifically (cache-equivalence tests, gradient tests) beyond Eugene Yan's general post, PyTorch gradcheck docs, and CS336's own test suite. Raschka's reasoning-book exact publication date varies across retailers (Aug–Nov 2026); Manning's page did not state it. The Smol Training Playbook month (2025-10) is from memory of its release, not a date on the page. The 'Alisa's book of LLMs' Notion page loads client-side; only its first section (neural-net basics/backprop) could be read via Notion's API. Links checked 27 Oct 2026.