Skip to content
AI from Scratch
EN

AI from Scratch

Build a complete language model, end to end, with no internet and no AI libraries.

This project answers one concrete question: when you type something into a chat box and it answers you, what exactly just happened? Not in outline: down to the last detail, with the code in front of you, running on your machine.

By the end you will have built with your own hands:

  • An automatic differentiation engine (your own PyTorch, 900 lines of NumPy).
  • A BPE tokenizer, the same algorithm as GPT-4 and LLaMA.
  • A complete GPT transformer, trained by you, that generates Spanish.
  • Proof that this GPT is identical, number for number, to a PyTorch one.
  • An inference engine with a KV cache, 17 times faster than the naive one.
  • Quantization to 8, 4, 3 and 2 bits.
  • Instruction fine-tuning and LoRA.
  • Preference alignment with DPO.
  • An HTTP server with streaming and a chat that works.
  • A RAG system and an agent that uses tools.

All of it commented, all of it verified, all of it running on a laptop with no connection.

A note on languages. This website is available in English and Spanish. The code itself, its comments and the training corpus are in Spanish: that is the original project, and translating the source would mean the listings on this site no longer matched the files you run. So the model you train generates Spanish, and the source listings you will read are commented in Spanish. Everything explaining them is in English.


Read this before you start

The corpus in this project is SYNTHETIC. It is generated by datos/generar_corpus.py from templates, and that has a consequence worth being clear about from day one:

The quality figures you are going to see are artificially good.

this projectreal human text
perplexity of the large GPT1.273-5
distinct words~1,200tens of thousands
sentence structuresa few dozenunlimited

The corpus is predictable on purpose: that way everything trains in minutes, it is 100% reproducible and there is nothing to download. The code is correct and the comparisons between stages are valid — what is not realistic is the absolute value.

When you want to see real figures, put books into datos/crudo/ and run python datos/generar_corpus.py --incluir-crudo. You will see a worse model... and you will learn more, because that is when the real problems show up.


Getting started

cd ia-desde-cero
python3 -m venv .venv
.venv/bin/pip install numpy

NumPy is the only required dependency.

PyTorch is optional and exactly one script in the whole project uses it (etapas/06_transformer/04_el_mismo_gpt_en_pytorch.py), which is good for two things: proving that your NumPy GPT produces exactly the same numbers as one written in PyTorch, and letting you train much larger models on the GPU. If you do not install it, you lose nothing essential:

.venv/bin/pip install torch    # optional
.venv/bin/python comprobar_entorno.py

And from there, the full route:

.venv/bin/python datos/generar_corpus.py
.venv/bin/python etapas/00_calentamiento/01_que_es_aprender.py

Every script opens with a long explanation, runs on its own and finishes by telling you which one comes next.

Shortcut: .venv/bin/python ruta_completa.py runs the 14 stages in order, training every model. It takes 15 minutes and finishes by saying 30/30 correctos. With --rapido, about 6.


The map

StageWhat you buildWhat you understandTime
00 Warm-upRegression and XOR in pure PythonWhat learning is, what a gradient is, why depth is needed< 1 s
01 TokenizerComplete BPE from scratchHow text gets into the machine, and why AI cannot count letters2 s
02 BigramsA language model by countingWhat a language model IS; why counting does not scale4 s
03 AutogradGradient engine (scalar and tensor)Backpropagation, automated and verified (34/34)1 s
04 MLPEmbeddings + dense networkHow the curse of dimensionality gets broken4 s
05 AttentionAttention derived step by stepThe mechanism that changed everything, and why 1/√dk< 1 s
06 TransformerA GPT trained by youThe complete architecture, its parameters and its cost9 min
06.4 PyTorch bridgeThe same model in PyTorchThat yours is a real transformer, and how to train on a GPU1 min
07 TrainingOptimizers, init, regularizationWhy training runs break and how to avoid it2 min
08 InferenceSampling, KV cache, quantizationHow each word is generated and how it fits on your laptop13 s
09 Fine-tuningSFT with masking + LoRAHow a text continuer becomes an assistant2 min
10 AlignmentDPO from scratchHow you teach it which answer is better38 s
11 ServerHTTP + SSE + chat clientThe complete journey of your message—
12 RAG and toolsSearch, RAG, agentHow you give it new data and the ability to act2 min
13 EvaluationA long-dependency testWhy a single number is never enough to compare models1 s

Times are measured, not estimated, on an Apple M4 Pro with NumPy on CPU. The full route (ruta_completa.py) takes 15.4 minutes and runs 30 steps; the 9 minutes of the GPT are almost the whole total.


Web version

