Building GPT From Scratch: Training and Text Generation in 200 Lines

    This article walks through a minimal, roughly 200-line GPT implementation to explain the core mechanics of a decoder-only language model: tokenization, the transformer decoder skeleton, the training loop, and autoregressive sampling. It also outlines a practical path from the minimal闭环 to production engineering, and four general principles for constraining AI coding assistants. Readers will gain a verifiable mental model of how tensors flow, how loss backpropagates, and how probabilities are sampled.

    1. Why a Minimal Implementation Is Worth Studying

    The architecture of a large model is not mysterious; what is genuinely complex is engineering scale and data quality. Building a trainable language model that can generate text in about 200 lines of code shifts attention away from framework details and back to first principles: how tensors flow, how loss backpropagates, and how probabilities are sampled. For beginners, it is the shortest path; for experienced developers, it is a verifiable mental model.

    The goal of the minimal version is not to replicate the general capabilities of a large model, but to get the smallest end-to-end loop of a Transformer decoder running: read a corpus, split it into tokens, predict the next token, backpropagate to update parameters, and loop to generate. Once you understand this loop, scaling up to more parameters, longer context, and distributed training becomes much less disorienting.

    2. Data and Tokenization: It All Starts With Tokens

    Training corpora usually come from plain text. The first step is to build a character-level or subword-level vocabulary that maps text to a sequence of integers. A character-level implementation is the most intuitive and requires little code, but produces longer sequences; subword tokenization significantly compresses sequence length and is the common choice in production systems.

    1. # Minimal character-level tokenization example
    2. text = open("input.txt", encoding="utf-8").read()
    3. chars = sorted(set(text))
    4. stoi = {c: i for i, c in enumerate(chars)}
    5. itos = {i: c for c, i in stoi.items()}
    6. data = [stoi[c] for c in text]

    Data splits should follow time- or source-based isolation to avoid heavy overlap between the training and validation sets, which inflates metrics. Corpus cleaning (denoising, deduplication, normalization) often has a larger impact on final results than fine-tuning the model architecture.

    3. Model Architecture: The Minimal Decoder Skeleton

    There are only four core components: token embeddings, positional encoding, multi-head self-attention, and a feed-forward network. Self-attention aggregates context at each position by relevance; the causal mask ensures that when predicting the t-th token, only the first t-1 positions are visible; the multi-head mechanism captures different relationships in different subspaces.

    1. # Core logic of single-head causal self-attention
    2. q = x @ Wq; k = x @ Wk; v = x @ Wv
    3. att = (q @ k.transpose(-2, -1)) / (k.size(-1) ** 0.5)
    4. att = att.masked_fill(tril_mask == 0, float("-inf"))
    5. att = att.softmax(dim=-1)
    6. out = att @ v

    In practice, placing LayerNorm before each sublayer (pre-normalization) is better for deep stability; residual connections preserve the gradient path; the feed-forward layer usually expands the dimension and then reduces it, providing nonlinear transformation capacity. The number of layers, heads, and embedding dimensions determine capacity, as well as memory and compute cost.

    4. The Training Loop: Loss, Backprop, and Optimization

    The training objective is to maximize the likelihood of the training corpus, which is equivalent to minimizing cross-entropy. Shift the input sequence one position to the right to form the targets; the model outputs logits with a dimension equal to the vocabulary size, cross-entropy produces a scalar loss, and backpropagation updates the parameters.

    1. logits = model(idx)
    2. loss = F.cross_entropy(logits.view(-1, vocab_size), targets.view(-1))
    3. loss.backward()
    4. optimizer.step(); optimizer.zero_grad()

    Practical points include: gradient clipping to suppress explosions; learning-rate warmup and cosine decay for stability; mixed precision to reduce memory; and gradient accumulation to simulate larger batches. Validation loss is used for early stopping and hyperparameter selection, avoiding a model that only “looks good” on the training set.

    5. Generation: Autoregressive Sampling

    Generation is the reverse of training: given a context, predict the probability distribution of the next token, sample it, append it back to the context, and repeat. Temperature adjusts the sharpness of the distribution; top-k and top-p truncate the long tail; repetition penalties mitigate degeneration.

    1. for _ in range(max_new_tokens):
    2. logits = model(idx[:, -block_size:])[:, -1, :]
    3. probs = (logits / temperature).softmax(dim=-1)
    4. idx_next = torch.multinomial(probs, num_samples=1)
    5. idx = torch.cat([idx, idx_next], dim=1)

    There is no universally optimal sampling strategy; it must be balanced per task: deterministic tasks favor low temperature and greedy decoding, while creative tasks favor high temperature and nucleus sampling. Fixing a random seed makes results reproducible and eases debugging.

    6. Constraining an AI Coding Assistant: Four General Principles

    The minimal implementation also highlights three common problems with AI coding assistants: wrong assumptions, over-engineering, and incidental changes. Four rules can constrain their behavior, much like giving a new team member a code of conduct.

    1. Think before coding: surface confusion and tradeoffs, ask when unsure, and do not hide assumptions.
    2. Keep it simple: prefer the smallest working solution and avoid irrelevant abstractions and showmanship.
    3. Make minimal changes: only change what was requested; do not rename things or delete comments along the way.
    4. Close the verification loop: provide how to run and test, and state the edge cases that are not covered.

    In practice, this can be a specification file at the repository root that tools read automatically before each session; the rules can also be written into task templates and review checklists. Combined with general capabilities such as cloud development environments, containerized execution, and log monitoring, you can chain “generate-run-verify” into a loop and significantly reduce rework.

    7. From the Minimal Loop to Production Engineering

    Once the 200-line version runs, the scaling path is clear: switch to subword tokenization, increase model and batch size, introduce distributed data parallelism, add checkpoints and resumable training, and wire in monitoring, alerting, and experiment tracking. Using cloud container platforms and object storage to manage data and artifacts can standardize and make training tasks reproducible. Cloud providers such as Baidu AI Cloud typically offer general-purpose capabilities like containers, storage, logging, and monitoring, which can serve as a reference direction for production engineering.

    In short, the value of a minimal GPT lies not in being “small” but in being “clear.” Master the training-and-generation loop first, then layer on data, compute, and engineering discipline—that is the right path to reliable large-model applications.