Train a Small Language Model from Scratch: A Practical Guide

    This guide walks through training a small language model from scratch, using the task of generating short name-like strings as the running example. It covers the full pipeline: organizing text into document sequences, building a character-level tokenizer, implementing a minimal decoder-only Transformer, setting up the optimizer and training loop, and sampling text during inference. It also includes a troubleshooting checklist and a path for scaling from a toy model to production, with no prior large-model experience required.

    Train a Small Language Model from Scratch: A Practical Guide

    1. Why Bother Training a Small Model Yourself

    Large language models are often described as extremely complex, but their skeleton is actually assembled from a few basic parts: a body of text data, a set of rules that turn text into integers, a multi-layer neural network, a gradient descent optimizer, and a training loop that drives parameter updates. Compressing these parts into a few hundred lines of code is the most effective way to understand large models.

    Implementing it yourself has three benefits. First, you can see how the objective of “predicting the next symbol” runs through the data, the model, and the loss function. Second, you can experiment repeatedly within training cycles that last from seconds to minutes, quickly building intuition about the relationship between hyperparameters, data size, and model capacity. Third, you gain a transferable engineering structure; later, whether you scale up the parameter count or switch data domains, the points to change are clear and controllable.

    This article uses “learning to generate short, name-like strings” as the example task. The dataset has about thirty thousand records, one name per line. The task looks simple, yet it covers all the elements of language modeling, and training can be done on an ordinary personal computer or even in a browser.

    2. Overall Workflow and Directory Structure

    A minimal viable solution can be split into the following modules to make problems easier to locate:

    1. minillm/
    2. data/ # raw text and preprocessed artifacts
    3. tokenizer.py # character-level encoding and decoding
    4. model.py # network architecture
    5. optimizer.py # parameter update rules
    6. train.py # training loop
    7. sample.py # inference sampling

    It is recommended to first get the shortest loop from “data to sampling” working, then progressively replace and enhance each module. This way, any anomaly can be quickly attributed to a specific stage.

    3. Data Layer: Organizing the Corpus into Document Sequences

    The “fuel” of a language model is a stream of text. In production scenarios, a document might be a web page, an article, or a conversation; in the example task, a document is a name. The key actions in data preparation are cleaning and shuffling:

    1. import os, random, urllib.request
    2. if not os.path.exists('input.txt'):
    3. url = 'https://example.org/names.txt' # placeholder address; replace with an accessible data source
    4. urllib.request.urlretrieve(url, 'input.txt')
    5. docs = [line.strip() for line in open('input.txt').read().strip().split('\n') if line.strip()]
    6. random.shuffle(docs)
    7. print(f"Number of documents: {len(docs)}")

    Engineering practice also requires attention to a few points: fix the random seed to ensure reproducibility; split into a training set and a validation set to observe whether overfitting occurs; measure the length distribution to decide the maximum sequence length. The impact of data quality on the final result is usually greater than fine-tuning the model architecture.

    4. Tokenizer: A Two-Way Mapping Between Text and Integers

    Neural networks only accept numerical input, so an encoding layer is needed. Industrial solutions mostly split text into subword units to improve compression and vocabulary utilization, while in a teaching scenario the most intuitive approach is character-level mapping: assign an integer ID to each character that appears in the dataset, then build a reverse index for decoding.

    1. chars = sorted(list(set(''.join(docs))))
    2. stoi = {ch: i for i, ch in enumerate(chars)}
    3. itos = {i: ch for ch, i in stoi.items()}
    4. def encode(s): return [stoi[c] for c in s]
    5. def decode(ids): return ''.join(itos[i] for i in ids)
    6. print(decode(encode('emma'))) # restores to emma

    The advantages of character-level tokenization are a simple implementation, a tiny vocabulary, and no out-of-vocabulary problem; the drawback is longer sequences and higher demands on modeling long-range dependencies. Understanding this tradeoff helps you judge when a more complex encoding strategy is needed in real projects.

    5. Model Architecture: A Minimal Decoder-Only Transformer

    The mainstream approach uses a decoder-only stacked structure, whose core is “masked self-attention + feed-forward network + residual connections and normalization.” Below is a skeleton that prioritizes readability:

    1. import torch, torch.nn as nn
    2. from torch.nn import functional as F
    3. class Block(nn.Module):
    4. def __init__(self, n_embd, n_head):
    5. super().__init__()
    6. self.ln1 = nn.LayerNorm(n_embd)
    7. self.attn = nn.MultiheadAttention(n_embd, n_head, batch_first=True)
    8. self.ln2 = nn.LayerNorm(n_embd)
    9. self.mlp = nn.Sequential(nn.Linear(n_embd, 4*n_embd), nn.GELU(),
    10. nn.Linear(4*n_embd, n_embd))
    11. def forward(self, x, mask):
    12. h = self.ln1(x)
    13. a, _ = self.attn(h, h, h, attn_mask=mask, need_weights=False)
    14. x = x + a
    15. x = x + self.mlp(self.ln2(x))
    16. return x
    17. class TinyLM(nn.Module):
    18. def __init__(self, vocab_size, n_embd=64, n_head=4, n_layer=3, block_size=16):
    19. super().__init__()
    20. self.tok = nn.Embedding(vocab_size, n_embd)
    21. self.pos = nn.Embedding(block_size, n_embd)
    22. self.blocks = nn.ModuleList([Block(n_embd, n_head) for _ in range(n_layer)])
    23. self.ln_f = nn.LayerNorm(n_embd)
    24. self.head = nn.Linear(n_embd, vocab_size)
    25. self.block_size = block_size
    26. def forward(self, idx, targets=None):
    27. B, T = idx.shape
    28. x = self.tok(idx) + self.pos(torch.arange(T, device=idx.device))
    29. mask = torch.triu(torch.ones(T, T, device=idx.device), diagonal=1).bool()
    30. for b in self.blocks: x = b(x, mask)
    31. logits = self.head(self.ln_f(x))
    32. loss = None if targets is None else F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
    33. return logits, loss

    Key points: token embeddings map integers to vectors; positional embeddings add order information; the causal mask ensures that position t can only see the first t symbols, avoiding “peeking at the answer”; residual connections and layer normalization keep a deep network trainable; the final linear layer outputs a distribution over the vocabulary.

    6. Optimizer and Training Loop

    The optimizer updates parameters along the gradient direction. In practice, the most common choice is an adaptive method with first- and second-moment estimates, combined with learning rate warmup and cosine decay for more stable convergence. The core of the training loop is “fetch a batch — forward pass — compute loss — backpropagate — update — log”:

    1. opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
    2. def get_batch(data, bs, block):
    3. ix = torch.randint(len(data), (bs,))
    4. x = torch.stack([data[i:i+block] for i in ix])
    5. y = torch.stack([data[i+1:i+block+1] for i in ix])
    6. return x, y
    7. for step in range(5000):
    8. x, y = get_batch(train_ids, 32, model.block_size)
    9. _, loss = model(x, y)
    10. opt.zero_grad(set_to_none=True); loss.backward(); opt.step()
    11. if step % 500 == 0: print(step, loss.item())

    A causal relationship worth emphasizing: the loss is the cross-entropy between the predicted distribution and the true next symbol, and it measures both correctness and confidence; batch size affects gradient noise, where too large leads to insufficient generalization and too small makes updates unstable; the learning rate must match the model size, and as the model grows you usually need to lower the peak learning rate appropriately and extend warmup.

    7. Inference Sampling: From Distribution to Text

    After training, inference is an autoregressive process: feed the starting symbol into the model, take the distribution at the last position, sample after temperature scaling, append it to the end of the sequence, and loop until a stopping condition is met.

    1. @torch.no_grad()
    2. def sample(model, start='a', n=200, temperature=1.0):
    3. idx = torch.tensor([encode(start)], dtype=torch.long)
    4. out = idx
    5. for _ in range(n):
    6. logits, _ = model(out[:, -model.block_size:])
    7. p = F.softmax(logits[:, -1, :] / temperature, 1)
    8. nxt = torch.multinomial(p, 1)
    9. out = torch.cat([out, nxt], 1)
    10. return decode(out[0].tolist())

    Temperature is the key knob for controlling randomness: a low temperature produces conservative, repetitive output; a high temperature yields more diversity but may produce meaningless fragments. You can also add end-of-sequence detection, repetition penalties, or beam search during decoding to fit different business requirements for determinism and diversity.

    8. Common Pitfalls and a Tuning Checklist

    • Loss does not decrease for a long time: first check whether the labels are off by one and whether the mask direction is correct.
    • Good on the training set but poor on the validation set: typical overfitting; reduce model capacity, add data, or introduce regularization.
    • Output is always the same character: the learning rate is too high or there is numerical instability; try lowering it and add gradient clipping.
    • Out of GPU memory: reduce batch size and sequence length, or enable mixed precision and gradient accumulation.
    • Results are not reproducible: fix all random seeds and record the data version and hyperparameters.

    9. Upgrade Path from a Toy to Something Usable

    After getting the minimal loop working, you can expand along four lines: on the data side, introduce deduplication, quality filtering, and mixing strategies; on the tokenizer side, switch to subword encoding to shorten sequences; on the model side, go deeper and wider and adopt more stable normalization and initialization; on the training side, add distributed data parallelism, checkpoint resume, and a metrics dashboard. If you use cloud resources, you can rely on general-purpose capabilities for the supporting pieces, for example using object storage to hold the corpus and checkpoints, a container platform to run training jobs, and logging and monitoring services to track loss curves and resource usage.

    10. Conclusion

    A small language model is essentially a combination of three things: a data distribution, conditional probability modeling, and sampling-based decoding. Writing every layer by hand, you will find that most of the complexity of so-called large models comes from scale and engineering details, not from principles that are inherently incomprehensible. Master this minimal skeleton, and then talk about scaling and optimization with a much clearer mindset.