The Foundations of LLMs, Part I: Pretraining and Midtraining
Contents
I had been planning to make a YouTube video about building an LLM from scratch for quite some time. However, just as I was preparing to release it, Andrej Karpathy released an excellent video on the topic, and it quickly went viral. After that, I decided to shelve my version. I am now turning the material into a written guide on the autoregressive transformer architecture. We will implement a GPT-like Large Language Model (LLM) from scratch in Python using PyTorch as the only dependency. I assume basic familiarity with PyTorch. For those new to it, Introduction to PyTorch Code Examples from Stanford provides a helpful starting point before we build and train our model end to end.
The complete code for the GPT-like autoregressive transformer implemented in this article is available in this GitHub Gist. In 222 lines of self-contained Python, the program automatically downloads Mary Shelley's Frankenstein, builds a character-level tokenizer, pretrains the transformer on a GPU, Apple Silicon chip, or CPU, and samples new text from the trained weights.
Note that the model implemented and trained in this article, also referred to as the base model, is a text completer rather than a chatbot. Turning a base model into a chatbot typically involves midtraining, followed by post-training with Supervised Fine-Tuning (SFT) and Reinforcement Learning (RL). Implementing those stages is beyond the scope of this program, though we cover midtraining conceptually at the end of this article. Still, a pretrained generative LLM is a powerful tool for sampling knowledge.
Tokenization
Given input text, our objective is to generate output text conditioned on that input. Neural networks only operate on numbers, so in traditional transformer models (excluding byte-latent transformers, which group raw UTF-8 bytes into dynamic patches without a fixed vocabulary), the first stage is always tokenization: converting a text string into a sequence of integer IDs. This applies whether the architecture is encoder-only (such as BERT, which reads an entire passage bidirectionally to classify or search text), encoder-decoder (such as T5, which encodes an input sequence and decodes a separate output sequence for tasks like translation), or decoder-only (such as GPT-2, which predicts the next token from left to right). The simplest method is character-level tokenization, where each distinct character in the text corpus receives a unique integer ID:
import string
class CharacterLevelTokenizer:
"""A character-level tokenizer that treats individual characters as tokens."""
def __init__(self, text: str = string.printable) -> None:
"""Builds the vocabulary from the given text."""
self.vocab: list[str] = sorted(set(text))
self.vocab_size: int = len(self.vocab)
self.char_to_token: dict[str, int] = {char: idx for idx, char in enumerate(self.vocab)}
def encode(self, text: str) -> list[int]:
"""Converts a string into a list of token IDs."""
return [self.char_to_token[char] for char in text]
def decode(self, token_ids: list[int]) -> str:
"""Converts a list of token IDs back into a string."""
return "".join(self.vocab[token_id] for token_id in token_ids)
tokenizer = CharacterLevelTokenizer()
enc = tokenizer.encode("robot") # -> [87, 84, 71, 84, 89]
dec = tokenizer.decode(enc) # -> "robot"As shown above, CharacterLevelTokenizer extracts the sorted set of unique characters from the input text to build its vocabulary list self.vocab of length self.vocab_size. Calling encode looks up each character of "robot" in self.char_to_token to produce [87, 84, 71, 84, 89], and calling decode indexes back into self.vocab to reconstruct "robot" with no loss of information.
While character-level tokenization keeps the vocabulary tiny and simple, production LLMs use subword tokenizers so the model can read common words as single tokens and pack far more text into the same context window (maximum input length) rather than spelling every word letter by letter. For example, Byte-Pair Encoding (BPE) starts with individual characters and repeatedly merges the most frequent adjacent pair in the corpus (such as merging
"t"and"h"into"th", and then"th"and"e"into"the"), whereas WordPiece merges pairs that maximize the overall probability of the training corpus under a unigram (single-token frequency) language model. Production vocabularies also reserve special control tokens, such as Beginning-of-Sequence (BOS) and End-of-Sequence (EOS, often written<|endoftext|>) markers, to separate unrelated documents during training and to signal when generation should stop. In this article, we useCharacterLevelTokenizerfor simplicity and minimal dependencies.
Architecture
Our model is an autoregressive transformer, meaning it generates text one token at a time by feeding each newly generated token back into its input to predict the next. Before examining attention and feed-forward layers in isolation, let us inspect the top-level Config dataclass and Transformer module. The Config object stores seven hyperparameters (configuration settings chosen before training begins): vocab_size (number of unique tokens), block_size (maximum sequence length the model can read at once), n_layer (number of stacked transformer blocks), n_head (number of parallel attention heads per block), and n_embd (length of each token's embedding vector, which controls the model's representational capacity). It also stores dropout (the probability \(p\) of randomly zeroing neuron outputs during training so the network does not memorize fixed pathways) and bias (whether linear and normalization layers add a learnable offset vector \(\mathbf{b}\) in \(\mathbf{y} = \mathbf{x}W^\top + \mathbf{b}\), which production LLMs often disable to save parameters and improve training stability):
from dataclasses import dataclass
import torch
import torch.nn as nn
import torch.nn.functional as F
@dataclass(frozen=True) # We like our dataclasses frozen!
class Config:
"""Transformer config."""
vocab_size: int # Tokenizer vocabulary size
block_size: int # Max sequence length (context window)
n_layer: int # Number of transformer layers
n_head: int # Attention heads per layer
n_embd: int # Embedding dimension (must be divisible by `n_head`)
dropout: float # Dropout probability
bias: bool # Whether `nn.Linear` and `nn.LayerNorm` use bias
@property
def head_size(self) -> int:
"""Returns the per-head dimension (embedding is split evenly across attention heads)."""
return self.n_embd // self.n_head
class Transformer(nn.Module):
"""Autoregressive transformer language model."""
def __init__(self, cfg: Config) -> None:
"""Initializes the building blocks of the transformer."""
super().__init__()
self.block_size = cfg.block_size
self.tok_emb_table = nn.Embedding(cfg.vocab_size, cfg.n_embd)
self.pos_emb_table = nn.Embedding(cfg.block_size, cfg.n_embd)
self.blocks = nn.Sequential(*[Block(cfg) for _ in range(cfg.n_layer)])
self.ln = nn.LayerNorm(cfg.n_embd, bias=cfg.bias)
self.proj = nn.Linear(cfg.n_embd, cfg.vocab_size)
# Weight tying: reduces the total number of parameters without degrading accuracy
# Reference: https://arxiv.org/abs/1608.05859
self.proj.weight = self.tok_emb_table.weight
def forward(self, token_ids: torch.Tensor, targets: torch.Tensor | None = None) -> tuple:
"""Computes logits and optional loss."""
B, T = token_ids.shape
tok_emb = self.tok_emb_table(token_ids)
pos_emb = self.pos_emb_table(torch.arange(T, device=token_ids.device))
emb = tok_emb + pos_emb
out = self.ln(self.blocks(emb))
if targets is None:
logits = self.proj(out[:, [-1], :]) # Last-token projection with time dimension
loss = None
else:
logits = self.proj(out)
loss = F.cross_entropy(logits.view(B * T, -1), targets.view(-1))
return logits, loss
@torch.no_grad()
def generate(
self,
token_ids: torch.Tensor,
max_new_token_ids: int,
temperature: float = 0.7,
top_k: int | None = None,
) -> torch.Tensor:
"""Generates token IDs autoregressively."""
self.eval()
for _ in range(max_new_token_ids):
logits, _ = self(token_ids[:, -self.block_size :])
logits = logits[:, -1, :] / temperature
if top_k is not None:
k = min(top_k, logits.size(-1))
threshold = torch.topk(logits, k).values[:, [-1]]
logits[logits < threshold] = -float("inf")
probs = torch.softmax(logits, dim=-1)
next_token = torch.multinomial(probs, num_samples=1)
token_ids = torch.cat((token_ids, next_token), dim=1)
return token_idsLet us trace forward step by step. Its input token_ids is a 2D integer tensor (grid of numbers) of shape (B, T), where B is the batch size (how many independent text sequences we process in parallel) and T is the sequence length (how many token positions are in each sequence, up to block_size). Looking up token_ids in self.tok_emb_table produces tok_emb of shape (B, T, n_embd), which assigns each token ID a learnable vector (embedding) representing its identity. Because token embeddings alone do not record token order, the learned lookup table self.pos_emb_table maps the position indices 0, 1, ..., T - 1 (created by torch.arange(T, device=token_ids.device)) into a positional tensor pos_emb of shape (T, n_embd) rather than using fixed sinusoidal encodings (hand-crafted sine and cosine waves). Adding tok_emb and pos_emb uses PyTorch broadcasting to stretch pos_emb across all B batch items, yielding a combined representation emb of shape (B, T, n_embd) that encodes both what each token is and where it sits in the sequence.
Learned positional embeddings are simple to implement and work well within a fixed context window, but they cannot extrapolate to positions \(t \ge \text{block\_size}\) because
pos_emb_tablehas no rows for those positions. Most production transformer architectures instead use Rotary Position Embedding (RoPE), which encodes position by splitting the attention query and key vectors (unpacked in the next section) into 2D pairs and rotating each pair at its own frequency by an angle proportional to the token index \(t\). Because the dot product (multiplying matching entries of two vectors and summing them) between a rotated query and key depends on their relative offset \(t_1 - t_2\) rather than their absolute positions, RoPE adapts more naturally to longer sequences. In this article, we use learned positional embeddings for simplicity.
Next, out = self.ln(self.blocks(emb)) passes the embeddings through self.blocks, a stack of transformer blocks that mix information across tokens via Multi-Head Attention (MHA) and refine each token's representation via a Multilayer Perceptron (MLP, a two-layer feed-forward network). Afterward, self.ln applies layer normalization, which shifts and scales each token's n_embd vector to have a mean of 0.0 and a variance (spread around the mean) of 1.0, then applies a learnable per-feature scale, so the final projection receives well-scaled activations (intermediate layer outputs). Finally, self.proj projects the normalized representation into logits, which are raw, unnormalized scores for every token in the vocabulary. Notice self.proj.weight = self.tok_emb_table.weight: because both nn.Embedding(vocab_size, n_embd) and nn.Linear(n_embd, vocab_size) store their weight matrix with shape (vocab_size, n_embd), they can share the exact same underlying tensor in memory (weight tying). This reduces parameter count and lets the input and output layers share a single learned representation of each token. In practice, weight matrices are initialized to small random numbers rather than large values or zeros (which would keep neurons symmetric and unable to specialize). Drawing initial weights from a distribution with small variance, such as a narrow bell-shaped (Gaussian) curve centered at zero, keeps early activations and logits bounded and prevents the softmax function (which converts raw logits into probabilities) from saturating into extreme, overconfident guesses on step one.
At the end of forward, execution branches based on whether actual target tokens (targets, often called ground-truth labels) are supplied. During inference (generating text from a trained model, when targets is None), we only need to predict the single token that comes after the current sequence. Accordingly, out[:, [-1], :] slices only the final time step, using a single-element list [-1] to preserve the 3D shape (B, 1, n_embd), before self.proj projects it to (B, 1, vocab_size) logits. This avoids unnecessary matrix multiplications on earlier positions. During training, self.proj(out) computes logits of shape (B, T, vocab_size) for every position. Because PyTorch's F.cross_entropy (a loss measuring prediction error against the true token) expects class scores along dimension 1 rather than last, we flatten the batch and time axes into a 2D prediction matrix of shape (N, vocab_size) and a 1D label vector of shape (N,), where \(N = B \times T\), using logits.view(B * T, -1) (where -1 automatically infers vocab_size) and targets.view(-1).
This cross-entropy calculation implements the core objective of self-supervised, causal pretraining: left-to-right next-token prediction without peeking ahead. It is self-supervised because raw text supplies its own labels automatically: the targets are simply the inputs offset by one token, requiring no human annotation and enabling training on massive unlabeled corpora. By maximizing the probability assigned to the true next token at every position in the training corpus, the model learns the statistical structure of language. Formally, we minimize the average negative log-likelihood per token across a sequence of length \(T\):
$$\mathcal{L}_{\text{pretrain}}(\theta) = -\frac{1}{T}\sum_{t=1}^T \log P_{\theta}(x_{t} \mid x_{\lt t})$$
Here, \(P_{\theta}\) is the next-token distribution predicted by our transformer with weights \(\theta\), \(x_{t}\) is the true target token at position \(t\), and \(x_{\lt t} = (x_1, \dots, x_{t-1})\) denotes all preceding tokens. Intuitively, if the model assigns a probability near \(1.0\) to the true next token, \(-\log P_{\theta}\) is close to \(0.0\), and the loss penalty is tiny. If the model assigns a very small probability to the true token, \(-\log P_{\theta}\) grows very large, and the resulting gradient (a slope showing which direction to nudge the weights) strongly pushes \(\theta\) to raise that token's score on future steps. Exponentiating this per-token cross-entropy loss (also called log-perplexity) yields perplexity, \(\text{PPL} = e^{\mathcal{L}}\), which measures the effective number of equally likely next tokens the model chooses among at each step. At random initialization, guessing uniformly across a vocabulary \(\mathcal{V}\) gives a perplexity of \(\lvert \mathcal{V} \rvert\) and a baseline loss of \(\ln \lvert \mathcal{V} \rvert\) (for example, about 4.55 for a 95-character vocabulary), providing a quick sanity check that training starts in the right range.
Multi-Head Attention and Transformer Blocks
While the final projection and loss calculation define the training objective, the model's ability to understand context comes from the repeated attention and feed-forward layers inside self.blocks. To see how tokens exchange information and build contextual meaning across a sequence, let us unpack self.blocks(emb) and examine AttentionHead, MultiHeadAttention, and Block at the tensor level:
class AttentionHead(nn.Module):
"""A single causal self-attention head."""
def __init__(self, cfg: Config) -> None:
"""Initializes QKV projection and dropout, and caches causal mask to avoid recomputing it."""
super().__init__()
self.qkv = nn.Linear(cfg.n_embd, 3 * cfg.head_size, bias=cfg.bias)
self.dropout = nn.Dropout(cfg.dropout)
self.register_buffer("mask", torch.tril(torch.ones(cfg.block_size, cfg.block_size)))
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Computes masked single-head self-attention for the input tensor."""
_, T, D = x.shape
q, k, v = self.qkv(x).split(self.qkv.out_features // 3, dim=-1)
attn_scores = q @ k.transpose(-2, -1)
attn_scores = attn_scores * D**-0.5 # Prevent softmax from blowing up
attn_scores = attn_scores.masked_fill(self.mask[:T, :T] == 0, float("-inf")) # Mask future tokens
attn_weights = torch.softmax(attn_scores, dim=-1)
attn_weights = self.dropout(attn_weights)
return attn_weights @ v
class MultiHeadAttention(nn.Module):
"""A Multi-Head Attention (MHA)."""
def __init__(self, cfg: Config) -> None:
"""Initializes multi-head self-attention with output projection and dropout."""
super().__init__()
self.heads = nn.ModuleList([AttentionHead(cfg) for _ in range(cfg.n_head)])
self.proj = nn.Linear(cfg.n_embd, cfg.n_embd)
self.dropout = nn.Dropout(cfg.dropout)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Computes masked multi-head self-attention for the input tensor."""
out = torch.cat([head(x) for head in self.heads], dim=-1)
out = self.dropout(self.proj(out))
return out
class Block(nn.Module):
"""Transformer block."""
def __init__(self, cfg: Config) -> None:
"""Initializes a transformer block."""
super().__init__()
self.ln1 = nn.LayerNorm(cfg.n_embd, bias=cfg.bias)
self.mha = MultiHeadAttention(cfg)
self.ln2 = nn.LayerNorm(cfg.n_embd, bias=cfg.bias)
self.mlp = nn.Sequential(
nn.Linear(cfg.n_embd, 2 * cfg.n_embd, bias=cfg.bias), # Flexible: can change to e.g. `4 * cfg.n_embd`
nn.GELU(),
nn.Linear(2 * cfg.n_embd, cfg.n_embd, bias=cfg.bias),
nn.Dropout(cfg.dropout),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Performs a forward pass: attention + MLP with residuals and layer norms."""
x = x + self.mha(self.ln1(x))
x = x + self.mlp(self.ln2(x))
return xThe AttentionHead class implements a single causal self-attention head. Self-attention, popularized by the Attention Is All You Need paper, is a communication mechanism that, in its causal form, lets each token in a sequence gather relevant context from itself and earlier tokens. Rather than running three separate matrix multiplications, self.qkv(x) projects each token's n_embd vector into a combined vector of width 3 * cfg.head_size, and .split(self.qkv.out_features // 3, dim=-1) slices that last axis into three tensors q, k, and v of shape (B, T, head_size):
Query (
q): Like asking a librarian, "Which books talk about dinosaurs?" The query vector represents what the current token at position \(i\) is looking for as it scans the sequence for useful context, such as a verb searching for its subject or a pronoun searching for the noun it refers to.Key (
k): Like the title labels or catalog cards on the library shelves. Each token at position \(j \le i\) advertises what kind of information it holds through its key vector, and the dot product between token \(i\)'s query and token \(j\)'s key measures how closely the catalog label matches the search request.Value (
v): Like the actual pages inside each book. Once the query-key dot products determine how much attention token \(i\) should pay to each token \(j \le i\), the head computes a weighted sum of the value vectors to retrieve and blend the content from the matching positions.
To compute all pairwise query-key dot products in one operation, k.transpose(-2, -1) swaps the last two axes of k from (B, T, head_size) to (B, head_size, T). The batched matrix multiplication q @ k.transpose(-2, -1) (one matrix multiply per sequence in parallel) then produces a (B, T, T) grid of raw similarity scores attn_scores. Next, we scale attn_scores by D**-0.5 (note that in this compact program, D is unpacked from x.shape as cfg.n_embd, whereas standard multi-head formulations scale by cfg.head_size**-0.5). To enforce causality so token \(i\) can never peek at future tokens \(j \gt i\), __init__ pre-builds a lower-triangular matrix (ones on and below the diagonal, zeros above) via torch.tril(torch.ones(cfg.block_size, cfg.block_size)) and stores it with self.register_buffer("mask", ...). Registering it as a buffer tells PyTorch to move the tensor to the model's device (such as the GPU) alongside its weights without treating it as a trainable parameter. During forward, attn_scores.masked_fill(self.mask[:T, :T] == 0, float("-inf")) replaces all upper-triangular future entries (\(j \gt i\)) of attn_scores with \(-\infty\). Formally, omitting the causal mask and dropout, scaled dot-product attention with scaling dimension \(d\) computes:
$$\text{Attention}(Q, K, V) = \text{softmax}\big(\frac{Q K^\top}{\sqrt{d}}\big) V$$
Dividing by \(\sqrt{d}\) keeps the variance of the dot products bounded as embedding dimensions grow, preventing softmax from saturating into extreme 0.0 or 1.0 probabilities, where gradients vanish (shrink toward zero, stalling learning). Because \(\exp(-\infty) = 0\), torch.softmax(attn_scores, dim=-1) turns every masked future position into an exact 0.0 weight while normalizing the allowed past and present positions in each row to sum to 1.0. Multiplying attn_weights @ v then aggregates the value vectors into an output of shape (B, T, head_size).
In MultiHeadAttention, we run cfg.n_head independent AttentionHead modules in parallel, concatenate their (B, T, head_size) outputs along the last axis (dim=-1) to recover shape (B, T, n_embd), and pass the result through the output projection self.proj. Running multiple heads in parallel lets the model attend to several types of relationships simultaneously, so one head can track local punctuation or syntax while another tracks longer-range references such as character names. Applying self.dropout to the projected output regularizes the layer by randomly zeroing output features during training, which discourages co-adaptation and reduces overfitting.
The Block class pairs cross-token communication (self.mha) with per-token computation (self.mlp). Before each sublayer, layer normalization (self.ln1 and self.ln2) standardizes the input features, and after each sublayer, a residual connection (x = x + ...) adds the unnormalized input x directly to the sublayer's output. Because the derivative of \(x + f(x)\) with respect to \(x\) is \(1 + f'(x)\), this residual addition creates an unimpeded highway through the block stack that carries gradients back to the earliest layers, mitigating vanishing gradients. This placement is known as Pre-Norm, as opposed to the original transformer's Post-Norm layout (which normalized after the residual addition). Normalizing only inside the sublayer branch keeps the main residual highway unobstructed and stabilizes deep training. While self.mha mixes information across time steps, self.mlp processes each token position independently: it projects the n_embd vector up to a wider hidden (internal) dimension (2 * cfg.n_embd), applies a smooth nonlinear GELU (Gaussian Error Linear Unit) activation so the two linear layers do not collapse into a single matrix multiply, and projects back down to cfg.n_embd. We use 2 * cfg.n_embd here instead of the standard 4 * cfg.n_embd to keep our miniature model compact at 140,127 parameters.
Many large-scale LLMs keep this core transformer block blueprint while swapping in targeted upgrades such as these five for speed and quality:
- RMSNorm (Root Mean Square Normalization): Replaces
LayerNormby scaling each token's representation vector using only its root-mean-square magnitude (the square root of the average squared value) without subtracting the mean, saving computation while preserving stability.- SwiGLU (Swish-Gated Linear Unit): Replaces the GELU activation in the MLP with a gating branch that multiplies one linear projection by a second, smoothly activated linear projection, letting the network selectively amplify or suppress individual features.
- Grouped Query Attention (GQA): Lets multiple query heads share the same key and value projections instead of giving every head its own pair, sharply shrinking memory use during generation with minimal quality loss.
- Mixture of Experts (MoE): Replaces the single dense MLP with several parallel specialist MLPs (experts) and a small learned router that activates only a few of them per token, growing total model capacity without proportionally increasing compute per token.
- FlashAttention: Computes mathematically identical attention in small blocks inside fast on-chip GPU memory (SRAM) so the full \(T \times T\) attention score matrix never has to be written to slower main GPU memory, speeding up training and unlocking longer contexts.
Autoregressive Generation
During training, the model processes all \(T\) tokens of a sequence in parallel using teacher forcing, meaning it always receives the actual ground-truth tokens from the dataset as context at every position, even if its own prediction at the previous position was wrong. At inference, however, future target tokens do not exist, so Transformer.generate runs sequentially. It first calls self.eval() to disable random dropout layers (if you call generate in the middle of a training loop, call model.train() afterward to re-enable dropout). On each step, it crops the model input to the trailing self.block_size tokens via token_ids[:, -self.block_size :] so its length never exceeds the block_size rows of pos_emb_table. It then extracts the 2D slice of final-position logits logits[:, -1, :] of shape (B, vocab_size), representing raw scores \(\mathbf{z} \in \mathbb{R}^{\lvert \mathcal{V} \rvert}\) across the vocabulary \(\mathcal{V}\) for each sequence in the batch. To balance coherence and creativity, we divide the logits by a temperature parameter \(\tau \gt 0\) and optionally restrict sampling to the \(k\) highest-scoring candidate tokens \(\mathcal{V}_k \subset \mathcal{V}\):
$$P(x_{t} = v \mid x_{\lt t}) = \frac{\exp(z_{v} / \tau)}{\sum_{j \in \mathcal{V}_k} \exp(z_{j} / \tau)}$$
The diagram above illustrates how temperature \(\tau\) reshapes the probability distribution for the prompt "Artificial intelligence will transform the ...". Dividing logits by a small temperature (\(\tau = 0.2\)) magnifies score differences fivefold before exponentiation, concentrating 82% of the probability mass on the top candidate ("future") and driving tail options near zero. This sharp distribution suits deterministic tasks like coding or math, whereas moderate temperatures (\(\tau = 0.7\) and \(\tau = 1.0\)) give meaningful weight to plausible alternatives like "world" (22%) and "industry" (16% to 18%), and high temperatures (\(\tau = 2.0\)) compress logit gaps to flatten the distribution across candidates.
When top_k is enabled in generate, torch.topk(logits, k).values[:, [-1]] finds the \(k\)-th largest logit score in each row as a cutoff threshold, and logits[logits < threshold] = -float("inf") sets all tokens outside the top \(k\) to \(-\infty\) so torch.softmax assigns them zero probability. Rather than always picking the single highest-scoring token with torch.argmax (greedy decoding, which frequently gets stuck in repetitive loops), torch.multinomial(probs, num_samples=1) samples an index from the categorical distribution, like spinning a weighted roulette wheel where each token's slice equals its probability:
$$x_{t} \sim \text{Categorical}(P(x_{t} \mid x_{\lt t}))$$
High-probability tokens are selected most often, while lower-probability tokens inside the top-\(k\) set retain a controlled chance of being chosen, allowing natural variation across runs. Each sampled token index next_token of shape (B, 1) is appended to token_ids along the time dimension via torch.cat((token_ids, next_token), dim=1), and the loop repeats until max_new_token_ids tokens have been generated (production decoders also halt early as soon as the model emits an End-of-Sequence EOS token). Because generation simply samples plausible-sounding continuations from a learned probability distribution with no built-in truth check, LLMs can produce fluent but false statements, a failure mode known as hallucination.
Notice that
generatefeeds the growing sequence (cropped to the trailingself.block_sizetokens) back intoself(...)from scratch on every step, recomputing attention over all earlier tokens in the window again and again. Because causal masking ensures that earlier tokens never depend on future tokens, production inference engines store each layer's previously computed key (k) and value (v) vectors in a KV cache (a running memory buffer of past keys and values). On each new step, the model processes only the single newly generated token, computes its query, key, and value at each layer, appends the key and value to the cache, and attends over the updated cache, avoiding redundant recomputation of the prefix.
Pretraining Loop
With the architecture in place, we can pretrain our model on Mary Shelley's Frankenstein. In the program below, sample_batch picks batch_size random starting indices in the tokenized book, slices chunks of length block_size as input token_ids, and slices the same chunks offset by one character (idx + 1 : idx + block_size + 1) as targets. Notice how we also split the model's parameters by tensor dimension (param.ndim < 2). Here, 1D tensors (such as LayerNorm scale vectors and the default bias vectors retained on Transformer.proj and MultiHeadAttention.proj) go to AdamW, while 2D weight and embedding matrices go to Muon:
import urllib.request
def sample_batch(data: torch.Tensor, batch_size: int, block_size: int) -> tuple:
"""Randomly samples training sequences for Next-Token Prediction (NTP)."""
idxs = torch.randint(len(data) - block_size, (batch_size,)) # Random starting positions
token_ids = torch.stack([data[idx : idx + block_size] for idx in idxs]) # Input sequences
targets = torch.stack([data[idx + 1 : idx + block_size + 1] for idx in idxs]) # Same sequences shifted by +1 (NTP)
return token_ids, targets
with urllib.request.urlopen("https://www.gutenberg.org/cache/epub/84/pg84.txt") as f: # Read Frankenstein
text = f.read().decode("utf-8")
tokenizer = CharacterLevelTokenizer(text)
device = torch.device("cuda:0" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")
cfg = Config(vocab_size=tokenizer.vocab_size, block_size=32, n_layer=4, n_head=4, n_embd=64, dropout=0.0, bias=False)
max_steps, log_interval, batch_size, learning_rate = 2_000, 10, 256, 1e-3
data = torch.tensor(tokenizer.encode(text), device=device)
model = Transformer(cfg).to(device).train()
n_params, adamw_params, muon_params = 0, [], []
for param in model.parameters():
n_params += param.numel()
(adamw_params if param.ndim < 2 else muon_params).append(param)
print(f"Model parameters: {n_params:,}\n")
adamw = torch.optim.AdamW(adamw_params, lr=3e-4, betas=(0.9, 0.95), eps=1e-8, weight_decay=0.01)
muon = torch.optim.Muon(muon_params, lr=0.02, momentum=0.95, weight_decay=0.1)
for step in range(1, max_steps + 1):
token_ids, targets = sample_batch(data, batch_size, cfg.block_size)
adamw.zero_grad()
muon.zero_grad()
_, loss = model(token_ids, targets)
loss.backward()
adamw.step()
muon.step()
if step % log_interval == 0:
print(f"\rStep {step}/{max_steps} ({step / max_steps:.2%}) | Loss: {loss.item():.4f} ", end="", flush=True)
# Seed the model with the prompt "I am" to kick off text generation
token_ids = torch.tensor(tokenizer.encode("I am"), device=device).reshape(1, -1)
output = model.generate(token_ids, max_new_token_ids=512)[0]
print(f"\n\nOUTPUT:\n\n{tokenizer.decode(output.tolist())}")Why do we pair two different optimizers (algorithms that update weights from gradients), each with its own learning rate? The learning rate sets how far weights move on each update, and we explicitly pass lr=3e-4 to AdamW and lr=0.02 to Muon, leaving the learning_rate = 1e-3 variable above unused. AdamW updates each individual weight independently by dividing a running average of the gradient (betas[0]=0.9) by the square root of a running average of squared gradients (betas[1]=0.95), with eps=1e-8 added to the denominator to prevent division by zero. It also gently shrinks weights toward zero at each step (weight_decay=0.01). For 2D weight matrices, however, raw gradients are often dominated by a few large singular directions (the main axes along which a matrix stretches vectors). Muon accumulates gradient momentum (a smoothed running average of past gradients, momentum=0.95) and applies Newton-Schulz iterations (a fast matrix-only approximation loop) to approximately orthogonalize the 2D update matrix, pushing all of its singular values toward 1. This equalizes the step size across all singular directions, normalizing the spectral norm (the matrix's largest stretch factor) so a larger learning rate (lr=0.02) can be taken safely. Inside each step of the loop, zero_grad() clears the previous step's gradients (since PyTorch accumulates gradients by addition into .grad buffers by default), loss.backward() uses the chain rule (the calculus rule that propagates slopes backward through layers) to compute gradients across the network, and step() updates the weights.
Scaling this loop to production pretraining introduces a few essential practices omitted from our toy program. First, even though next-token prediction uses unlabeled text, base pretraining data is heavily curated by humans through deduplication (removing repeated passages so the model does not memorize boilerplate), quality filtering (discarding corrupted or low-signal pages), and tuned domain mixtures (balancing sources such as web text, books, and code). Second, large runs stabilize and speed up optimization with linear learning rate warmup (starting the learning rate near zero and ramping it up over early steps so noisy initial gradients do not destabilize random weights before decay begins), mixed precision (running most matrix math in lower-precision floating-point formats while keeping sensitive state such as master weights in 32-bit floats, to cut memory and accelerate compute), and gradient accumulation (accumulating gradients across several smaller micro-batches before calling
step()to emulate very large effective batch sizes).
Pretraining Results
Running the 2,000-step pretraining loop takes under 40 seconds on a MacBook Pro with an Apple M4 Pro chip. Over those 2,000 steps (processing \(2{,}000 \times 256 \times 32 \approx 16.4\text{M}\) characters), the cross-entropy loss drops from a random-guessing baseline of \(\ln \lvert \mathcal{V} \rvert = \ln 95 \approx 4.55\) down to 1.3831 (a perplexity of \(e^{1.3831} \approx 3.99\), meaning the model narrowed 95 possible characters down to about 4 plausible candidates on average). Our 140,127-parameter character model learns English word boundaries, punctuation, and Shelley's vocabulary from raw character statistics:
Model parameters: 140,127
Step 2000/2000 (100.00%) | Loss: 1.3831
OUTPUT:
I am the forth which were on his stranger. The light of many our reasun alive in the enter of my
cottagers, there in the murderer, when I walked in
my enemy sat much of spring in its removed. I had not for my friend, and the cottager of the lack of
the wint on the lovely of cestant, and that the old man, but I was entered that
the eviner of my hands. My journey is many beauty will of compassins of the more spully appeared
with meaning a man work was not rease to be macking my own and a
gentle understand evenEvaluating a real base model goes far beyond checking training loss and eyeballing a few samples. Teams measure held-out validation loss (cross-entropy, or log-perplexity, on unseen text kept out of training), score the model on downstream task benchmarks (standardized tests for reading comprehension, math, and coding), and run contamination checks (audits that catch test examples accidentally leaked into the training corpus). Plotting held-out loss against training compute (measured in FLOPs, or floating-point operations) reveals predictable scaling laws (empirical trends showing loss falling smoothly as compute, parameters, and data grow). For instance, Chinchilla compute-optimal scaling showed that parameters and training tokens should scale together as the compute budget grows, and lower held-out loss generally tracks stronger downstream capabilities.
Why does predicting the next token produce such broad abilities? Because a single network must compress vast numbers of diverse contexts into shared weights, it is forced to learn structure at many levels, from syntax and semantics to world facts, style, task patterns, and multi-step procedures like tracing code or arithmetic. At the same time, next-token prediction balances generalization (statistical compression extracting reusable patterns for unseen inputs) against memorization (reproducing training passages verbatim, especially repeated or duplicated ones), and low training loss alone cannot tell the two apart. Equally important, pretraining does not directly optimize truthfulness (it rewards probable continuations over verified facts), verbalized calibration (matching the certainty a model states in its answers to its actual accuracy), source attribution (tracking which document backed a claim), persistent memory across sessions (retaining new facts once weights are frozen), or post-cutoff knowledge (events after the training corpus was collected).
Midtraining
In production pipelines, base pretraining on web-scale text provides broad world knowledge, but even filtered web corpora remain noisy and low in reasoning density. Roughly, the boundary between pretraining and midtraining (closely related to, and often used interchangeably with, continual pretraining) is defined by starting point and goal rather than by dataset size: pretraining starts from random weights to build a general base model, whereas continual pretraining starts from an existing pretrained checkpoint (a saved snapshot of trained weights) to adapt its data distribution or capabilities. As analyzed in a survey on midtraining, midtraining bridges the gap between noisy web pretraining and stronger reasoning and specialized capabilities by optimizing the same per-token autoregressive next-token prediction objective across three pillars:
$$\mathcal{L}_{\text{midtrain}}(\theta) = -\frac{1}{T}\sum_{t=1}^T \log P_{\theta}(x_{t} \mid x_{\lt t})$$
Targeted Data Distributions: Increasing the share (known as upsampling) of high-utility reasoning data, such as code, STEM, synthetic (AI-generated) textbooks, chain-of-thought traces of step-by-step reasoning, and fill-in-the-middle data, where a middle span of code is moved to the end so the model learns to infill missing code from prefix and suffix context. Teams also use this stage for Domain-Adaptive Pretraining (DAPT) on specialized corpora such as law, medicine, or proprietary code, and for temporal knowledge updating on newer text. In one continual pretraining study, continuing from an existing checkpoint matched the performance of retraining from scratch on old and new data combined at roughly half the compute, when the old and new datasets were similar in size. To prevent catastrophic forgetting, or overwriting previously learned general knowledge when adapting to a narrower distribution, teams mix in a replay buffer of earlier general pretraining tokens. In that same study, around 5% replay sufficed for weak distribution shifts, while strong shifts (such as moving to a new language) needed closer to 25%. Because training on raw, unstructured text erodes conversational formatting, continual pretraining runs before Supervised Fine-Tuning (SFT) so it does not degrade instruction-following.
Learning Rate Annealing: Decaying the learning rate along a cooldown schedule such as cosine decay (smoothly lowering the step size along a half-cosine curve) or Warmup-Stable-Decay (WSD), which holds the learning rate on a steady plateau during base pretraining and decays it rapidly during midtraining. When resuming from a checkpoint where the learning rate has already decayed to near zero, teams re-warm and re-decay the learning rate, briefly raising it so weights can adapt to the new data before cooling it back down. WSD gives horizon flexibility, letting teams stop and anneal at any token count without fixing the total training length upfront, while roughly matching the final loss of a cosine schedule tuned to that same length. In all cases, smaller final steps reduce the update variance caused by mini-batch gradient noise and let the weights settle into a lower-loss minimum (weight settings with smaller error) on curated data.
Context Length Extension: Progressively expanding the context window
block_sizefrom short initial sequences to much longer contexts by adapting positional encodings and training on a mixture of long and short documents. Because RoPE represents token positions as rotation angles at different frequencies (like clock hands moving at different speeds), rescaling those frequencies slows the rotations so longer sequences fit inside the trained angular range. YaRN refines this by interpolating (smoothly stretching) mainly the slow, low-frequency dimensions while leaving the fast, high-frequency ones largely untouched, so sharp local token order is preserved. Training on short sequences before expanding to long sequences also saves compute, since attention cost grows quadratically with length, and acts as a form of curriculum learning (starting with easier examples before harder ones), which has been shown to accelerate convergence when training transformers to learn in context.
Conclusion
In this article, we implemented and pretrained a GPT-like autoregressive transformer from scratch using PyTorch, covering character-level tokenization, causal multi-head self-attention, residual connections, next-token prediction with AdamW and Muon, and the foundations of midtraining. While our 140K-parameter model produces only stylistic echoes of Shelley rather than fully coherent prose, it follows the same core algorithmic blueprint that powers large-scale systems. End-to-end LLM systems form a three-layer stack. Pretraining and midtraining largely set the model's knowledge ceiling, while post-training (including Supervised Fine-Tuning on prompt-response examples and Reinforcement Learning from feedback or reward signals) teaches the model to access that knowledge reliably. Finally, inference and agent harnesses (runtime wrappers providing tools, retrieval, and multi-step control loops) let the model apply that knowledge. Because raw base models remain open-ended text completers, transforming a next-token predictor into a helpful conversational assistant begins with Supervised Fine-Tuning (SFT), which we explore in Part II.