Coding a Language Model from Scratch - Transformers & Tokenizers

October 2026

Inspired by Parameter Golf and CS336, thought I'd build a language model from scratch to complement my ongoing AI research.

image

At a high-level, we'll:

  1. Build a Tokenizer - create our tokenizer & tokenize our datasets
  2. Implement the Linear Layer - implement SwiGLU, attention, RoPE, etc
  3. Build the Transformer - define our loss function, optimizers, learning rates
  4. Run the training loop - set up data loading, checkpointing
  5. Decode - see what outputs look like at different checkpoints

We'll start training locally on an M5 MacBook and move to RunPod instances as our compute needs increase.

Note: since this post ended up quite long, here’s a brief Table of Contents:

Let’s start with our tokenizer.

Byte-Pair Encoding

The first thing we'll train is our byte-pair encoder.

image

Quick review of BPE

Our transformer doesn't operate on words, it operates on tokens -- IDs that correspond to different "words" in our vocabulary that we turn a dataset or prompt into via tokenization.

image

The way we get this vocabulary is by using byte-pair encoding (BPE).

BPE starts with individual bytes -- 256 one-byte characters as our vocab to start -- then goes through the most common pairs and merges them, and keeps doing this until we hit a certain vocabulary size.

image

It could almost be considered a form of vocabulary compression:

  • if we merely had a small vocab of characters our token count would be huge and therefore expensive to process
  • while an entire-word vocabulary would be enormous and need constant updates as new words were invented
image

Sub-word tokens hit the sweet spot, saving us from the sparse-graph of an enormous word-level vocabulary while avoiding the unnecessary compute of a too-small vocab with excessive tokens.

And BPE ensures the sub-word chunks used are those most frequently represented.

Our train_bpe() function will return two things:

  1. vocab - dict[int, bytes]
    1. these are the final merged tokens that make up our vocab
  2. merges - list[tuple[bytes,bytes]]
    1. every merge starting from the original 256 one-byte characters that gives us our vocab
    2. this is not merely an artifact for testing, but actually used during encoding to take our corpus through the same merges

Then we actually go run our byte-pair encoder, going through merges until we hit max vocab size.

Pre-token vs token vs token ID

There is actually a step before BPE called pre-tokenization -- where we split the corpus by:

  1. documents (via special tokens) - so we don't merge across pages or include special tokens in our merge counts
  2. words (via our PAT regex) - so we don't merge across words
image

This gives us three distinct concepts:

Concept
Meaning
Example
Pre-token
Word-like chunk from regex
" unexpected"
Token
Byte sequence recognized by BPE vocabulary after merges
b" un", b"expected"
Token ID
Integer representing a token
7427

Running our Byte-Pair Encoder on TinyStories and OpenWebText

Training our byte-pair encoder on TinyStories with a 10,000 limit on vocab size goes pretty smoothly:

Running on OpenWebText with a 32k max vocab size yields a different story:

Pre-tokenization is fine, but 1 minute and 31 seconds just to get 1% of the BPE merges means 2.5 hours for just the validation set alone.

We definitely need to speed things up.

Speeding up BPE

Our naive implementation is slow because we repeat two expensive operations for each merge:

  1. Recount every adjacent pair across every unique pre-token.
  2. Rebuild every pre-token, even if it doesn't contain the pair being merged.

To avoid this we'll track:

pair_counts - a frequency dictionary

heap - to efficiently find the most frequent pairs instead of using max()

pair_to_words - our inverted index/map for each pair to the pre-tokens containing it, which lets us find and change only the required pairs instead of all pairs

pair_to_words = {
    (b'a', b'b'): {12, 45, 78},
    (b'b', b'c'): {12, 91},
}

So instead of our old approach:

Merge 1 → Scan every pre-token
Merge 2 → Scan every pre-token
Merge 3 → Scan every pre-token
...
Merge 31,743 → Scan every pre-token

We now do:

Merge "th"
    ↓
Find only pre-tokens containing (t, h)
    ↓
Update those pre-tokens
    ↓
Adjust affected pair counts
    ↓
Extract next highest-frequency pair from heap

Running this gets us a comically large speedup, 17 seconds instead of 2.5 hours!

However running on the full OpenWebText training set shows a RAM spike to 80GB when merely trying to read the full corpus, so we need some kind of streaming/chunking.

Implementing 8Mb chunking gets us what we need:

The longest token is a bit weird, but since this is OpenWebText this could easily be a scraping artifact, our timelines:

Pre-tokenization: 19 min 53 sec Merging: 3 min 16 sec

With pre-tokenization as the new bottleneck, multiprocessing could help but we'll skip for now as it's unlikely to inhibit our progress.

Encoding and Decoding

With our byte-pair encoder done and run on our corpus, we can use the produced vocab and merges to create our Tokenizer class that encodes and decodes:

image

