Skip to content
AI from Scratch
EN

The internet is gone

A concrete plan for rebuilding an AI from scratch, with no network, no libraries and nothing to look up.

It is the scenario that gives the whole project its point. Let us take it seriously.


What you need to have

Essential

  1. A computer with Python. Any from the last 15 years.
  2. This repository. 3 MB of code. It fits in an email.
  3. Text. The more the better. This is the scarce resource.

What you do NOT need

  • Internet.
  • A GPU.
  • PyTorch, TensorFlow, JAX, transformers, tokenizers.
  • NumPy, if you will settle for tiny models (stages 00 and 03.1 are pure Python). With NumPy you go ~100 times faster.

Step 0 · Getting text

This is the hard problem, not the code. The code is 3 MB and you have it. Text cannot be reconstructed from memory.

In order of value:

SourceTypical volumeQuality
A downloaded Wikipedia dump (compressed)20 GBexcellent
Project Gutenberg15 GBexcellent
Your emails, documents, notes0.1-5 GBvery good, very personal
Source code on your disk1-10 GBgood for reasoning
Documentation of installed programs0.5 GBgood
Manuals, scanned PDFsvariesthey need OCR
Printed books, transcribed by hand~0.5 MB/daythe last resort

Advice from the future: save a Wikipedia dump and a copy of Gutenberg on an external disk today. They are ~35 GB and they are, literally, the difference between being able to do this and not.

Scale reference (from this project):

TextWhat you can trainResult
1 MBGPT of ~1 M parametersstructured language, no meaning
100 MBGPT of ~10 Mcoherent sentences, correct grammar
1 GBGPT of ~100 Mmeaningful paragraphs, some facts
10 GBGPT of ~500 Mgenuinely useful for specific tasks
100 GBGPT of ~5,000 Ma decent assistant, if you have months of compute

Step 1 · Tokenizer (1 hour)

python etapas/01_tokenizador/02_entrenar_bpe.py --vocab 8192

Decisions:

  • Vocabulary: 8,000 if you have <100 MB of text; 32,000 if you have GB. Too large with little data = tokens the model will never see.
  • Over bytes, always. That way no text is unrepresentable.
  • Train it on the SAME corpus you are going to use for the model. Otherwise you will have ghost tokens.
  • Save the JSON file and do not lose it. Without the tokenizer, the model weights are noise: the ids mean nothing without the table.

Step 2 · Deciding the model size (10 minutes of arithmetic)

Do not skip this. Doing this sum first saves weeks.

1. How many tokens do I have?           D
2. Target parameters (Chinchilla):      N ≈ D / 20
3. Choose layers and dimension:         N ≈ 12 · layers · dim²
4. Total FLOPs:                         6 · N · D
5. Time = FLOPs / (your throughput)

A real example. You have 500 MB of Spanish text:

D ≈ 500 MB / 3 bytes per token ≈ 170 million tokens
N ≈ 170M / 20 ≈ 8.5 million parameters
   -> 8 layers, dimension 300  (12·8·300² = 8.6 M)  ✓
FLOPs = 6 · 8.6e6 · 1.7e8 = 8.8e15
With NumPy on a decent CPU (~50 effective GFLOP/s):
   8.8e15 / 5e10 = 176,000 s ≈ 2 days

Two days of laptop for an 8.6 M model that writes coherent Spanish. Perfectly feasible.

Proportions that work (do not invent your own):

n_head   = dim / 64          (64 dimensions per head; it is the standard)
mlp      = 4 × dim
context  = 256 to 1024       (the cost grows with the square)
batch    = the largest that fits in memory

Step 3 · Training (hours or days)

python etapas/06_transformer/01_entrenar.py \
    --capas 8 --dim 300 --cabezas 5 --contexto 256 \
    --pasos 200000 --lote 16 --lr 6e-4

The recipe you should not change without a reason

AdamW, betas (0.9, 0.95), weight decay 0.1
warm-up: 2% of the steps
cosine decay down to 10% of the max lr
gradient clipping to norm 1.0

What to watch

SignalDiagnosisSolution
Initial loss ≠ log(V)broken init or data leakagecheck before going on
Loss → NaNexplosionlower lr, more warm-up, check clipping
Loss flat at 0lr too low or dead gradientraise lr, check init
Validation risingoverfittingstop, or get more data
Gradient norm growingit is about to explodelower the lr now
Abrupt stepslr too highlower it

Be disciplined about checkpoints

Save every N steps, including the optimizer state (Adam's m and v). If you save only the weights, Adam starts from scratch on resume and you can tell.


Step 4 · Turning it into an assistant (hours)

python etapas/09_finetuning_lora/01_sft_chat.py --todas

You need instruction data. With no internet, you write it yourself:

  • 200-1,000 (question, answer) pairs written by hand are already enough to start. It is a weekend of work.
  • Take advantage of structures that already have a question-answer shape: FAQs, your own emails, exams, manuals.
  • The three critical points: a consistent template, loss masking on the answer only, and an end token so it learns to shut up.

Step 5 · Using it

python etapas/11_servidor_chat/servidor.py     # http://localhost:8017
python etapas/11_servidor_chat/chat.py --local # or from the terminal

And above all: give it tools and RAG. A small model with access to your documents and a calculator is infinitely more useful than the same model on its own. [Stage 12.]


The critical decisions, summarized

If you take only one table away from this document, make it this one:

DecisionConsequence if you get it wrongReversible
Tokenizerthe whole model is tied to itNO
Vocabulary sizeyou waste parameters or lose efficiencyNO
Context windowa hard limit on what it can seeexpensive
Model size vs dataunder- or over-trainedretrain
Corpus qualityit determines everythingretrain
Learning rateit diverges or takes 10 times longerrestart
Validation splityou believe false resultsyes, but it hurts

The first two are irreversible. Think about them twice.


The five mistakes you are going to make

By frequency, with their symptoms:

  1. Forgetting zero_grad(). Gradients accumulate between steps. Training "almost" works and never quite converges.
  2. Data leakage between training and validation. Validation comes out suspiciously good. If your validation loss is lower than your training loss, there is almost certainly a leak.
  3. The tokenizer silently drops characters. You train on mutilated text and never notice. Always check that decode(encode(x)) == x. (This mistake is documented inside the project because I made it while building it: see the comment in etapas/12_rag_y_herramientas/03_herramientas.py.)
  4. Causal mask in the wrong place. The model sees the future: it trains beautifully and then generates rubbish. Unmistakable symptom: ridiculously low training loss.
  5. Wrong shift between x and y. y must be x shifted by one position. One index error here and the model learns to copy the input.

The order to rebuild it in

If you only have a week:

day 1   text + tokenizer + check reversibility
day 2   mininn + verify gradients (do not skip this!)
day 3   small GPT, train for an hour, check that it generates something
day 4   train the large model (leave it running)
day 5   write instruction data by hand
day 6   SFT + server
day 7   RAG over your documents + tools

And the most important piece of advice: get something working end to end on day one, however bad it is. A horrible model that generates text is infinitely more valuable than a perfect half-built one, because it gives you a feedback loop. Everything else is improving it.


Coda

The astonishing thing about all of this is not that it is difficult. It is that it is not.

The complete knowledge for building a language model fits in a 3 MB repository and can be understood in a week. What makes GPT-4 GPT-4 is not an architectural secret: it is scale, data and systems engineering. The ideas are public, they are in this project, and you have run them.

If everything vanished tomorrow, with this repository, a laptop and a disk with Wikipedia on it, you would have a working language model in a week.

That, in the end, is what understanding something means.


Next: 07-glosario.md