How to Train a Tiny AI Language Model from Scratch: A Complete Practical Guide

    This practical guide explains how to build and train a tiny language model from scratch, covering dataset preparation, character-level tokenization, a miniature Transformer architecture, the training loop, and inference with sampling. It also shows how the same core training loop scales from a small educational model to production-grade LLMs, giving readers a hands-on path to understanding language model fundamentals.

    Many developers begin learning about large language models by reading papers or calling existing APIs, but both approaches have clear limitations. Papers are abstract and lack hands-on components, while APIs hide every detail inside a black box. Training a tiny model is valuable because it compresses all the core parts of a language model—data, tokenization, the neural network, the optimizer, and the training and inference loops—into a codebase that can be read completely and iterated on quickly.

    A well-designed minimal implementation often depends only on the Python standard library, and a few hundred lines of code can cover all the algorithmic elements of an LLM. This approach follows an important teaching tradition in the industry: simplify large language models to their most basic elements and build understanding step by step through small projects such as an automatic differentiation engine, a character-level language model, and a small GPT. Once you understand every detail of a tiny model, approaching the engineering optimizations of production-grade models becomes much more effective.

    More importantly, this practice reveals the essence of LLMs: when a model generates a conversational reply, it is fundamentally doing document completion. Given a prompt as the beginning of a document, the model continues the text based on learned statistical patterns. Understanding this point can correct many mystified assumptions about AI.

    1. Why Train a Tiny Model

    Many developers begin learning about large language models by reading papers or calling existing APIs, but both approaches have clear limitations. Papers are abstract and lack hands-on components, while APIs hide every detail inside a black box. Training a tiny model is valuable because it compresses all the core parts of a language model—data, tokenization, the neural network, the optimizer, and the training and inference loops—into a codebase that can be read completely and iterated on quickly.

    A well-designed minimal implementation often depends only on the Python standard library, and a few hundred lines of code can cover all the algorithmic elements of an LLM. This approach follows an important teaching tradition in the industry: simplify large language models to their most basic elements and build understanding step by step through small projects such as an automatic differentiation engine, a character-level language model, and a small GPT. Once you understand every detail of a tiny model, approaching the engineering optimizations of production-grade models becomes much more effective.

    More importantly, this practice reveals the essence of LLMs: when a model generates a conversational reply, it is fundamentally doing document completion. Given a prompt as the beginning of a document, the model continues the text based on learned statistical patterns. Understanding this point can correct many mystified assumptions about AI.

    2. Preparing the Dataset: Fuel for Model Learning

    Language model training starts with text data. In production-grade settings, the data is usually a massive collection of web pages, with each page treated as a document. In a tiny model, we use a minimal but equivalent example: tens of thousands of common names, one name per line, with each name treated as a document.

    The core data-loading code can be very concise:

    1. import os, urllib.request, random
    2. if not os.path.exists('input.txt'):
    3. names_url = 'https://raw.githubusercontent.com/karpathy/makemore/refs/heads/master/names.txt'
    4. urllib.request.urlretrieve(names_url, 'input.txt')
    5. docs = [l.strip() for l in open('input.txt').read().strip().split('\n') if l.strip()]
    6. random.shuffle(docs)
    7. print(f"num docs: {len(docs)}")

    There are several practical details worth noting:

    1. Local cache check: Check whether the file already exists to avoid repeated downloads. This is a basic engineering habit for training scripts.
    2. Cleaning and filtering: Use strip() to remove blank lines and leading or trailing whitespace. Dirty data directly pollutes the patterns the model learns.
    3. Random shuffling: shuffle ensures that training samples appear in random order and avoids bias introduced by the data ordering itself.

    After training, the model should be able to generate new names with a similar style, such as kamon, karia, or vialan. These names are not in the training set, but they follow the statistical patterns of the training data. This is the most direct demonstration that a language model learns patterns and generalizes.

    3. Tokenizer: The Bridge Between Text and Numbers

    Neural networks can only process numbers, so there must be a mechanism that converts bidirectionally between text and token ID sequences. The tokenizer is responsible for this.

    In a character-level tokenization scheme, the implementation is simplest: build a mapping from characters to integers, look up each character during encoding, and reverse the lookup during decoding. This approach has a very small vocabulary—usually only dozens of tokens—requires no training, and is less prone to out-of-vocabulary issues. Its disadvantages are longer sequences and lower information density.

    Production-grade models generally use subword tokenization, merging frequent character chunks to balance vocabulary size and sequence length for better inference efficiency. There is also a common technique: add special delimiter tokens at the beginning and end of a name to explicitly tell the model where a document starts and ends. This is important for the model to learn document boundaries.

    1. chars = sorted(list(set(''.join(docs))))
    2. stoi = {ch: i + 1 for i, ch in enumerate(chars)}
    3. stoi['.'] = 0 # '.' as a special document boundary token
    4. itos = {i: ch for ch, i in stoi.items()}
    5. def encode(s): return [stoi[c] for c in s]
    6. def decode(ids): return ''.join(itos[i] for i in ids)

    4. Model Architecture: A Miniature Transformer

    A tiny model usually adopts an architecture similar to mainstream GPT models. Its core components include:

    1. Token embeddings and positional embeddings: Each token ID is mapped to a vector through an embedding matrix, and a positional embedding is added so the model can perceive the token’s position in the sequence.
    2. Multi-head self-attention: This is the core of the Transformer. Each position computes attention weights through three linear transformations—Query, Key, and Value—enabling selective attention to context. A causal mask ensures that each position can only see previous tokens and cannot “peek into the future.”
    3. Feed-forward network and residual connections: After attention, a two-layer MLP is combined with residual connections and layer normalization to form a complete Transformer block. Several blocks are usually stacked.
    4. Output layer: The final linear layer maps hidden states to the vocabulary size and produces the distribution for the next token.

    For a small character-level model, typical hyperparameters might be: embedding dimension 128, 4 attention heads, 4 Transformer blocks, and context length 256. With this configuration, training can finish in a few minutes on a standard laptop CPU.

    5. The Training Loop: Learning to Predict the Next Token

    The training objective is consistent: given the preceding context, maximize the probability of the next token, which is the cross-entropy loss. A standard training loop includes the following steps:

    1. optimizer = Adam(parameters, lr=1e-3)
    2. for step in range(10000):
    3. # 1. Sample a batch of (context, target) pairs from the data
    4. xb, yb = get_batch(docs, block_size=256, batch_size=32)
    5. # 2. Forward pass to compute loss
    6. logits, loss = model(xb, yb)
    7. # 3. Backward pass
    8. optimizer.zero_grad()
    9. loss.backward()
    10. # 4. Update parameters
    11. optimizer.step()

    Several key practical points:

    • Batch sampling strategy: Each time, cut a fixed-length context window from a random document. The target sequence is shifted one position to the right relative to the input sequence, naturally creating the training signal for “predict the next token.”
    • Automatic differentiation engine: After loss computation, calling backward() lets the framework—or a self-implemented micro-autograd—compute gradients automatically. Implementing a tiny automatic differentiation engine yourself is the deepest way to understand this process.
    • Adam optimizer: Compared with plain SGD, Adam maintains momentum and an adaptive learning rate for each parameter, converging faster and more stably. It is the default choice for training small models.
    • Learning rate scheduling: A warmup plus cosine decay strategy can be used, with small exploratory steps early and fine convergence later.

    During training, monitor the loss curve continuously. Healthy training shows a steady decline that gradually flattens. If the loss fluctuates sharply, try reducing the learning rate or batch size.

    6. Inference and Sampling: Generating New Content from the Model

    After training, inference is a loop: provide an initial context—usually the document start boundary token—and the model outputs a probability distribution for the next token. Sample one token, append it to the end of the context, and repeat until an end token is generated or the maximum length is reached.

    The sampling strategy directly affects generation quality:

    • Greedy decoding: Always choose the highest-probability token. The result is deterministic but tends to repeat mechanically.
    • Temperature sampling: Divide logits by a temperature coefficient T and then apply softmax. T < 1 makes the distribution sharper and the output more conservative; T > 1 makes the distribution flatter and the output more diverse.
    • Top-k / Top-p truncation: Sample only from the highest-probability candidates, balancing diversity and plausibility.

    In the name-generation example, a sufficiently trained model will generate many new names that “sound reasonable” but have never been seen before. This directly proves that the model has learned distributional patterns rather than memorizing the data.

    7. From Tiny Model to Production Model: Transferring Understanding

    After completing tiny model training, you can clearly understand that production-grade models differ from it in scale, not in principle:

    • The dataset changes from tens of thousands of names to corpora with trillions of tokens.
    • The tokenizer changes from character-level to large-scale subword schemes.
    • Parameter counts change from tens of thousands to tens of billions, requiring distributed training, mixed precision, memory optimization, and other engineering techniques.
    • The training pipeline adds multiple stages such as pretraining, supervised fine-tuning, and reinforcement learning from human feedback.

    But the core loop—sampling data, forward computation, backpropagation, updating parameters, and generation sampling—is exactly the same. Once you master the tiny model, you hold the key to understanding all language models. It is worth continuing with hands-on experiments: adjust the number of layers and dimensions and observe the effects, change the sampling temperature and compare generation quality, and try replacing the dataset with your own text data. Each change will deepen your understanding by another layer.