Back to Blog

Build a Language Model: Every Part Explained with Code

Imagine repeatedly covering the next letter in a book and asking a machine to guess it. At first, its guesses are almost random. Every mistake nudges its internal numbers. After enough examples, it starts picking up spaces, spelling, phrases, dialogue, and fragments of narrative.

That is the experiment we are going to build. You will see the whole path from a plain text file to generated text, including the code inside the Transformer. No pretrained weights, no external model API, and no hidden model class.

We will start with UTF-8 bytes as tokens, then explain how BPE combines frequent pieces. The network uses causal attention, rotary positions, RMSNorm, SwiGLU, and residual connections. Each code block contributes to the same runnable Python file, except the clearly marked BPE experiment at the end.

Think of the model as a trainable machine for turning a context into a ranked list of possible continuations. It learns the ranking from examples. Our job is to make each stage of that machine understandable.

1. Give the experiment a small, explicit shape

Save the blocks in order as tiny_lm.py. Install PyTorch with python3 -m pip install torch. Put UTF-8 training text in train.txt and separate held-out text in valid.txt. Each file needs more than 65 bytes. For meaningful learning, use substantially more text than that minimum.

Small dimensions make mistakes easier to inspect. BATCH is how many independent passages we process at once. CONTEXT is how many token positions appear in each passage. WIDTH is how many numbers describe one position inside the model.

import math
from pathlib import Path
import torch
from torch import nn
import torch.nn.functional as F

torch.manual_seed(42)
torch.set_num_threads(4)
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
VOCAB, CONTEXT = 256, 64
WIDTH, HEADS, LAYERS, FF = 128, 4, 4, 384
BATCH, STEPS = 16, 2000

A batch will have shape [16, 64]: sixteen passages, each sixty-four tokens long. The internal representation will have shape [16, 64, 128]: the same passages and positions, now described by 128 learned numbers each.

Four heads divide width 128 into groups of 32 coordinates. That division needs to be exact, and rotary positions need an even head width. The code runs on a CUDA GPU when available and otherwise on CPU. CPU is useful for checking correctness; training speed depends on hardware and data.

2. A tokenizer is a reversible naming system

The network cannot multiply the letter “a” by a matrix. It needs an integer ID. Our first tokenizer uses the byte values already present in UTF-8, so the vocabulary is always 256 entries.

Encoding “cat” produces [99, 97, 116]. Those numbers are labels, not quantities: token 100 is not semantically “one more” than token 99. Later, an embedding table will replace each label with a learned vector.

def encode(text):
    return list(text.encode("utf-8"))

def decode(ids):
    return bytes(ids).decode("utf-8", errors="replace")

def load_tokens(path):
    text = Path(path).read_text(encoding="utf-8")
    ids = torch.tensor(encode(text), dtype=torch.long)
    if len(ids) <= CONTEXT:
        raise ValueError("Text must exceed CONTEXT bytes")
    return ids

assert encode("cat") == [99, 97, 116]
assert decode(encode("Hello, 世界")) == "Hello, 世界"

Some characters occupy several bytes. “é” occupies two in UTF-8; many Chinese characters occupy three. Keep all the bytes together when decoding. During generation the model can produce an invalid byte sequence, so errors="replace" displays replacement characters rather than crashing. Valid UTF-8 text round-trips through these functions.

Choose the training and validation documents before running the experiment. Training text changes the weights; validation text tells us how those weights behave on text they were not updated on. Keep duplicates out of both sides where possible. TinyStories is one possible story corpus. Use its separate splits or create document-level splits of your own text.

3. Turn one passage into many prediction questions

Take the bytes for “cat!”: [99, 97, 116, 33]. The input is [99, 97, 116]. The target is [97, 116, 33]. At the first position we ask what follows “c”; at the second, what follows “ca”; at the third, what follows “cat”.

One passage teaches several next-token predictions in parallel. The causal mask we build later ensures that the first position cannot peek at the later positions.

The first line says that a sequence probability is a product of next-token probabilities. The symbol θ means all learned model parameters; x₍<t₎ means the tokens before position t. The second line is the one-position shift in get_batch. For the first token, the prefix is empty; our training windows instead supply a first input token and score the tokens following it. The multiplication describes the general language-model factorization; this implementation conditions on at most the latest CONTEXT tokens.

