Skip to the content.

LLMs from Scratch, Mini: Build and Train a Small GPT in One PyTorch File

A compact, heavily commented GPT-style transformer language model built from scratch in a single PyTorch file (gpt.py, about 430 lines including comments), with a line-by-line explanation of how it works. It includes a tokenizer, causal self-attention, the transformer block, a training loop with warmup and cosine decay, checkpointing, and text generation with temperature and top-k sampling.

It is sized to train on a laptop: the tiny preset has about 0.8 million parameters and is meant for a CPU, and the small preset (about 10.8 million) is meant for an NVIDIA GPU or an Apple-silicon Mac. There is also a NumPy version of the core math (attention_numpy.py) with tests, so you can check your understanding without installing PyTorch. It is for developers and students who want to understand how large language models work by building a small one end to end.

Last reviewed: December 2026. Requires Python 3.10+ and PyTorch 2.1 or newer. Parameter counts below are computed from the architecture; training times depend heavily on hardware, so none are promised here.

Contents

What you will build

"To be or" ──► tokenizer ──► [20, 53, 1, 40, 43, 1, 53, 56]
                                  │
                     token embedding + position embedding
                                  │
                    ┌─────────────▼─────────────┐
                    │  Block × n_layer           │
                    │   x = x + Attention(LN(x)) │   tokens look at earlier tokens
                    │   x = x + MLP(LN(x))       │   each token thinks on its own
                    └─────────────┬─────────────┘
                              LayerNorm
                                  │
                       Linear to vocabulary size
                                  │
              scores for every possible next token at every position
                                  │
          training: cross-entropy loss   │   generation: sample, append, repeat

By the end you will have trained a model that writes text in the style of whatever you trained it on, and you will know what every line of the model does.

Quick start

  1. Install PyTorch for your platform using the selector at pytorch.org/get-started/locally. A CPU-only build is enough for the tiny preset.

  2. Get some text. Any UTF-8 file of at least a few hundred kilobytes works. A classic choice is the “tiny Shakespeare” file (about 1.1 MB, 65 distinct characters) from the char-rnn project:

git clone https://github.com/Ralpberry-Labs/llm-from-scratch-mini.git
cd llm-from-scratch-mini
curl -o input.txt https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt

Public-domain books from Project Gutenberg, your own notes, or a code base concatenated into one file also work. More text gives better results.

  1. Train and sample:
python gpt.py train --data input.txt --preset tiny          # CPU-friendly
python gpt.py sample --prompt "ROMEO:" --tokens 400

# With a GPU or Apple silicon:
python gpt.py train --data input.txt --preset small --batch-size 64 --max-iters 5000

The best checkpoint (lowest validation loss) is saved to out/ckpt.pt. Device selection is automatic: CUDA, then Apple’s MPS, then CPU. Override with --device cpu.

  1. Run the tests:
python -m unittest discover -s tests -v

The NumPy tests always run. The PyTorch tests run when PyTorch is installed and are skipped otherwise.

Presets and parameter counts

Preset Layers Heads Width (n_embd) Context (block_size) Dropout Parameters (char vocab of 65) Parameters (byte vocab of 256) Intended hardware
tiny 4 4 128 128 0.1 812,288 836,736 Laptop CPU
small 6 6 384 256 0.2 10,745,088 10,818,432 GPU or Apple silicon

How the count works (no biases, tied embeddings): each block has 12 × n_embd² weights (attention 4 × n_embd², MLP 8 × n_embd²) plus 2 × n_embd LayerNorm gains; add the final LayerNorm, the token embedding vocab × n_embd (shared with the output layer) and the position embedding block_size × n_embd. Check any configuration with:

python gpt.py info --preset small --vocab-size 65

For comparison, the smallest GPT-2 model has 12 layers, 12 heads, width 768, a 1,024-token context and about 124 million parameters, so small is roughly a tenth of its size.

How a GPT works in five sentences

  1. Text is split into tokens (here characters or bytes), and each token becomes a vector.
  2. Attention lets each token gather information from the tokens before it, weighted by how relevant they are.
  3. An MLP then transforms each token’s vector on its own; stacking attention and MLPs many times builds up useful features.
  4. A final layer turns each vector into a score for every possible next token, and training nudges the weights so the true next token gets a high score.
  5. To generate, the model repeatedly predicts the next token, samples one, appends it, and runs again.

That is the whole idea. Everything else is details that make it train well.

Walkthrough of gpt.py

The file is organized in five numbered sections. Open it next to this guide.

1. Configuration

GPTConfig holds every architectural choice:

