AI Engineering from Scratch
Practice
Practice AI engineering by doing it. Implement the code that the lessons build, implement methods from research papers, train tiny models to a target, and run experiments that you answer with numbers. Each task runs Python with numpy in your browser. The checks tell you what is wrong and why, and each task links to the lesson that teaches it.
- Implement31 tasks
Write a function that a lesson builds. The checks compare it with examples, properties, hidden edge cases and a reference.
- Research10 tasks
Implement the core method of a research paper. The checks test the equations and the properties that the paper states.
- Train5 tasks
Train a tiny model in your browser to a target score inside a step budget. The checks measure it on held-out data.
- Lab5 tasks
Run a short experiment, measure the effect of one variable, and answer with numbers that the checks compare with a reference run.
- Solved
- 0 / 51
- Attempted
- 0
- Streak
- 0 days
- Easy
- 0 / 16
- Medium
- 0 / 28
- Hard
- 0 / 7
Problems
51 problems
- Power iteration for the top eigenpair
The top eigenvalue and eigenvector of a symmetric matrix by power iteration, with a tolerance, an iteration limit and a sign rule.
ImplementMediumPhase 0125 min - Vectorized pairwise distances
Euclidean distance and cosine similarity matrices from one matrix product, with a clip at 0 and a zero-vector rule.
ImplementMediumPhase 0120 min - Linear regression by gradient descent
Mean squared error, its gradients for weights and bias, and a batch gradient descent loop that records the cost after each update.
ImplementEasyPhase 0220 min - Train softmax regression on four blobs
Train multinomial logistic regression with gradient descent to reach a held-out accuracy and log loss target on four Gaussian blobs.
TrainEasyPhase 0225 min - Logistic regression from scratch
A stable sigmoid, the binary cross-entropy loss and its gradient, and a gradient descent loop that records the loss.
ImplementMediumPhase 0225 min - Gini impurity and the best split
Gini impurity and the best decision tree split over all features, with midpoint thresholds, weighted child impurity and a fixed tie rule.
ImplementHardPhase 0235 min - K-means assignment and update
The k-means assignment and update steps with a tie rule and an empty cluster rule, and a full run until the assignments stop changing.
ImplementMediumPhase 0225 min - Measure bias and variance
Fit polynomials of degree 1 to 12 on resampled training sets and measure bias squared, variance and test error at each degree.
LabMediumPhase 0230 min - Train a 2-4-1 network on XOR
Train a small sigmoid network with full-batch gradient descent until it labels noisy XOR points with 95 percent held-out accuracy.
TrainEasyPhase 0330 min - Backpropagation through a two-layer MLP
Forward pass with a cache and a backward pass that returns the gradient of every weight and bias of a two-layer sigmoid network.
ImplementHardPhase 0340 min - Fit a sine curve with a tanh network
Train a 1-16-1 tanh network on noisy samples of sin(x) until its held-out mean squared error against the true curve is below 0.01.
TrainMediumPhase 0335 min - Focal loss
Binary and multi-class focal loss with gamma and alpha, from logits and without overflow, plus the binary gradient.
ResearchEasyPhase 0320 min - Stable softmax and cross-entropy
Batched softmax, mean cross-entropy and its gradient, without overflow for large logits.
ImplementEasyPhase 0320 min - SGD with momentum
One momentum update with the lesson's velocity rule, and a loop that minimizes a quadratic with or without Nesterov lookahead.
ImplementEasyPhase 0320 min - Adam and AdamW step
One Adam update with bias correction and a step counter that starts at 1, plus AdamW decoupled weight decay, as a pure function of the state.
ImplementMediumPhase 0325 min - Inverted dropout
Inverted dropout with a given random generator: training forward with an exact mask, backward with the same mask, identity at inference.
ImplementEasyPhase 0315 min - Batch normalization forward and backward
Training and inference forward passes with running statistics, and the full backward pass for x, gamma and beta.
ImplementHardPhase 0345 min - Sweep the learning rate
Sweep gradient descent learning rates on a seeded regression, find the best rate and the first rate that diverges, and compare with 2 over the top eigenvalue.
LabEasyPhase 0320 min - Train a tanh network on two spirals
Train a 2-24-24-1 tanh network with mini-batch Adam until it separates two noisy spirals with 95 percent held-out accuracy.
TrainMediumPhase 0345 min - CLIP symmetric contrastive loss
Normalize image and text embeddings, build the temperature-scaled similarity matrix, and compute the symmetric InfoNCE loss and its gradient.
ResearchMediumPhase 0430 min - Beam search with EOS and length normalization
Keep the best beam_width partial sequences over a step function, finish beams at EOS, and rank them with a length penalty.
ImplementHardPhase 0545 min - BM25 ranking
Score tokenized documents against a query with BM25: the lesson idf, term frequency saturation with k1, length normalization with b, and a ranked list.
ImplementMediumPhase 0525 min - Train a character bigram language model
Train a table of next-character logits with gradient descent until the held-out negative log-likelihood beats a unigram model.
TrainMediumPhase 0540 min - Scaled dot-product attention with a mask
Batched softmax(QK^T / sqrt(d_k)) V with an optional boolean mask, plus the causal mask that a decoder uses.
ImplementMediumPhase 0725 min - Grouped-query attention
GQA forward with H query heads and G shared key and value groups, plus mean pooling of a multi-head checkpoint into groups.
ResearchMediumPhase 0730 min - Split heads, merge heads, multi-head attention
Reshape (B, T, D) into H heads and back, then run batched multi-head self-attention with given projection matrices.
ImplementMediumPhase 0730 min - Sinusoidal positional encoding
Build the sin and cos position table with interleaved columns and base 10000, and add it to a batch of token embeddings.
ImplementEasyPhase 0715 min - Rotary position embedding
Rotate adjacent coordinate pairs of queries and keys by position times base^(-2i/d), so attention scores depend only on the position gap.
ImplementMediumPhase 0725 min - LayerNorm and RMSNorm
LayerNorm with gamma and beta and RMSNorm with a weight, both over the last axis, with eps inside the square root.
ImplementEasyPhase 0715 min - Sweep the sampling temperature
Sweep the temperature on fixed logits, measure entropy and top 1 probability, find where entropy crosses 2 bits, and count the tokens top p keeps.
LabEasyPhase 0720 min - Temperature, top-k and top-p sampling
Scale logits by temperature, keep the top k or the top p mass, renormalize, and draw one token with a seeded rng.
ImplementMediumPhase 0730 min - Top-k MoE gating and the Switch load-balancing loss
Route tokens to the top k experts with renormalized softmax gates, and compute the Switch Transformer auxiliary loss E times sum f_i P_i.
ResearchMediumPhase 0730 min - Fixed-capacity KV cache
Append keys and values to a preallocated cache, attend one query over the valid prefix, and reject an append past the capacity.
ImplementMediumPhase 0725 min - Tiled attention with an online softmax
FlashAttention in numpy: a running max and a running sum over key blocks give exact attention for any block size.
ResearchHardPhase 0740 min - Speculative decoding: accept, reject and resample
The min(1, p/q) acceptance rule and the residual distribution that keep speculative decoding exactly equal to the target model.
ResearchHardPhase 0735 min - DDPM noise schedule, closed form noising and posterior
Build the linear beta schedule and alpha bars, sample x_t from x_0 in closed form, and compute the mean and variance of q(x_{t-1} | x_t, x_0).
ResearchMediumPhase 0830 min - Rectified flow loss and Euler sampler
Interpolate along straight paths, regress the velocity x1 - x0 with the flow matching loss, and integrate a velocity field with Euler steps.
ResearchMediumPhase 0825 min - Q-learning and SARSA updates
One tabular Q-learning or SARSA update with no bootstrap at a terminal step, and epsilon-greedy actions from a seeded rng with lowest-index ties.
ImplementEasyPhase 0915 min - Discounted returns with episode ends
Reward-to-go returns for one episode and for a batch of joined episodes with done flags, plus return normalization.
ImplementEasyPhase 0915 min - Generalized advantage estimation
TD errors and GAE advantages with gamma, lambda, done flags and a bootstrap value, plus the critic targets.
ImplementMediumPhase 0925 min - PPO clipped surrogate loss
The PPO loss to minimize from new and old log probabilities and advantages, the clip fraction, and the gradient with respect to the new log probabilities.
ImplementMediumPhase 0925 min - GRPO group advantages and clipped objective
Normalize rewards within each group, estimate the KL with k3, and compute the clipped GRPO objective averaged per answer over valid tokens.
ResearchMediumPhase 0930 min - DPO loss and implicit rewards
The direct preference optimization loss, its implicit rewards and its gradient, from policy and reference log probabilities.
ResearchMediumPhase 1025 min - Symmetric int8 quantization
Absmax int8 quantization with one scale per tensor and one scale per row, with dequantization and a zero-row rule.
ImplementMediumPhase 1020 min - Sweep the quantization bit width
Sweep symmetric absmax quantization from 2 to 8 bits on weights with outliers, compare one scale per tensor with one scale per row.
LabMediumPhase 1030 min - Cosine similarity top-k search
Normalize embedding rows, score queries against documents with cosine similarity, and return the top k documents with a fixed tie rule.
ImplementEasyPhase 1115 min - LoRA linear layer
Forward pass of a linear layer with a low rank adapter, merge of the adapter into the weight, and the trainable parameter count.
ImplementEasyPhase 1115 min - Read an SGLang sweep on an L4
Use real SGLang runs on an NVIDIA L4 to find the saturation point, the SLO limit, the FP8 gain and the effect of a smaller prefill chunk.
LabMediumPhase 1730 min - Parse and validate tool calls
Parse tool calls from a raw model reply and validate their arguments against a JSON Schema subset with JSON pointer error paths.
ImplementHardPhase 1950 min - BPE pair counts and merges
Count weighted adjacent pairs, pick the best pair with a fixed tie rule, merge it without overlap and train a BPE merge list.
ImplementMediumPhase 1930 min - Reciprocal rank fusion
Merge several ranked lists of document ids into one ranking with reciprocal rank fusion, optional list weights and a fixed tie rule.
ImplementEasyPhase 1912 min
No problem matches these filters.
Tracks
12 tracks
- Math foundationsMatrix operations, gradients and optimization written with numpy.
- Classical MLThe models that come before deep learning, written from the equations.
- Deep learning coreLosses, backpropagation, normalization and optimizers.
- OptimizersGradient descent, momentum and Adam, one update rule at a time.
- Transformers from scratchAttention, heads, positions and normalization: the parts of a transformer block.
- LLM inferenceTokenizers, sampling, beam search, the KV cache and LoRA.
- RL basicsReturns, advantages and the PPO objective.
- RAG building blocksDense and sparse retrieval scores that a RAG system ranks with.
- Agent building blocksThe parsing and validation code around an agent loop.
- Papers to codeImplement the core method of a research paper and test it against the paper's equations.
- Train tiny modelsTrain a small model in your browser to a target score inside a step budget.
- Experiment labsChange one variable, measure the effect, and answer with numbers.
How it works
- Run checks your code against the examples in the statement.
- Submit runs every check: the examples, properties that any correct answer has, hidden edge cases and a comparison with the reference solution.
- A train task draws your loss curve while it runs, then measures your model on held-out data. A lab compares your answers with the numbers of a reference run.
- A failed check shows the expected value, your value and what the check means.
- Hints open one at a time. The solution and the notes open after you pass.
- Python runs in your browser with Pyodide. The first run downloads about 15 MB, then the browser keeps it. Your code and progress stay in this browser. No account is necessary.
- To work offline, clone the repository and run
python3 scripts/practice/run.py <id> my_answer.py.