Language Model Training and Text Generation in About 200 Lines of Code
Explore the core workflow of a small decoder-only language model, from text encoding and causal self-attention to next-token training and autoregressive generation. This article explains tensor shapes, loss computation, sampling strategies, and practical checks for implementation errors, while clarifying the limits of a compact educational model.
1. What About 200 Lines of Code Can—and Cannot—Do
The value of a compact language model implementation is not its line count. What matters is whether it captures three essential stages: converting text into model-ready data, learning language patterns by predicting the next token, and using those predictions to generate text step by step.
This article focuses on a decoder-only autoregressive language model. “Autoregressive” means that the model predicts the next token from the tokens already available, appends that token to the context, and repeats the process.
No specific source code is provided, so the discussion does not assume a particular implementation or parameter configuration. Instead, it covers structures commonly found in educational models. About 200 lines can express the core algorithm, but such implementations usually depend on existing tensor operations, automatic differentiation, and optimizers. Short code does not imply simple underlying computation, nor does it provide production-ready reliability, security, or serving capabilities.
A small model’s ability to learn local text patterns also does not mean it can reliably understand facts, follow instructions, or perform complex reasoning. Model size, data quality, training objectives, and available training resources all affect the outcome.
2. Training Starts by Turning Text into Integer Sequences
Why text cannot be fed directly into the network
Neural networks operate on numerical tensors. Raw text must first be encoded as an integer sequence, then mapped to vectors through an embedding layer.
Educational implementations often use character-level encoding: collect the characters in the corpus and assign each one an integer ID. For example:
Original text: windEncoded sequence: [7, 12, 5, 19]
These numbers are indices, not measurements. An ID of 19 is not more important than an ID of 7, and their difference does not represent semantic distance.
Character-level encoding is easy to understand, but it produces relatively long sequences. Other systems may use subword tokenization or another scheme. The basic pipeline remains the same:
Text → Tokens → Integer IDs → Vector representations
Why inputs and targets are shifted by one position
Suppose a corpus segment is encoded as:
[7, 12, 5, 19, 3]
A training example can be constructed as:
Input: [7, 12, 5, 19]Targets: [12, 5, 19, 3]
At each position, the model predicts the next token:
- Given the first token, predict the second.
- Given the first two tokens, predict the third.
- Given the first three tokens, predict the fourth.
- Continue in the same way.
An input sequence of length T therefore provides T prediction tasks, rather than just one prediction after the entire sequence. This makes more efficient use of the training data.
Split the data without introducing leakage
The training set is used to update parameters. The validation set measures whether the model can still predict text that was not used for those updates.
For continuous text, avoid generating many heavily overlapping windows and then randomly splitting those windows into training and validation sets. The two sets may contain nearly identical passages, making validation results look better than they should.
A safer approach is to split the data by document or contiguous section first, then sample windows separately from each split. If the goal is to evaluate generalization across documents, keep documents isolated between the training and validation sets.
3. Tensor Shapes Reveal Much of the Model
Let:
Bbe the batch size.Tbe the context length.Vbe the vocabulary size.Cbe the hidden representation dimension.
The main shape transformations are:
Integer input [B, T]Token embeddings [B, T, C]With positional information [B, T, C]After decoder blocks [B, T, C]Vocabulary logits [B, T, V]
The final output is not generated text. It contains raw, unnormalized scores—usually called logits—for every vocabulary token at each sequence position.
When studying an implementation, annotate the shape beside each important operation. Many bugs come from confusing batch, sequence, and feature dimensions, or transposing the wrong dimensions in attention, rather than misunderstanding the model itself.
4. Why the Model Needs Both Token and Position Information
Token embeddings represent what a token is
An embedding layer is a learnable lookup table. Each integer ID maps to a vector of length C.
These vectors typically start with random values and change during training. The model is not given a predefined meaning for each character or token. Instead, the prediction task teaches it which vector representations help reduce error.
Positional information represents where a token is
Token embeddings and attention without positional information do not adequately represent the order of a sequence.
For example, “Alice helps Bob” and “Bob helps Alice” contain the same words but describe different relationships. The model needs additional information about order.
A simple educational implementation can learn a vector for each position and add it to the token vector:
Position representation = Token vector + Position vector
A fixed-size learned position table limits the sequence lengths the model can process. Training and generation must respect that limit.
5. Causal Self-Attention: Use the Past Without Seeing the Future
The roles of queries, keys, and values
Self-attention maps each position’s representation into three sets of vectors:
- Queries: what information the current position is looking for.
- Keys: the matching signals offered by other positions.
- Values: the information that can be aggregated after matching.
For a single attention head, the core computation is:
Attention scores = Queries × transpose(Keys) / sqrt(d)Attention weights = softmax(Attention scores + Causal mask)Output = Attention weights × Values
Here, d is the query and key dimension for that head. Dividing by sqrt(d) controls the scale of the dot products, reducing the risk that large scores make the softmax distribution excessively concentrated.
Why the causal mask is essential
During training, the model usually receives the entire input sequence at once. However, when predicting the next token at a particular position, it must use only that position and the positions before it.
Consider this input:
[A, B, C, D]
The target at the first position is B. If that position can read the second input position, it has already seen the answer.
A causal mask blocks attention to later positions. With query positions represented by rows and attended positions by columns, the allowed region is lower triangular:
Allowed Blocked Blocked BlockedAllowed Allowed Blocked BlockedAllowed Allowed Allowed BlockedAllowed Allowed Allowed Allowed
Blocked positions receive extremely low scores before softmax, making their attention weights approach zero.
Without this mask, training loss may look excellent while generation behaves poorly. The model has learned to rely on future information that is unavailable during generation.
Multiple heads provide different representation perspectives
Multi-head attention computes several sets of queries, keys, and values in parallel, then combines their outputs.
Different heads can learn different association patterns. However, it is not valid to assume that a particular head must specialize in grammar, references, or any other fixed function.
In a common equal-width design, the hidden dimension C must be divisible by the number of attention heads, with each head handling a portion of the feature dimensions.
6. What Else Belongs in a Decoder Block?
Attention alone does not make a typical decoder block. Such blocks also commonly include normalization, a feed-forward network, and residual connections.
Feed-forward networks apply nonlinear transformations at each position
Attention exchanges information across positions. The feed-forward network independently transforms the vector at each position.
It typically expands the dimension, applies a nonlinear activation, and projects back to the original dimension:
C-dimensional representation→ Wider intermediate representation→ Nonlinear transformation→ C-dimensional representation
The same feed-forward parameters are usually shared across positions, but each position processes its own input vector.
Residual connections help information and gradients flow
A residual connection adds a submodule’s input directly to its output:
New representation = Original representation + Submodule output
This lets the submodule learn an incremental adjustment instead of reconstructing all the information from scratch. It also helps optimize deeper networks.
Normalization controls internal numerical scales
One common design applies normalization before attention and before the feed-forward network:
h = h + causal_attention(normalize(h))h = h + feed_forward(normalize(h))
This is a common arrangement, not the only valid ordering. If the model uses regularization such as dropout, training and evaluation modes must also be handled correctly.
7. Training: From Prediction Errors to Parameter Updates
Turning logits into prediction probabilities
The final linear projection converts each position’s C-dimensional representation into V logits. Applying softmax produces a probability distribution over the next token.
Training aims to increase the probability of the correct target token relative to the alternatives.
Cross-entropy measures prediction error
For a single prediction position, the loss is:
Loss = -log(Probability assigned to the correct token)
The more probability the model assigns to the correct answer, the lower the loss. A low probability for the correct answer produces a high loss.
For a batch, losses are usually averaged across valid positions. If sequences contain padding, padded positions should be excluded from the loss calculation.
Implementations generally pass raw logits directly to a numerically stable cross-entropy function. There is no need to compute probabilities manually and then apply normalization again.
What happens in one training iteration?
The following framework-independent pseudocode shows the basic loop:
Repeat:inputs, targets = sample_training_batch()switch_to_training_mode()clear_parameter_gradients()logits = model(inputs)loss = cross_entropy(logits, targets)backpropagate(loss)optimizer_update()periodically_evaluate_validation_set()
Backpropagation calculates gradients of the loss with respect to model parameters. The optimizer then updates those parameters using the gradients and its internal state.
One parameter update is an iteration or training step. A complete pass through the training dataset is usually called an epoch. If the implementation samples random windows, the number of training steps does not directly indicate how many complete passes through the data have occurred.
Validation loss matters more than training loss alone
Falling training loss only shows that the model is becoming better adapted to its training data. If validation loss keeps rising, the model may be overfitting, or the training and validation data may have different distributions.
During evaluation, disable gradient recording and switch to evaluation mode. This reduces overhead and prevents training-time randomness from distorting the results.
8. Generation: Produce One New Token at a Time
The main difference between training and generation is that training provides the correct next token. During generation, the model must continue using its own selected outputs.
The basic process is:
sequence = encode(prompt)Repeat for the requested number of steps:context = trailing portion of sequence within the maximum lengthlogits = model(context)next_token_logits = logits at the final positionprobabilities = softmax(next_token_logits)new_token = select a token from probabilitiesappend new_token to sequenceresult = decode(sequence)
Only the final position’s logits are used because they predict what should come after the current context.
Greedy selection versus random sampling
Greedy selection chooses the highest-probability token at every step. It is more deterministic, but it can produce repetitive or locally rigid text.
Random sampling draws a token according to the probability distribution. It introduces variety but can also select lower-quality candidates.
Neither method is universally better. The choice depends on the task.
Temperature controls distribution concentration
Temperature sampling typically adjusts logits as follows:
Adjusted logits = Original logits / Temperature
For positive temperatures, lower values generally make the distribution more concentrated, while higher values make it flatter.
A temperature of zero cannot be substituted directly into this formula. For deterministic selection, use a separate maximum-score operation.
Candidate filtering reduces low-probability selections
Generation can also retain only a fixed number of the highest-probability candidates, or retain a candidate set whose cumulative probability reaches a specified threshold. The remaining probabilities are then renormalized before sampling.
These methods change the token-selection strategy; they do not add knowledge to the model. If relevant information is missing from the training data, adjusting sampling parameters cannot guarantee factual answers.
9. Important Errors to Check—and How to Test for Them
Verify the input–target shift
Print and decode a short input sequence and its targets. Confirm that the targets are shifted one position forward.
If the targets are identical to the inputs, the model may simply learn to copy the token at the current position.
Check for access to future information
Construct two sequences that are identical through a chosen position but differ afterward. With dropout and other sources of randomness disabled, outputs at the earlier positions should remain unchanged.
If changes to later tokens affect earlier predictions, inspect the causal mask and any other operation that could leak information across positions.
Test whether the model can fit a tiny dataset
Train repeatedly on a small, fixed set of examples and check whether the loss decreases substantially. This is an effective way to verify that the training pipeline is connected correctly.
Memorizing a few examples only suggests that the implementation may be working. It does not demonstrate generalization.
Investigate numerical problems
If the loss becomes non-finite, check for:
- An excessively high learning rate.
- A mask that leaves an attention row with no valid positions.
- Out-of-range token indices.
- Unstable normalization or loss computation.
If generated text becomes repetitive, examine the training data, context length, model capacity, and sampling strategy together. Temperature is not the explanation for every generation problem.
10. The Boundary Between an Educational Model and a Real Application
The main benefit of understanding an implementation of roughly 200 lines is not that you have mastered a complete intelligent system. It is that you can trace the computational chain:
Text encoding→ Context representations→ Causal information aggregation→ Next-token prediction→ Loss computation→ Gradient updates→ Autoregressive generation
Real applications require additional work, including data cleaning, access control, sensitive-information handling, model saving and restoration, version management, resource monitoring, and generation-quality evaluation.
For standard full attention, the attention matrix grows quadratically with sequence length. Increasing the context length can therefore substantially raise computation and accelerator-memory requirements.
During generation, caching past keys and values can reduce repeated computation. That is a performance optimization, however, and should not be introduced prematurely while the core logic remains unverified.
The most effective learning sequence is to build and validate the smallest complete workflow first, then add structure and optimizations incrementally. For every new module, identify the problem it solves, track its tensor shapes, and define a test for correctness. That is how you move from code that runs to an implementation whose results you can explain and whose errors you can reliably locate.
