Train a Tiny Language Model from Scratch: A Complete, Runnable Guide
Learn how to build a minimal character-level language model from scratch, including tokenization, causal self-attention, automatic differentiation, optimization, training, text generation, and evaluation. The goal is not production-level performance, but a clear understanding of how modern language models work from data to generated text.
1. What Does It Mean to Build Your Own Small AI Model?
The phrase “train your own small AI model” can refer to three very different goals:
Train a small language model from scratch
You prepare the data, implement the model architecture, and build the training process yourself. This approach is best for learning the fundamentals.Fine-tune an existing model
You start with a pretrained model and adapt it using domain-specific or business data. This is usually more practical, with lower data and compute requirements than training from scratch.Train a task-specific small model
Examples include text classification, keyword extraction, intent recognition, and simple sequence generation. These models are usually smaller and have more focused objectives.
This article focuses on the first approach: implementing a tiny language model that can be trained and used to generate text from scratch.
The main value is not the quality of the final output. Instead, the project breaks a language model into understandable and testable components.
A minimal language model generally includes:
- A text dataset
- A tokenizer
- A parameterized neural network
- An automatic differentiation mechanism
- A loss function
- An optimizer
- A training loop
- An inference and sampling loop
Even a model with only a few thousand parameters can demonstrate most of the core ideas behind modern language models.
2. Start with a Simple Dataset
To reduce implementation complexity, begin with a simple and consistently formatted dataset. For example, prepare a list of common names, with one sample per line:
emmaoliviaavaisabellasophiacharlotte
Each line can be treated as an independent document. The model is not supposed to memorize the names directly. It should learn patterns in how characters are arranged, such as:
- Which characters are more likely to appear at the beginning
- Which characters commonly follow a given character
- How long a name usually is
- Which character combinations look natural
- When a sample should end
After training, the model may generate strings that do not appear in the training data but still look plausible. This indicates that the model has learned a probability distribution rather than simply copying the dataset.
In real projects, data may come from business documents, question-and-answer records, code snippets, or structured text. The more complex the data, the more attention must be paid to cleaning, deduplication, encoding consistency, length limits, and privacy protection.
For learning purposes, start with a few thousand to tens of thousands of short texts. First verify that the complete training pipeline works, then gradually increase the dataset size.
3. Tokenization: Converting Text into Numbers
Neural networks cannot directly process characters or words. They receive sequences of integers, so a tokenizer is required.
The simplest option is character-level tokenization. Suppose the dataset contains the following characters:
a b c d e ... z
Assign an integer ID to each character:
a -> 0b -> 1c -> 2...
Then add a special end-of-document token:
end_token -> 26
For example, the string:
anna
might be encoded as:
[0, 13, 13, 0, 26]
The end token is important because it tells the model that the current document is complete and that generation can stop.
At minimum, the tokenizer should support both directions:
def encode(text):# Convert a string to a list of token IDs...def decode(tokens):# Convert token IDs back to a string...
Character-level tokenization is simple and easy to understand, but it creates longer sequences. More advanced tokenizers merge common character sequences into larger tokens, reducing sequence length. For a tiny educational model, however, character-level tokenization is sufficient to demonstrate the full training process.
The same vocabulary must be used during training and inference. If an unseen character appears during inference, the tokenizer needs a way to represent it as an unknown token. Real projects also need to handle case sensitivity, whitespace, and special symbols consistently.
4. A Language Model Predicts the Next Token
During training, a language model does not directly learn to generate a complete sentence. Instead, it predicts the next token at every position.
For example, an encoded sequence might be:
[a, n, n, a, end]
This sequence can be split into training examples:
| Input | Target |
|---|---|
| a | n |
| a n | n |
| a n n | a |
| a n n a | end |
The model receives an input sequence and produces a probability distribution for each position. If the vocabulary contains 27 tokens, the model outputs 27 scores for every position. After normalization, these scores represent the probabilities of the possible next tokens.
Training usually uses cross-entropy loss. When the model assigns a high probability to the correct target token, the loss is lower. When it concentrates probability on incorrect tokens, the loss increases.
The training objective can be summarized as:
Given the previous tokens, predict the next token as accurately as possible.
By repeating this local prediction task across many examples, the model gradually learns the structure of the text.
5. Model Architecture: A Minimal Transformer
A simplified Transformer decoder can be used to model context. Its core components include the following.
5.1 Token Embeddings
Each token ID is mapped to a vector:
token 5 -> [0.12, -0.31, 0.44, ...]
These vectors are not manually designed. They are updated during training. After training, tokens with similar usage patterns may develop similar representations.
5.2 Positional Embeddings
Token embeddings alone are not enough because the model must distinguish between:
a b
and:
b a
Positional embeddings add information about where each token appears in the sequence, allowing the model to understand order.
5.3 Causal Self-Attention
Autoregressive generation has an important restriction: the current position must not see future tokens. When predicting the second character, the model may use the first character, but it must not read the later correct answer.
This requires masked, or causal, self-attention. The basic process is:
- Compute queries, keys, and values from the input vectors.
- Calculate the relevance between the current position and previous positions.
- Mask future positions.
- Compute a weighted combination of the visible positions.
Attention allows the model to dynamically determine which earlier tokens are most relevant when predicting the current token.
5.4 Feed-Forward Network
After the attention layer combines information across positions, a feed-forward network applies a nonlinear transformation independently at each position. It commonly consists of two linear layers and an activation function, increasing the model’s expressive capacity.
5.5 Residual Connections and Normalization
Residual connections help reduce optimization difficulties in deeper networks by allowing information to flow directly to later layers. Normalization helps keep numerical values stable and makes training smoother.
For a minimal implementation, one or a few layers are enough. Use a small hidden dimension and a short context length. Although the resulting model has limited capability, it should be sufficient to observe the loss decrease and produce generated text.
6. Automatic Differentiation: The Key to Training
Training depends on gradients. A gradient describes how the loss changes when a parameter changes slightly.
Manually deriving gradients for an entire neural network would require substantial effort. A small automatic differentiation engine makes the process much easier to understand.
Each numerical object in the computation graph can record:
- Its current value
- Its gradient
- Its parent nodes
- The local derivative used during backpropagation
- The operation that produced it
For example:
z = x * y + b
The system calculates z, but also records the operations that produced it. During backpropagation, it starts from the final loss, traverses the computation graph in reverse order, and applies the chain rule to pass gradients back to x, y, and b.
Automatic differentiation usually has two stages:
Forward pass: Compute predictions and loss from the parametersBackward pass: Compute the gradient of the loss for every parameter
For educational purposes, a scalar-based automatic differentiation system is sufficient. It will not be highly efficient, but it clearly demonstrates the mechanism behind modern deep learning frameworks.
7. How the Optimizer Updates Parameters
Once gradients have been calculated, the model parameters must be updated. The simplest method is gradient descent:
parameter.value -= learning_rate * parameter.grad
Here:
parameter.valueis the current parameter value;parameter.gradis the gradient of the loss with respect to that parameter;learning_ratecontrols the update size.
In practical training, optimizers with momentum and adaptive update behavior are often used. They maintain first- and second-order statistics for each parameter, allowing different parameters to use more suitable update steps.
Old gradients must be cleared before each update. Otherwise, gradients accumulate across training steps:
for parameter in parameters:parameter.grad = 0
If the learning rate is too large, the loss may fluctuate sharply or diverge. If it is too small, training may be extremely slow. The loss curve is therefore useful when adjusting the learning rate.
8. The Complete Training Loop
A minimal training loop may look like this:
for step in range(total_steps):document = random_choice(documents)tokens = [start_token] + encode(document)inputs = tokens[:-1]targets = tokens[1:]logits = model(inputs)loss = cross_entropy(logits, targets)zero_gradients()loss.backward()optimizer_step()if step % report_interval == 0:print(step, loss.value)
Each iteration performs the following operations:
- Randomly select a document.
- Encode it as a token sequence.
- Shift the sequence to create inputs and targets.
- Run the forward pass.
- Calculate the loss between predictions and the true targets.
- Run backpropagation.
- Update the parameters.
- Periodically report the training state.
If the implementation is correct, the training loss will generally decrease over time. However, a lower loss does not mean that the model has developed strong language ability. It only means that the model has become better at predicting the current dataset and training objective.
9. Inference and Sampling: Generating Text
After training, generation can start from a beginning token and proceed one token at a time:
tokens = [start_token]for _ in range(max_length):logits = model(tokens)next_token = sample(logits[-1])tokens.append(next_token)if next_token == end_token:breakprint(decode(tokens[1:]))
The model generates one token, appends it to the context, and then predicts the next token.
If the token with the highest probability is always selected, the output is usually more stable, but it may also become repetitive or monotonous. If tokens are sampled from the probability distribution, the output becomes more varied but may contain less plausible combinations.
A temperature parameter can be used to control this behavior:
- Lower temperature: a more concentrated probability distribution and more stable output
- Higher temperature: a flatter distribution and more varied output
- Excessively high temperature: increasingly random text
Sampling strategies should match the task. For short name generation, moderate randomness is often more natural than always selecting the most likely token.
10. How to Tell Whether the Model Learned Real Patterns
A single generated sample is not enough for evaluation. More reliable checks include the following.
10.1 Monitor the Training Loss
Check whether the loss decreases overall and whether it shows abnormal oscillations.
10.2 Check Generation Diversity
If every output is identical, the model may be too deterministic or overconfident. If the outputs are completely random, the model may not have learned the data patterns yet.
10.3 Split the Data into Training and Validation Sets
Use the training set to update parameters and the validation set to measure generalization. If validation loss continues to rise, the model may be overfitting.
10.4 Compare Basic Statistics
Compare generated and original data based on:
- Sequence length
- Character frequency
- Distribution of starting characters
- Common character combinations
10.5 Check for Data Leakage
If generated outputs closely duplicate training samples, determine whether the model has learned general patterns or simply memorized the data.
11. From an Educational Project to a Practical Application
A tiny model is useful for learning, but it should not be expected to handle complex production tasks directly. Potential areas for improvement include:
- Adding more high-quality training data
- Using a more suitable tokenization method
- Increasing the context length
- Adding more layers and a larger hidden dimension
- Using mini-batch training for better stability
- Adding validation sets and checkpoint saving
- Using hardware acceleration and tensorized computation
- Cleaning and deduplicating data
- Filtering sensitive information
- Adding safety review and quality evaluation for generated outputs
For enterprise applications, training a large model entirely from scratch is usually not the most practical approach. A more suitable strategy may combine an existing foundation model with domain data, retrieval-augmented generation, and parameter-efficient fine-tuning.
Cloud platforms such as Baidu AI Cloud may provide general-purpose capabilities for compute resources, object storage, logging, monitoring, and model training. However, the appropriate design still depends on the dataset size, compliance requirements, latency targets, and budget.
12. Summary
The real value of training your own small AI model is not producing a program that can generate a few strings. It is understanding the complete language-model workflow:
Text data-> Tokenization-> Token sequences-> Model forward pass-> Loss function-> Automatic differentiation-> Parameter updates-> Probability sampling-> New text
Starting with a character-level dataset provides a practical way to learn language modeling, attention, automatic differentiation, and optimization. After completing this minimal experiment, you can move on to more efficient tokenizers, larger-scale training pipelines, model fine-tuning, and deployment services.
This progression turns “knowing how to call AI” into a deeper understanding of how to design and build AI systems.
