Building a GPT from Scratch: A 200-Line Training and Generation Walkthrough

    This article walks through a minimal GPT implementation of roughly 200 lines of code, explaining why such a compact version is valuable for learning and as a baseline for further development. It covers the full pipeline in seven stages: corpus loading and cleaning, tokenization and encoding, batch construction, model definition, the training loop, evaluation and saving, and autoregressive generation. Core components are broken down with code, including character-level vocabularies, sliding-window batches, token and position embeddings, causal self-attention, feed-forward layers, cross-entropy loss, temperature-based sampling, and context truncation. The article also highlights common misconceptions and offers engineering recommendations for moving from a teaching implementation toward a scalable architecture.

    1. Why a Minimal Implementation Is Worth Reading Repeatedly

    In deep learning engineering, a common mistake is treating “it runs” as the same as “I understand it.” Once frameworks wrap up automatic differentiation, operator scheduling, mixed precision, and distributed communication, a language model can indeed be assembled in a few dozen lines of code. Yet developers often cannot explain why tensor shapes change the way they do, why the loss goes down, or why generation drifts off track.

    The value of a minimal implementation lies precisely in what cannot be omitted. It has no heavy engineering wrappers, and it places the core elements—attention, positional encoding, residual connections, normalization, cross-entropy, and autoregressive sampling—side by side in the most direct way possible. The total code stays around 200 lines, which is just enough to cover the closed loop of a trainable, generative language model. That makes it well suited as a teaching sample and as a baseline for secondary development.

    One thing should be stated up front: the goal of this kind of implementation is to explain the principles, not to chase training results. It is usually trained on a small corpus with a limited number of parameters, and the generated output is mainly used to verify that the pipeline is correct rather than to produce usable text.

    2. The Overall Flow: A Closed Loop in Seven Stages

    Broken apart, the minimal implementation can be summarized in seven stages. The first six belong to the training side, and the last one belongs to inference.

    1. Corpus loading and cleaning: organize the raw text into a single string or a sequence of lines, and remove noise.
    2. Tokenization and encoding: build a character-level or subword-level vocabulary, and map the text to a sequence of integers.
    3. Batch construction: cut fixed-length segments from the long sequence and construct inputs and targets.
    4. Model definition: embedding layers, positional encoding, multi-head self-attention, feed-forward network, and output projection.
    5. Training loop: forward pass, loss computation, backpropagation, and parameter updates.
    6. Evaluation and saving: watch the loss curve and save parameters for reproducibility.
    7. Autoregressive generation: start from a prompt, sample token by token, and concatenate the output.

    Each stage is expanded below, along with an explanation of why it must be written this way.

    3. Data and Tokenization: Everything Starts with Integer Sequences

    A minimal implementation usually adopts a character-level vocabulary because it needs no extra dependencies and its logic is clear at a glance. The construction is straightforward: iterate over the corpus, collect every character that appears, deduplicate and sort them, build a character-to-integer mapping, and keep the reverse mapping for decoding.

    1. chars = sorted(set(text))
    2. stoi = {c: i for i, c in enumerate(chars)}
    3. itos = {i: c for c, i in stoi.items()}
    4. data = [stoi[c] for c in text]

    One engineering fact must be emphasized here: a character-level vocabulary performs stably when the corpus is small, but in real scenarios it quickly exposes its weaknesses. A vocabulary that grows too large bloats the embedding matrix, and sequences that grow too long push up the attention cost. For this reason, production environments generally adopt subword segmentation schemes that control vocabulary size by merging high-frequency fragments, striking a balance between out-of-vocabulary words and sequence length.

    The core of batch construction is the sliding window. Set a context length block_size, pick a random starting point from the integer sequence, and cut a segment of length block_size+1. The first block_size tokens serve as input, and the last block_size tokens serve as the target.

    1. x = data[i:i + block_size]
    2. y = data[i + 1:i + block_size + 1]

    The one-position offset is the key to language modeling: at position t the model sees the first t tokens and must predict token t+1. This offset is not a trick; it is the training objective itself.

    4. Model Structure: Four Components Hold Up Attention

    A minimal GPT consists of four parts: token embeddings, position embeddings, one or more Transformer blocks, and an output linear layer. All tensor shapes revolve around batch size B, context length T, and embedding dimension C.

    1. tok_emb = nn.Embedding(vocab_size, C)
    2. pos_emb = nn.Embedding(block_size, C)
    3. blocks = nn.Sequential(*[Block(C) for _ in range(n_layer)])
    4. ln_f = nn.LayerNorm(C)
    5. head = nn.Linear(C, vocab_size)

    The forward pass can be written as a clear chain of shape transformations:

    1. idx = torch.stack([x, y], dim=0) # illustrative only
    2. B, T = x.shape
    3. x = tok_emb(x) + pos_emb(torch.arange(T)) # B, T, C
    4. x = blocks(x) # B, T, C
    5. x = ln_f(x) # B, T, C
    6. logits = head(x) # B, T, vocab_size

    Position embeddings cannot be omitted. Self-attention is by itself insensitive to order, so without positional information “the cat chases the dog” and “the dog chases the cat” look completely identical to the model.

    Inside the attention block there are three steps: linear projections produce the query, key, and value; scaled dot-product attention is computed; and the output is projected and added back through a residual connection. The purpose of multiple heads is to let different heads attend to different relationship patterns—for example, one head focuses on adjacent words while another focuses on long-distance references.

    1. q = self.q(x); k = self.k(x); v = self.v(x)
    2. att = (q @ k.transpose(-2, -1)) * self.scale
    3. att = att.masked_fill(tril == 0, float('-inf'))
    4. att = F.softmax(att, dim=-1)
    5. out = att @ v

    The causal mask is the most essential difference between GPT and bidirectional encoders: position t cannot see anything after t, otherwise the model “peeks at the answer” during training and cannot reproduce it during inference.

    The feed-forward network is usually two linear layers with an activation in between, with the intermediate dimension expanded fourfold. Its role is to apply a position-wise nonlinear transformation to the representation after attention aggregation. Residual connections and layer normalization together keep deep networks trainable, avoiding vanishing gradients and activation drift.

    5. Training Objective and Optimization: Cross-Entropy and Learning Rate

    The loss function is position-wise cross-entropy, which measures the gap between the predicted distribution and the actual next token.

    1. loss = F.cross_entropy(logits.view(B * T, -1), y.view(B * T))

    The training loop consists of four actions: clear gradients, forward pass, backward pass, and update. A minimal implementation commonly pairs a small learning rate with a simple schedule, such as linear warmup followed by cosine decay, in order to avoid early divergence and stabilize convergence.

    1. for step in range(max_steps):
    2. xb, yb = get_batch()
    3. logits, loss = model(xb, yb)
    4. opt.zero_grad()
    5. loss.backward()
    6. opt.step()

    It must be pointed out that a minimal implementation has limited results on a real corpus, due to small model capacity, few training steps, small data scale, and the absence of regularization and learning-rate fine-tuning. Its significance is to verify that the pipeline is correct, not to match a production-scale model. To engineer it, you need to introduce capabilities such as mixed precision, gradient accumulation, distributed data parallelism, checkpoint resume, and metric monitoring. These typically rely on general cloud components such as container platforms, object storage, logging services, and monitoring and alerting.

    6. The Generation Process: Autoregressive Sampling and Temperature

    Generation is the reverse of training: during training the target is known, while during generation the target is unknown and the previous output can only be fed in as the next input.

    1. idx = torch.tensor([[stoi[p] for p in prompt]])
    2. for _ in range(max_new_tokens):
    3. idx_cond = idx[:, -block_size:]
    4. logits, _ = model(idx_cond)
    5. logits = logits[:, -1, :] / temperature
    6. probs = F.softmax(logits, dim=-1)
    7. idx_next = torch.multinomial(probs, num_samples=1)
    8. idx = torch.cat([idx, idx_next], dim=1)

    Temperature controls the sharpness of the distribution: a temperature below one makes the distribution sharper and the output more conservative, while a temperature above one flattens the distribution and makes the output more random. Greedy decoding is equivalent to the limiting case where temperature approaches zero, but it easily falls into repetition. Real systems also introduce strategies such as top-k sampling, repetition penalties, and length penalties to balance fluency and diversity.

    Context truncation during generation is equally critical: once the sequence exceeds block_size, the earliest tokens must be dropped, otherwise the position embeddings go out of bounds. This step is often overlooked in minimal implementations, yet it directly determines whether long-text generation throws an error.

    7. Common Misconceptions and Engineering Recommendations

    First, treating “the loss goes down” as “the model has learned.” A falling loss only shows that optimization is working; whether language structure is genuinely modeled has to be judged by the coherence of generated samples.

    Second, ignoring data quality. Minimal implementations are often trained on small corpora, and if the corpus itself is noisy, the generated output will inevitably be chaotic. The gains from data cleaning, deduplication, and quality filtering often outweigh tuning hyperparameters.

    Third, confusing the training and inference paths. Training uses teacher forcing while inference uses autoregression, and the mismatch between the two distributions causes error accumulation. This is one of the systematic reasons for degraded generation quality.

    Fourth, lacking a reproducibility design. Fixing random seeds, recording data versions, and saving parameters and configurations are prerequisites for reproducing experiments. In engineering, you can use object storage to keep checkpoints, use a logging service to record training curves, and use monitoring and alerting to track resource and loss anomalies.

    Fifth, using a teaching implementation directly in production. A teaching implementation lacks concurrency control, authentication, rate limiting, caching, and canary release capabilities. Real business workloads should be wrapped through a managed inference service or a container platform, together with elastic scaling and an observability system.

    8. From 200 Lines to a Scalable Architecture

    Using the minimal implementation as a skeleton, you can extend it step by step: replace the character-level vocabulary with subword segmentation; expand single-head attention into multi-head, multi-layer attention; introduce rotary or relative positional encoding to improve length extrapolation; add feed-forward normalization variants to improve stability; adopt better optimizers and learning-rate warmup; and build instruction fine-tuning and preference alignment pipelines on the data side.

    If you rely on the general capabilities of Baidu AI Cloud, you can run training tasks on a container platform, store the corpus and checkpoints in object storage, and connect training metrics to logging services and monitoring and alerting, thereby gaining engineering reliability without changing the core algorithm. It should be emphasized that these are general cloud practices and do not involve any proprietary interfaces or parameters.

    9. Conclusion

    The value of 200 lines of code lies not in being “short” but in being “complete.” It lays out the minimal closed loop of a language model in front of the reader: how integer sequences enter the model, how attention aggregates context, how cross-entropy drives parameter updates, and how autoregression turns a probability distribution into text. Once you understand this chain, distributed training, long-context optimization, alignment, and inference acceleration are no longer black boxes but the same set of principles expanded under different constraints.