Training GPT: A Detailed Walkthrough

Tokens, embeddings, causal attention, and next-token prediction.

Before we begin

This post looks closely at the structure of Generative Pre-trained Transformers, or GPT. The resources below are useful, particularly Dr. Junho Lim's Korean talk on broader questions such as why GPT works well and what query, key, and value mean.

Here, I'll focus on the architecture at the code level. I don't yet have firm opinions on the broader questions, and I find concrete structure more useful for understanding how the model works.

Most of the explanatory figures come from Jay Alammar's article.


What is GPT?

Its name describes a generative, pretrained Transformer. The Transformer paper introduced the architecture for translation in 2017. If it's unfamiliar, this introduction may help.

Autoregressive generation: predict a token from the preceding context.
Autoregressive generation: predict a token from the preceding context.

Generative means the model produces a suitable next token from the tokens it receives. For instance, after a Korean token meaning “today,” it might produce one meaning “the weather.”

Pretrained means it learns from a corpus before being used for downstream tasks. Predicting the next token supplies its training target: the label is the token that actually follows. GPT-3 attracted attention for strong task performance without task-specific weight updates, which we'll discuss below.

The Transformer architecture and its relationship to GPT.
The Transformer architecture and its relationship to GPT.

The Transformer part refers to its architecture, closely related to the original decoder. A friend once asked how BERT or GPT could use only an encoder or decoder when a Transformer has both.

The objectives differ. Translation encodes a source language and decodes a target language. Language-model pretraining doesn't need that complete translation pipeline. Calling GPT “a decoder” can be confusing if we carry the translation meaning too literally. For this discussion, think of it as a language model using attention.

Few-shot learning

A major reason GPT-3 drew attention was solving tasks without fine-tuning. A common NLP approach had been to pretrain a model, then train it again on many labeled examples of a particular task. BERT commonly follows that pattern. That second stage is fine-tuning.

Consider sentiment analysis with NSMC, the Naver Sentiment Movie Corpus.

Korean movie reviews with positive and negative sentiment labels.
Korean movie-review examples. The first four labels are positive (1); “Is this even a movie?” and “With enough money, I could make something better” are negative (0). The last row is the prediction target. English glosses appear below.
Reading the Korean reviews
굳ㅋ
Good, lol.
음악이 주가 된, 최고의 음악영화
A great music film, with the music at its heart.
괜찮네요오랜만포켓몬스터잼밌어요
Not bad. Pokémon is fun after all this time.
최고!!!!!!!!!!!!!!
The best!
이게 영화야?
Is this even a movie?
돈만있으면 내가 이것보단 더잘만들겠따 ㅋ
With enough money, I could make something better, lol.
아이디어가 아주 좋다 재밌다
The idea is really good; it’s fun.
These glosses explain the text; the model inputs above remain Korean.

NSMC contains Naver movie reviews: scores 1–4 are negative, labeled 0, and 9–10 positive, labeled 1. There are 150,000 training sentences and 50,000 test sentences. The task is to classify a new review, such as “The idea is great; it's fun.”

Traditional fine-tuning trains on those labeled reviews so the model can output 1 for a positive example. This improves performance but requires substantial labeled data and a separate training process for each task.

GPT-3 can instead receive examples in its input and continue the pattern without updating its weights.

A few-shot prompt containing labeled sentiment examples.
A few-shot prompt: Korean reviews followed by sentiment labels. The unfinished final line says “The idea is really good; it’s fun:” and asks the model to continue with a label.

Few-shot inference gives the model N examples, then asks it to complete the next one. The examples do not cause a weight update. This makes the approach flexible across different tasks.

GPT-3 completing a Korean sentiment-classification prompt.
The model continues with 1 for the positive target, then generates more review–label pairs. Those later examples are model output and include an incorrect label; they are not verified ground truth.

It produced 1 for the positive review, apparently picking up the convention from the examples. It may simply have followed the pattern. When I allowed a longer output, it added its own examples, and the last prediction was wrong. Even generating Korean seemed impressive given how little Korean was in GPT-3's data.

