All projects

A language model trained from scratch, running in the browser

Tiny GPT

A 1.8 million parameter transformer that writes Polish verse one character at a time. I trained it on Pan Tadeusz, and every forward pass runs in the browser, in code written without any ML library.

Role
Idea, training, code and measurements.
Stack
  • Python
  • PyTorch
  • TypeScript
  • React 19
  • Vite
  • Web Worker
  • Vitest
Live
tiny-gpt-oktawian.vercel.appgithub.com/mauupa0/tiny-gpt-browser
Tiny GPT website

Problem

I wanted to understand a transformer from the inside instead of just calling an API. The test of that understanding was rewriting the whole forward pass by hand and proving it computes the same thing as PyTorch.

What I built

  • Training in PyTorch on CPU: 4 layers, 4 attention heads, a 128-character context and a 71-character vocabulary.
  • Inference written by hand in TypeScript: embeddings, LayerNorm, causal attention with a KV cache, a GELU MLP, temperature and top-k sampling.
  • The whole model runs in a Web Worker, and the fp16 weights take 3.6 MB.
  • Every written letter can be opened up: the attention of all 16 heads, the 768 MLP neurons, the logit lens after every step and the exact contribution of every head to the chosen letter.
  • Break it mode: two classic bugs and a head silencer, switched live next to the intact model, which keeps writing.

By the numbers

parameters, 37.5 min of training on CPU
1.8M
max logit difference against PyTorch
7e-6
letters per second in the browser, median of 7 runs
361
Vitest tests and browser checks at 1440 and 360 px
56 + 64

Decisions that mattered

Parity with PyTorch as the test

The test runs four fixed inputs through the TypeScript code character by character and compares the logits at every position, plus all attention maps, with PyTorch. The difference is 5.7e-6 for fp32 weights and 6.7e-6 for fp16, against a 1e-3 limit.

A test that can fail

Two negative controls break the model on purpose: they drop the 1/√d scaling or let a query read one character past the causal mask. Both exceed the limit, so the test really guards the math.

No ML library in the browser

No ONNX and no TensorFlow.js: just arrays of numbers and loops. That keeps the page light and lets every step of the model be shown on screen.