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.
- GPT-1 paper
- GPT-2 paper
- GPT-3 paper
- GPT-3 projects
- Jay Alammar's illustrated explanation
- Junho Lim's talk, in Korean
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.
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 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.
- 굳ㅋ
- 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.
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.
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.
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.
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
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.
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.

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 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.
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.
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

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.
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.
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.
Learnable embeddings

1. Token embedding

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.

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)

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.
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.
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.
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

1. Layer normalization
import torch.nn as nn
layer_norm = nn.LayerNorm(hidden_size, eps=1e-5)
ln_vector = layer_norm(final_embed_vector)
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

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.
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.
Each token now has smaller query, key, and value representations in each head.

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.
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.




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

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).

Concatenate the heads and apply the hidden-to-hidden output projection. That completes the attention stage.
3. Residual addition and normalization

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

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.

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

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

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

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.

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

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


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

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.