Two main functions here:

  1. Encoding (text -> token IDs): uses the ordered merges to determine token boundaries, then the reverse vocabulary mapping (bytes -> ID) to produce token IDs
    1. more compute-expensive than decoding at tokenizer level b/c it must determine which merges to apply
  2. Decoding (token IDs -> text): uses only vocab (ID -> bytes). Concatenates the bytes, then decodes the complete byte sequence using UTF-8.

And the initialization:

image

Why do we need merge_ranks?

During encoding, multiple adjacent byte pairs might be eligible for merging. It's important that we prioritize pairs according to the order in which they were learned during BPE training, not their current frequency.

We could just go down the merges list in order, but this would involve inefficiently checking all 32,000 merge rules for every pre-token.

Instead merge_ranks lets us examine only the adjacent pairs currently present with O(1) average-time lookups, select the highest priority one, merge it, and repeat.

How the training corpus and vocab size affect efficacy

We have two tokenizers, one trained on TinyStories and the other on OpenWebText.

Running each on 10 randomly sampled documents from each dataset yields the following:

TinyStories tokenizer - 4.15 bytes/token (8,733 bytes ÷ 2,106 tokens)
OpenWebText tokenizer - 4.46 bytes/token (32,949 bytes ÷ 7,389 tokens)

Using the TinyStories tokenizer on the same OpenWebText sample:

TinyStories tokenizer on OpenWebText sample: 3.34 bytes/token

Compression is reduced to 3.34 bytes/token, producing 33.5% more tokens. A good example of how important the training corpus and vocabulary size are, and how it relates to the data being tokenized.

Tokenizing and next steps

So we've trained a tokenizer on a dataset, added encoding/decoding abilities (with chunking), and now we'll actually use this tokenizer to tokenize the datasets themselves.

What's output by the tokenizer -- the token IDs -- are what the transformer trains on to learn to predict the next token.

Now we can encode our datasets and store these eventual "tokenized inputs" as NumPy arrays of datatype uint16, since 65,536 values are more than sufficient for our 32k vocab size and only requires 2 bytes per token.

Now we'll move on to the transformer itself.

Building the Transformer

We're going to create a transformer that:

  1. uses an input embedding to convert token IDs to dense vectors
  2. passes the embedded tokens through num_layers Transformer blocks
  3. then applies a learned linear "output embedding" projection to produce the predicted next-token logits
image

Creating our Linear Layer

First we'll create a Linear class that will act as a reusable building block used throughout both attention and feed-forward networks.

In attention, this might look something like the following:

self.Wq = Linear(d_model, d_model)  # Query
self.Wk = Linear(d_model, d_model)  # Key
self.Wv = Linear(d_model, d_model)  # Value
self.Wo = Linear(d_model, d_model)  # Output

where Q, K, and V transform the input into query, key, and value representations, and Output projects the combined attention-head outputs back into the model's representation space.

While feed-forward might look something like:

self.W1 = Linear(d_model, d_ff)
self.W3 = Linear(d_model, d_ff)
self.W2 = Linear(d_ff, d_model)

where W1 projects into a larger feature space for the activation branch, W3 projects back into the same space for the gating branch, and W2 projects the combined result back to d_model dimensionality.

Implementation

We'll start with a simple Linear class:

nn.Module is PyTorch's base class for neural network components. It automatically tracks parameters and integrates with autograd.

nn.Parameter tells PyTorch that self.weight contains learnable parameters that should receive gradients during training

forward() performs the linear transformation

What are in_features and out_features?

These define the layer's shape:

linear = Linear(in_features=3, out_features=2)

For a visual example:

image

This is how we can expand dimensionality like in feed-forward, or project hidden representation into logits for vocab tokens in our final output, etc.

What is Xavier?

Xavier initialization chooses the scale of random weights based on the layer's input and output dimensions.

The goal of Xavier-style initialization is to start the network in a numerically well-behaved state so gradient-based learning can proceed effectively.

# Xavier-style truncated normal initialization
std = math.sqrt(2 / (in_features + out_features))

nn.init.trunc_normal_(
	self.weight,
	mean=0.0,
	std=std,
	a=-3 * std,
	b=3 * std,
)
  • mean=0 - random weights are centered around zero
  • std=std - use the scale calculated from the layer dimensions
  • a=-3*std - no initialized weight below -3 standard deviations
  • b=3*std - no initialized weight above +3 standard deviations

Truncating removes extreme values that might destabilize training by slightly reducing the actual variance compared with an un-truncated normal distribution.

image

Note: Xavier helps, but doesn't guarantee stable training.

Why do we need a transpose?

The reason we use a transpose in x @ self.weight.T is because of the difference in classic linear algebra notation vs PyTorch convention, namely that one uses column vectors while the other uses row vectors:

image

Since W is stored as (out_features, in_features) because of PyTorch's row-oriented input vectors, we use weight.T during multiplication to reconcile.

A cheatsheet on when you need a transpose:

image

Add the embedding module

Next we'll add a simple embedding module to our transformer:

which is just a really simple matrix of dimensions:

  • number of rows = vocabulary size (one for each possible token ID)
  • number of columns = dimension size (how many dimensions we want to represent each token)

