10 - Attention, Transformers, and Large Language Models

Class: CSCE-421


Notes:

These slides are based on Chapter 12 of Deep Learning: Foundations and Concepts

Word Embedding

Example

I swam across the river to get to the other bank.
I walked across the road to get cash from the bank.

07 - Inbox/Visual Aids/image-21.png452x170

Notes:

Neural language and word embedding

vn=Exn

Notes:

Checkpoint 1 (word embedding)

To understand Large Language Models (LLMs) like ChatGPT, we have to start at the very beginning: How do we teach a neural network to read words, and how do we teach it to understand context?

1. The "Context" Problem (The Example) Read these two sentences:

As a human, you instantly know the word "bank" means two completely different things here. You know this because you subconsciously looked at the surrounding words ("river" and "swam" vs. "cash"). In a standard Neural Network (like a CNN or MLP), the weights are permanently fixed after training. If you feed it the word "bank," it will always process it using the exact same fixed weights, completely ignoring the unique context of the sentence.

2. The Solution: Attention To solve this, we need a network that can change its weights on the fly depending on the specific sentence it is reading. This is called Attention. In an Attention layer, when the network is trying to process the word "bank," it dynamically calculates a set of weighting coefficients that determine how much "attention" it should pay to every other word in the sentence. In the first sentence, it will assign a massive mathematical weight to the word "river", effectively blending the meaning of "river" into "bank".

3. Neural Language & Word Embeddings Before we can even do Attention, we have to convert English words into numbers, because neural networks can only do math. This happens in the very first layer of the network, called the Embedding Layer.

4. The Neural Network View (EXAM QUESTION WARNING!) Your professor explicitly mentioned an exam question here: "Explain the embedding layer from a neural network point of view." Mathematically, doing vn=Exn is the exact same formula as passing data through a standard Fully Connected layer (wTx). However, because we use the exact same E matrix to transform every single word in our sentence, the answer your professor is looking for is: An embedding layer is a fully connected layer that is shared among all the input vectors.

Attention

Transformer processing

The input data to a transformer is a set of vectors {xn} of dimensionality D, where n=1,…,N

X~= TransformerLayer [X]

image-27.png174

Notes:

Attention coefficients

yn=∑m=1Nanmxm

where

anm⩾0, and ∑m=1Nanm=1.

Commonly used coefficients

anm=exp⁡(xnTxm)∑i=1Nexp⁡(xnTxi),an= Softmax [xnTx1xnTx2⋮xnTxN]

We have a different set of coefficients for each output vector yn

Notes:

Attention in general (cross attention) - IMPORTANT

image-28.png351x254

Notes:

Checkpoint 2 (Attention in general)

To understand Large Language Models, we have to understand the core engine inside them: the Transformer layer and its Attention mechanism.

1. Transformer Processing Imagine a sentence with N words (tokens). From the previous slides, we know the Embedding Layer converts each of these words into a vector of numbers of size D.

2. Attention Coefficients How does the network make these word vectors "smarter"? It uses a linear combination. To generate the new output vector for the first word (y1), the network looks at all the input vectors (x1,x2,…,xN) and blends them together.

3. Attention in general (Q, K, V) - IMPORTANT This is the most critical concept. Calculating attention just by comparing X to X is a bit rigid. To make the network highly flexible, we introduce a database-like retrieval system using three matrices: Queries (Q), Keys (K), and Values (V). Think of a video streaming search:

In neural networks:

  1. You take a Query vector (the word you are currently trying to process) and calculate the dot product with every single Key vector (every other word's tags).
  2. You apply Softmax to those scores to find out which Keys best match your Query (this gives you your coefficients).
  3. You multiply those coefficients by the Value vectors to get your final output. (Note: In "Self-Attention", Q, K, and V are all just the input matrix X itself, meaning the sentence is searching itself for context!).

4. The Rules of Q, K, V (Exam Warning!) Your professor highlighted specific exam questions regarding the dimensions and permutations of these matrices:


Let's break down the exact math behind general attention from scratch so you can confidently put it on your cheat sheet. Your 3-step logic is actually perfectly correct conceptually, but it is missing the specific linear algebra rules that make it work.

Here is the detailed, step-by-step breakdown of how the matrices operate, why we use rows, and how the sizes are calculated.

1. What are "Rows"?

In Transformers, data is structured as a matrix where each row represents a single word (or token), and the columns are the numerical features (the embedding dimensions) of that word. Therefore, when we talk about Q, K, and V matrices, we are looking at stacks of words. A single "Q vector" is just one row from the Q matrix, representing the specific "Query" word you are currently trying to process.

2. Step 1: The Dot Product (QKT)

You want to know how similar your single Query word (a row in Q) is to every single Key word (the rows in K). The mathematical way to measure similarity between two vectors is the dot product.

3. Step 2: Softmax

You apply the Softmax function to that single row vector of raw scores. Softmax simply converts these numbers into a probability distribution—it turns them into a row of percentages (coefficients) between 0 and 1 that sum perfectly to 1.

4. Step 3: Multiplying by V

This is where the linear algebra magic happens. You now have a row vector of percentages, and you need to multiply it by the V matrix (where each row is a Value word).

5. What is the size of the final output?

Instead of processing one query word at a time, the equation Y=Softmax[QKT]V processes all query words at once using matrix multiplication. Here is how the dimensions determine the final output size:

General attention in matrix form

Y=Softmax[QKT]V

where Softmax [L] takes the exponential of every element of L and then normalizes each row independently to sum to one

image-30.png428x177

Notes:

Self-attention without parameters

Y=Softmax[XXT]X

where Softmax [L] takes the exponential of every element of L and then normalizes each row independently to sum to one

Notes:

Self-attention with parameters

Q=XW(q)∈RN×Dk K=XW(k)∈RN×Dk V=XW(v)∈RN×Dv

image-31.png507

Notes:

Comparison of Cross and Self Attention

image-32.png507

Notes:

Dot-product scaled attention

Y=Attention(Q, K, V)≡Softmax[QKTDk]V

image-33.png164

Notes:

Multi-head attention

Hh=Attention(Qh, Kh, Vh) Qh=XWh(q)Kh=XWh(k)Vh=XWh(v) Y(X)= Concat [H1,…,HH]W(o)

image-34.png373x410

Notes:

Question: Why are we doing this multi-head attention?

The most common version of attention is the dot product scaled multi-head self attention.

Checkpoint 3 (Self attention and multi-head)

To understand how Large Language Models like ChatGPT process text, we need to look at how they build their "Attention" mechanism step-by-step.

1. Self-Attention without parameters In the previous slides, we learned that Attention uses Queries (Q), Keys (K), and Values (V). If we want a sentence to simply look at itself for context, the most basic thing we can do is just plug the raw input matrix X (our sentence of word vectors) directly into all three variables.

2. Self-Attention with parameters To make the network smart, we need to give it learnable weights so it can figure out exactly what to pay attention to. We do this by introducing three independent weight matrices: W(q), W(k), and W(v).

3. Comparison of Cross and Self Attention This is a crucial distinction for understanding different model architectures:

4. Dot-product scaled attention When we compute similarity scores using the dot product (QKT), we run into a severe mathematical danger.

5. Multi-head attention If you read a sentence, you can analyze it for different things simultaneously: one part of your brain looks for grammar, another looks for emotion, and another looks for names. Multi-head attention gives the neural network the same ability.

Transformer Layers

Transformer layers

Z= LayerNorm [Y(X)+X] Z=Y( LayerNorm [X])+X

00 - TAMU Brain/6th Semester (Spring 26)/CSCE-421/Ex2/Visual Aids/image-35.png134x262

Notes:

MLP in Transformer layers

Transformer layers

X~= LayerNorm [MLP[Z]+Z] X~=MLP(Z′)+Z, where Z′= LayerNorm [Z]

Notes:

Positional encoding

Notes:

Checkpoint 4 (transformer layers)

Now that we know how Attention works, we can finally build the actual "Transformer Layer" (often called a Transformer Block). A modern Large Language Model simply takes this block and stacks it on top of itself dozens of times.

1. The Transformer Layer: Residuals and Normalization To stack multiple attention layers successfully without gradients vanishing, we must use Residual (Skip) Connections. This is why we enforced the strict rule that the output of an attention layer must have the exact same dimensionality (N×D) as the input. We simply take the original input X and add it to the attention output Y(X).

2. MLP in Transformer layers There is one major flaw with Attention: it only computes linear combinations of the input vectors. It just blends existing words together. If we want the network to think deeply and extract complex, non-linear features, we need to pass this data through a standard neural network (a Multi-Layer Perceptron, or MLP).

3. Positional Encoding We have one final, critical problem to solve. The Transformer architecture we just built is perfectly permutation equivariant. If you scramble the order of the rows (words) in the input matrix, the network does the exact same math, and simply outputs the scrambled rows in the exact same order.

LLMs I

Language models: Narrow sense

p(x1,…,xN)=∏n=1Np(xn∣x1,…,xn−1)

Notes:

n-gram model and LLMs (Courtesy R. Kambhampati)

p(x1,…,xN)=p(x1)p(x2∣x1)∏n=3Np(xn∣xn−1,xn−2)

Notes:

Language models: Broad sense

Notes:

Checkpoint 5 (n-gram and LLMs)

To understand how Large Language Models (LLMs) like ChatGPT work, we have to look at the fundamental mathematical goal of a language model: figuring out the probability of a sequence of words.

1. Language Models: Narrow Sense (The Product Rule) Language models learn the joint probability distribution p(x1,…,xN) of an ordered sequence of words. In simple terms, this means the model evaluates how likely a specific sentence is to exist. To calculate the probability of a whole sentence, we use the "product rule of probability". This rule breaks the sentence down step-by-step: the probability of the whole sentence is the probability of the first word, multiplied by the probability of the second word given the first word, multiplied by the probability of the third word given the first two words, and so on. Mathematically, this is written as: $$p(x_1, \ldots, x_N) = \prod_{n=1}^N p(x_n \mid x_1, \ldots, x_{n-1})$$
2. The Exponential Explosion Problem If you wanted to build a simple computer program to do this, you could just create a giant lookup table. You would count how many times word combinations appear in real books and store those probabilities. However, as your notes and homework point out, the size of this table grows exponentially with the length of the sequence. If your vocabulary has 50,000 words, predicting just the 4th word means your table must have a unique row for every possible 3-word combination (50,000×50,000×50,000). For long sentences, building a physical table becomes computationally impossible.

3. The Old Solution: n-gram Models Before modern deep learning, scientists solved this table explosion by simply artificially cutting off the memory of the model. This is called an n-gram model. Instead of looking at the entire history of the sentence, an n-gram model assumes the next word only depends on the L most recent words.

4. The Modern Solution: LLMs Modern LLMs, like ChatGPT, do not use n-grams; they track a massive context history (e.g., the previous 3,000 words). If we used a table for this, we would need 50,0003000 entries, which is physically impossible. The breakthrough of LLMs is that they compress and approximate this gigantic table using a mathematical function (the neural network). Instead of storing every possible combination, the network learns the underlying patterns. Therefore, even though LLMs have billions of parameters, they are actually incredibly tiny compared to the size of the true probability table they are approximating.

Decoder Transformers

Decoder transformers I

Notes:

|X| Decoder transformers II

Y=Softmax(X~ W(p))

where Y is a matrix whose nth row is ynT, and X~ is a matrix whose nth row is x~nT

...

Decoder transformers: casual language modeling

I swam across the river to get to the other bank.

image-37.png227
Figure 12.16 An illustration of the mask matrix for masked self-attention. Attention weights corresponding to the red elements are set to zero. Thus, in predicting the token 'across', the output can depend only on the input tokens '<start>' 'I' and 'swam'.

Notes:

Decoder transformer architecture

00 - TAMU Brain/6th Semester (Spring 26)/CSCE-421/Ex2/Visual Aids/image-36.png
Figure 12.15 Architecture of a GPT decoder transformer network. Here 'LSM' stands for linear-softmax and denotes a linear transformation whose learnable parameters are shared across the token positions, followed by a softmax activation function. Masking is explained in the text.

Notes:

Remember self attention:

Difference between training and generation/inference

Sampling strategies during generation/inference I

p(y1,…,yN)=∏n=1Np(yn∣y1,…,yn−1)

Notes:

Sampling strategies during generation/inference II

yi=exp⁡(ai/T)∑jexp⁡(aj/T)

Notes:

Checkpoint 6 (decoder transformers)

To understand modern Generative AI like ChatGPT, we only need to look at the Decoder-Only Transformer (also known as the GPT architecture, which stands for Generative Pretrained Transformer).

1. Decoder Transformers I & II (The Architecture) A Decoder model is fundamentally just a massive multi-class classifier whose only job is to predict the next word.

2. Causal Language Modeling (The Mask) If we want to train the model efficiently, passing one word at a time is too slow. Instead, we pass the entire sentence through the network at once.

3. Training vs. Generation (Inference)

4. Sampling Strategies (How to pick the next word) When the model outputs a probability distribution for the next word, how do we actually pick one?

Encoder Transformers

Encoder transformers: Masked language modeling

Notes:

Encoder transformer architecture

image-38.png

Figure 12.18 Architecture of an encoder transformer model. The boxes labelled 'LSM' denote a linear transformation whose learnable parameters are shared across the token positions, followed by a softmax activation function. The main differences compared to the decoder model are that the input sequence is not shifted to the right, and the 'look ahead' masking matrix is omitted and therefore, within each self-attention layer, every output token can attend to any of the input tokens.

Notes:

Sequence-to-sequence transformers

Notes:

Comparison of self and cross attention

image-39.png187x395 image-40.png161x397

Figure 12.19 Schematic illustration of one crossattention layer as used in the decoder section of a sequence-to-sequence transformer. Here Z denotes the output from the encoder section. Z determines the key and value vectors for the crossattention layer, whereas the query vectors are determined within the decoder section.

Notes:

Sequence to sequence transformer architecture

image-41.png

Figure 12.20 Schematic illustration of a sequence-to-sequence transformer. To keep the diagram uncluttered the input tokens are collectively shown as a single box, and likewise for the output tokens. Positional-encoding vectors are added to the input tokens for both the encoder and decoder sections. Each layer in the encoder corresponds to the structure shown in Figure 12.9, and each cross-attention layer is of the form shown in Figure 12.19.

Notes:

Checkpoint 7 (encoder transformers & others)

To complete our understanding of Transformers, we need to look at the other two ways we can build them: Encoders (for understanding text) and Sequence-to-Sequence (for translating text).

1. Encoder Transformers: Masked Language Modeling Unlike the Decoder (GPT) which generates text one word at a time, an Encoder model (like BERT) is designed to read an entire sentence and output a fixed-length vector that captures the overall meaning of that text. This is perfect for tasks like sentiment analysis (e.g., deciding if a movie review is positive or negative).

2. Encoder Transformer Architecture Because of its bidirectional nature, the architecture of an Encoder is much simpler than a Decoder:

3. Sequence-to-Sequence Transformers What if we want to translate an English sentence into Dutch? We can combine both architectures.

4. Comparison of Self and Cross Attention This brings us to the most important mechanism in a Sequence-to-Sequence model:

5. Sequence to Sequence Transformer Architecture The architecture is simply the Encoder block and the Decoder block glued together. The Encoder processes the input, and the Decoder features an extra "Cross-Attention" layer right in the middle of its block to pull in the Encoder's data.

LLMs II

Large Language models: Pretraining

Notes:

...

Large language models: Emerging properties

Notes:

Large language models: Prompting

image-42.png426

Notes: