Home / Code Lab

Code Lab

Implement it from scratch with numpy and the standard library. Read the problem, close the page, write it in 30 to 45 minutes, then compare with the reference.

Rules of the game and formats to practice

Almost every AI engineer loop now includes an "implement it from scratch" round. Interviewers use these to separate people who have used transformers, RAG, and agents from people who understand them - you can't fake your way through a causal mask or a numerically stable softmax with API knowledge. Frontier labs and serious AI startups routinely ask for attention, tokenizers, sampling, and KV caches in plain numpy; product-focused teams lean on the RAG, agent-loop, and streaming-parser variants.

Rules of the game

  • Dependencies: numpy + Python stdlib only. No PyTorch, no transformers, no framework crutches. That's the point.
  • Self-contained: every file runs standalone with python3 <file>.py and finishes with All tests passed.
  • Structure: each file has a PROBLEM statement (what you'd be asked, with exact signatures), INTERVIEW NOTES (what strong solutions demonstrate, common mistakes, follow-up variations), a clean reference solution, and assert-based tests.

How to practise: read only the docstring, close the file, implement it yourself under time pressure (30-45 min is typical), then run the tests and diff against the reference. Being able to talk while coding - naming the stability trick, the complexity, the failure mode - is what actually gets scored.

Formats these files don't cover yet

Two formats show up in 2025-2026 loops that a build-from-scratch file can't fully rehearse. Practise them on top of the files above.

  • Async fan-out with safe retries. Reported online assessments ask you to write an async function that calls several APIs at once and to explain how retries avoid repeating an operation. The full version: fan out N LLM calls under a concurrency cap (asyncio.Semaphore), a per-call timeout, exponential backoff with jitter on 429s and 5xx only, an idempotency key per logical operation so a retry never repeats a side effect, and cancellation of the remaining calls when a time or token budget runs out. To practise, port 11_rate_limiter_and_retry.py to asyncio and add those four pieces, with a test that a cancelled batch leaves no orphaned tasks.
  • Find the planted bugs. Some onsites hand you a working-looking implementation with several bugs and ask you to find and fix each one and write the test that would have caught it. One reported research-engineer round used a transformer with four marked regions, and some AI-enabled rounds use a small multi-file repo with 4-5 sub-questions. To practise, have someone plant bugs in 01_attention.py or 07_mini_gpt_forward.py (mask applied after softmax, missing √d_k, wrong transpose axis, residual connection dropped) and remove the tests first: the skill on display is writing the test that catches each one.

Running

python3 12-coding-challenges/01_attention.py
# ...
# All tests passed.

The only dependency is numpy (pip install numpy).

1Attention from scratch
Scaled dot-product attention, multi-head, causal masking
Medium
2Byte-level BPE tokenizer: train, encode, decode
Byte-level BPE: train, encode, decode
Medium
3Sampling strategies: temperature, top-k, top-p, min-p, repetition penalty
Temperature, top-k, top-p, min-p, repetition penalty
Easy
4Positional encodings: sinusoidal + RoPE
Sinusoidal PE, RoPE
Medium
5Numerically stable softmax, LayerNorm, RMSNorm
Stable softmax/log-softmax, LayerNorm, RMSNorm
Easy
6Autoregressive decoding with vs. without a KV cache
Autoregressive decode loop with vs. without KV cache
Medium
7Mini GPT Forward Pass
Full GPT block forward pass: embeddings → attention → MLP → logits
Hard
8Semantic Search + RAG Pipeline
Embed, index, cosine retrieval, context assembly (mini-RAG)
Medium
9Text Chunking Strategies
Fixed, sliding-window, recursive, sentence chunkers
Easy
10Minimal Agent Loop with Tool Use
Tool-calling agent loop with a mock LLM
Medium
11Token-Bucket Rate Limiter + Retry with Backoff
Token bucket, exponential backoff with jitter
Medium
12Eval Metrics: pass@k, QA F1, Model-Graded Harness
pass@k unbiased estimator, QA F1/EM, judge harness skeleton
Medium
13Streaming SSE Parser + Tool-Call Assembler
SSE parser, incremental tool-call argument assembly
Hard
14LoRA Adapters: Zero Init, Merging, Multi-Adapter Serving
LoRA forward, merge, and batched multi-adapter serving
Medium
15Beam Search with Length Normalization
Beam search with length normalisation
Medium
16Semantic Cache with TTL, LRU and Tag Invalidation
Exact and semantic cache tiers, TTL, LRU, tag invalidation
Medium
17Hybrid Search: BM25, Reciprocal Rank Fusion, MMR
BM25, reciprocal rank fusion, MMR diversity re-ranking
Medium
18Constrained JSON Decoding with a Schema Walker
Masking invalid tokens against a schema during decode
Hard
19Speculative Decoding: Draft, Verify, Accept
Draft-and-verify with the exact rejection-sampling rule
Hard