Field Meaning Effect of increasing it
vocab_size Number of distinct tokens Set by the tokenizer; bigger vocabularies mean shorter sequences
block_size Longest context the model can see More memory (attention cost grows with the square of it)
n_layer Number of stacked blocks More capacity, slower
n_head Attention heads per block More, smaller “views” of the sequence; must divide n_embd
n_embd Width of every vector More capacity; parameters grow with its square
dropout Fraction of activations randomly zeroed while training Less overfitting on small datasets
bias Biases in Linear and LayerNorm layers Off by default; makes little difference
manual_attention Use the explicit attention formula instead of the fused kernel Slower; useful for learning and debugging

2. Tokenizers

Models work on integers, so text must be converted:

tok = CharTokenizer.from_text("hello world")
tok.encode("hello")         # e.g. [3, 2, 4, 4, 5]
tok.decode([3, 2, 4, 4, 5]) # "hello"

Production LLMs use subword tokenizers (for example byte-pair encoding), which split text into common chunks like " the" or "ing". Character tokenizers are simpler to understand and work well for small experiments.

3. Embeddings

x = self.tok_emb(idx) + self.pos_emb(pos)

tok_emb is a lookup table: row i is the learned vector for token i. Attention itself has no notion of order, so pos_emb adds a learned vector for each position (0, 1, 2, …). The sum is each token’s starting representation, shape (B, T, n_embd).

4. Causal self-attention

This is the heart of the transformer. For every token, the model computes three vectors with learned linear maps:

Then:

scores  = Q Kᵀ / sqrt(head_size)          how well each query matches each key  (T × T)
scores  = mask(scores)                     a token may not look at future tokens
weights = softmax(scores, along each row)  each row sums to 1
output  = weights V                        weighted average of values

Why divide by sqrt(head_size)? Dot products of random vectors grow with their length; scaling keeps scores in a range where softmax is not saturated, so gradients flow.

Why the causal mask? During training, the model predicts every position’s next token in parallel. Without the mask, position 5 could simply look at position 6 and copy the answer. The mask sets those scores to minus infinity, which softmax turns into zero weight.

Multiple heads: the n_embd channels are split into n_head groups, and each group runs attention independently, so different heads can track different relationships (the previous character, the start of the word, a matching quote). The heads’ outputs are concatenated and mixed by the output projection proj.

In code, one Linear computes Q, K and V for all heads at once, and reshapes do the splitting:

q, k, v = self.qkv(x).split(C, dim=2)
q = q.view(B, T, self.n_head, self.head_size).transpose(1, 2)   # (B, nh, T, hs)
...
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)     # fused kernel
y = y.transpose(1, 2).contiguous().view(B, T, C)                # heads side by side

F.scaled_dot_product_attention computes exactly the formula above in one optimized kernel (using FlashAttention-style algorithms where the hardware supports it). Set manual_attention=True to run the explicit version, which the tests check gives the same output.

5. The MLP

self.fc2(F.gelu(self.fc1(x)))     # n_embd -> 4*n_embd -> n_embd

Attention moves information between tokens; the MLP processes each token independently. Expanding to four times the width and back, with a GELU non-linearity in between, gives the model most of its parameters and much of its “knowledge”. GELU is a smooth version of ReLU.

6. The transformer block

x = x + self.attn(self.ln1(x))
x = x + self.mlp(self.ln2(x))

Two ideas make deep stacks trainable:

7. The output layer and the loss

logits = self.lm_head(self.ln_f(x))                       # (B, T, vocab_size)
loss = F.cross_entropy(logits.view(-1, V), targets.view(-1))

logits are unnormalized scores for every possible next token at every position. Cross-entropy is the negative log of the probability the model gave to the correct next token, averaged over all positions. A model that guesses uniformly scores ln(vocab_size): ln(65) ≈ 4.17 for tiny Shakespeare. Lower is better.

Weight tying: self.tok_emb.weight = self.lm_head.weight uses one matrix both to embed tokens and to score them at the output. It saves parameters and usually helps small models.

8. Initialization

Weights start as small random numbers (normal with standard deviation 0.02). The projections that write into the residual stream (proj and fc2) are scaled down further by 1 / sqrt(2 × n_layer), so the residual stream does not grow as more blocks add to it. With this setup the initial loss is close to ln(vocab_size), which the tests check.

9. The training loop

Each iteration:

  1. Sample a batch of random windows from the training data. The targets are the same windows shifted one token to the right, so every position has a next-token answer.
  2. Forward pass to get the loss.
  3. Backward pass (loss.backward()) to compute gradients.
  4. Clip gradients to a norm of 1.0, which prevents rare huge updates.
  5. Optimizer step with AdamW.