One-shot gives one example. Zero-shot gives only a natural-language task description. That's convenient but difficult; even people can struggle with an underspecified instruction. Here are examples.

A one-shot sentiment-classification example.
A one-shot prompt. The sole example is “Good, lol: 1”; the unlabeled target is “The idea is really good; it’s fun:”.
The model’s response to a one-shot prompt.
The one-shot continuation labels the target 1, then generates another Korean review and label. Both remain the original model output.
A zero-shot sentiment prompt with English instructions.
English instructions ask for 0 (negative) or 1 (positive). The Korean target means “The idea is really good; it’s fun.”
Zero-shot predictions for Korean review text.
Original zero-shot outputs for three Korean sentences, with the model’s own English renderings and scores. The Korean variants are roughly “The idea is really good; it’s fun,” “The idea is very similar; it’s fun,” and an awkward negated variant. These outputs are not polished translations.

For zero-shot, I gave the task description in English. I found the result striking: the instruction described 0 as negative and 1 as positive but didn't explicitly demand one of those two integers. The model supplied intermediate real-valued scores, closer to one for positive reviews and zero for negative ones. The results looked sensible to me. It made the attention around GPT-3 understandable.

Size

GPT-3 model sizes.
GPT-3 model sizes.

The best-known GPT-3 model has 175 billion trainable parameters.

Correction recorded March 12, 2024, thanks to reader Ttiriringgu: the original post compared parameter counts with roughly a hundred billion neurons in the brain. Parameters aren't neurons. Units are a closer analogy to neurons; weights are closer to synaptic connections, of which a brain has far more. The original numerical comparison was inappropriate.

A historical comparison of language-model parameter counts.
A historical comparison of language-model parameter counts.

GPT-3 towers over earlier models in this historical chart. The scale difference was extraordinary.


Taking GPT apart

Let's follow how language moves through the architecture and becomes a training signal. The PyTorch snippets were written for explanation, not copied from OpenAI's official implementation.

Tokenization

Text must become numerical model input. Tokenization and encoding assign distinct IDs to the units the model recognizes, much as names distinguish people.

A vocabulary assigning IDs to word tokens.
Word-token IDs for the sentence “My biggest problem is that I don’t know myself.” Each Korean word is assigned a number. The original ordering and token boundaries remain unchanged.

The intuitive method is to give every word an index. That is word tokenization. But we can't give a separate entry to every possible word, so the vocabulary defines a finite set the model recognizes. The examples here discuss a vocabulary of 32,200 for a BERT setup and 50,257 for GPT-style tokenization. A vocabulary-based tokenizer can map an unknown unit to [UNK].

Whole-word tokenization of a Korean sentence.
The same Korean sentence plus an uncommon character. The example word tokenizer encodes the words and decodes the unknown character as UNK.

Whole-word tokenization has three difficulties.

It doesn't share inflected forms. Korean 웃다 can appear as 웃는다 or 웃고있다. Treating every form as a different token wastes opportunities to share structure.

It is vulnerable to out-of-vocabulary words. A limited dictionary will encounter many unknown forms.

Related forms lose their relationship. 나를 and 나의 share the noun 나 with different particles, but become unrelated entries.

Subword tokenization splits a word into reusable pieces. BERT uses WordPiece. The SentencePiece example below illustrates the same broad idea. GPT-3 itself uses GPT-2-style reversible byte-pair encoding, not SentencePiece; the original post conflated those two facts. See the linked GPT-3 paper, section 2.1.

Subword tokenization of the same Korean sentence.
Subword tokenization of the same sentence, “My biggest problem is that I don’t know myself.” Korean pieces are kept because their boundaries are the subject of the example.

For example, 나를 can split into a piece for “I/me” and a particle, and 나의 into the same base plus another particle. The related forms reuse a piece. Splitting also helps preserve part of the meaning of unfamiliar words.