pθ(x1,…,xn)=∏t=1npθ(xt∣x<t)inputi=xi,targeti=xi+1\begin{aligned} p_\theta(x_1,\ldots,x_n)&=\prod_{t=1}^{n}p_\theta(x_t\mid x_{<t})\\ \text{input}_i&=x_i,\qquad \text{target}_i=x_{i+1} \end{aligned}
def get_batch(data, generator=None):
    starts = torch.randint(
        len(data) - CONTEXT, (BATCH,),
        generator=generator)
    windows = torch.stack([
        data[s:s + CONTEXT + 1] for s in starts.tolist()
    ]).to(DEVICE)
    x = windows[:, :-1]
    y = windows[:, 1:]
    return x, y

We request 65 tokens to build an input of length 64 and its shifted target of length 64. Every target is a real token from the original text. Nothing needs a human-written label.

Random starting positions expose the model to different windows. Windows can overlap, so processed token positions are not a count of unique training tokens. This small implementation loads the corpus into RAM; a large corpus should be streamed or memory-mapped.

4. RMSNorm keeps the scale under control

Each position is now going to carry a vector of numbers. As layers transform those vectors, their magnitude can drift. RMSNorm adjusts a vector using its root mean square, then applies a learned gain to every coordinate.

Imagine two vectors pointing in the same direction, but one is ten times longer. Normalization brings their scales closer, so the next calculation is less dominated by that difference. It does not make the vectors identical in every respect, and it does not subtract their mean.

Here x is one position’s vector, d is its width, γ is the learned gain, and ε is the small stability constant. The index i picks one coordinate; j runs over every coordinate when measuring the scale. In code: x.square().mean(...) computes the average inside the square root, rsqrt supplies the reciprocal square root, and gain supplies γ. All coordinates share the same denominator, but each gets its own learned gain.

RMSNorm⁡(x)i=γixi1d∑j=1dxj2+ε\operatorname{RMSNorm}(x)_i =\gamma_i\frac{x_i}{\sqrt{\frac{1}{d}\sum_{j=1}^{d}x_j^2+\varepsilon}}
class RMSNorm(nn.Module):
    def __init__(self, width, eps=1e-5):
        super().__init__()
        self.gain = nn.Parameter(torch.ones(width))
        self.eps = eps

    def forward(self, x):
        original_dtype = x.dtype
        z = x.float()
        scale = torch.rsqrt(
            z.square().mean(-1, keepdim=True) + self.eps)
        return (z * scale * self.gain).to(original_dtype)

square().mean() measures average squared size. rsqrt takes one divided by its square root. Multiplying by that value rescales the vector. The small epsilon avoids division by zero.

gain starts at one, then training learns which coordinates deserve more or less scale. nn.Parameter tells PyTorch that these numbers should receive gradients and optimizer updates. Computing the normalization in float32 helps avoid numerical trouble if other parts later use lower precision.

5. Positions need a signal of their own

Attention compares vectors. We also want those comparisons to reflect where tokens occur. Rotary positional embeddings, or RoPE, rotate pairs of query and key coordinates by angles determined by position.

Think of each coordinate pair as a tiny clock hand. Position changes the hand’s angle. Different pairs turn at different rates. When a query meets a key, their rotations make the comparison depend on their positional relationship.

p is the zero-based token position, j identifies a coordinate pair, and dₕ is the head width (32 here). Each pair gets a different angular speed. The primed coordinates are the rotated result, not a derivative. The matrix is a two-dimensional rotation: it changes direction while preserving length. This is exactly the even/odd pairing in apply_rope, applied to both queries and keys.