The whole project is also published as a static website: the documents, the README of each stage and the complete source code, with search, diagrams and interactive demos.

.venv/bin/python web/construir_web.py           # generates web/sitio/
.venv/bin/python web/construir_web.py --servir  # and opens it locally

To publish it, copy everything inside web/sitio/ to the public folder of your hosting (public_html, www, htdocs…). They are static files: no application server, no database, no build step.

It includes 14 diagrams, 10 formulas translated into plain language and 4 demos that run on real data from the models you trained yourself:

DemoWhat it does
Tokenizeryou type text and see how it splits into tokens, with your BPE
Temperatureyou move the slider and watch the probability distribution change
Attentionthe real attention maps from your GPT, layer by layer and head by head
Learning rateyou move the slider and watch descent converge or explode

If you retrain the models and regenerate the site, the demos will show your new results.

Two languages

The site is published in English and Spanish. In the top bar there is a selector with a globe and the flag of the current language; switching leaves you on the same page, not on the home page.

When you arrive at the root, it decides on its own:

  1. If you ever chose a language by hand, that choice wins.
  2. If not, the device language.
  3. If the device speaks neither, English.

The raw project — docs/, etapas/, curso/ and all the code — is in Spanish and is not touched. The translations live inside web/, as one more asset of the site:

docs/03-matematicas-minimas.md   ->  web/textos/en/docs/03-matematicas-minimas.md

The filenames are kept even though they are Spanish: that way the mapping is mechanical and the URLs of the two sites are identical apart from the language prefix, which is exactly what lets you switch without getting lost.

The figures are translated too. The 14 diagrams, the mind map and the 10 formulas are drawn once in Spanish and translated label by label (web/traduccion_figuras.py), never by substring, so a short word cannot slip inside another one. If you add a figure and forget to translate it, the generator tells you at build time instead of publishing it half done.

To add another language: copy a block in web/idiomas.py, translate it, add its table in web/traduccion_figuras.py and create web/textos/<code>/. The generator walks IDIOMAS on its own.


Audiobook mode

The site has a player at the top that reads the topics out loud: 35 chapters, around 2.9 hours. It is meant for listening with headphones, phone in your pocket or on the bedside table.

.venv/bin/python web/generar_audio.py    # creates web/sitio/audio/ (~1.5 min, 43 MB)
.venv/bin/python web/construir_web.py    # and the player appears

It uses the system voices (macOS, the say command) — Mónica for Spanish and Daniel for English — at 175 words per minute, and converts to .m4a at 32 kbit/s with afconvert. No internet and no paid service needed: the voices are already on the computer.

The text is not read as-is. web/audio.py prepares it first: it skips code blocks (announcing how many there are), summarizes tables, and turns symbols into something pronounceable — √dk is read "square root of d k", 10²⁴ is read "ten to the twenty-fourth", 3e-4 is read "three times ten to the minus four". Without that, the voice spells out gibberish.

What the player does:

Picks up where you left offchapter, minute and speed, even if you close the browser
Locked screenplay/pause and chapter changes from your AirPods or the lock screen
Sleep timer15, 30, 45, 60 minutes or "1 chapter"; fades the volume before stopping
Speedfrom 0.8× to 2×
Chains chapterswhen one ends it moves on to the next, hands free
Gets out of the waythe ✕ hides it; the 🎧 button at the bottom right brings it back

To publish it you also need to upload web/sitio/audio/ (43 MB). If you do not, nothing breaks: the player simply does not appear and the rest of the site works the same.

Two warnings for iPhone: the browser will not start playing on its own, you have to press play once (that is iOS, not the code); and the sleep timer cannot fade the volume because Safari does not allow changing it, so there it simply stops.


The documents