The original SentencePiece demonstration.
A SentencePiece demonstration on that Korean sentence, not the official GPT-3 tokenizer. The displayed pieces and IDs remain the original output.

Common words remain whole in this example; 문제이다 splits into two pieces. The uncommon character becomes [UNK] in this particular tokenizer. More on subword tokenization.

Inputs

The input stage highlighted in the GPT pipeline.

1. Input IDs and label IDs

Next-token prediction creates its own labels from the text, so a separate annotated label set isn't needed. The window size is the number of tokens in one input. The example makes the shift clear.

An input token window and labels shifted one position ahead.
An input token window and labels shifted one position ahead.
import h5py
import random
from torch.utils.data import Dataset
 
 
class GPTDataset(Dataset):
    def __init__(self, dataset_path: str, seq_len: int, window_size: int, rng: random.Random):
        self.dataset = h5py.File(dataset_path, 'r')['token_ids']
        self.seq_len = seq_len
        self.window_size = window_size
        self.rng = rng
        self.size = len(self.dataset)
 
    def __len__(self):
        return self.size
 
    def __getitem__(self, idx):
        start_point = self.rng.randint(0, self.size)
        end_point = min(start_point + (window_size + 1), self.size)
        window = self.dataset[start_point: end_point]  # Windowing
 
        input_ids = window[:-1]
        label_ids = window[1:]
        return input_ids, label_ids
 
  • Pick a random start in the dataset.
  • Choose the end of the sample.
  • Slice window size plus one consecutive tokens.
  • The first 1,024 form the input IDs.
  • Tokens two through 1,025 form the label IDs.

Fetch batch_size samples to form arrays shaped (batch_size, seq_length). The model receives input IDs and compares its predictions with label IDs. In this example, seq_length equals the chosen window size.

2. The future mask

GPT predicts from the current and preceding tokens, not later ones, so attention must hide future positions.

A triangular causal attention mask.
A triangular causal attention mask.

The mask is a seq_length by seq_length matrix. True means hide that position; false means allow it. The diagonal separates past/current positions from the future. It is the same causal structure for every sample.

def create_future_mask(x: torch.Tensor, offset: int = 0) -> torch.Tensor:
 
    seq_len = x.size(-1)  # seq_length
 
    # Create shifted upper triangular matrix.
    future = torch.ones((seq_len, seq_len), dtype=torch.bool, device=x.device)
    future = future.triu(1)
 
    future_mask = future.view((1,) * (x.ndim - 1) + future.size())
    return future_mask.expand(x.shape + future_mask.shape[-1:])  # (b, s, s)
 

Here is the result with batch size two and sequence length four.

The causal mask for a short four-token example.
The causal mask for a short four-token example.

Learnable embeddings

The embedding stage highlighted in the model.

1. Token embedding

A sparse one-hot representation of token IDs.
Each Korean word from “My biggest problem is that I don’t know myself” maps to its token ID and a sparse one-hot vector. The vectors are unchanged.

Encoding gave each token an ID, equivalent to selecting a one-hot vector. One-hot vectors are equally distant and sparse, so they don't directly express relationships. Embedding maps them into a smaller learned space.

An example mapping nine-dimensional one-hot tokens to three dimensions.
The same Korean tokens map to illustrative three-dimensional vectors. The sentence means “My biggest problem is that I don’t know myself”; the numbers are the source’s example embeddings.
Similar movie-related terms located near each other in an embedding space.
An embedding visualization from the linked article, trained on 38,870 movie reviews. Korean labels group the films Veteran and Assassination, their lead and supporting actors, directors, and other people. Examples include Yoo Ah-in, Hwang Jung-min, Ha Jung-woo, and directors Ryoo Seung-wan and Choi Dong-hoon. The plotted positions remain the original results.

The second picture places terms with similar roles near each other. This article explains that example further.

GPT's embedding is trainable, part of the model rather than a fixed preprocessing result.

import torch.nn as nn
 