Details worth knowing:

Technique Where Why
AdamW with betas (0.9, 0.95) configure_optimizer Standard for transformers; adaptive step sizes
Weight decay only on matrices configure_optimizer Regularizes weights without shrinking LayerNorm gains or biases
Linear warmup, then cosine decay lr_at Avoids unstable early updates, then anneals for a better final loss
Train/validation split (90/10) train Validation loss tells you whether the model generalizes or memorizes
Keep the best checkpoint train Saves the model with the lowest validation loss, not the last one
bfloat16 autocast on supported CUDA GPUs train Faster, less memory, no loss scaling needed
Optional torch.compile --compile Can speed up training on CUDA after a compilation delay

10. Generating text

for _ in range(max_new_tokens):
    logits, _ = self(idx[:, -block_size:])        # look at the last block_size tokens
    logits = logits[:, -1, :] / temperature       # scores for the next token only
    # optionally keep only the top_k scores
    next_id = torch.multinomial(softmax(logits), 1)
    idx = torch.cat((idx, next_id), dim=1)

This is autoregressive generation: one token at a time, each conditioned on everything before it. This simple version recomputes the whole context every step; real inference engines cache keys and values from previous steps (a “KV cache”) to avoid that.

Tensor shapes cheat sheet

With batch size B, sequence length T, width C = n_embd, heads nh, head size hs = C / nh, vocabulary V:

Step Shape
Input token IDs idx (B, T)
Token + position embeddings (B, T, C)
qkv(x) (B, T, 3C)
q, k, v after the head split (B, nh, T, hs)
Attention scores q @ kᵀ (B, nh, T, T)
Attention output weights @ v (B, nh, T, hs)
After merging heads and proj (B, T, C)
MLP hidden layer (B, T, 4C)
Logits (B, T, V)
Loss scalar

The (T, T) attention matrix is why memory grows with the square of the context length in naive implementations.

The math without PyTorch

attention_numpy.py implements softmax, LayerNorm, GELU, a single attention head, vectorized multi-head attention and a full transformer block in under 100 lines of NumPy. Run it to see attention weights:

python attention_numpy.py

The tests in tests/test_attention_numpy.py prove properties worth understanding:

Test What it shows
test_attention_is_causal Changing future tokens never changes earlier outputs; weights above the diagonal are zero
test_first_token_attends_only_to_itself Position 0 has nothing earlier to look at
test_vectorized_multi_head_equals_loop_over_heads The reshape trick in gpt.py equals running heads one by one
test_block_keeps_shape_and_is_causal A full block preserves shape and causality
test_uniform_prediction_loss_is_log_vocab Why the initial loss is about ln(V)
test_softmax_rows_sum_to_one_and_stable Subtracting the max avoids overflow

Reading the training log

iter     0 | train ~4.17 | val ~4.17 | lr 1.00e-05 | 0s      (format of each line; values are illustrative)
iter   250 | train  ...  | val  ...  | lr  ...    | ...

The first line should show both losses near ln(vocab_size) (about 4.17 for 65 characters). If not, something is wrong with the data or initialization. Then watch the gap:

What you see Meaning What to do
Both losses falling together Learning well Keep going
Train falling, validation flat or rising Overfitting (memorizing) More data, more dropout, smaller model, stop earlier
Both flat and high Underfitting or a bug Larger model, higher learning rate, check the data
Loss becomes nan Unstable training Lower the learning rate, check for empty data, keep gradient clipping on

As a rough guide for character-level models, samples start to look like words once the loss drops well below 2, and show recognizable structure (names, line breaks, punctuation) as it approaches 1.5. Exact numbers depend on the dataset.

Sampling settings

Setting Flag Low value High value Good default
Temperature --temperature Safe, repetitive Creative, error-prone 0.7 to 0.9
Top-k --top-k Only the most likely tokens Wider choice 20 to 100
Length --tokens Short Long (keeps sliding the window) 300 to 1,000
Seed --seed     Change it for different samples

Temperature divides the logits before softmax: below 1 sharpens the distribution, above 1 flattens it. Top-k discards everything except the k highest-scoring tokens before sampling.

Experiments to try

Each of these teaches something specific. Change one thing at a time and compare validation loss.

  1. Remove the causal mask (set is_causal=False and remove the mask in the manual path). Training loss collapses toward zero while generation produces garbage. Why? The model learned to copy the answer from the future.
  2. Remove positional embeddings. The model can no longer tell order; watch the loss plateau higher.
  3. Remove residual connections in Block. Deeper models train much worse.
  4. Change n_head with fixed n_embd (1, 2, 4, 8). Fewer, larger heads versus more, smaller ones.
  5. Turn off weight tying. More parameters; does it help at this scale?
  6. Byte versus char tokenizer on text with accents or emoji.
  7. Context length: --block-size 32 versus 256. Short contexts cannot learn long-range structure like matching speaker names.
  8. No warmup (--warmup 1) with a high learning rate (--lr 3e-3). Observe instability.
  9. Dropout 0.0 on a small dataset: watch the train/validation gap widen.
  10. Replace learned position embeddings with sinusoidal ones from the original transformer paper, or try rotary embeddings (RoPE).

From this model to a real LLM

This file uses the same core architecture as GPT-2-style models. Modern open models keep the decoder-only transformer and change details:

Component This repo Common in recent open models
Tokenizer Characters or bytes Byte-level BPE or similar, vocabularies of 32k to 200k+
Position information Learned absolute embeddings Rotary position embeddings (RoPE)
Normalization LayerNorm, pre-norm RMSNorm, pre-norm
MLP GELU, 4× width Gated variants such as SwiGLU
Attention Standard multi-head Grouped-query attention to shrink the KV cache
Context length 128 to 256 tokens Thousands to hundreds of thousands of tokens
Training data About a megabyte Trillions of tokens
After pretraining None Instruction tuning and preference optimization
Inference Recompute everything each step KV cache, batching, quantization

Scale matters enormously, but the training objective, next-token prediction with cross-entropy, is the same one you implemented here.

Troubleshooting

TypeError: LayerNorm.__init__() got an unexpected keyword argument 'bias'. Your PyTorch is older than 2.1. Upgrade.

not enough text: need at least ~10x block_size characters. The validation split (10 percent) must be longer than one context window. Use more text or a smaller --block-size.

Out of memory on GPU. Lower --batch-size first, then --block-size, then switch to the tiny preset.

Training is slow on CPU. Use the tiny preset, reduce --max-iters and --eval-iters, or try --device mps on Apple silicon.

MPS errors or unsupported operations. PyTorch’s Apple backend improves with each release. Upgrade PyTorch, or fall back to --device cpu.

characters not in vocabulary when sampling. The character tokenizer only knows characters seen in training. Use a prompt made of those characters, or train with --tokenizer byte.

Generated text is repetitive. Raise --temperature slightly or increase --top-k; train longer.

FAQ

Can I really train a language model on a laptop? A small one, yes. It will learn spelling, word shapes and the style of its training text. It will not answer questions or follow instructions; that takes far more parameters, data and fine-tuning.

How is this different from using a pretrained model? Here you train every weight from random numbers, which is the best way to understand what happens inside. For practical applications, you would fine-tune a pretrained model instead.

Why characters instead of a real tokenizer? Fewer moving parts. You can see every token, and the vocabulary is tiny. Swapping in a subword tokenizer is a good next exercise.

Why is the initial loss about 4.17? With 65 equally likely characters, cross-entropy is ln(65) ≈ 4.17. A freshly initialized model is close to guessing uniformly.

What does “causal” mean here? Each position can only use information from itself and earlier positions, matching how text is generated left to right.

Why F.scaled_dot_product_attention instead of writing attention by hand? It is the same math, fused into a faster and more memory-efficient kernel. The manual version is kept in the file (manual_attention=True) for learning, and a test checks they agree.

Does this work on Windows? Yes, wherever PyTorch runs. --compile support varies by platform; leave it off if it errors.

How do I make it bigger? Increase n_layer and n_embd (keeping n_embd divisible by n_head), add more data, and train longer. Watch the train/validation gap.

Where to go next

Repository layout

llm-from-scratch-mini/
├── gpt.py                         # the whole model, training and sampling (PyTorch)
├── attention_numpy.py             # the core math in NumPy, no PyTorch needed
├── tests/
│   ├── test_attention_numpy.py    # 8 tests, always run
│   └── test_gpt.py                # 8 tests, run when PyTorch is installed
├── LICENSE
└── README.md

Contributing

Pull requests are welcome: clearer explanations, new experiments, a BPE tokenizer exercise, KV-cache generation, or RoPE as an option. Please keep gpt.py a single readable file, keep comments explaining why, add a test for any behaviour change, and run the test suite with PyTorch installed.

License

MIT.

If this helped transformers finally click for you, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.