Building a Mini GPT from Scratch: Training and Text Generation Explained
This article walks through building a minimal, trainable character-level GPT in roughly 200 lines of code. It covers how to turn raw text into integer sequences, the five core model components and their tensor shapes, the four signals that indicate healthy training, and the autoregressive sampling loop with its temperature, top-k, and top-p controls. It also outlines what a toy implementation still needs before production use and how to constrain AI coding assistants when reproducing this kind of code. Readers will gain a clear mental model of how a small language model fits together and where its practical limits lie.
Why a Minimal Implementation Is Worth Studying Closely
A widely shared result in deep learning engineering is that a trainable, text-generating character-level language model can run in about 200 lines of code. The goal is not to replace industrial systems. Instead, it strips a Transformer-style model down to its essential parts, removing the engineering layers such as distributed training, mixed precision, and operator fusion, and keeping only the smallest loop that runs and converges.
This minimal loop is valuable for three reasons. First, it turns abstract concepts into observable tensor flows, so you can verify your understanding line by line as shapes change. Second, it exposes the skeleton shared by all large models: embeddings, positional encoding, multi-head self-attention, the feed-forward network, residuals and normalization, and the output projection. Third, it provides a reliable debugging path. When large-scale training fails to converge, being able to reproduce and isolate the problem on this mini version is a key measure of engineering skill.
Note that a minimal implementation typically runs on pure CPU or a single GPU, with a modest plain-text corpus and a model size ranging from hundreds of thousands to a few million parameters. Its goal is not high-quality text. It is to make the training loss decrease steadily and to move generation from random characters toward character sequences that look like text.
Data: Turning Text into Integer Sequences the Model Can Consume
The first step is building the vocabulary. The character-level approach maps every unique character in the corpus to an integer, so the vocabulary size equals the number of distinct characters, usually a few dozen to a few hundred. Compared with subword tokenization, a character-level implementation needs no tokenizer training and the least code, at the cost of longer sequences and slower convergence.
The second step is slicing training samples. Set a context length (for example, 64 or 128) and slide a window over the long text with a fixed stride. Each window produces both input and target at once, where the target is the input shifted one position to the right. Example code:
# Character-level vocabularychars = sorted(set(text))stoi = {c: i for i, c in enumerate(chars)}itos = {i: c for c, i in stoi.items()}def get_batch(data, block_size, batch_size):ix = torch.randint(len(data) - block_size, (batch_size,))x = torch.stack([data[i:i+block_size] for i in ix])y = torch.stack([data[i+1:i+block_size+1] for i in ix])return x, y # both have shape (batch_size, block_size)
The intuition to build here is that language modeling predicts character t+1 given the previous t characters. The input sequence and the label sequence are therefore naturally offset by one position, they have identical shapes, and you can compute cross-entropy position by position.
Model: Five Components and Their Shape Contracts
Token and position embeddings. Two learnable matrices map character IDs and position IDs into vectors of the same dimension, which are added together before entering the main body. The position embedding is learnable rather than a sinusoidal function, a common trade-off in minimal implementations.
Multi-head self-attention. The core is three linear projections that produce Q, K, and V, a scaled dot product that yields attention weights, and a weighted sum over V. The critical piece is the causal mask: setting the upper triangle to negative infinity ensures position t can only see positions 0 through t. Otherwise the model peeks at the answer during training and cannot generate autoregressively at all.
w = q @ k.transpose(-2, -1) * k.shape[-1] ** -0.5w = w.masked_fill(tril[:T, :T] == 0, float('-inf'))w = F.softmax(w, dim=-1)out = w @ v
Feed-forward network. Two linear transformations with a nonlinear activation in between, where the intermediate dimension is usually four times the embedding dimension. It performs feature transformation along the channel direction.
Residuals and layer normalization. Every sub-layer is wrapped in an add-residual-then-normalize structure, which is the prerequisite for training deep networks. Modern implementations often place normalization before the sub-layer for more stable training.
Output projection. This maps the hidden state at each position to logits over the vocabulary, changing the shape from (batch, sequence, embedding dim) to (batch, sequence, vocab size). During training, flatten the first two dimensions and compute cross-entropy against the flattened labels.
The whole forward pass can be summarized as one shape flow: (B, T) → embeddings → (B, T, C) → alternating attention and feed-forward → (B, T, C) → projection → (B, T, V).
Training Loop: Four Signals of a Healthy Loss Curve
The training body is a standard fetch-batch, forward, compute-loss, backward, update loop, and noticeable results usually appear within a few thousand to tens of thousands of steps. Watch four signals to judge whether training is healthy.
First, whether the loss decreases and then plateaus; if it oscillates or diverges from the start, check the learning rate and normalization placement first. Second, whether the gradient norm stays stable; spikes often indicate numerical instability. Third, whether the learning rate schedule is reasonable, commonly a linear warmup followed by cosine decay. Fourth, whether overfitting occurs, shown by training loss continuing to fall while validation loss rises, in which case reduce the model or add data.
An often-overlooked detail: a character-level model’s perplexity looks high, but after a few thousand steps the generation quality shifts from completely random to showing word-frequency patterns. This is a practical sign that the pipeline is working end to end.
Generation: Autoregressive Sampling and Three Tunable Knobs
The generation stage has no labels. The model appends its previous output back to the input and advances in a loop. Note that no loss is needed here; you only take the logits at the last position.
for _ in range(max_new_tokens):idx_cond = idx[:, -block_size:] # keep only the recent contextlogits, _ = model(idx_cond)logits = logits[:, -1, :] / temperature # temperatureprobs = F.softmax(logits, dim=-1)idx_next = torch.multinomial(probs, num_samples=1)idx = torch.cat((idx, idx_next), dim=1)
Three knobs determine the output style. Temperature controls how sharp the distribution is: below 1 is more conservative and repetitive, above 1 is more divergent with more noise. Top-k samples only from the k highest-probability candidates, suppressing long-tail garbage. Top-p (nucleus sampling) truncates by cumulative probability, which is more adaptive than a fixed k. In practice, temperature is usually set between 0.7 and 0.9 and paired with top-p.
Also understand a structural limit: the context window is fixed, so once it is exceeded the leftmost content must be truncated. The model therefore has no true long-range memory, and generation is sequential and cannot be parallelized, so throughput is bounded by one forward pass per step.
From Toy to Usable: What Production Requires
For a minimal version to reach production, it needs several capabilities at a minimum, and these map to general cloud component categories. Large corpora and checkpoints are suited to object storage; training jobs are suited to elastic scheduling on a container platform; multi-node, multi-GPU setups need collective communication and mixed precision; experiment tracking and metric visualization rely on monitoring, alerting, and logging services; and data cleaning and deduplication usually require a separate data processing pipeline. In addition, industrial solutions replace the character-level vocabulary with byte-pair-encoding-style tokenization, replace learnable position embeddings with rotary position encoding, and introduce grouped-query attention to reduce inference memory.
Extension: Constraining AI Coding Assistants with General Rules
When reproducing this kind of code with AI coding tools, three typical deviations are commonly observed: the model invents requirements that were never stated, expands a five-line solution into fifty lines of over-engineering, and changes B while modifying A even though B was not requested. Four transferable constraints help. Clarify before acting, surfacing uncertainties explicitly instead of hiding assumptions. Prefer the simplest solution and avoid unnecessary abstractions. Strictly limit the scope of changes, leaving unrelated code and comments untouched. After finishing, always provide a way to verify, such as running tests or a minimal reproduction script. Writing these rules into a configuration file at the project root, so the tool reads them automatically before each conversation turn, is the lowest-cost and most direct approach.
The value of mastering the mini implementation ultimately lies not in those 200 lines, but in being able to make accurate judgments about the shapes, loss behavior, and sampling behavior of any large model system. That is the dividing line between being able to use a model and being able to tune one.