ϕp,j=p 10000−2j/dh[x2j′x2j+1′]=[cos⁡ϕp,j−sin⁡ϕp,jsin⁡ϕp,jcos⁡ϕp,j][x2jx2j+1]\begin{aligned} \phi_{p,j}&=p\,10000^{-2j/d_h}\\ \begin{bmatrix}x'_{2j}\\x'_{2j+1}\end{bmatrix} &=\begin{bmatrix}\cos\phi_{p,j}&-\sin\phi_{p,j}\\\sin\phi_{p,j}&\cos\phi_{p,j}\end{bmatrix} \begin{bmatrix}x_{2j}\\x_{2j+1}\end{bmatrix} \end{aligned}
def apply_rope(x):
    # x: [batch, heads, time, head_width]
    t, d = x.shape[-2:]
    frequencies = 10000.0 ** (
        -torch.arange(0, d, 2, device=x.device).float() / d)
    positions = torch.arange(t, device=x.device).float()
    angles = positions[:, None] * frequencies[None, :]
    cos, sin = angles.cos(), angles.sin()
    even, odd = x[..., 0::2], x[..., 1::2]
    rotated = torch.stack((
        even * cos - odd * sin,
        even * sin + odd * cos
    ), dim=-1)
    return rotated.flatten(-2)

The last two lines implement the usual two-dimensional rotation formula for each pair. The angle table has shape [time, head_width / 2]; broadcasting applies it to every batch item and head.

We rotate queries and keys, while values keep their original coordinates. A more optimized implementation caches these sine and cosine tables. Recomputing them here keeps the code easier to follow.

6. Attention lets each position retrieve useful context

At every position, three learned projections create a query, a key, and a value. A query represents what the current position is looking for. A key represents what another position offers for matching. A value is the information retrieved if that match receives weight.

These are useful interpretations of learned vectors, not human-written labels inside them. In “the cat sat because it was tired”, an attention head could learn relationships that help connect a pronoun with earlier context. No rule explicitly tells a head to do that.

For one head, Q, K, and V are the query, key, and value matrices after splitting the projections; Q and K also receive the rotary transform. The superscript ⊤ means transpose. S is the table of match scores, and M is the causal mask. Row i belongs to the current position; column j belongs to a candidate context position. A is row-wise softmax: its weights sum to one. Oᵢ is the resulting weighted mixture. If the allowed scores are [2, 1], their weights are approximately [0.73, 0.27], so the output is 0.73V₁ + 0.27V₂. The code’s masked_fill performs the same exclusion as adding M.

