Build Your Own X: AI Edition - Build an LLM, Tokenizer, Transformer, RAG, Vector Database, Coding Agent and MCP Server from Scratch
A curated list of the best free tutorials for building your own AI technology from scratch: a large language model (LLM), a BPE tokenizer, a transformer, an autograd engine, a RAG pipeline, a vector database, a coding agent, an MCP server, a diffusion model, a speech recognizer and more. It is for developers who learn best by re-creating things, and who want to understand how modern AI actually works under the hood instead of only calling APIs.
Last reviewed: December 2026. Every link was opened during review. Tutorials are grouped by what you build, with the main language and a difficulty level.
Table of Contents
- How to Use This List
- Suggested Learning Order
- Best Picks: If You Only Do One Per Topic
- What Hardware Do You Need?
- Warm-Up: Puzzles That Build Intuition
- Build Your Own Neural Network and Autograd Engine
- Build Your Own Tokenizer
- Build Your Own Word Embeddings
- Build Your Own Transformer
- Build Your Own LLM (GPT from Scratch)
- Build Your Own Pre-Training Dataset
- Build Your Own Llama, Qwen or Mixture-of-Experts Model
- Build Your Own Fine-Tuning, LoRA and RLHF
- Build Your Own Reasoning Model
- Build Your Own LLM Inference Engine
- Build Your Own GPU Kernels
- Build Your Own Distributed Training
- Build Your Own Search Engine and Vector Database
- Build Your Own RAG System
- Build Your Own AI Agent and Coding Agent
- Build Your Own MCP Server and Client
- Build Your Own LLM Evaluation Harness
- Build Your Own Diffusion Model (Image Generator)
- Build Your Own GAN, VAE and CLIP
- Build Your Own Vision Transformer and Vision-Language Model
- Build Your Own Speech Recognizer
- Build Your Own RNN and State Space Model
- Build Your Own Game-Playing AI (AlphaZero and RL)
- Build Your Own Interpretability Tools
- FAQ
- Project Ideas After the Tutorials
- Where to Go Next
- Contributing
- License
- Credits
How to Use This List
Each entry looks like this:
[Language] [Tutorial title](link) - Format. Level. What you will build.
- Format: Article, Video, Repo (code you read and run), Notebook, Course, or Docs.
- Level: Beginner (comfortable with Python), Intermediate (knows PyTorch basics and some linear algebra), Advanced (comfortable reading papers and writing performance-sensitive code).
How to get the most out of a “from scratch” tutorial:
- Read or watch once without coding to see the whole shape.
- Rebuild it in a fresh folder without copying, looking back only when stuck.
- Change one thing the tutorial did not do: a new dataset, a different tokenizer, a new sampling method, a different language.
- Write tests for the parts you can test (tokenizer round-trips, attention mask shapes, retrieval recall on a tiny dataset).
- Write a short README explaining what you built and what surprised you.
Suggested Learning Order
If you want to understand the modern LLM stack end to end, this order works well:
- Autograd engine (micrograd) - you learn backpropagation.
- Character-level language model (makemore) - you learn training loops and sampling.
- BPE tokenizer - you learn how text becomes tokens.
- Transformer and GPT - you learn attention and the architecture behind LLMs.
- Fine-tuning and preference tuning - you learn how base models become assistants.
- Inference engine with a KV cache - you learn why serving LLMs is a memory problem.
- Vector search and RAG - you learn how to give models knowledge.
- Agent and MCP server - you learn how models act in the world.
- Evaluation harness - you learn how to know if any of it works.
Side quests: diffusion (images), speech recognition (audio), AlphaZero (planning), GPU kernels (performance).
Best Picks: If You Only Do One Per Topic
| You want to build | Best single pick | Why this one | Rough time |
|---|---|---|---|
| Autograd engine | micrograd video | Shortest path to really understanding backpropagation | 1 day |
| Tokenizer | “Let’s build the GPT Tokenizer” plus minbpe | Covers BPE, regex pre-splitting and special tokens, with reference code to test against | 2-3 days |
| Transformer | The Annotated Transformer | Paper and code side by side, nothing hidden | 2-4 days |
| GPT-style LLM | “Let’s build GPT” then nanoGPT | Builds intuition first, then gives you a codebase that scales | 1-2 weeks |
| Chat model, end to end | nanochat | A small, readable codebase that covers the whole pipeline from tokenizer to chat UI | 2-4 weeks |
| Fine-tuning and DPO | LLMs-from-scratch Appendix E and DPO notebook | Everything implemented by hand, no library magic | 1 week |
| Inference engine | KV cache article, then nano-vllm | First the core idea, then a real but small engine | 1-2 weeks |
| Vector database | Pinecone’s Faiss series plus the HNSW paper | Explains every index type you will implement | 1-2 weeks |
| RAG | RAG From Scratch notebooks plus your own eval set | Broad coverage of techniques, and you measure what helps | 1 week |
| Coding agent | “How to Build an Agent” then mini-swe-agent | Proves the core loop is small, then shows what good looks like | 2-3 days |
| MCP server | Official “Build an MCP server” tutorial, then the spec | The SDK path first, the protocol second | 1-2 days |
| Diffusion model | The Annotated Diffusion Model | Math and code together for DDPM | 1 week |
| Speech recognizer | Distill CTC article plus the Hugging Face Audio Course | Core loss function first, then a full practical pipeline | 2 weeks |
What Hardware Do You Need?
Honest, approximate guidance (your results will vary with model size, batch size and patience):
| Project | Laptop CPU | Laptop with Apple silicon or a gaming GPU | Rented or cloud GPU |
|---|---|---|---|
| micrograd, tokenizer, search engine, MCP server, agent loop | Fine | Fine | Not needed |
| Character-level GPT on Shakespeare | Slow but works with a small model | Comfortable | Not needed |
| GPT-2 small (124M) reproduction on billions of tokens | No | Too slow for the full run | Needed (multi-GPU for the fast path) |
| nanochat full pipeline | No | No | Needed; the repo documents its target hardware |
| Fine-tuning a 1B-8B model with LoRA | No | Small models only, depending on memory | Recommended |
| Small DDPM on 32x32 images | Very slow | Works | Faster |
| Speech recognizer with CTC on a small dataset | Slow | Works | Faster |
| Vector database with 1M vectors | Works | Works | Not needed |
Tip: free notebook environments (with limited GPU time) are enough for most Beginner and Intermediate entries in this list.
Warm-Up: Puzzles That Build Intuition
Short, self-checking exercises that make the bigger builds much easier.
[Python]Tensor Puzzles - Notebook. Intermediate. Re-implement NumPy and PyTorch functions using only broadcasting and a few primitives; the best cure for shape bugs.[Python]Autodiff Puzzles - Notebook. Intermediate. Write the derivatives of common tensor functions and check them automatically.[Python]GPU Puzzles - Notebook. Intermediate. Learn CUDA’s programming model through small puzzles that run in a notebook.[Python]LLM Training Puzzles - Notebook. Advanced. Puzzles about memory and compute efficiency when training across many GPUs.[Interactive]Transformer Explainer - Web app. Beginner. Runs a small GPT-2 in your browser and shows every step of a forward pass.[Interactive]LLM Visualization - Web app. Beginner. A 3D walkthrough of the computations inside GPT-style models, layer by layer.
Build Your Own Neural Network and Autograd Engine
What you learn: computation graphs, the chain rule as code, gradient descent, and what PyTorch’s loss.backward() really does.
[Python]The spelled-out intro to neural networks and backpropagation: building micrograd - Video. Beginner. A scalar-valued autograd engine and a small neural network library in about 150 lines.[Python]micrograd - Repo. Beginner. The reference code for the video above.[Python]Neural Networks: Zero to Hero (course page) and notebooks - Video course. Beginner to Intermediate. From micrograd to a GPT, one video at a time.[Python]MiniTorch - Course. Intermediate. A teaching re-implementation of the core of PyTorch: tensors, autodiff, broadcasting, parallel and GPU operations.[Python]Autodidax: JAX core from scratch - Docs. Advanced. Builds a mini JAX with tracing,jvp,vmap,gradandjit.[Python]Convolutional Neural Networks (CS231n notes) - Article. Intermediate. The math and shapes behind convolution layers, explained well enough to implement them yourself.[Video]3Blue1Brown: Neural Networks series - Video. Beginner. Visual intuition for gradient descent, backpropagation, and how transformers work.
Build Your Own Tokenizer
What you learn: Byte Pair Encoding (BPE), why tokenization causes odd LLM behavior, special tokens, and how GPT-style tokenizers split text with regex before merging.
[Python]Let’s build the GPT Tokenizer - Video. Intermediate. A BPE tokenizer from scratch, plus why tokenization explains many LLM quirks.[Python]minbpe and its lecture notes - Repo. Intermediate. Minimal, clean BPE implementations, including a GPT-4-style regex tokenizer.[Python]Hugging Face LLM Course: Byte-Pair Encoding tokenization - Article. Beginner. Implements the BPE training algorithm step by step.[Python]Hugging Face LLM Course: WordPiece tokenization and Unigram tokenization - Article. Intermediate. The two other major subword algorithms, implemented from scratch.[Python]Hugging Face LLM Course: Building a tokenizer, block by block - Article. Intermediate. Assembling normalization, pre-tokenization, model and post-processing into a full tokenizer.[Reference]tiktoken, SentencePiece and Hugging Face Tokenizers - Repos. Production tokenizers to compare your output against.
Test your tokenizer: encode then decode 10,000 random Unicode strings and check you get the original back; check that emoji, Chinese text and code with tabs all round-trip.
Build Your Own Word Embeddings
What you learn: how meaning becomes vectors, negative sampling, and the bridge between language models and retrieval.
[Concepts]The Illustrated Word2vec - Article. Beginner. A visual explanation of skip-gram with negative sampling that is detailed enough to implement.[Python]Sentence Transformers: training overview - Docs. Intermediate. Train or fine-tune your own sentence embedding model with contrastive losses.[Python]Train and Fine-Tune Sentence Transformers Models (Hugging Face) - Article. Intermediate. Dataset formats and losses for training embedding models for search and similarity.
Build Your Own Transformer
What you learn: scaled dot-product attention, multi-head attention, positional encodings, residual connections, layer normalization and masking.
[Python]The Annotated Transformer - Notebook. Intermediate. The original “Attention Is All You Need” paper, line by line, as working PyTorch code.[Concepts]The Illustrated Transformer - Article. Beginner. The visual explanation most people read first.[Python]Transformers from scratch (Peter Bloem) - Article. Intermediate. Builds self-attention up from first principles, with simple code.[Python]UvA DL Tutorial 6: Transformers and Multi-Head Attention - Notebook. Intermediate. A clean implementation with experiments that show what attention learns.[Python]Dive into Deep Learning: The Transformer Architecture - Notebook. Intermediate. Encoder-decoder transformer in PyTorch, JAX or TensorFlow.[Concepts]Attention? Attention! (Lilian Weng) - Article. Intermediate. The history and variants of attention mechanisms.[Video]Transformers, the tech behind LLMs (3Blue1Brown) - Video. Beginner. Visual intuition for embeddings, attention and the residual stream.
Build Your Own LLM (GPT from Scratch)
What you learn: data loading, training a decoder-only transformer, sampling, scaling a model up, and what goes into a real chat model.
[Python]Let’s build GPT: from scratch, in code, spelled out - Video. Intermediate. A character-level GPT trained on Shakespeare, built up in about two hours.[Python]Let’s reproduce GPT-2 (124M) with code in build-nanogpt - Video and Repo. Advanced. Train a GPT-2-sized model on real web data, with mixed precision,torch.compile, FlashAttention and distributed training.[Python]nanoGPT - Repo. Intermediate. A small, readable codebase for training and fine-tuning medium-sized GPTs.[Python]nanochat - Repo. Advanced. A full ChatGPT-style pipeline on a small budget: tokenizer training, pre-training, mid-training, supervised fine-tuning, RL, evaluation and a web chat UI.[C/CUDA]llm.c - Repo. Advanced. GPT-2 training in plain C and CUDA, without PyTorch.[Python]Build a Large Language Model (From Scratch), code repository - Repo, Notebooks. Intermediate. Free notebooks covering data preparation, attention, a GPT model, pre-training, classification fine-tuning and instruction fine-tuning. (The code is free; the companion book is paid.)[Python]GPT in 60 Lines of NumPy with picoGPT - Article and Repo. Intermediate. A GPT-2 forward pass in pure NumPy that loads the real GPT-2 weights.[Python]minGPT - Repo. Intermediate. An earlier, educational GPT implementation with clear model and trainer files.[Python]Stanford CS336 Assignment 1: Basics - Repo. Advanced. Implement a BPE tokenizer, a transformer language model, AdamW and a training loop from scratch, with tests to check your work.[Video]Deep Dive into LLMs like ChatGPT - Video. Beginner. A non-code overview of the full training pipeline, useful before starting nanochat.[Python]modded-nanogpt - Repo. Advanced. A community speedrun that trains a GPT-2-small-level model as fast as possible; each record documents the trick that made it faster.[Python]LitGPT - Repo. Intermediate. Readable, from-scratch implementations of many open-weight architectures, with pre-training, fine-tuning and deployment recipes.
Which GPT-from-scratch resource should you pick?
| Resource | Format | Scope | Best for |
|---|---|---|---|
| Let’s build GPT (video) | Video, about 2 hours | Character-level GPT on one GPU or CPU | Your first transformer language model |
| nanoGPT | Repo | GPT-2 training and fine-tuning | A clean base for your own experiments |
| build-nanogpt and “Let’s reproduce GPT-2” | Video and Repo | GPT-2 124M on real data, with performance tricks | Learning how real pre-training runs are engineered |
| nanochat | Repo | Tokenizer to chat UI, including SFT and RL | Understanding the complete modern pipeline |
| LLMs-from-scratch | Notebooks | Data to instruction tuning, plus many bonus notebooks | Learners who prefer reading and step-by-step notebooks |
| picoGPT | Repo, about 60 lines | Inference only, NumPy | Seeing the whole forward pass at once |
| CS336 Assignment 1 | Repo with tests | Tokenizer, model, optimizer, training loop | Rigor: you are graded by unit tests |
| llm.c | C and CUDA | GPT-2 training without frameworks | Systems programmers |
| modded-nanogpt | Repo | Speedrun of GPT-2 small training | Seeing which tricks make training faster |
| LitGPT | Repo | Many open architectures, pre-training and fine-tuning recipes | Moving from toy models to real open-weight models |
Build Your Own Pre-Training Dataset
What you learn: why data quality matters as much as model size, deduplication, quality filtering and tokenizing at scale.
[Concepts]FineWeb: decanting the web for the finest text data at scale - Article. Intermediate. A detailed account of building a large web-text dataset, with ablations showing which filtering and deduplication steps help.[Python]datatrove - Repo. Intermediate. The data processing library used for FineWeb; read its pipeline blocks for extraction, filtering and deduplication.
Build spec: take one Common Crawl WET file or a Wikipedia dump, extract text, filter by language and simple quality heuristics (length, symbol ratio, repeated lines), deduplicate with MinHash, tokenize with your own tokenizer and write fixed-length shards. Train a small model on filtered versus unfiltered data and compare validation loss.
Build Your Own Llama, Qwen or Mixture-of-Experts Model
What you learn: the changes modern open-weight models made to GPT-2 (RMSNorm, rotary position embeddings, SwiGLU, grouped-query attention) and sparse mixture-of-experts layers.
[Python]Converting GPT to Llama (LLMs-from-scratch bonus material) - Notebook. Intermediate. Turn a GPT implementation into Llama 2 and Llama 3 architectures step by step and load real weights.[Python]Qwen3 from scratch (LLMs-from-scratch bonus material) - Notebook. Intermediate. A from-scratch implementation of a recent open-weight architecture.[Python]llama3-from-scratch - Notebook. Intermediate. Llama 3 inference implemented one tensor operation at a time, loading the official weights.[Python]Llama from scratch (Brian Kitano) - Article. Intermediate. Implements the Llama architecture changes and trains a small model, with advice on how to debug as you go.[C]llama2.c - Repo. Intermediate. Train a tiny Llama 2 in PyTorch, then run inference in a single, short C file.[Python]makeMoE: Implement a Sparse Mixture of Experts Language Model from Scratch - Article. Intermediate. Adds top-k routing and expert layers to a small character-level model.
Build Your Own Fine-Tuning, LoRA and RLHF
What you learn: supervised fine-tuning, parameter-efficient fine-tuning, and preference tuning (DPO, RLHF).
[Python]LoRA from scratch (LLMs-from-scratch Appendix E) - Notebook. Intermediate. Implement low-rank adapters yourself and fine-tune a GPT model with them.[Python]Direct Preference Optimization from scratch (LLMs-from-scratch bonus material) - Notebook. Advanced. Implement the DPO loss and align an instruction-tuned model with preference data.[Course]Hugging Face smol course - Course. Intermediate. Practical fine-tuning and alignment of small language models.[Reference]TRL and PEFT - Repos. Production libraries to compare your implementation against.[Reference]torchtune and Unsloth - Repos. Fine-tuning libraries whose recipes are worth reading once your own LoRA works.[Concepts]A Gentle Introduction to 8-bit Matrix Multiplication for transformers at scale (Hugging Face) - Article. Intermediate. How LLM.int8() quantization works, which matters when you fine-tune large models on small GPUs.
Build Your Own Reasoning Model
What you learn: reinforcement learning with verifiable rewards, chain-of-thought and inference-time scaling.
[Python]Build a Reasoning Model (From Scratch), code repository - Repo, Notebooks. Advanced. Free code for adding reasoning to a small LLM via inference-time techniques and reinforcement learning. (The companion book is paid.)[Python]TinyZero - Repo. Advanced. A minimal reproduction of RL-trained reasoning on simple tasks such as countdown and multiplication, using a small model.
Build Your Own LLM Inference Engine
What you learn: the KV cache, batching, paged memory, quantization, and why token generation is memory-bandwidth bound.
[Python]Understanding and Coding the KV Cache in LLMs from Scratch - Article. Intermediate. Add a KV cache to a GPT implementation and measure the speedup.[Python]nano-vllm - Repo. Advanced. A compact vLLM-style inference engine with prefix caching, tensor parallelism and CUDA graphs, small enough to read in an afternoon.[Python]gpt-fast - Repo. Advanced. Fast transformer inference in a few hundred lines of PyTorch:torch.compile, int8 and int4 quantization, speculative decoding and tensor parallelism.[Concepts]A Visual Guide to Quantization - Article. Intermediate. How number formats, scaling and methods like GPTQ work, with diagrams.[Paper]Efficient Memory Management for LLM Serving with PagedAttention - Paper. Advanced. The idea behind vLLM’s paged KV cache; implement a toy block allocator after reading it.[Reference]llama.cpp, vLLM and SGLang - Repos. Production engines to study once your toy engine works.
Build Your Own GPU Kernels
What you learn: how GPUs execute code, memory hierarchy, tiling, and why FlashAttention is fast.
[CUDA]How to Optimize a CUDA Matmul Kernel for cuBLAS-like Performance - Article. Advanced. Ten kernels, each faster than the last, with explanations of coalescing, shared memory and tiling.[CUDA]flash-attention-minimal - Repo. Advanced. A FlashAttention forward pass in about 100 lines of CUDA.[Python]Triton tutorials - Docs. Advanced. Write GPU kernels in Python: vector add, fused softmax, matrix multiplication, layer norm and fused attention.[Video]GPU MODE lectures - Video and Repo. Intermediate to Advanced. A community lecture series on CUDA, Triton, profiling and kernel optimization.[C++]ThunderKittens - Repo. Advanced. A small embedded DSL for writing fast tile-based kernels; good to read after you have written plain CUDA.[Verilog]tiny-gpu - Repo. Advanced. A minimal GPU design in Verilog, to understand the hardware your kernels run on.
Build Your Own Distributed Training
What you learn: data, tensor, pipeline and context parallelism, and ZeRO-style sharding.
[Python]picotron - Repo. Advanced. A minimal framework implementing 4D parallelism for education, with accompanying video walkthroughs.[Docs]The Ultra-Scale Playbook - Article. Advanced. Explains every parallelism strategy with measurements; read it alongside picotron.
Build Your Own Search Engine and Vector Database
What you learn: inverted indexes, BM25, approximate nearest neighbor search (HNSW, IVF), and product quantization.
[Python]Building a full-text search engine in 150 lines of Python code - Article. Beginner. Inverted index, tokenization, TF-IDF ranking. Add BM25 as an exercise.[Concepts]Faiss: The Missing Manual (Pinecone) - Article series. Intermediate. Vector index types explained with code, including HNSW and product quantization.[Paper]Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs - Paper. Advanced. The HNSW paper; its pseudocode is clear enough to implement directly.[C++]hnswlib - Repo. Advanced. A compact, header-only HNSW implementation to read after writing your own.[Reference]Faiss (see its wiki), Annoy, pgvector, Qdrant and Chroma - Repos. Real systems to benchmark your index against.
Build spec for your own vector database:
- Brute-force cosine search over NumPy arrays (your correctness baseline).
- An HNSW index with
Mandefparameters; measure recall@10 against the baseline. - Persistence to disk with a simple append-only file and a rebuild on startup.
- Metadata filtering (for example
where year > 2020). - A tiny HTTP API with
upsert,queryanddelete. - A benchmark table: recall, queries per second and memory for 10k, 100k and 1M vectors.
Build Your Own RAG System
What you learn: chunking, embeddings, retrieval, reranking, prompt construction, citations and evaluation.
[Python]RAG From Scratch (LangChain) - Notebooks and videos. Beginner to Intermediate. Indexing, retrieval and generation, then query translation, routing and advanced indexing techniques.[Python]Simple Local RAG - Notebook and video. Beginner. A RAG pipeline over a PDF that runs entirely on a local GPU.[Python]Advanced RAG on Hugging Face documentation (Hugging Face Cookbook) - Notebook. Intermediate. Chunking strategies, embedding choices, reranking and evaluation.[Concepts]Introducing Contextual Retrieval (Anthropic) - Article. Intermediate. Adding chunk-specific context before embedding, combined with BM25 and reranking, with retrieval failure-rate measurements.[Python]ColBERT - Repo. Advanced. Late-interaction retrieval, a strong alternative to single-vector embeddings.[Python]rank_bm25 - Repo. Beginner. A tiny BM25 implementation; read it, then write your own.[Python]RAG Evaluation (Hugging Face Cookbook) - Notebook. Intermediate. Build a synthetic evaluation set and score a RAG system with an LLM judge.[Reference]Ragas - Repo. Intermediate. A library of RAG and LLM application metrics to compare with your own scorers.
Build spec for your own RAG system:
- Ingest Markdown and PDF files, split into chunks with overlap, keep source and position metadata.
- Embed chunks with an open embedding model and store them in your vector database from the previous section.
- Add BM25 keyword search and merge results (hybrid search), then rerank the top 20.
- Build a prompt that includes numbered sources and asks the model to cite them.
- Create an eval set of 50 questions with expected source documents; report retrieval recall@5 and answer correctness.
- Add a “no answer” path when retrieval confidence is low.
Build Your Own AI Agent and Coding Agent
What you learn: the tool-calling loop, tool design, context management, stopping conditions and sandboxing.
[Go]How to Build an Agent (Amp) - Article. Beginner. A working code-editing agent in a few hundred lines: an LLM, a loop and three tools (read file, list files, edit file).[Python]mini-swe-agent - Repo. Intermediate. A coding agent of about 100 lines that only uses bash, yet performs well on SWE-bench; the clearest proof that the loop is simple.[Concepts]Building effective agents (Anthropic) - Article. Beginner. Workflow patterns (prompt chaining, routing, orchestrator-workers) and when you actually need an agent.[Concepts]Writing effective tools for agents (Anthropic) - Article. Intermediate. How to design, evaluate and improve the tools your agent calls.[Python]You Should Write An Agent (Fly.io) - Article. Beginner. An argument, with code, for writing a small agent yourself to understand what the frameworks do.[Python]Claude Cookbooks - Notebooks. Intermediate. Recipes for tool use, sub-agents, retrieval and evaluation that you can re-implement without a framework.[Python]Hugging Face Agents Course - Course. Beginner. Agent fundamentals, then building agents with several frameworks, ending with a benchmark-graded final project.[Python]smolagents - Repo. Intermediate. A small agent library where the model writes its actions as Python code; easy to read end to end.[Reference]SWE-agent, Aider, OpenAI Codex CLI, Gemini CLI and OpenCode - Repos. Open-source coding agents to study once your own works.[Benchmark]SWE-bench - Benchmark. Advanced. Real GitHub issues used to evaluate coding agents; run your agent on a few instances.
Build spec for your own coding agent:
- A loop: send messages and tool definitions to a model, run any tool calls, append results, repeat until the model answers without tools or a step limit is hit.
- Tools:
read_file,list_dir,search(ripgrep),edit_file(exact string replace),run(shell command with a timeout). - Safety: run commands in a container or a throwaway directory, require confirmation for anything that deletes files or touches the network.
- Context management: truncate long tool outputs, summarize old turns when the context gets large.
- Evaluation: 10 small bug-fix tasks in a toy repository, each with a failing test; measure how many your agent fixes.
Build Your Own MCP Server and Client
What you learn: the Model Context Protocol (MCP) for connecting AI applications to tools and data: tools, resources and prompts over stdio or HTTP.
[Docs]What is the Model Context Protocol? - Docs. Beginner. The concepts: hosts, clients, servers, tools, resources and prompts.[Python, TypeScript, more]Build an MCP server - Docs. Beginner. The official tutorial: a weather server with two tools, in several languages.[Python, TypeScript, more]Build an MCP client - Docs. Intermediate. Connect to servers and let a model call their tools.[Spec]MCP Specification - Docs. Advanced. The JSON-RPC messages, lifecycle, transports and authorization rules; read it to build a server without an SDK.[Python]MCP Python SDK and[TypeScript]MCP TypeScript SDK - Repos. The official SDKs with examples.[Python]FastMCP - Repo. Beginner. A popular high-level Python framework for MCP servers and clients; compare its decorators with the raw protocol messages.[Reference]MCP reference servers - Repo. Small, readable servers (filesystem, git, fetch, memory) to learn from.[Tool]MCP Inspector - Repo. A visual tool for testing and debugging your server.
Build spec for your own MCP server (no SDK):
- Read JSON-RPC 2.0 messages line by line from stdin, write responses to stdout, log only to stderr.
- Handle
initialize, thentools/listandtools/call. - Expose two tools with JSON Schema input definitions, for example
search_notesandadd_noteover a local folder of Markdown files. - Validate inputs and return tool errors as results the model can read, not as crashes.
- Test it with MCP Inspector, then connect it to an MCP-capable client.
Build Your Own LLM Evaluation Harness
What you learn: building eval sets, automatic and model-graded scoring, and catching regressions.
[Concepts]Your AI Product Needs Evals (Hamel Husain) - Article. Beginner. A practical approach: unit-test-style assertions, human review and model-graded evals, used together.[Python]Using LLM-as-a-judge for automated evaluation (Hugging Face Cookbook) - Notebook. Intermediate. Build an LLM judge, then measure how well it agrees with human ratings and improve the prompt.[Reference]lm-evaluation-harness - Repo. Intermediate. The widely used harness for academic benchmarks; read how tasks and metrics are defined.[Reference]Inspect - Repo. Intermediate. An evaluation framework from the UK AI Security Institute with datasets, solvers and scorers as separate parts, a good design to copy.[Reference]simple-evals - Repo. Beginner. Small, readable implementations of several popular benchmarks.
Build spec for your own eval harness:
- A JSONL file of test cases: input, expected behavior, tags.
- Three scorer types: exact or regex match, a Python function, and an LLM judge with a written rubric.
- Run all cases concurrently with retries and a cache so re-runs are cheap.
- Output a table by tag and a diff against the previous run, so you see regressions.
- Check your LLM judge against 30 hand-labeled cases before trusting it.
Build Your Own Diffusion Model (Image Generator)
What you learn: the forward noising process, denoising networks (U-Nets), sampling, classifier-free guidance, and flow matching.
[Python]The Annotated Diffusion Model (Hugging Face) - Article. Intermediate. DDPM in PyTorch, step by step, with the math alongside the code.[Concepts]What are Diffusion Models? (Lilian Weng) - Article. Advanced. The math of diffusion and score-based models in one place.[Python]Hugging Face Diffusion Models Course - Course. Intermediate. Train your own diffusion model from scratch, then fine-tune and guide existing ones.[Python]Practical Deep Learning Part 2: From Deep Learning Foundations to Stable Diffusion - Video course. Advanced. Rebuilds the pieces of Stable Diffusion from foundations.[Python]minDiffusion - Repo. Intermediate. A minimal, self-contained DDPM implementation.[Python]denoising-diffusion-pytorch - Repo. Intermediate. A compact and widely used DDPM implementation to compare against.[Python]diffusion-nbs (fast.ai) - Notebooks. Intermediate. Notebooks that open up Stable Diffusion’s components (text encoder, VAE, U-Net, scheduler) and run them by hand.[Course]MIT 6.S184: Flow Matching and Diffusion Models - Course. Advanced. Lecture notes and labs that build flow matching and diffusion models from the underlying differential equations.[Python]Flow Matching Guide and Code with the flow_matching library - Paper and Repo. Advanced. A comprehensive guide to flow matching with reference code.
Build spec: train a small DDPM on 32x32 images (for example a dataset of emoji or icons) on one GPU, then add classifier-free guidance with class labels, then swap the training objective to flow matching and compare samples at the same number of steps.
Build Your Own GAN, VAE and CLIP
[Python]DCGAN Tutorial (PyTorch) - Docs. Intermediate. Train a generative adversarial network to generate faces.[Python]Variational AutoEncoder (Keras example) - Docs. Intermediate. A convolutional VAE on MNIST with the reparameterization trick.[Python]Simple OpenAI CLIP implementation - Repo. Intermediate. Train a small CLIP model on image-caption pairs, then use it for image search.[Reference]OpenAI CLIP - Repo. The original model code to compare against.
Build Your Own Vision Transformer and Vision-Language Model
[Python]UvA DL Tutorial 15: Vision Transformers - Notebook. Intermediate. Patch embeddings and a ViT trained on CIFAR-10.[Python]nanoVLM with the nanoVLM blog post - Repo and Article. Advanced. A small, readable codebase that connects a vision encoder to a language model and trains a vision-language model.
Build Your Own Speech Recognizer
What you learn: audio features (log-mel spectrograms), CTC loss, encoder-decoder speech models, and decoding.
[Concepts]Sequence Modeling with CTC (Distill) - Article. Intermediate. A visual explanation of Connectionist Temporal Classification, the loss behind many speech recognizers.[Python]Hugging Face Audio Course - Course. Beginner to Intermediate. Audio data, transformer architectures for audio, speech recognition, text-to-speech and a voice assistant project.[Python]Fine-Tune Whisper for Multilingual ASR (Hugging Face) - Article. Intermediate. Fine-tune a speech recognition model for a new language end to end.[Paper]Robust Speech Recognition via Large-Scale Weak Supervision (Whisper) - Paper. Intermediate. The architecture and data choices behind Whisper.[Python]openai/whisper - Repo. Intermediate. The model code is short; readmodel.pyanddecoding.pyafter the paper.[C/C++]whisper.cpp - Repo. Advanced. A dependency-free C/C++ inference implementation; useful for learning how to port a model.[Python]Speech Recognition with Wav2Vec2 (torchaudio) - Docs. Intermediate. Run a CTC-based acoustic model step by step: features, emissions and greedy decoding.[Python]Hugging Face Audio Course: Automatic Speech Recognition and Text-to-Speech units - Course. Intermediate. Evaluation with word error rate, fine-tuning ASR, and how TTS models generate speech.[Reference]Kokoro and Parler-TTS - Repos. Small open text-to-speech models to read if you want to build the other half of a voice assistant.
Build spec: compute log-mel spectrograms yourself with NumPy, train a small convolutional and transformer encoder with CTC loss on a digits or short-commands dataset, implement greedy and beam-search CTC decoding, and report word error rate.
Build Your Own RNN and State Space Model
[Concepts]The Unreasonable Effectiveness of Recurrent Neural Networks - Article. Beginner. Character-level RNN language models and what they learn.[Python]NLP From Scratch: Classifying Names with a Character-Level RNN, Generating Names and Translation with a Sequence to Sequence Network and Attention - Docs. Beginner to Intermediate. Three classic PyTorch tutorials that build RNN models without high-level helpers.[Python]makemore - Repo. Beginner. Character-level models from bigrams to MLPs, RNNs and a transformer.[Python]The Annotated S4 - Notebook. Advanced. Structured state space sequence models implemented in JAX alongside the paper.[Python]Mamba: The Hard Way - Article. Advanced. Implementing the Mamba selective scan with Triton.
Build Your Own Game-Playing AI (AlphaZero and RL)
[Concepts]A Simple Alpha(Go) Zero Tutorial - Article. Intermediate. Monte Carlo tree search plus a policy-value network, explained compactly.[Python]alpha-zero-general - Repo. Intermediate. A clean AlphaZero implementation for any two-player turn-based game, with Othello, Connect Four and more.[Python]Spinning Up in Deep RL - Docs and Repo. Intermediate. Concise implementations of VPG, PPO, DDPG, TD3 and SAC with explanations.
Build Your Own Interpretability Tools
[Concepts]A Mathematical Framework for Transformer Circuits - Article. Advanced. How to think about attention-only transformers as circuits.[Python]ARENA - Course. Intermediate to Advanced. Exercises that build a transformer from scratch and then reverse-engineer it.[Python]TransformerLens - Repo. Intermediate. A library for inspecting and editing model activations; use it to check your own experiments.
FAQ
Do I need to be good at math to build these? For the Beginner entries, high school algebra and a willingness to look things up are enough. For transformers and diffusion you need matrix multiplication, derivatives and basic probability. Building the code is one of the best ways to learn that math.
Should I build in Python or something else? Python first, because almost every tutorial uses it. Re-implementing a piece in another language (a tokenizer in Rust, an MCP server in Go, inference in C) is an excellent second pass.
Is “from scratch” really from scratch? Usually it means “without the high-level library that hides the idea”. Using NumPy or PyTorch tensors is fine; using a library call that does the whole thing is not.
Can I build a useful LLM on my own computer? You can build and train a small model that writes plausible text in a narrow domain. It will not compete with large commercial models, and that is not the goal. The goal is understanding, which then makes you much better at using, fine-tuning and evaluating large models.
How long will this take? The full suggested learning order is roughly 3 to 6 months of evenings and weekends. Single entries take an afternoon to two weeks (see the Best Picks table).
What should I put on my resume? A few deep builds beat many shallow ones. Pick two or three, add your own twist and an evaluation, and write a clear README with results.
Are AI coding assistants allowed? For learning, write the core logic yourself. Use assistants to explain errors or review your code. Copying generated code defeats the purpose of a from-scratch build.
Project Ideas After the Tutorials
Once you have built the basics, combine them into something only you would make:
- A tokenizer for your language or domain: train BPE on legal text, chemistry, or a non-English language, and measure tokens per word against a general tokenizer.
- A tiny LLM for one job: train a 10M to 50M parameter model on a narrow corpus (recipes, chess games in PGN, SQL queries) and compare it with a fine-tuned open model.
- A local “chat with my notes” app: your vector database, your RAG pipeline, and a local model, with your eval set proving it works.
- A coding agent for one language: an agent that only fixes failing tests in a small Python or JavaScript project, with a benchmark of 20 tasks.
- An MCP server for a tool you use: your calendar file, a home server, a hobby database; then use it from an AI assistant.
- A speech-to-notes pipeline: your speech recognizer plus a summarizer, running fully on a laptop.
- A KV-cache visualizer: show memory per request and per layer as tokens are generated, with and without grouped-query attention.
Share what you build in a pull request to the “Show your build” discussion, and help others learn from it.
Where to Go Next
- Go deeper on theory: read the free textbooks Understanding Deep Learning (Simon Prince) and Dive into Deep Learning, both linked from many entries above.
- Take a full course: Stanford CS336 (Language Modeling from Scratch) turns many entries in this list into a graded semester of work.
- Contribute upstream: many projects here (nanoGPT forks, MCP reference servers, evaluation libraries) welcome small fixes, which is a great next step after building your own version.
- Reproduce a paper: pick a recent paper with a small-scale experiment, re-implement it from the description, and publish what matched and what did not.
- Teach it: write a blog post or record a short video of your build. Explaining it is the final test of understanding.
Contributing
Pull requests are welcome. Please keep entries accurate:
- Add tutorials that build the thing from scratch, not tutorials that only call a high-level API.
- Use the entry format: language tag, title, format, level, one sentence on what you build.
- Only link to free content. If code is free but an accompanying book is paid, say so.
- Check that the link works and the code still runs with reasonably current library versions.
License
This list is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). Linked tutorials and code belong to their authors and keep their own licenses.
If this helped you, a star helps others find it.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.