GPT and Transformer Basics
Transformer Architecture and Language Models
What is a Transformer?
GPT Acronym
The initials GPT stand for Generative Pretrained Transformer. Generative refers to the ability to generate new text. Pretrained means the model has undergone learning from a massive dataset, with the implication that further fine-tuning on specific tasks is possible. Transformer is the key piece: a specific kind of neural network — a machine learning model — that is the core invention behind the current boom in AI.
Transformer as Core Invention
The transformer architecture was introduced by Google in 2017, originally for translating text between languages. The variant underlying tools like ChatGPT is trained to take in a piece of text (possibly with images or sound) and produce a prediction for what comes next in the passage. This prediction takes the form of a probability distribution over many possible chunks of text.
Types of Transformer Models
Transformers are versatile. Some models take audio and produce a transcript; others go the opposite direction, generating synthetic speech from text. Tools like DALL·E and Midjourney, which generate images from text descriptions, are also based on transformers. The focus here is on the next-token prediction variant.
Next-Token Prediction and Text Generation
At first glance, predicting the next word seems different from generating text. However, once a prediction model exists, generation works by:
Giving the model an initial snippet of text.
Having it predict a probability distribution over next tokens.
Sampling a token from that distribution (e.g., the most likely, or a random choice).
Appending that token to the text.
Repeating the process — using the entire new text as input for the next prediction.
This iterative process of repeated prediction and sampling is what happens when interacting with ChatGPT or other large language models. The model produces one word at a time. Early GPT-2 generated stories that often didn't make sense; GPT-3, the same basic model but much larger, produces coherent, context-aware narratives.
High-Level Data Flow in a Transformer
The following describes the flow of data when a transformer chatbot generates a given word.
Tokenization
The input text is broken into small pieces called tokens. For text, these are typically words, subword units, or common character combinations. For images or sounds, tokens might be patches or chunks. Each token is associated with a vector (a list of numbers) encoding the meaning of that piece.
Embedding Vectors
Each token's vector can be thought of as coordinates in a high-dimensional space. Words with similar meanings tend to have vectors close together in that space. These vectors are obtained from a learned embedding matrix.
Attention Block
The sequence of vectors passes through an attention block. This operation allows vectors to "talk to each other" — passing information back and forth to update their values. The attention block determines which words in context are relevant to which other words and how meanings should be updated. For example, the word model in "machine learning model" vs. "fashion model" receives different contextual updates. All meaning is encoded in the vector entries.
Multi-Layer Perceptron (Feed-Forward) Block
After attention, vectors pass through a multi-layer perceptron (MLP) or feed-forward layer. Here, vectors do not interact; each is processed independently in parallel. This step is like asking many questions about each vector and updating it based on the answers. The operations in both blocks consist of large matrix multiplications involving learned weight matrices.
Iterative Processing and Final Probability Distribution
The process repeats — alternating between attention blocks and MLP blocks — until the final layer. The goal is that by the end, all essential meaning of the passage is baked into the very last vector in the sequence. A final operation (multiplication by an unembedding matrix followed by softmax) converts that last vector into a probability distribution over all possible tokens (all possible next chunks of text).
From Prediction to Chatbot
To turn a next-token predictor into a chatbot, a system prompt establishing the setting (e.g., "You are a helpful AI assistant") is used. The user's question becomes the first piece of dialogue. The model then predicts what a helpful assistant would say. Additional training (e.g., reinforcement learning from human feedback) improves this, but the core idea is iterative prediction.
Background: Deep Learning Essentials
Machine Learning Approach
Machine learning solves tasks (e.g., image labeling, next-word prediction) by setting up a flexible structure with tunable parameters (knobs and dials) and using many examples to adjust those parameters to mimic desired behavior. This contrasts with explicitly programming a procedure.
Deep Learning Specifics
Deep learning describes a class of models that scale remarkably well. All such models use the same training algorithm: backpropagation. For this algorithm to work at scale, models must follow a specific format:
Input must be an array of real numbers (a tensor; one-, two-, or higher-dimensional).
Data is progressively transformed through many layers, each structured as an array of numbers.
The final layer is the output (e.g., a list of numbers representing a probability distribution).
Model Parameters and Weights
Model parameters are called weights. The only way weights interact with data is through weighted sums. Non-linear functions are sprinkled throughout, but they do not depend on parameters. Weighted sums are usually packaged as matrix-vector products: each component in the output is a weighted sum of input components. Weight matrices contain tunable parameters; data vectors are transformed by these matrices.
For example, GPT-3 has 175 billion weights organized into nearly 28,000 distinct matrices, falling into eight categories.
Matrix Multiplication as Core Operation
When peeking under the hood of a tool like ChatGPT, almost all computation is matrix-vector multiplication. A sharp distinction must be made between:
Weights (learned, typically colored blue or red in diagrams) — the actual "brains" of the model.
Data being processed (gray) — encodes the specific input for a given run.
Step 1: Tokenization and Embedding
Vocabulary and Tokens
The model has a predefined vocabulary — a list of all possible tokens (e.g., 50,257 tokens for GPT-3). In practice, tokens are pieces of words or punctuation, but for explanation, it's simpler to pretend they are whole words. The first step is breaking input into tokens and turning each into a vector.
The Embedding Matrix (WE)
The embedding matrix (labeled WE) has one column for each token in the vocabulary. Each column determines the vector into which that token is transformed. The matrix is initialized randomly and learned during training. For GPT-3, the vocabulary is 50,257 and the embedding dimension is 12,288, giving about 617 million weights in this matrix alone.
Geometric Interpretation of Embeddings
Word vectors can be thought of as points in a high-dimensional space. Visualizing a list of three numbers as a point in 3D is straightforward; embeddings for GPT-3 have 12,288 dimensions. The large dimensionality is important because many distinct semantic directions are needed.
During training, the model settles on embeddings where directions in the space carry semantic meaning. For instance:
The difference between woman and man is similar to the difference between king and queen, suggesting a gender direction.
The difference between Italy and Germany added to Hitler gives a vector close to Mussolini, encoding national and historical associations.
Germany minus Japan plus sushi yields a vector near bratwurst.
In a simple word-vector model, words with similar meanings cluster together (e.g., tower is near other "tower-ish" words). The classic example of analogies via vector arithmetic (e.g., king - man + woman ≈ queen) illustrates that embeddings encode relational semantics.
Dot Product and Similarity
A key mathematical tool is the dot product of two vectors:
Computationally: multiply corresponding components and sum.
Geometrically: positive when vectors point in similar directions, zero when perpendicular, negative when opposite.
For example, the vector cats minus cat might represent a "plurality direction." Dot products of this vector with plural nouns (e.g., dogs) are higher than with singular noun (dog), quantitatively measuring pluralness. Numbers like one, two, three show increasing dot products with this direction, indicating the model's sense of count.
Context Size and Fixed Array
The network can only process a fixed number of vectors at a time — its context size. For GPT-3, the context size is 2048. The data flowing through always looks like an array of 2048 columns, each of 12,288 dimensions. This limits how much text the transformer can incorporate when making predictions. This is why long conversations with early ChatGPT could lose the thread.
Initially, each vector is simply plucked from the embedding matrix, encoding only the token's basic meaning. The network's primary goal is to enable each vector to soak up context — the meaning of a given word becomes richer and more specific based on surroundings, including distant context.
Step 2: The Final Output – Unembedding and Softmax
Predicting the Next Token
The desired output is a probability distribution over all tokens that might come next. For example, if the context ends with "Professor" and the text includes "Harry Potter" and "least favorite teacher," a well-trained network would assign high probability to "Snape."
This involves two steps:
Use an unembedding matrix (WU) to map the last vector in the context to a list of 50,257 values (one per token).
Apply the softmax function to normalize this list into a valid probability distribution.
It may seem odd to use only the last embedding, but during training, each vector in the final layer is used simultaneously to predict what comes after it, making training more efficient.
The Unembedding Matrix (WU)
The unembedding matrix has one row per token, with each row having the same dimension as the embedding (12,288). It is also learned from random initialization. For GPT-3, this adds another 617 million parameters, bringing the total to slightly over 1 billion (a small fraction of the 175 billion total).
Softmax Function
Softmax converts an arbitrary list of real numbers (which can be negative, >1, or not sum to 1) into a valid probability distribution (each value between 0 and 1, sum to 1).
Mathematically:
Raising e to each number yields positive values.
Dividing by the sum normalizes them to sum to 1.
Larger input values dominate the output; smaller values become near zero. This is "soft" because when multiple inputs are similarly large, they all get meaningful weight, and changes are continuous.
Temperature and Sampling
A temperature parameter T can be added:
Higher T: distribution becomes more uniform (gives more weight to lower values), allowing less likely tokens to be chosen — more creative but risk nonsense.
Lower T: large values dominate more; T=0 makes the distribution a delta function on the maximum token (always choose the most predictable word).
T is analogous to temperature in thermodynamics.
For example, with seed "Once upon a time there was a":
Temperature 0 yields a trite Goldilocks derivative.
Higher temperature produces more original but possibly nonsensical text (e.g., "a young web artist from South Korea" then degenerating).
API constraints often cap temperature at 2 for practical reasons.
Logits and Probabilities
The raw, unnormalized outputs of the final matrix multiplication are called logits. After softmax, they become probabilities. The term "logit" is commonly used in machine learning for these pre-softmax scores.
Parameter Count Example (GPT-3)
GPT-3 has 175 billion parameters total, composed of:
Nearly 28,000 distinct weight matrices
Eight different categories of matrices
Two categories have been covered:
Embedding Matrix Size
Vocabulary size: 50,257 tokens
Embedding dimension: 12,288
Parameters: 50,257×12,288≈617 million
Unembedding Matrix Size
Same dimensions in reverse: 12,288 rows, 50,257 columns? Actually, it has 50,257 rows (one per token) and 12,288 columns, so again ≈ 617 million parameters.
Total So Far
Embedding + Unembedding ≈ 1.23 billion parameters. This is a small fraction of the 175 billion; the remaining parameters reside in attention and MLP blocks across many layers.
Key Takeaways
Transformers are built on tokens, embeddings, attention, and feed-forward layers, all implemented via matrix multiplications.
Word embeddings encode semantic meaning in high-dimensional vectors; directions correspond to semantic features.
Attention allows context-dependent updates to token vectors; MLP layers process each vector independently.
The model predicts the next token using the last vector in the sequence, transformed by the unembedding matrix and softmax.
Temperature controls randomness in sampling from the predicted distribution.
Deep learning requires all operations to be weighted sums (matrix products) with differentiable nonlinearities, enabling backpropagation training.
GPT-3's 175 billion parameters are distributed across many matrices; understanding the role of each matrix type is essential for grasping transformer mechanics.

Ask anything
We've read this whole study set, so questions about it get the best answers.