e.g. 10,000 tokens represented by 512 dimensions each.

Unlike a Linear layer, there is no matrix multiplication here. It's simply a lookup operation (with PyTorch's tensor indexing retrieving the appropriate rows in parallel):

return weight[token_ids]

Initial values are just random from a truncated normal distribution, and during training the gradients update the embedding vectors.

So are embedding models just an artifact of training LMs?

Embedding models take input tokens and output a vector representation.

A language model does the same thing, but auto-regressively decodes that vector representation into token probabilities, then repeats for the next token, and the next, so on.

But an embedding model isn't merely just an artifact that enables auto-regressive decoding, usually you take an already-trained Large Language Model, then fine-tune it to output the embedding vector so it has better performance for semantic representation.

But (from my understanding) you're still re-using the expensively-trained large language model.

Layer Normalization

Next we'll create our normalization block.

If you recall from our diagram, each transformer block has two sub-layers: a multi-head self-attention mechanism and a feed forward network.

image

The original Transformer paper uses a residual connection around each of the two sub-layers, aka a "post-norm" architecture since layer normalization is applied to the sub-layer output.

image

But later work found moving layer normalization to the input of each sub-layer instead improves training stability.

image

The output of each sub-layer is then added to the sub-layer input via the residual connection -- an intuition here is that of a clean "residual stream" without any normalization going from input embeddings to final Transformer output, which is said to improve gradient flow.

Since this pre-norm variant is now standard, that's what we'll implement.

RMSNorm

During training, activation magnitudes can become excessively large or small as information flows through successive Transformer layers.

So we'll create RMSNorm, which normalizes each token's vector to a consistent scale, allowing the model to learn how much to scale each dimension afterward.

To implement, we take a vector, calculate its root mean square, and then divide each element by this -- keeping the vector's RMS approximately equal to 1.

image

And the code, with the weights initially starting with ones b/c we initially want normalization to happen without any additional learned scaling.

The key insight is that RMSNorm processes every token independently, condensing each token's feature vector into one RMS value, then uses that value to normalize the original vector without changing its dimensions.

A quick recap of the input tensor

Suppose we have:

x.shape = (2, 3, 4)

# (batch_size, sequence_length, d_model)