token_embeddings = nn.Embedding(vocab_size, hidden_size)
 
An embedding table associating each token ID with a vector.

torch.nn.Embedding can be understood as a table: each ID selects a vector whose values change during training. Hidden size is the vector's dimension. Multiplying a one-hot vector by the matrix gives the same result.

A clarification: an embedding lookup is itself differentiable with respect to the selected weights. It need not literally construct a one-hot vector and multiply it for training to work.

Looking up token zero in a learned embedding matrix.
Looking up token zero in a learned embedding matrix.
The equivalent one-hot matrix multiplication.
The equivalent one-hot matrix multiplication.

With nine possible tokens and three embedding dimensions, selecting ID zero matches multiplying [1,0,0,0,0,0,0,0,0] by the weight matrix.

For GPT input IDs, the resulting shape is (batch_size, seq_length, hidden_size). Hidden size depends on the configuration. The original discussion mixed GPT-2-like example sizes with GPT-3. The 175B GPT-3 model has hidden size 12,288 and 96 layers, as shown in its paper's Table 2.1.

2. Position embedding

import torch.nn as nn
    
position_embeddings = nn.Embedding(seq_len, hidden_size)
 
def position_embed(input_ids, position_embeddings):
 
    seq_length = input_ids.size(1)
    position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device)
    position_ids = position_ids.unsqueeze(0).expand_as(input_ids)
 
   position_embedding_vector = position_embeddings(position_ids)
 
    return position_embedding_vector

Token IDs alone don't encode position, so position IDs select another learned embedding. The positions run from zero through seq_length minus one.

Position embeddings with batch size two, length four, and dimension eight.
Position embeddings with batch size two, length four, and dimension eight.

With batch size two, length four, and hidden size eight, the position vectors have the same shape as the token embeddings.

3. Dropout

import torch.nn as nn
 
drop = nn.Dropout(0.1)
final_embed_vector = drop(token_embed_vector + position_embed_vector)

Add the token and position embeddings, then apply dropout. In the code, each value is independently zeroed with probability 0.1.

Dropout zeroing one value and scaling surviving values.
Dropout zeroing one value and scaling surviving values.

One of ten values happened to become zero in this example. The exact count needn't match the probability. Surviving values are scaled by 1/(1-p).

Final embedding = Dropout(Token embedding + Position embedding).

A GPT layer

One GPT layer highlighted inside the stack.

1. Layer normalization

The normalization operation within a GPT layer.
The normalization operation within a GPT layer.
import torch.nn as nn
 
layer_norm = nn.LayerNorm(hidden_size, eps=1e-5)
ln_vector = layer_norm(final_embed_vector)
Layer normalization applied independently to sample representations.
Layer normalization applied independently to sample representations.

Layer normalization normalizes values within the relevant representation, without mixing independent samples. It appears several times in GPT and helps training behave more consistently. Further explanation.

2. Masked multi-head self-attention

The masked multi-head self-attention stage.

Masked means future tokens are hidden. Multi-head means attention is computed through more than one head.

