Skip to the content.

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

Each entry looks like this:

[Language] [Tutorial title](link) - Format. Level. What you will build.

How to get the most out of a “from scratch” tutorial:

  1. Read or watch once without coding to see the whole shape.
  2. Rebuild it in a fresh folder without copying, looking back only when stuck.
  3. Change one thing the tutorial did not do: a new dataset, a different tokenizer, a new sampling method, a different language.
  4. Write tests for the parts you can test (tokenizer round-trips, attention mask shapes, retrieval recall on a tiny dataset).
  5. 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:

  1. Autograd engine (micrograd) - you learn backpropagation.
  2. Character-level language model (makemore) - you learn training loops and sampling.
  3. BPE tokenizer - you learn how text becomes tokens.
  4. Transformer and GPT - you learn attention and the architecture behind LLMs.
  5. Fine-tuning and preference tuning - you learn how base models become assistants.
  6. Inference engine with a KV cache - you learn why serving LLMs is a memory problem.
  7. Vector search and RAG - you learn how to give models knowledge.
  8. Agent and MCP server - you learn how models act in the world.
  9. 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.


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.


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.

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.


Build Your Own Transformer

What you learn: scaled dot-product attention, multi-head attention, positional encodings, residual connections, layer normalization and masking.


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.


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.

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.


Build Your Own Fine-Tuning, LoRA and RLHF

What you learn: supervised fine-tuning, parameter-efficient fine-tuning, and preference tuning (DPO, RLHF).


Build Your Own Reasoning Model

What you learn: reinforcement learning with verifiable rewards, chain-of-thought and inference-time scaling.


Build Your Own LLM Inference Engine

What you learn: the KV cache, batching, paged memory, quantization, and why token generation is memory-bandwidth bound.


Build Your Own GPU Kernels

What you learn: how GPUs execute code, memory hierarchy, tiling, and why FlashAttention is fast.


Build Your Own Distributed Training

What you learn: data, tensor, pipeline and context parallelism, and ZeRO-style sharding.


Build Your Own Search Engine and Vector Database

What you learn: inverted indexes, BM25, approximate nearest neighbor search (HNSW, IVF), and product quantization.

Build spec for your own vector database:

  1. Brute-force cosine search over NumPy arrays (your correctness baseline).
  2. An HNSW index with M and ef parameters; measure recall@10 against the baseline.
  3. Persistence to disk with a simple append-only file and a rebuild on startup.
  4. Metadata filtering (for example where year > 2020).
  5. A tiny HTTP API with upsert, query and delete.
  6. 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.

Build spec for your own RAG system:

  1. Ingest Markdown and PDF files, split into chunks with overlap, keep source and position metadata.
  2. Embed chunks with an open embedding model and store them in your vector database from the previous section.
  3. Add BM25 keyword search and merge results (hybrid search), then rerank the top 20.
  4. Build a prompt that includes numbered sources and asks the model to cite them.
  5. Create an eval set of 50 questions with expected source documents; report retrieval recall@5 and answer correctness.
  6. 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.

Build spec for your own coding agent:

  1. 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.
  2. Tools: read_file, list_dir, search (ripgrep), edit_file (exact string replace), run (shell command with a timeout).
  3. Safety: run commands in a container or a throwaway directory, require confirmation for anything that deletes files or touches the network.
  4. Context management: truncate long tool outputs, summarize old turns when the context gets large.
  5. 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.

Build spec for your own MCP server (no SDK):

  1. Read JSON-RPC 2.0 messages line by line from stdin, write responses to stdout, log only to stderr.
  2. Handle initialize, then tools/list and tools/call.
  3. Expose two tools with JSON Schema input definitions, for example search_notes and add_note over a local folder of Markdown files.
  4. Validate inputs and return tool errors as results the model can read, not as crashes.
  5. 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.

Build spec for your own eval harness:

  1. A JSONL file of test cases: input, expected behavior, tags.
  2. Three scorer types: exact or regex match, a Python function, and an LLM judge with a written rubric.
  3. Run all cases concurrently with retries and a cache so re-runs are cheap.
  4. Output a table by tag and a diff against the previous run, so you see regressions.
  5. 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.

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


Build Your Own Vision Transformer and Vision-Language Model


Build Your Own Speech Recognizer

What you learn: audio features (log-mel spectrograms), CTC loss, encoder-decoder speech models, and decoding.

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


Build Your Own Game-Playing AI (AlphaZero and RL)


Build Your Own Interpretability Tools


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:

Share what you build in a pull request to the “Show your build” discussion, and help others learn from it.


Where to Go Next


Contributing

Pull requests are welcome. Please keep entries accurate:

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.