These dimensions represent:

  • batch_size (2) - the number of independent token sequences processed in parallel
    • could be different users’ requests in inference, or all from the same training dataset during training (where sequences in a batch don't benefit from learnings from the other sequences in a batch)
  • sequence_length - number of tokens in each sequence (e.g. a prompt sentence)
  • feature dimension (d_model) - number of numerical features representing each token in a given layer (e.g. 512)

RMSNorm example

In this example:

2 x 3 x 4 = 24

Think of this as two matrices, one for each sequence:

image

Each row represents one token's embedding/activation vector, and RMSNorm will process each of these six rows independently.

We can also track the shape after every operation in our RMSNorm.forward():

image

After calculating our scalar, we then divide the original features by this scalar -- broadcasting to get our number of values back to 24.

A real transformer would look more like the following:

batch_size = 32
sequence_length = 256
d_model = 512

General Mental Model

For a tensor of shape:

(B, T, D)

where:

  • B = batch size
  • T = sequence length
  • D = feature dimension

You can think of the following:

RMSNorm - summarizes each D-dimensional token vector into one scalar, then broadcasts it back so input and output shapes remain: (B,T,D)

Linear - changes the feature dimension, e.g. (B,T,512) -> (B,T,2048)

Embedding - adds a feature dimension to integer token IDs, e.g. (B,T) -> (B,T,512)

Attention - mixes information across token positions within each sequence

The main distinction here is that RMSNorm reduces dimensions temporarily to calculate a statistic -- not compress the representation -- and retains all 512 feature dimensions for every token throughout the operation.

Feed-Forward Network (SwiGLU)

Next we'll add our non-linear activations.

The original Transformer paper used ReLU activations with the feed-forward layer's dimensionality typically 4x the input dimensionality.

We will use the modern "SwiGLU" activation, which combines the SiLU activation function (like ReLU but smooth at zero) with a gating mechanism called a Gated Linear Unit (GLU).

Why?

Because Noam Shazeer (now a co-worker) proposed this combination and conducted experiments showing their performance to exceed baseline ReLU and SiLU, with the following quote:

“We offer no explanation as to why these architectures seem to work; we attribute their success, as all else, to divine benevolence.”

We will also use the canonical 8/3 x d_model for our feed-forward dimensionality. [1]

Intuition for SwiGLU and gating

Here's a breakdown of the mathematical notation:

image

but I find it easier to understand in the following form:

image

We basically split input x into two branches, a gate and value branch -- both branches independently transform the same input vector, but serve different purposes:

  1. Value branch (W3x) - produces the features/content we want to process
  2. Gate branch (SiLU(W1x)) - produces a scaling factor for each of those features

The gate branch controls how much of each feature from the value branch passes through, interacting through element-wise multiplication:

image

Here the gate:

  • Suppresses feature 1 by 90%.
  • Amplifies feature 2 by 50%.
  • Completely suppresses feature 3.

The combined vector then passes through W2, which mixes the features and projects them back to d_model.

For an example input:

x.shape = (32, 256, 512)

we have the following output shapes following each operation:

image

Notice that batch size and sequence length never change, only the feature dimension expands and contracts.

Why have both a gate and value branch?

The difference in equation sheds some light here:

image

The extra branch in SwiGLU allows multiplicative interactions between learned features, giving the network additional expressive capacity.

SiLU also isn't bounded between 0-1, so it can amplify, suppress, reverse etc -- not just an on/off switch.

The simplest mental model I keep in mind:

value branch = signal

gate branch = modulation of that signal based on input

Positional Embeddings (RoPE)

Next we'll inject token positional information into the model using Rotary Position Embeddings (RoPE).

This is how the model can receive and learn from information about the distances between tokens, like discovering that "She" in position 2 corresponds to "Alice" in position 1000.

An intuitive understanding of RoPE

The problem RoPE solves is: how do we encode token position for attention such that:

  1. the positional effect is relative, not absolute
  2. this effect is achieved through an ordinary dot product

Requirement #1: Relative position - it shouldn't matter if "She" and "Alice" are position 3 and 8 or position 1000 and 1005, all that should matter is that they're 5 apart.

Requirement #2: Ordinary dot product - the dot product is the hot loop of attention, therefore we don't want even tiny complications, but an efficient, KV cache-friendly, algebraically simple-and-guaranteed method of calculation

Previous solutions failed on one of these requirements (sine, absolute, relative embeddings), but RoPE satisfied both.

Here's an analogy showing how relative embeddings fail on lack of independent query / clean dot product:

image

And more detail on why the clean dot product solution is so important:

image

RoPE creates the full spectrum of varying-precision levers per-token for attention to learn position

Recall that RoPE adds positional information specifically for attention, and attention doesn't operate on tokens, but on the token's feature vector, aka the 512 or so values representing that token split into 64 dimensions for each head.

By dividing each head’s feature vector into pairs, you'd get e.g. 32 different pairings, each of which gets assigned its own rotation speed.

image

Remember, this is all within a single token, meaning every token has all 32 feature pairs -- not just one frequency/rotation speed per token.

This gives each token 32 different levers of varying rotational precision which attention can use to learn positional information.

Why different rotation speeds?

We use different rotation speeds so learning has enough precision to capture both nearby token positions and far-away ones.

This stems from the fact that we use cosine and sine for their geometric properties:

  1. that 2D rotation matrices preserve vector norms
  2. they turn absolute positions into relative distances during a dot product (recall our requirements above)

But using cosine also means we repeat values every 2\*pi radians, so:

  • Fast rotation speeds - more clearly show nearby tokens differences, but cause big-distance tokens to lap themselves
  • Slow rotation speeds - can capture big distances between tokens without overlap, but lack of precision hurts representation of closer tokens

By including the full spectrum of speeds across the feature pairs, the attention Q/K projection matrices can learn to organize information across feature pairs with different RoPE rotation frequencies.

Through training, features that benefit from fast or slow positional sensitivity can become represented in the corresponding dimensions, and retrieved via a simple dot product -- allowing us to attend to both close and far tokens in a relative and efficient manner.

Scaled Dot-Product Attention

Next we'll implement scaled dot-product attention, the first step of which is implementing the core building block of softmax.

Softmax

This merely takes an unnormalized vector of scores and turns it into a normalized distribution.

image

and the function:


def softmax(x: torch.Tensor, dim: int) -> torch.Tensor:
    # Subtract maximum for numerical stability
    max_value = x.max(dim=dim, keepdim=True).values
    shifted = x - max_value

    # Exponentiate each value
    exp_values = torch.exp(shifted)

    # Normalize so values sum to 1
    return exp_values / exp_values.sum(dim=dim, keepdim=True)

Note: we subtract the maximum because exponentiating large numbers can cause floating-point overflow, and subtracting the max produces the exact same probabilities due to cancellation in both the numerator and denominator.

E.g. instead of:

x = [1000, 1001, 1002]

we use:

shifted = [-2, -1, 0]

Attention

Now we can actually implement attention, the core mechanism that allows transformer tokens to exchange information.

It's defined as:

image

which is basically:

  1. Q and K - compute similarity scores between tokens
  2. Scale - divide scores by sqrt(d_k) to keep their magnitudes controlled
  3. Mask - apply a mask to prevent decoder-only use from attending to future tokens
  4. Softmax - convert scores into attention weights
  5. V - multiply these weights by the value vectors to get weighted values

Our implementation:

For a visual representation of the causal mask:

image

Attention itself is an in-depth topic, and for understanding Q, K, and V I highly recommend 3Blue1Brown's video to acquire an intuitive grasp of the operation.

MultiHead Self-Attention

With the core attention calculation implemented, now we'll build the module that:

  1. Uses our Linear class to generate Q, K, and V
  2. Splits these vectors into multiple attention heads
  3. Applies RoPE to Q and K
  4. Runs scaled dot-product attention independently for each head with a causal mask
  5. Concatenates the results and projects them back to d_model

A nice visual:

image

Multiple attention heads allow the model to learn different attention patterns simultaneously, at an abstract level this could be:

  • one head focused on grammar
  • another focused on colors and shapes
  • another focused on nouns and relationships

The learned attention patterns aren't this explicit, but the above provides an intuitive example of what's happening behind the scenes in each head.

Why the need for multiple heads?

Intuitively it's so each head can learn different relationships, but if you're like me you may also wonder why that can't be accomplished in a single vector.

So what's the mathematical difference with the split?

The answer is softmax, by computing it per-head we allow each head to attend to different tokens than if all of them were in a single softmax.

Transformer Block

We now have all the components needed for a full Transformer block:

  • RMSNorm
  • Multi-head self-attention
  • RoPE
  • SwiGLU feed-forward network

which we can combine into the full transformer block:

image

to eventually slot into our full language model:

image

The code tying it all together:

The Full Transformer LM

With TransformerBlock created now we can create our full TransformerLM:

Note the creation of the LM head:

self.lm_head = Linear(d_model, vocab_size)

This is what transforms each token's 512-dimensional hidden state into 10,000 scores, one for every possible next token.

Importantly, these are logits -- not probabilities.

We don't apply softmax here because the cross-entropy loss function we'll implement later operates directly on logits.

And with that we have a full transformer architected, ready to be thrown in a training loop.

Tracing our FLOPs and matmuls

Before we begin our training loop, let's quickly trace our code to gain some intuition behind where compute goes for different architectures.

Here are the matrix multiplications in one Transformer block:

image
  • T = sequence length, number of tokens being processed per sequence
  • H = number of attention heads

At small context length, the FFN consumes more matmul FLOPs than attention.

At large context, since T^2 for attention, it becomes proportionally more expensive.

Calculating this for the following model configurations:

image

We get the following:

image

Increasing model size shifts the computation burden toward the Transformer blocks, particularly SwiGLU and the attention projections.

LM head's share drops substantially, and unsurprisingly the relative share of the attention score/value multiplications also decreases at fixed context length.

Now if we 16x the context length for GPT-2 XL from 1,204 to 16,384:

image

We see the following:

  • attention matmuls FLOPs jump from 9.2% of FLOPs to 61.7%
  • forward-pass matmul FLOPs increase from 3.52 trillion to 133.58 trillion (38x)

Attention becomes the dominant computational cost since it scales quadratically with sequence length, while the projection and FFN operations scale linearly.

Main lessons from this exercise

The big takeaway is that model width and context length create different scaling bottlenecks:

Increasing…
Main computational consequence
(D), model width
Projection and FFN FLOPs grow approximately quadratically
(F), FFN width
FFN parameters and compute grow linearly in (F)
(L), layer count
Transformer block compute grows linearly
(T), context length
Attention score/value matmuls grow quadratically
(B), batch size
Total forward-pass compute grows linearly
(H), attention heads, fixed (D)
Matmul FLOPs stay approximately unchanged when (d_k=D/H)

A further distinction matters for performance engineering: FLOPs don't fully determine runtime or memory usage -- attention's quadratic intermediate score matrix, kernel efficiency, memory bandwidth, and the ability to fuse operations all matter.

This is why long-context inference and training benefit from techniques such as FlashAttention, which reduces memory traffic and avoids materializing the full attention matrix, even though the attention arithmetic still scales quadratically with sequence length.

Training our Transformer LM

We now have our:

  1. tokenizer - to turn our data into tokens
  2. model - the transformer itself

What's left:

3. Loss - define our loss function (cross-entropy) 4. Optimizer - define optimizer to minimize this loss 5. Training loop - supporting infra, load data, save checkpoints, manage training

Cross-Entropy Loss

Defining our loss function is the first step towards training.

At its core, the transformer is just a dumb machine that does one thing: minimizes this loss function.

We use a cross-entropy loss function:

image

where the probability p is defined via:

image

which can be expanded to:

image

Breaking it down

All this is really saying is take the logit corresponding to the correct next token ID, e.g. say sat is correct:

image

and raise Euler's number e to that logit to get the numerator.

image

Then exponentiate every vocabulary logit and add them all together to get your denominator.

image

Then divide the numerator by denominator to get your final probability.

image

Now we can use the cross-entropy loss function's negative log

image

And this is the loss for this single prediction.

Now we repeat for all training sequences and for every token position within that sequence and average.

In plain English:

For every training sequence, and for every token position within that sequence, calculate the negative log probability that the model assigns to the correct next token. Add all those losses together and divide by the total number of predictions to get the average loss.

The key idea is that cross-entropy doesn't merely check whether the model's highest-probability guess was correct. It measures how much probability the model assigned to the correct token.

This gives gradient descent a continuous learning signal, even when the model predicts the wrong token as most likely.

One forward pass = thousands of predictions

Remember, one forward pass produces thousands of predictions, if:

batch_size = 32
seq_len = 256

then a single forward pass produces:

32 x 256 = 8192 predictions

each with its own cross-entropy loss, since it's predicting every token in a sequence and all sequences in a batch.

image

And because of causal attention, one forward pass can make all 256 next-token predictions per sequence simultaneously, without running the transformer 256 separate times.

The SGD Optimizer

With our loss function created we can start exploring optimizers.

The simplest gradient-based optimizer is Stochastic Gradient Descent (SGD):

image

with the definitions:

image

Simply multiply the gradient by the learning rate (which we decay over time) to get our update:

To get a feel for how this works we can run a simple experiment:

def run_experiment(lr, initial_weights):
    weights = torch.nn.Parameter(initial_weights.clone())
    optimizer = SGD([weights], lr=lr)

    print(f"\nLearning rate: {lr}")

    for step in range(10):
        optimizer.zero_grad()

        loss = (weights ** 2).mean()

        loss.backward()

        optimizer.step()

        print(f"Step {step + 1}: loss = {loss.item():.6f}")

with the most important part being:

loss = (weights ** 2).mean()
loss.backward()
optimizer.step()

The ideal solution is for every weight to equal zero:

  • loss measures how far the weights are from zero
  • loss.backward() computes how the loss changes with each weight
  • optimizer.step() moves the weights in the direction that should reduce the loss

Running this experiment across learning rates yields the following:

image

This is why picking the right learning rate is so crucial to training stability and convergence.

AdamW

While SGD is good for building intuition about learning rates and optimizers, modern language models are typically trained with more sophisticated solutions like the popular Adam optimizer.

We will use AdamW, which introduces state for smoother learning via two moments that are determined on past gradients and weight decay.

AdamW introduces three improvements on SGD:

  1. First moment(m) - exponential moving average of gradients (smooths the update direction)
  2. Second moment (v) - EMA of squared gradients, helps adjust update magnitudes for individual parameters
  3. Weight decay - gradually shrinks weights toward zero, independent of gradient update (this is what turns Adam into AdamW)
image

Then we also have bias correction + adaptive update to compensate for starting these moving averages at zero:

image

What does this achieve?

Consider two parameters:

image

Even though both have the same smoothed gradient, parameter B receives a smaller update because its historical squared-gradient estimate is much larger.

This is the adaptive part of AdamW: the optimizer scales each weight's update according to its own gradient history.

SGD uses the current gradient directly.

AdamW smooths gradients over time and normalizes their update magnitudes using historical squared gradients.

This is why AdamW needs more memory, we're storing two additional tensors (m and v) for every trainable parameter.

How much memory does AdamW training require?

Count everything that must be stored in GPU memory.

  1. Parameters - all model weights (P). Each FP32 weight takes 4 bytes.
  2. Gradients - one gradient per parameter, another 4 bytes.
  3. Optimizer state - AdamW stores two additional values (m and v) per parameter, another 8 bytes
  4. Activations - intermediate tensors produced by each layer, multiplied by 4 bytes

AdamW Memory = ~16P + Activation Memory

Learning Rate Scheduling

Before we move on to our training loop we need to set our learning rate schedule.

The learning rate value that leads to the quickest decrease in loss often varies during training.

It's typical to use a learning rate schedule, where we start with a bigger learning rate, making quicker updates in the beginning, and slowly decay it to a smaller value over time:

image

Some common stages:

  1. Warmup - gradually increase the learning rate from 0 to its maximum, avoiding overly aggressive updates early in training
  2. Cosine decay - gradually reduce the learning rate using a smooth cosine curve
  3. Final - keep the learning rate at its minimum

A simple scheduler implementation:

The parameters:

  • it - current training iteration
  • max_learning_rate - peak learning rate
  • min_learning_rate - final learning rate
  • warmup_iters - number of warmup steps
  • cosine_cycle_iters - step at which cosine decay finishes

How this interacts with AdamW

AdamW already reads the current learning rate every time optimizer.step() runs.

This scheduler is what adjusts it before each step in the training loop.

for step in range(num_steps):
    lr = get_lr_cosine_schedule(
        step,
        max_learning_rate=3e-4,
        min_learning_rate=3e-5,
        warmup_iters=100,
        cosine_cycle_iters=num_steps,
    )

    for group in optimizer.param_groups:
        group["lr"] = lr

    optimizer.zero_grad()
    logits = model(inputs)
    loss = cross_entropy(logits, targets)
    loss.backward()
    optimizer.step()

Gradient Clipping

During training, we sometimes hit training examples that yield large gradients, which can destabilize training.

To mitigate this we can use a technique called gradient clipping, where we enforce a limit on the gradient's L2 norm after each backward pass:

  • if the norm is below our threshold, leave the gradients unchanged
  • if it exceeds the threshold, scale every gradient down by the same factor

Note: we don't calculate a separate clipping threshold for each weight matrix, it's one global norm across the entire model.

This is because we want to limit the magnitude of the entire model's gradient while preserving its direction.

Final infrastructure

We're nearly at the end here, just two final bits of infrastructure to facilitate training:

  1. our Data Loader
  2. Checkpointing

Data Loader

First, a common practice is to build a data loader which turns our giant sequence of tokens into a stream of batches:

which we then point to our saved uint16t datasets using memory mapping:

dataset = np.memmap(
    "data/ts_train.bin",
    dtype=np.uint16,
    mode="r",
)

inputs, targets = get_batch(
    dataset=dataset,
    batch_size=32,
    context_length=256,
    device="cpu",
)

print(inputs.shape)   # (32, 256)
print(targets.shape)  # (32, 256)

This is useful in a few ways:

  1. we ensure all training sequences are the same length
  2. np.memmap avoids loading the entire tokenized dataset into RAM, the OS reads the requested portions as needed
  3. we're able to randomly sample across our dataset

Why random sampling?

If we train in consecutive order, we might introduce bias due to the natural organization in our datasets (e.g. maybe math is learned first before reading, etc).

In general, randomization produces more stable and representative gradient updates.

In our code we're doing pure stochastic for simplicity, but at a frontier lab we'd likely do a seed-reproducible random order without replacement (so we parse the whole corpus with no duplicates).

Also note, we want to ideally shuffle sequences or documents, not individual tokens within them:

Original:
[A1, A2, A3] [B1, B2, B3] [C1, C2, C3]

Shuffled document order:
[C1, C2, C3] [A1, A2, A3] [B1, B2, B3]

Checkpointing

We also need to save models as we train, both to:

  • avoid losing training progress if a job crashes or gets interrupted
  • as well as just having access to intermediate models for research purposes.

What needs to be saved?

  1. Model weights - everything our Transformer has learned so far
  2. Optimizer state - AdamW's m, v, and step counters
  3. Training iteration - so we know where to resume, including the learning-rate schedule
  • optimizer.state_dict() and model.state_dict() return dictionaries containing configurations and state
  • torch.save() and torch.load() both serialize and reconstruct the checkpoint to/from disk
  • load_state_dict() restores the saved values into the existing model or optimizer

We'll save checkpoints at certain step intervals.

On to the Training Loop

At last we can assemble all our components:

  • tokenizer
  • transformer model
  • optimizer

At a high-level here's what we're doing:

Tokenized dataset (.bin)
        ↓
get_batch()           Sample input and target sequences
        ↓
TransformerLM()       Forward pass → logits
        ↓
cross_entropy()       Calculate loss
        ↓
loss.backward()       Calculate gradients
        ↓
clip_gradients()      Limit extreme gradients
        ↓
AdamW.step()          Update model weights
        ↓
Repeat

With more detail:

We'll ensure hyperparameters are easy to specify as command-line arguments for easy experimentation, but with that we can run our first train script with:

uv run python train.py \
  --steps 5000 \
  --batch-size 32 \
  --context-length 256 \
  --eval-interval 100

Training a 40,000 and 5,000 step model

Running the command above on TinyStories took about 1.5 hours on my M5 MacBook Air, and we processed 5000 x 32 x 256 = 40,960,000 training tokens.

I also kicked off a 40,000 step run that ran for 8-12 hours overnight, here are the metrics from both runs:

Significantly lower loss, 1.4 vs 1.9

By integrating Weights & Biases (now CoreWeave Forge), we can visually see how our validation and training loss continues trending downward, with the 40,000 step run continuing after the 5,000 step run stops.

image

And our learning rate schedule visualized across runs:

image

Things look good:

  • Our training loss generally decreased
  • Validation loss decreased
  • Loss stayed finite (no NaN or inf)
  • Checkpoint saving / restoration worked
  • Our metrics.jsonl correctly recorded steps, losses, and elapsed time for plotting learning curves

With our models trained let's move on to generation.

Generating Text (aka Decoding)

Now that we can actually train models, let's enable text-generation by writing the inference code that turns next-token predictions into actual sentences.

During training, our model predicts the next token at every position simultaneously.

During generation, we instead predict one token, append it to the prompt, and repeat.

Prompt: "Once upon a time"

Model predicts: "there"

Prompt: "Once upon a time there"

Model predicts: "was"

Prompt: "Once upon a time there was"

Model predicts: "a"

...

This is called autoregressive decoding.

The decoder itself is quite simple:

Things worth noting are:

  • temperature
  • top-p
  • context truncation
  • torch.inference_mode()

Why model(context)[0,-1,:]?

Notice this line:

logits = model(context)[0, -1, :].float()

this is what gives us the logits for the prediction after the final prompt token:

image

What does temperature do?

Mathematically temperature is expressed with the following effect on probabilities:

image

The parameter T controls the distribution's sharpness:

  • temperature = 0.5 - more concentrated on high-probability tokens
  • temperature = 1 - original model probabilities
  • temperature = 1.5 - flatter distribution, more randomness

Note: temperature only affects inference, not model weights

What is top-p for?

Top-p sampling lets us renormalize only using candidates within a specified probability range.

Suppose our model predicts:

image

With top_p = 0.8, we only retain cat and dog because their cumulative probability reaches 0.8.

Then we discard the remaining tokens, renormalize the distribution, and sample from the survivors -- reducing the likelihood of sampling highly unlikely tokens.

image

Why did we truncate the context?

We truncated context with:

tokens[-context_length:]

because our model was trained with a context length of 256, so it can't directly process longer sequences.

So as generation continues, we retain the most recent 256 tokens and discard the older ones, while still keeping the full sequence for final output.

As we've seen in our calculations, increasing context length increases attention compute quadratically, and a large focus on LLM utility comes from increasing this context length.

What is @torch.inference_mode() for?

Generation only needs forward passes.

Unlike training, we don't need to calculate gradients or retain activations for backpropagation -- torch.inference_mode() reduces memory use and computational overhead.

Why did we include these optimizations?

Since our model is relatively small, including top-p and temperature allow us to improve (qualitative) performance of our generations quite a bit.

Now let's actually generate some text and see how different levels of training affect the output.

Comparing 40,000 step vs 5,000 step generations

With our decoder in place let's generate some outputs and actually compare the generations of our different checkpoints.

We'll sample using the following prompt:

Once upon a time, an OpenAI researcher named Ashwin discovered

The 5000 step checkpoint command:

uv run python sample.py \                                 ✔  cs336-basics    11:55:50 AM
  --checkpoint runs/ts/checkpoint.pt \
  --vocab artifacts/TinyStoriesV2-GPT4-train_10000/vocab.pkl \
  --merges artifacts/TinyStoriesV2-GPT4-train_10000/merges.pkl \
  --device mps \
  --max-new-tokens 256 \
  --temperature 0.8 \
  --top-p 0.9

Output:

Some improper grammar and poor narrative cohesion but it is a story with somewhat sensible elements.

Let's try the 40,000 step checkpoint. Our command:

uv run python sample.py \
  --checkpoint runs/ts_full/checkpoint.pt \
  --vocab artifacts/TinyStoriesV2-GPT4-train_10000/vocab.pkl \
  --merges artifacts/TinyStoriesV2-GPT4-train_10000/merges.pkl \
  --device cpu \
  --max-new-tokens 256 \
  --temperature 0.8 \
  --top-p 0.9

Output:

Qualitatively we can see the 40,000 step output has better grammar, fewer contradictions and less repetition.

It's still lacking narrative cohesion, but there's clearly a scale-driven path to additional intelligence with more training and better data.

What did we actually do here

We started with raw text and built the full pipeline needed to train a language model and generate stories:

image
  • Tokenizer - we trained a BPE vocabulary, implemented encoding/decoding with efficiency enhancements to overcome throughput bottlenecks, and tokenized our datasets
  • TransformerBlock - we built modules for our linear layer, embeddings, softmax, RMSNorm, RoPE, multi-head attention, and SwiGLU to ultimately turn token sequences into next-token logits
  • TransformerLM - we finished our language model by adding cross-entropy loss, AdamW, a learning rate scheduler with cosine decay, and gradient clipping
  • Training infrastructure - then we added data loading for randomization / memory purposes, validation, and checkpointing, with everything logged on Weights & Biases/CoreWeave for easy loss graphs and record-keeping
  • Generation - finally we implemented autoregressive decoding with temperature and top-p sampling to generate stories from our trained models

We trained two models, with our 40,000 step run reaching a validation loss of 1.41, compared with 1.92 for the 5,000 step run, and both produced story-like texts with improvements clearly seen in the model from additional training.

image

We saw the shifting bottlenecks: from BPE merges making pre-tokenization expensive to increasing context lengths shifting compute toward attention's quadratic cost.

image

Overall this was a great exercise to build intuition and discover areas for additional research, but imo the biggest insight was seeing how elegant mathematical solutions underpinning equations (like RoPE) translated into tangible gains.

Our next experiments

Some further explorations I began were:

  • hyperparameter sweeps - to find the optimal settings and architectures for our runs
  • additional compute - using some RunPod B200s to get our loss even lower and see how good our model can get just with TinyStories' dataset
  • better data - using RunPod B200s to train an OpenWebText-based model

But I decided the compute budget was better spent on:

  1. experiments in reducing token count via reinforcement learning
  2. chasing a top-score in Parameter Golf via tokenizer fusion

You can read about both of these in upcoming posts.

Footnotes

[1] - Why not 4×, as in traditional Transformer feed-forward networks?

Because SwiGLU uses three weight matrices rather than two. Using an intermediate dimension of approximately \(8/3\) instead of 4 keeps the total parameter count roughly comparable.