Training a Small Language Model from Scratch: A Full Walkthrough
This article walks through the complete process of training a small language model from scratch, breaking the pipeline into independently verifiable modules: dataset preparation, tokenization, automatic differentiation, network architecture, optimizer and training loop, and the inference loop. It explains why a minimal, few-hundred-line implementation is valuable for interpretability and low-cost experimentation, and includes runnable Python snippets for each stage. You will also find practical guidance on data splitting, character-level versus subword tokenization, common backpropagation pitfalls, GPT-2-style causal self-attention, Adam updates, sampling strategies such as temperature and top-k/top-p, a troubleshooting order for common issues, and how to move from a minimal implementation toward production engineering.
1. Why Bother Training a Small Model Yourself
Large language models are engineered as a set of independently verifiable modules: data, tokenization, the computation graph, network architecture, the optimizer, the training loop, and the inference loop. Production systems turn these modules into distributed, scalable services, but the causal relationships between them do not change just because the scale grows. Wiring every stage together with a minimal amount of code offers a benefit that has little to do with performance: explainability. Every line of code maps to a clear responsibility, so when something breaks you can quickly tell whether the problem lies in the data, the gradients, or the sampling step.
The other practical benefit is cost control. A small model can be trained on an ordinary laptop or a single GPU, the dataset is usually on the order of a few megabytes, and training takes minutes. That makes repeated experimentation the norm, and repeated experimentation is exactly what you need to understand model behavior. One caveat matters: a small model only learns local statistical regularities, so do not expect general reasoning ability. Its value is that it exposes the full mechanics of training and inference.
2. The Dataset: The Only Fuel the Model Has
A model does not generate knowledge on its own; it only fits the distribution present in the data. The smallest usable dataset can be a plain text file with one sample per line. For example, thirty thousand names, one per line. Read the file, split on lines, strip whitespace, drop empty lines, then shuffle everything so the original ordering does not introduce spurious correlations.
import os, random, urllib.requestif not os.path.exists('input.txt'):url = 'https://example-host/names.txt' # placeholder; use your own local dataurllib.request.urlretrieve(url, 'input.txt')docs = [l.strip() for l in open('input.txt').read().split('\n') if l.strip()]random.shuffle(docs)print('num docs:', len(docs))
Three details in data preparation are easy to overlook. First, how you split: divide the training and validation sets by document, not by character, otherwise fragments of the same document end up on both sides and your metrics look artificially good. Second, length strategy: concatenating several short documents into fixed-length training samples raises computational density significantly, but you should record document boundaries to avoid teaching the model a meaningless “continue across documents” pattern. Third, character set statistics: scan the full text first to get the deduplicated set of characters, because the size of that character set directly determines the output layer dimension and memory footprint.
From a task perspective, the training objective is deliberately plain: given the preceding text, predict the next character. When the input is a prompt, the model’s output is formally a document completion. This is the key to understanding conversational models: a conversation is just a document organized in a particular format, and the model is still doing continuation.
3. The Tokenizer: Round-Tripping Between Characters and Integers
A neural network only accepts numbers, so you need a reversible mapping: text to a sequence of integers, and integers back to text. Production tokenizers usually rely on subword segmentation to compress sequence length and improve throughput, but a minimal implementation can use a character-level mapping, which is simple and fully reversible.
chars = sorted(set(''.join(docs)))stoi = {c: i for i, c in enumerate(chars)}itos = {i: c for c, i in stoi.items()}encode = lambda s: [stoi[c] for c in s]decode = lambda ids: ''.join(itos[i] for i in ids)
The character-level approach has zero dependencies and no out-of-vocabulary problem; its drawback is longer sequences, so the model has to process more steps to cover the same text. A common engineering compromise is to keep the character-level version as a baseline and compare it against a subword scheme under the same compute budget, deciding on validation loss rather than subjective impression.
4. Automatic Differentiation: Backpropagation in Minimal Form
To train a model you must be able to compute gradients. A minimal implementation usually contains two core classes: a scalar autodiff node that records operations and accumulates gradients backward, and a tensor container that handles batched matrix operations. The scalar version is valuable because it writes the chain rule with no ambiguity.
class Value:def __init__(self, data, _prev=()):self.data, self.prev, self.grad = data, set(_prev), 0.0self._backward = lambda: Nonedef __add__(self, o):o = o if isinstance(o, Value) else Value(o)out = Value(self.data + o.data, (self, o))def _backward():self.grad += out.grad; o.grad += out.gradout._backward = _backwardreturn out__radd__ = __add__def backward(self):topo, seen = [], set()def build(v):if v not in seen:seen.add(v); [build(p) for p in v.prev]; topo.append(v)build(self); self.grad = 1.0for v in reversed(topo):v._backward()
Three things cause most of the bugs here. Gradients must be accumulated, not overwritten, or gradients are lost when the same node is reached through multiple paths. The topological order must be built first and then traversed in reverse. In-place modification destroys the computation graph, so parameter updates in the training loop need no-grad semantics to isolate them. Once those three points are handled cleanly, swapping in any network architecture will not cause gradient problems.
5. Network Architecture: A Minimal GPT-2-Style Skeleton
A trainable language model skeleton has five parts: token and position embeddings, a stack of self-attention blocks, a feed-forward layer, layer normalization, and an output projection. The core of self-attention is the scaled dot product, together with a causal mask that ensures only left-side context is visible.
# Sketch: key steps of single-head causal self-attentionscores = q @ k.transpose(-2, -1) / (head_size ** 0.5)scores = scores.masked_fill(causal_mask == 0, float('-inf'))w = scores.softmax(dim=-1)out = w @ v
Two conventions are worth following. Residual connections and layer normalization should appear as a pair; otherwise gradient magnitudes get out of control when you stack layers deeply. Weight tying, where the output projection shares parameters with the input embedding, usually lowers loss on small datasets because it reduces the number of free parameters to fit. The number of layers, heads, and the embedding dimension should match the data scale: with only a few megabytes of data, pushing the model to hundreds of millions of parameters only produces overfitting.
6. The Optimizer and the Training Loop
The point of Adam is to maintain both first and second moment estimates and correct for bias, so the learning rate adapts per parameter. A minimal implementation only needs two extra state tensors per parameter.
for step in range(max_steps):xb, yb = get_batch(data, batch_size, block_size)logits, loss = model(xb, yb)model.zero_grad(); loss.backward()for p in model.parameters():p.data -= lr * p.grad # sketch: real code uses Adam's adaptive updateif step % 100 == 0:print(step, loss.data)
A stable training loop depends on a few habits: fix the random seed for reproducibility; evaluate on the validation set at fixed intervals to see whether overfitting has started; apply an exponential moving average to the loss so a single noisy batch does not mislead you; use warmup followed by cosine decay for the learning rate, which noticeably reduces early oscillation. Batch size and context length together determine memory usage, so tune them as a single group of parameters.
7. The Inference Loop and Sampling Strategy
Inference has no gradients; you repeatedly do forward pass, take the distribution at the last step, sample, and concatenate. Temperature controls randomness: a low temperature gives conservative, repetitive output, while a high temperature diverges and tends to produce garbage. Top-k or top-p truncation further suppresses long-tail noise.
for _ in range(max_new_tokens):idx_cond = idx[:, -block_size:]logits, _ = model(idx_cond)probs = logits[:, -1, :].softmax(dim=-1)idx_next = torch.multinomial(probs, num_samples=1)idx = torch.cat((idx, idx_next), dim=1)print(decode(idx[0].tolist()))
When evaluating generation quality, look at three kinds of metrics at once: validation loss reflects how well the model fits; the character-level validity rate of samples reflects format stability; and manual spot checks reveal diversity, so you can catch the model collapsing into a few high-frequency patterns. Only together do they tell you whether the issue is insufficient training, overfitting, or badly chosen sampling parameters.
8. Common Problems and the Order to Tune Them
If the loss does not go down, check the data pipeline and label alignment first, then the learning rate and initialization, and only then suspect the architecture. If generation repeats, adjust temperature and truncation first, then increase data diversity. If you run out of memory, give ground in this order: smaller batches, shorter context, fewer layers. To reproduce experiments in the cloud, a container platform can host the environment, object storage can hold datasets and checkpoints, a logging service can collect training metrics, and monitoring and alerting can track resource levels. These general-purpose capabilities are enough to support a complete experiment loop without relying on any proprietary interface.
9. From a Minimal Implementation to Production Engineering
Treat the two hundred lines of code as an executable specification, and scale along four lines when productionizing. On the data side, add cleaning, deduplication, and mixture management. On the training side, add mixed precision, gradient accumulation, and resuming from checkpoints. On the inference side, add batching and caching. On the operations side, fill in metrics, tracing, and canary rollouts. In these scenarios Baidu AI Cloud typically provides general infrastructure capabilities such as elastic compute, storage, and monitoring components that help teams run a validated training pipeline reliably. The real technical barrier remains a firm grasp of data quality and training details, not the number of lines of code.