S=QK⊤dh+MMij={0j≤i−∞j>iAij=exp⁡(Sij)∑kexp⁡(Sik)Oi=∑jAijVj\begin{aligned} S&=\frac{QK^\top}{\sqrt{d_h}}+M\\ M_{ij}&=\begin{cases}0&j\leq i\\-\infty&j>i\end{cases}\\ A_{ij}&=\frac{\exp(S_{ij})}{\sum_k\exp(S_{ik})}\\ O_i&=\sum_j A_{ij}V_j \end{aligned}
class Attention(nn.Module):
    def __init__(self):
        super().__init__()
        self.qkv = nn.Linear(WIDTH, 3 * WIDTH, bias=False)
        self.out = nn.Linear(WIDTH, WIDTH, bias=False)

    def forward(self, x):
        b, t, c = x.shape
        q, k, v = self.qkv(x).chunk(3, dim=-1)
        def split(z):
            return z.reshape(b, t, HEADS, c // HEADS).transpose(1, 2)
        q, k, v = [split(z) for z in (q, k, v)]
        q, k = apply_rope(q), apply_rope(k)
        scores = q @ k.transpose(-2, -1)
        scores = scores / math.sqrt(c // HEADS)
        allowed = torch.ones(t, t, dtype=torch.bool,
                             device=x.device).tril()
        scores = scores.masked_fill(~allowed, -torch.inf)
        weights = scores.softmax(dim=-1)
        mixed = weights @ v
        mixed = mixed.transpose(1, 2).contiguous().reshape(b, t, c)
        return self.out(mixed)

Follow one head. q and k each have shape [batch, heads, time, 32]. Multiplying q by the transposed keys produces [batch, heads, time, time]. Each row asks: for this query position, how strongly should I match every key position?

Dividing by the square root of the head width controls score scale. softmax turns each row into positive weights that sum to one. weights @ v takes a weighted mixture of the value vectors. A weight of 0.7 means that value contributes 70 percent of the mixture at that head and query.

The triangular mask is essential. For a four-token window, the allowed rows are [1,0,0,0], [1,1,0,0], [1,1,1,0], and [1,1,1,1]. Future scores become negative infinity; their softmax weights become zero. The model can attend to the current input token because it is predicting the following token.

Multiple heads create several independently learned retrieval patterns. We join their results back into width 128, then mix them with the output projection. Explicit attention is educational; PyTorch’s optimized attention operation can replace its score-and-mix calculation when speed matters.

7. A block both gathers information and processes it

Attention moves information between positions. A feed-forward network processes the vector at each position independently. SwiGLU makes one projection pass through SiLU, multiplies it by a second projection, and maps the expanded vector back to the model width.

You can picture the multiplication as a learned gate: one branch modulates the other. Because the gate is a SiLU output, its values are not restricted to zero and one.

These equations use a column vector x for one position. Wg, Wv, and Wd correspond to gate, value, and down in the code; ⊙ means coordinate-by-coordinate multiplication. PyTorch stores batches as rows, so nn.Linear applies the equivalent transposed weight multiplication. The last two lines describe the residual block: u is the intermediate representation after attention, and y is the final result. Both Norm functions are RMSNorm with separate learned gains. Attention uses all allowed positions; FFN then works independently at each position.

SiLU⁡(u)=u1+e−uFFN⁡(x)=Wd[SiLU⁡(Wgx)⊙(Wvx)]u=x+Attention⁡(Norm⁡1(x))y=u+FFN⁡(Norm⁡2(u))\begin{aligned} \operatorname{SiLU}(u)&=\frac{u}{1+e^{-u}}\\ \operatorname{FFN}(x)&=W_d\bigl[\operatorname{SiLU}(W_gx)\odot(W_vx)\bigr]\\ u&=x+\operatorname{Attention}(\operatorname{Norm}_1(x))\\ y&=u+\operatorname{FFN}(\operatorname{Norm}_2(u)) \end{aligned}
class FeedForward(nn.Module):
    def __init__(self):
        super().__init__()
        self.gate = nn.Linear(WIDTH, FF, bias=False)
        self.value = nn.Linear(WIDTH, FF, bias=False)
        self.down = nn.Linear(FF, WIDTH, bias=False)

    def forward(self, x):
        return self.down(F.silu(self.gate(x)) * self.value(x))

class Block(nn.Module):
    def __init__(self):
        super().__init__()
        self.norm1, self.norm2 = RMSNorm(WIDTH), RMSNorm(WIDTH)
        self.attention, self.ff = Attention(), FeedForward()

    def forward(self, x):
        x = x + self.attention(self.norm1(x))
        return x + self.ff(self.norm2(x))

The two additions are residual connections. Each sublayer proposes an adjustment to an existing representation. It can preserve useful information by making a small adjustment, rather than rebuilding the whole representation from scratch.

Shapes must agree for the addition: [B,T,128] plus [B,T,128]. Inside the feed-forward branch, the vector expands to [B,T,384] and contracts back. A stack of blocks repeats this gather-and-process cycle.

8. Connect the pieces into a next-token predictor

An embedding is a lookup table with 256 rows and 128 columns. Token 99 selects row 99. Training changes that row’s numbers so they become useful for prediction.

After four blocks and a final normalization, a linear layer converts each 128-number vector into 256 scores: one for each possible next byte. Those scores are logits. They become probabilities only when we apply softmax or a loss function that incorporates it.

E is the embedding table: E[xₜ] means look up the row named by token xₜ. hₜ⁽ᴸ⁾ is the position’s vector after L Transformer blocks. Wout is the head projection, z is the vector of logits, and V is vocabulary size (256). Here v names a candidate vocabulary entry; it is unrelated to the attention value vectors. The formula numbers candidates from 1 to V for readability; the Python IDs run from 0 to V−1. The conditional prefix is limited to the model’s context window.

ht(0)=E[xt]zt=WoutRMSNorm⁡(ht(L))p(xt+1=v∣x≤t)=ezt,v∑k=1Vezt,k\begin{aligned} h_t^{(0)}&=E[x_t]\\ z_t&=W_{\mathrm{out}}\operatorname{RMSNorm}(h_t^{(L)})\\ p(x_{t+1}=v\mid x_{\leq t})&=\frac{e^{z_{t,v}}}{\sum_{k=1}^{V}e^{z_{t,k}}} \end{aligned}
class LanguageModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.embedding = nn.Embedding(VOCAB, WIDTH)
        self.blocks = nn.Sequential(*[Block() for _ in range(LAYERS)])
        self.norm = RMSNorm(WIDTH)
        self.head = nn.Linear(WIDTH, VOCAB, bias=False)
        self.apply(self.initialize)

    @staticmethod
    def initialize(module):
        if isinstance(module, (nn.Linear, nn.Embedding)):
            nn.init.normal_(module.weight, mean=0.0, std=0.02)

    def forward(self, ids):
        if ids.size(1) > CONTEXT:
            raise ValueError("Input exceeds context length")
        x = self.embedding(ids)
        x = self.blocks(x)
        return self.head(self.norm(x))

The full shape journey is [16,64] integer IDs → [16,64,128] embeddings → [16,64,128] contextual vectors → [16,64,256] next-token scores.

One vector of 256 scores is one prediction question. A batch asks 1,024 questions at once. The input embeddings and output weights are separate learned tables in this version. Initialization gives them small random values; training supplies the structure.

9. Loss turns a wrong guess into a learning signal

Suppose the correct next token is “a”. If the model assigns it probability 0.5, its loss for that position is about 0.693. If it assigns only 0.01, the loss is about 4.605. The formula is minus the logarithm of the correct token’s probability.

Cross-entropy averages those penalties. It rewards assigning probability to what actually followed the context. It does not directly grade whether a passage is true, helpful, or a good answer to a user.

B is batch size, T is the number of prediction positions, and y is the correct next token. The first line averages the penalty over the batch. The second is the same single-position loss written directly in logits; stable implementations subtract the largest logit internally. PPL is perplexity. The final expression is the gradient for one position before batch averaging: probability minus the correct-token indicator. If the correct token has probability 0.2, its gradient is −0.8; a simple descent step raises that logit. Wrong-token logits receive positive gradients, pushing them down. This is the local error signal that backpropagation sends into the model.

L=−1BT∑b=1B∑t=1Tlog⁡pb,t(yb,t)ℓ(z,y)=log⁡∑vezv−zyPPL⁡=eL,∂ℓ∂zv=pv−1[v=y]\begin{aligned} \mathcal L&=-\frac{1}{BT}\sum_{b=1}^{B}\sum_{t=1}^{T}\log p_{b,t}(y_{b,t})\\ \ell(z,y)&=\log\sum_v e^{z_v}-z_y\\ \operatorname{PPL}&=e^{\mathcal L},\qquad \frac{\partial\ell}{\partial z_v}=p_v-\mathbf 1[v=y] \end{aligned}
def prediction_loss(logits, targets):
    return F.cross_entropy(
        logits.reshape(-1, VOCAB), targets.reshape(-1))

@torch.no_grad()
def evaluate(model, data, batches=10):
    was_training = model.training
    model.eval()
    rng = torch.Generator().manual_seed(123)
    losses = []
    for _ in range(batches):
        x, y = get_batch(data, rng)
        losses.append(prediction_loss(model(x), y).item())
    model.train(was_training)
    return sum(losses) / len(losses)

reshape combines batch and time so the loss sees a table of [1,024,256] scores and a list of 1,024 correct IDs. Pass raw logits: PyTorch handles the numerically stable log-softmax calculation internally.

Evaluation reads held-out text without building a gradient graph. Its private random generator samples the same windows each time and leaves the training sampler alone. Ten batches are a quick estimate, not a full-corpus score. A uniform 256-way predictor has loss ln(256), about 5.545 nats per byte.

If you report perplexity, use exp(average loss). Here it is byte-level perplexity. A BPE model predicts different units, so its perplexity is not directly comparable. Lower validation loss means better prediction on that evaluation setup, not automatically better reasoning.

10. Training is a repeated cycle of prediction and correction

loss.backward() works backward through the recorded calculations. It computes how a small change in each parameter would change the loss. The optimizer uses those gradients to adjust the parameters.

AdamW keeps moving estimates of gradient direction and magnitude, then applies adaptive updates with separate weight decay. We will use PyTorch’s implementation so the article can focus on the model and training flow.

g collects gradients for all parameters. Clipping caps their global length at c (1.0 in the code); define the scale as one when the gradient norm is zero. m tracks the smoothed gradient, while v tracks its squared magnitude; squares, roots, and division are elementwise. The hatted quantities correct the initial bias from starting m and v at zero. η is the learning rate, λ is weight decay, and β₁/β₂ are 0.9/0.95. The update index s starts at one. AdamW uses the clipped gradient and applies decay separately, as the first factor in the final line. PyTorch adds a tiny numerical allowance in norm clipping, so the clipping equation shows the idealized rule.

g=∇θLg~=gmin⁡(1,c∥g∥2)ms=β1ms−1+(1−β1)g~svs=β2vs−1+(1−β2)g~s2m^s=ms1−β1s,v^s=vs1−β2sθs=(1−ηsλ)θs−1−ηsm^sv^s+ϵ\begin{aligned} g&=\nabla_\theta\mathcal L\\ \widetilde g&=g\min\left(1,\frac{c}{\lVert g\rVert_2}\right)\\ m_s&=\beta_1m_{s-1}+(1-\beta_1)\widetilde g_s\\ v_s&=\beta_2v_{s-1}+(1-\beta_2)\widetilde g_s^2\\ \widehat m_s&=\frac{m_s}{1-\beta_1^s},\qquad \widehat v_s=\frac{v_s}{1-\beta_2^s}\\ \theta_s&=(1-\eta_s\lambda)\theta_{s-1} -\eta_s\frac{\widehat m_s}{\sqrt{\widehat v_s}+\epsilon} \end{aligned}
def train(model, train_data, valid_data):
    optimizer = torch.optim.AdamW(
        model.parameters(), lr=1e-3,
        betas=(0.9, 0.95), weight_decay=0.1)
    for step in range(STEPS):
        warmup = 50
        if step < warmup:
            lr = 1e-3 * (step + 1) / warmup
        else:
            progress = (step - warmup) / max(1, STEPS - warmup - 1)
            lr = 1e-4 + 0.5 * (1e-3 - 1e-4) * (
                1 + math.cos(math.pi * progress))
        for group in optimizer.param_groups:
            group["lr"] = lr
        model.train()
        x, y = get_batch(train_data)
        optimizer.zero_grad(set_to_none=True)
        loss = prediction_loss(model(x), y)
        if not torch.isfinite(loss):
            raise FloatingPointError("Non-finite loss")
        loss.backward()
        nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        optimizer.step()
        if (step + 1) % 100 == 0:
            val = evaluate(model, valid_data)
            print(f"step {step+1}: train={loss.item():.3f} val={val:.3f}")
    return optimizer

zero_grad clears the previous update’s gradients; PyTorch otherwise accumulates them. model(x) makes predictions. The loss scores them. backward computes parameter gradients. Clipping rescales the collected gradients when their total norm exceeds one. step applies the update.

The learning rate is the update-size control. Warmup increases it over the first fifty steps; cosine decay then lowers it toward 0.0001. Think of beginning cautiously while the network organizes its initially random representations, then making finer changes later. A schedule can help stability; it cannot rescue incorrect targets or a missing mask.

Watch training and validation together. Training loss describes recently sampled training text. Validation loss describes fixed held-out windows. If only training improves, inspect overfitting and data mismatch before buying more compute.

11. Generation feeds the model its own output

Training supplies the correct previous tokens from the dataset. Generation has to live with its own choices. One sampled token becomes part of the context for the next prediction, so errors and repetition can compound.

Only the final position’s logits matter for the next generated token. Earlier positions already belong to the prompt. We will sample from that final distribution, append the result, and repeat.

τ is temperature, z is the final position’s logits, and ∼ means draw a random sample from the stated distribution. Categorical is the mathematical name for choosing one vocabulary entry using its probability. The zero-temperature line is a separate greedy rule, matching the if branch in generate. Temperature changes relative probabilities before sampling; it does not update any weights.

pτ(v)=exp⁡(zv/τ)∑kexp⁡(zk/τ),τ>0xnext∼Categorical⁡(pτ)xnext=arg⁡max⁡vzvwhen τ=0\begin{aligned} p_\tau(v)&=\frac{\exp(z_v/\tau)}{\sum_k\exp(z_k/\tau)},\quad \tau>0\\ x_{\mathrm{next}}&\sim\operatorname{Categorical}(p_\tau)\\ x_{\mathrm{next}}&=\arg\max_v z_v\quad\text{when }\tau=0 \end{aligned}
@torch.no_grad()
def generate(model, prompt, count=200, temperature=0.8):
    if not prompt or temperature < 0:
        raise ValueError("Use a nonempty prompt and temperature >= 0")
    model.eval()
    ids = torch.tensor([encode(prompt)], device=DEVICE)
    for _ in range(count):
        logits = model(ids[:, -CONTEXT:])[:, -1, :]
        if temperature == 0:
            next_id = logits.argmax(-1, keepdim=True)
        else:
            probabilities = (logits / temperature).softmax(-1)
            next_id = torch.multinomial(probabilities, 1)
        ids = torch.cat((ids, next_id), dim=1)
    return decode(ids[0].tolist())

Temperature controls how concentrated the probabilities become. For logits [2,1], temperature 1 produces roughly [0.73,0.27]; temperature 0.5 produces roughly [0.88,0.12]. Lower temperatures favor already-favored tokens more strongly. Temperature zero uses a separate greedy branch.

multinomial draws a token according to the probabilities. That randomness can produce variety, but it cannot create knowledge the model has not learned. Keep only the latest 64 bytes when forming a prediction; earlier bytes then fall outside direct context.

This simple generator recalculates the whole window and its positional rotations at every step. It has no key-value cache, special stop token, or chat formatting. It stops at the requested number of new bytes. These deliberate simplifications keep its behavior visible.

12. Run the whole machine and save what it learned

Now the classes and functions connect. The first log line tells you the parameter count for this byte-level configuration. The loop prints losses, and the final call completes a prompt using the trained weights.

def main():
    train_data = load_tokens("train.txt")
    valid_data = load_tokens("valid.txt")
    model = LanguageModel().to(DEVICE)
    print("device:", DEVICE)
    print("parameters:", sum(p.numel() for p in model.parameters()))
    optimizer = train(model, train_data, valid_data)
    torch.save({
        "model": model.state_dict(),
        "optimizer": optimizer.state_dict(),
        "step": STEPS,
        "config": dict(vocab=VOCAB, context=CONTEXT, width=WIDTH,
                       heads=HEADS, layers=LAYERS, ff=FF),
        "tokenizer": "utf8-bytes-v1",
    }, "tiny_lm.pt")
    print(generate(model, "Once upon a time", count=300))

if __name__ == "__main__":
    main()

Run python3 tiny_lm.py from the folder containing your text files. Early samples may be nonsense; longer runs on suitable data can develop recognizable local patterns. With only 64 bytes of context, long stories and consistent characters are asking more than this model was designed to handle.

To reload, create LanguageModel with the same constants, load the checkpoint using torch.load("tiny_lm.pt", map_location=DEVICE, weights_only=True), and pass checkpoint["model"] to model.load_state_dict. Keep the architecture and tokenizer together with the weights.

This checkpoint supports reloading the model and contains optimizer state. Exact training continuation needs additional code to restore that optimizer, the schedule position, and all relevant random-generator states. Saving a dictionary alone does not make resume automatic.

The first success criterion is that the whole pipeline works and its held-out loss improves. Before a larger run, overfit one tiny batch and check causality: change later input tokens and confirm earlier logits remain unchanged. Those checks catch mistakes that a plausible-looking story can hide.

13. Upgrade the tokenizer: why BPE exists

Our byte model spends three prediction steps spelling “cat”. If a tokenizer learns a single token for a common piece, the model can represent that piece in one step. A fixed-length context then covers more text, though a larger vocabulary also makes the embedding and output tables larger.

BPE begins with the 256 byte tokens. Count adjacent pairs, merge the most frequent pair into a new token, count again, and repeat. If “a” followed by “b” is frequent, create a token containing the bytes “ab”. Later, that token can merge with another one.

The standalone experiment below makes the mechanics visible. Save it as bpe_demo.py, separately from the complete byte model above. It operates on one small byte stream and intentionally omits pre-tokenization, document boundaries, special tokens, and scalable pair-count updates.

C(a,b) counts occurrences of adjacent token IDs a and b in the current token stream. arg max selects the pair with the highest count. The star marks the winning pair, not multiplication. Replace that pair with a new token, recount on the updated stream, and repeat. If counts tie, the sample code uses the pair itself as a deterministic tie-breaker. Each token’s bytes remain the concatenation of the bytes represented by its children.

(a∗,b∗)=arg⁡max⁡(a,b) C(a,b)(a^*,b^*)=\underset{(a,b)}{\arg\max}\ C(a,b)
from collections import Counter

def replace_pair(ids, pair, new_id):
    out, i = [], 0
    while i < len(ids):
        if i + 1 < len(ids) and tuple(ids[i:i+2]) == pair:
            out.append(new_id)
            i += 2
        else:
            out.append(ids[i])
            i += 1
    return out

def learn_bpe(text, merge_count=20):
    ids = list(text.encode("utf-8"))
    vocab = {i: bytes([i]) for i in range(256)}
    merges = []
    for _ in range(merge_count):
        counts = Counter(zip(ids, ids[1:]))
        if not counts:
            break
        pair = max(counts, key=lambda p: (counts[p], p))
        new_id = len(vocab)
        vocab[new_id] = vocab[pair[0]] + vocab[pair[1]]
        ids = replace_pair(ids, pair, new_id)
        merges.append((pair, new_id))
    return vocab, merges

def bpe_encode(text, merges):
    ids = list(text.encode("utf-8"))
    for pair, new_id in merges:
        ids = replace_pair(ids, pair, new_id)
    return ids

def bpe_decode(ids, vocab):
    return b"".join(vocab[i] for i in ids).decode("utf-8")

Try vocab, merges = learn_bpe("banana banana banana", 8), then inspect the bytes in vocab. Encode a new string with bpe_encode(text, merges), and recover it with bpe_decode(ids, vocab).

Encoding must reuse the training-time merge order. It must not invent a new merge ranking for each input. The ID-to-bytes table is the decoder’s dictionary. Concatenate token bytes before UTF-8 decoding because a token may contain only part of a character.

To use BPE in the model, learn merges on training text only, freeze them, encode both data splits with those merges, and set VOCAB to the actual vocabulary size. Create and train a fresh model whose input and output tables fit that vocabulary. Save the merges and vocabulary with its checkpoint.

Token IDs change meaning with the tokenizer. Replacing the tokenizer underneath an already-trained byte model breaks that agreement. This is why tokenizer artifacts belong to the model, just as much as its weights do.

What changes when you scale up?

The reference project that informed this walkthrough used a 4,096-token BPE vocabulary, 128-token context, width 128, four layers, and four heads. Its separate input and output tables brought the total to about 1.9 million parameters. One saved 6,000-update run reported held-out loss about 2.40 on ten sampled batches. Those numbers describe that BPE experiment, not the byte model in this article.

The broader engineering work grows quickly: efficient data preparation, stable mixed-precision training, optimized attention, better evaluations, checkpoint recovery, and inference caching. Increasing context makes the explicit attention matrix grow with the square of sequence length. Doubling context creates four times as many entries in that matrix.

A base language model learns continuation. Instruction-following and assistant behavior require further data, training, and evaluation. A small model’s ability to produce a story is a satisfying result; its contradictions, repetition, and mistakes are evidence about what it still lacks.

Trace a single prediction all the way through: a byte becomes an ID, an ID selects a vector, attention retrieves context, a feed-forward layer transforms it, the output head ranks continuations, and the loss tells the optimizer how wrong that ranking was. Generation runs the same predictor repeatedly, feeding its choices back in.

That is the complete machine. Every larger experiment starts from these same questions: what are the tokens, what can each position see, what is being predicted, and what evidence shows that it is learning?

Originally published on X.