import math
import torch
import torch.nn as nn
from typing import Optional, Tuple
 
 
class AttentionLayer(nn.Module):
 
    def __init__(self, heads: int, dims: int, dropout: float = 0.1):
        super().__init__()
        self.attn = MultiHeadAttention(heads, dropout)
        self.proj_q = nn.Linear(dims, dims)  # (h, h)
        self.proj_k = nn.Linear(dims, dims)  # (h, h)
        self.proj_v = nn.Linear(dims, dims)  # (h, h)
        self.linear = nn.Linear(dims, dims)  # (h, h)
 
    def forward(self,
                q: torch.Tensor,
                k: torch.Tensor,
                v: torch.Tensor,
                past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
                mask: Optional[torch.Tensor] = None
                ) -> Tuple[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
        
        # Get Query, Key, Value / Shape : (batch_size, seq_length, hidden_size)
        q, k, v = self.proj_q(q), self.proj_k(k), self.proj_v(v)
 
        s = self.attn(q, k, v, mask)
        x = self.linear(s)  # (h, h)
 
        return x, (k, v)
 

Linear layers turn each input state into a query, key, and value. These projection weights are learned during pretraining. Each initially has shape (batch_size, seq_length, hidden_size), so every token has all three vectors.

Linear projections creating query, key, and value vectors.
Linear projections creating query, key, and value vectors.

We then split the vectors across attention heads. This allows multiple attention patterns rather than a single one.

import math
import torch
import torch.nn as nn
from typing import Optional, Tuple
 
 
class MultiHeadAttention(object):
 
    def __init__(self, heads: int, dropout: float = 0.1):
        super().__init__(dropout)
        self.heads = heads
        self.dropout = nn.Dropout(dropout)
 
    def forward(self,
                q: torch.Tensor,
                k: torch.Tensor,
                v: torch.Tensor,
                mask: Optional[torch.Tensor] = None) -> torch.Tensor:
 
        # Split the tensors to multi-heads.
        # Shape : (batch_size, seq_length, head_num, one_head_len)
        q = q.view(q.size()[:-1] + (self.heads, q.size(-1) // self.heads))
        k = k.view(k.size()[:-1] + (self.heads, k.size(-1) // self.heads))
        v = v.view(v.size()[:-1] + (self.heads, v.size(-1) // self.heads))
        
        # Shape : (batch_size, head_num, seq_length, one_head_len)
        q = q.transpose(-3, -2)
        k = k.transpose(-3, -2)
        v = v.transpose(-3, -2)
 
        if mask is not None:
            mask = mask.unsqueeze(-3)  # (batch_size, 1, seq_length, seq_length)
            mask = mask.type_as(x)  # (batch_size, head_num, seq_length, seq_length)
 
 
        # Calculate multi-headed attentions and merge them into one.
        k = k.transpose(-2, -1)  # (batch_size, head_num, one_head_len, seq_length)
        num_heads_sqrt = math.sqrt(k.size(-1))  # sqrt(head_num)
        
        # Matrix Multiple Query AND Keys / Divide with sqrt(head_num)
        # Shape : (batch_size, head_num, seq_length, seq_length)
        score = torch.matmul(q, k) / num_heads_sqrt
        
        # Add Large Negative where the mask is true
        # Shape : (batch_size, head_num, seq_length, seq_length)
        masked_score = score + mask * score.new_tensor(-1e6)
        
        # Softmax
        # float that large negative number has added becomes to zero
        masked_score  = masked_score.softmax(-1)
        masked_score  = self.dropout(masked_score)
        
        # Matrix Multiple score and value
        # Shape : (batch_size, head_num, seq_length, one_head_len)
        attention_score = torch.matmul(x, v)
        
        # (batch_size, seq_length, head_num, one_head_len)
        attention_score = attention_score.transpose(-3, -2).contiguous()
 
        # (batch_size, seq_length, hidden_size)
        original_shape = q.size()[:-3] + (q.size(-2), v.size(-1) * self.heads)
        attention_score = attention_score.view(original_shape)
 
        return attention_score
 

Each hidden-size vector becomes head_num smaller vectors, each of length one_head_len. The following figures show that split and rearrangement.

Splitting a vector into multiple attention heads.
Splitting a vector into multiple attention heads.
The tensor layout after the head split.
The tensor layout after the head split.

Each token now has smaller query, key, and value representations in each head.

Queries multiplied by transposed keys to obtain attention scores.

The query shape is (batch, heads, seq_length, head_dim), and the transposed keys have shape (batch, heads, head_dim, seq_length). Their product is (batch, heads, seq_length, seq_length): a score for each token against all tokens in that sample.

Scaled dot-product attention divides by the square root of head_dim. The historical snippet above uses the wrong dimension after transposing the key tensor; its comment also incorrectly calls this the square root of the number of heads. The intended operations are:

score = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(q.size(-1))
# After masking, softmax, and dropout:
attention = torch.matmul(masked_score, v)

These lines describe the tensors before the key transpose. The original snippet also uses x rather than masked_score in the value multiplication; that line needs the correction shown here.

The future-token mask applied to attention scores.
The future-token mask applied to attention scores.

Scores currently include every position. To hide the future, expand the mask across heads, add a large negative value at true positions, then apply softmax. Those future probabilities become effectively zero.

The original attention-score matrix.
Adding a large negative value at future positions.
Applying softmax to the masked scores.
Future attention probabilities reduced to zero.

Dropout is then applied to the probabilities. The masked positions are the future tokens, correcting a reversed description in the original text.

Attention probabilities multiplying value vectors.
Attention probabilities multiplying value vectors.

Multiplying those probabilities by the values gives each token a weighted combination of the allowed value vectors. Its shape is (batch, heads, seq_length, head_dim).

Combining the heads back into the hidden dimension.

Concatenate the heads and apply the hidden-to-hidden output projection. That completes the attention stage.

3. Residual addition and normalization

The residual path around the attention operation.

Add the layer’s original input to the attention output, then normalize for the next sublayer. This residual, or skip, connection preserves a direct path for the representation.

4. Feed-forward network

A feed-forward sublayer expanding and reducing the hidden dimension.

The feed-forward network expands hidden size by four, then reduces it again. This follows the Transformer design.

import torch.nn as nn
 
class PositionWiseFeedForward(nn.Sequential):
 
    def __init__(self, dims: int, rate: int = 4, dropout: float = 0.1):
        super().__init__(
            nn.Linear(dims, dims * rate),  # (b, s, 4 * h)
            gelu(),  # Activation Function
            nn.Dropout(dropout),
            nn.Linear(dims * rate, dims))  # (b, s, h)

The activation is GELU, shown below.

The GELU activation curve.

I also found a paper on Swish reporting better results in its experiments.

The Swish activation curve.

Swish can be implemented in PyTorch as follows.

import torch.nn as nn
 
 
class Swish(nn.Module):
 
    def __init__(self):
        super().__init__()
        self.sigmoid = nn.Sigmoid()
 
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = x * self.sigmoid(x)
 
        return x
 

5. Another residual addition

The residual connection around the feed-forward network.

Add the feed-forward output to its incoming residual representation. The next GPT layer begins with normalization. The stack depth depends on the model: the largest GPT-3 has 96 layers, rather than the 48 cited in the original example.

Predicting the next token

The final prediction stage after the GPT stack.

Apply the final layer normalization after the stack. The states have shape (batch_size, seq_length, hidden_size). To predict a token, we need a score for every vocabulary entry.

1. Output projection

The input embedding selected hidden-size vectors from vocabulary IDs. The output projection maps hidden states back to vocabulary logits, using the same weight matrix. The following example uses batch size two, sequence length four, vocabulary size three, and hidden size six.

The shared matrix used for input embeddings and output projection.

Both operations share a (vocab_size, hidden_size) parameter matrix, interpreted in the appropriate direction.

Input IDs becoming embeddings and then vocabulary logits.

The next figures show how each final state is compared with vocabulary vectors.

The output-projection calculation.
A final state scoring possible next tokens.

One way to picture it is the final state asking each vocabulary entry how well it fits as the next token.

2. Softmax and loss

Vocabulary logits converted to next-token probabilities.

Softmax turns logits into probabilities for reading or sampling the prediction. Training compares predictions with the shifted label IDs using cross-entropy; a logits-based cross-entropy implementation takes the logits directly.

Wrapping up

This was a long, detailed walkthrough, and writing it helped me organize my own understanding. I'd like to give a seminar on it in our university NLP class, so I plan to ask the professor. Whatever the outcome, sharing something I've learned seems valuable to both the listener and me. Studying language makes me hope I might one day build an innovative model myself.

References

  1. The Illustrated GPT-2
  2. Megatron-LM
  3. Swish paper
  4. GPT2 implementation