The docs/ folder holds the part that does not fit in code comments:

  • 00-mapa.md — the complete route and what decision gets made at each point.
  • 01-del-teclado-al-token.md — the exact trace of a message, millisecond by millisecond.
  • 02-como-nace-un-modelo.md — the real life cycle: data, compute, money, team and calendar.
  • 03-matematicas-minimas.md — exactly the maths you need. Not one bit more.
  • 04-hardware-y-escala.md — GPUs, memory, scaling laws, and what changes as you grow.
  • 05-fallos-y-limites.md — hallucinations, bias, contamination: why they really happen.
  • 06-plan-apocalipsis.md — the internet is gone: a concrete plan to rebuild all of it.
  • 07-glosario.md — Spanish ↔ English, with the definition that actually matters.
  • 08-mas-alla.md — RoPE, mixture of experts, reasoning models, Mamba: what exists today and is not implemented here, and where you would touch the code to add it.
  • 09-historia.md — how all of this was invented: from 1943 to 2025, with the two winters, the ideas ignored for decades and who was right too early.
  • 10-lo-que-no-cubre.md — where what you learn here runs out. The limits, stated plainly.
  • 11-otras-modalidades.md — image, diffusion, audio, video and multimodal: why the distance is shorter than it looks.
  • 12-entrenamiento-distribuido.md — ZeRO, tensor, pipeline: when the model does not fit on one GPU.
  • 13-agentes-y-multiagente.md — what an agent really is, the patterns, the frameworks, and the six reasons NOT to use one.
  • 14-roles-profesionales.md — AI Engineer, AI Developer, ML Engineer and the rest: what each one does, what they need to know and which part of this project prepares them.
  • 15-herramientas.md — Ollama, LM Studio, Hugging Face, vLLM, LoRA, vector databases… with tables, icons and a mind map of what to use when.
  • 16-terminos-actuales.md — today's vocabulary: agentic RAG, MCP, RLVR, GQA, distillation, contamination… and what gets said out there that is not quite right.

How the code is organized

ia-desde-cero/
├── mininn/              your "PyTorch": autograd, layers, optimizers
│   ├── tensor.py        the gradient engine  ← the most important file
│   ├── nn.py            Linear, Embedding, LayerNorm, Dropout...
│   └── optim.py         SGD, Adam, AdamW, clipping, lr schedules
├── etapas/              14 folders, in order, each with its scripts
├── datos/               local corpus generator (no downloads)
├── docs/                the theory
├── pesos/               the models you train along the way
├── ruta.py              import helper shared between stages
└── resultados.py        shared metrics registry across stages

Project rule: no number is written by hand. Every comparison table reads measured results (see resultados.py and the reasoning that file gives). If a figure is missing, it says it is missing.


What this project does differently

1. Everything is measured, nothing is asserted. When a text says "vowels cluster in embedding space", the script checks it against chance — and in stage 04 it turns out they do not cluster in the input matrix (65.7% against 64.7% for chance) and they do in the output one (81.0%). That kind of awkward result is reported exactly as it is, with an explanation of why.

2. The failures are in here. Several scripts document real bugs that showed up while building this: a tokenizer that silently ate letters, a loss that trained the model to do precisely the thing we wanted to delegate. They are explained where they happened, because diagnosing is half the craft.

3. There is external proof that this is real. Stage 06.4 loads the weights you trained with NumPy into a GPT written in PyTorch and compares the logits: relative difference 1.0e-06 and the same predicted token in all 256 positions. It is not that it resembles a transformer: the weights are interchangeable with a production library's.

4. The honest comparison. In stage 06 the GPT and the MLP come out almost tied on mean loss. It is not hidden: it is used to teach that an aggregate number is no good for comparing models, and stage 13 splits them 100% against 50% with a test that isolates one specific capability.


What you will NOT find here

There is a whole document devoted to this, because knowing the limits of what you know is part of knowing it: 10-lo-que-no-cubre.md.

In short:

  • Other modalities (vision, diffusion, audio). This is about language — although 11-otras-modalidades.md shows you how close everything else is.
  • Real distributed training on multiple GPUs: it is explained in depth in 12-entrenamiento-distribuido.md, but not implemented. That would need the hardware.
  • Classical reinforcement learning, deep theory, and the terabyte-scale data pipeline.
  • A good model. Ours has 810,000 parameters (4.2 M if you do stage 06.4) and learns from a synthetic corpus. It is a correct model, not a useful one. The difference between the two is, precisely, scale — and that is the lesson.

License

Copyright © 2026 S. Cuervo Martín. All rights reserved. See LICENCIA.md.

What is licensed is this material: these texts, this code and this teaching sequence. The concepts are not licensed — backpropagation, attention, BPE, LoRA and DPO are public ideas belonging to their authors, and what you learn here is yours to use wherever you like, including at work.


Intellectual credits

This project is built on other people's ideas, and it is worth knowing whose:

  • Rumelhart, Hinton and Williams (1986) — backpropagation.
  • Bengio et al. (2003) — neural language models with embeddings.
  • Sennrich et al. (2016) — BPE applied to subwords.
  • Vaswani et al. (2017) — Attention Is All You Need.
  • Radford et al. (2018-2020) — the GPT family and generative pre-training.
  • Hoffmann et al. (2022) — Chinchilla and the scaling laws.
  • Hu et al. (2021) — LoRA.
  • Rafailov et al. (2023) — DPO.
  • Andrej Karpathy — for showing that all of this can be taught with readable code, and for the micrograd/nanoGPT tradition this belongs to.