Attention Mechanisms and Transformer Architecture
Prerequisite Knowledge
This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.
Previously Covered in This Subject
- Encoder-Decoder Architecture — covered in Lecture 14
- Context Vector and Bottleneck — covered in Lecture 14
- Attention Mechanisms (Query, Key, Value) — covered in Lecture 14
- Self-Attention and Cross-Attention — covered in Lecture 14
- Attention Scoring (Dot-Product, Bahdanau) — covered in Lecture 14
- Attention Heatmaps and Interpretability — covered in Lecture 14
Attention Mechanisms and Transformer Architecture
15.1 Review -- Limitations of RNNs and the Encoder-Decoder Architecture
15.1.1 RNN Limitations
Why can a recurrent network tag every word in a sentence with its part of speech, yet completely fail at translating that same sentence into another language?
Traditional recurrent neural networks hit three hard walls.
Think of an RNN as someone reading a book aloud, one word at a time. They can only say one word after another. They cannot skip ahead. And after reading for a while, they start to forget what happened in chapter one. This is the RNN's life: sequential, short-memory, and locked to a fixed rhythm of input and output.
The length mismatch problem. A standard RNN expects the input sequence length to equal the output sequence length. Part-of-speech tagging works because each input word gets exactly one output tag. But translation does not. An English sentence of six words may need a French translation of ten words. A question of several words maps to an answer with an unknown number of words. The RNN has no natural way to handle this mismatch.
The long-range memory problem. Even LSTMs, with their explicit memory cells, start forgetting after about 100 to 200 tokens. The hidden state is a fixed-size vector. You cannot cram an entire paragraph into it. Earlier information gets overwritten by later information.
The sequential bottleneck. RNN processing is strictly step-by-step. You must wait for timestep to finish before starting timestep . There is no way to process all words at once. This kills parallelism and makes training on large datasets painfully slow.
15.1.2 The Encoder-Decoder Solution
The encoder-decoder architecture splits the task into two independent stages. The encoder reads the entire input sequence and compresses it into a single summary vector -- the context vector (also called a latent representation). The decoder takes this context vector and generates the output sequence word by word.
Picture a court translator. The encoder is the translator listening to the full statement in language A and jotting down key notes. The decoder is the same translator reading those notes and speaking the translation aloud in language B. The notes serve as the context vector -- the compressed bridge between two different-length sequences.
Encoder and decoder are not fixed architectures. Each is simply a neural network playing a role. You can build the encoder with an RNN, a CNN, or any other network. The decoder can also be any network type. The names describe what the component does, not how it is implemented.
The encoder extracts the pattern. The decoder uses that pattern to produce a sequence. This clean split handles the input-output length mismatch.
15.1.3 The Context Bottleneck Problem
The encoder-decoder design has its own failure point: the context vector itself.
Scope: The context vector is a single fixed-length vector. No matter how long or complex the input is, all of it must fit through this one narrow channel. When sequences grow long and patterns grow complex, one vector cannot faithfully represent everything.
Two specific problems arise. First, what if the context vector is poor? What if the encoder, being an RNN, focused mostly on the final few words and forgot the early ones? The resulting context misrepresents the input, and the decoder generates a poor output.
Second, in the basic design, the context vector feeds only the first timestep of the decoder. By the time the decoder reaches its tenth or twentieth output word, the original context may have faded entirely from the decoder's internal state.
Partial fix: Pass a copy of the context vector to every decoder timestep instead of just the first one. This keeps the input information alive throughout the generation. But it still does not solve the problem of the context vector being too small to hold everything.
The deeper fix -- the one that changed everything -- is the attention mechanism. Instead of one fixed context vector, attention lets the decoder consult different parts of the input at every decoding step. This is the topic of the next section.
15.1.4 Student Questions and Answers
Q: Several students asked about the EC3 exam format. What question types should we expect? What is the split between pre-mid-sem and post-mid-sem material?
A: EC3 mirrors the EC2 format. You will see similar question types: numerical computation, conceptual reasoning, and code debugging. EC3 adds application-based questions -- you may get a real-world scenario and need to pick which architecture fits best and explain why. You may also get component-level questions: instead of "define self-attention," the question might ask "what is the purpose of self-attention in this given scenario?" Expect decoding questions (find errors in a code snippet or architecture diagram) and dimension-tracking problems (trace how dimensions change through an encoder block). Go through all live session recordings and the PPT and reading material on the e-learning portal. That alone is enough -- no external sources needed.
Q: For assignments, our display names have a full stop after them. Does the name need to be an exact match for auto-grading?
A: Part of the evaluation is AI-assisted with faculty moderation on top. It is better to ask this as a query in the announcements section or write directly so the team can clarify.
RNNs fail on three fronts: length mismatch, long-range memory, and sequential bottleneck. The encoder-decoder fixes the length problem by splitting the task, but then creates the context bottleneck -- one fixed vector cannot capture everything. Attention is the fix. Every modern LLM (GPT, Claude, Gemini, Copilot) is built on Transformer architectures that grew from this exact insight.
Real-world connection: The encoder-decoder pattern shows up far beyond NLP. Image captioning uses a CNN encoder (to understand the image) and an RNN/Transformer decoder (to write the caption). Speech recognition uses an encoder to process the audio waveform and a decoder to produce the text output. The same split -- encode into a latent space, then decode from it -- underpins generative models like variational autoencoders (VAEs) and diffusion models.
15.1.5 Visual Intuition
Picture three diagrams side by side.
Diagram 1 -- Standard RNN: A horizontal chain of boxes, one per input word. Each box connects to exactly one output box below it. Input length equals output length. This is the part-of-speech tagging setup.
Diagram 2 -- Encoder-Decoder: Two separate blocks. On the left, a stack of input words feed into the encoder block, which outputs a single vector (the context). An arrow carries that vector across to the decoder block on the right, which produces output words one at a time. Input length and output length are independent.
Diagram 3 -- Context bottleneck failure: The same encoder-decoder diagram, but now a long input sentence is shown feeding into the encoder, and the single context vector is drawn as a tiny bottle neck. Information spills out the sides -- the vector is too small. This is why attention was invented.
15.1.6 Assumptions, Scope, and Pitfalls
Assumptions: The encoder-decoder framework assumes that all information needed for decoding can be captured in a single vector. This assumption holds for short, simple sequences. It breaks down for long or complex inputs.
Common pitfalls:
- Thinking "encoder" and "decoder" refer to specific network types (RNN, CNN, etc.). They are roles, not implementations.
- Assuming the context vector always carries enough information. For sequences beyond ~50 tokens, a fixed-size context vector is usually insufficient.
- Confusing encoder-decoder (architecture pattern) with autoencoders (unsupervised learning). They share the encode-decode idea but serve different purposes.
- Forgetting that passing the context to every decoder timestep only partially helps. The vector itself is still size-limited.
15.1.7 Recap and Bridge
RNNs are sequential, forgetful, and locked to matched input-output lengths. The encoder-decoder pattern solves the length mismatch but introduces the context bottleneck. The next section introduces attention, which eliminates the bottleneck by giving the decoder a tailored view of the input at every single timestep.
15.2 Attention Mechanism -- Core Intuition
15.2.1 Customized Context Per Timestep
What if, instead of giving the decoder the same summary of the entire input at every step, you could let it peek back at whichever input words matter most for the word it is about to generate right now?
That is the core idea behind attention. Produce a different context vector at every decoder timestep. Each context is customized -- it gives more weight to the input words that are relevant to the current output word and less weight to everything else.
Imagine you are translating a long sentence from French to English. When you generate the third English word, you might glance back mostly at the second and fifth French words. When you generate the seventh English word, you might focus on the first and fourth French words instead. The machine learns, from data, which input words to look at for each output position.
This solves the context bottleneck. You do not need one vector to capture everything. You build a fresh, targeted summary at every step, pulling in exactly the information you need for that step.
15.2.2 Scoring, Keys, Queries, and Values
The attention mechanism uses three kinds of vectors, all learned during training:
- Query (): Represents the current decoding state. At each decoder timestep, the query asks: "I am about to generate the next output word. Which input words should I pay attention to?"
- Key (): An identifier for each input word. The key says: "Here is who I am in the input sequence -- match against me."
- Value (): The actual information content of each input word. The value says: "Here is the useful information I carry -- if you pick me, take this."
Think of a library. The query is your research question. The keys are the titles on the book spines -- you scan them to decide which books are relevant. The values are the actual content inside the books. You do not read every book. You scan the titles (keys), pick the matching ones, and read only those (values). More relevant books get more of your attention. The same system works for every new question you ask.
The scoring process, step by step:
- Compare the query with every key. Each comparison gives a score -- a number that says how well this input word matches what you are trying to produce right now.
- Apply Softmax to the scores. This turns them into a probability distribution (the attention weights). All weights sum to 1.
- Weight the values. Multiply each input word's value vector by its attention weight.
- Sum everything up. Add the weighted values together. This sum is the customized context vector for the current decoder timestep.
The professor put it plainly: "The machine learns to give more importance, more score, or more weight to some nodes. And it gives lesser weight to all other nodes."
15.2.3 Attention Heatmaps and Interpretability
A valuable side effect of attention is interpretability. You can draw an attention heatmap: a grid where rows are input words, columns are output words, and the color at each cell shows how much attention the output word paid to that input word. Lighter colors mean stronger influence.
In a machine translation example from the lecture, the decoder generated the word "both" at the third timestep. The heatmap showed that the input word "very" had the strongest influence at that moment. The words "this" and "is" had much less. You can literally see which parts of the input the model considered most important for each part of the output.
Caution: While attention heatmaps are useful for debugging and building intuition, researchers debate exactly how much they can be trusted as explanations. High attention weight does not always mean causal importance. Use heatmaps as a clue, not as proof.
15.2.4 Visual Intuition
Draw a matrix where rows are the four input words ["this", "is", "very", "good"] and columns are the three output words ["c'est", "tres", "bien"]. Color each cell by attention weight.
At column 1 ("c'est"), the row for "this" lights up brightest. At column 2 ("tres"), the row for "very" dominates. At column 3 ("bien"), the row for "good" is brightest. The diagonal-like pattern shows the model learned word-level alignment -- exactly what you would expect from translation. The beauty is that it learned this alignment entirely from data, without any explicit alignment supervision.
15.2.5 Assumptions, Scope, and Pitfalls
Scope: The attention mechanism assumes that for any output position, the relevant input information can be expressed as a weighted sum of input value vectors. This works well when inputs have clear, localizable contributions. It can fail when the relationship is non-additive -- for instance, when the meaning depends on the interaction between two input words, not just their individual contributions.
Common pitfalls:
- Thinking attention "understands" language. It learns statistical correlations between positions. There is no semantic comprehension.
- Assuming attention weights tell the full story. High weight does not imply the model actually used that information downstream.
- Forgetting the Softmax step. Raw dot-product scores can be any real number. Only after Softmax do they become a proper distribution summing to 1.
- Treating attention as a complete model. It is a mechanism -- a building block. The full model also needs position information, feed-forward layers, and training objectives.
15.2.6 Recap and Bridge
Attention replaces one fixed context vector with a fresh, customized context at every decoder step. It works by matching a query against keys, scoring relevance, and computing a weighted sum of values. The next section covers the different flavors of attention -- self-attention, multi-headed attention, cross-attention, and masked attention -- and how they combine to build the Transformer.
Real-world connection: Attention mechanisms are now used well beyond NLP. In computer vision, attention helps models focus on relevant image regions when generating captions or answering visual questions. In speech processing, attention aligns acoustic frames with phoneme sequences. In recommendation systems, attention weights capture which past user behaviors are most relevant to predicting the next click.
15.3 Types of Attention
15.3.1 Self-Attention
What if every word in a sentence could look at every other word and decide, for itself, which other words matter most to its own meaning? That is self-attention.
In self-attention, the query, key, and value all come from the same sequence. You are asking: "within this sentence, how does each word relate to every other word?"
Formally, given a sequence of tokens each with a -dimensional embedding, self-attention produces an output sequence of the same length where each output is a weighted combination of all input values: where each serves as query, key, and value after projection through learned matrices .
Think of a group discussion. Each person (word) listens to everyone else and decides, for themselves, whose opinions matter most to what they want to say next. One person might care about the topic-setter's words. Another might care about the person who just spoke. Self-attention lets every word form its own custom "listening profile" over the entire group.
Application -- Word sense disambiguation. Consider "The bank is near." The word "bank" could be a financial institution or a riverbank. Self-attention helps disambiguate by letting "bank" attend to "the," "is," and "near." The surrounding context words provide the clues that resolve the meaning. Without self-attention, the model would see "bank" in isolation and have no way to know.
The diagonal of the attention matrix (a word attending to itself) is usually the strongest. In practice, these self-scores are often neglected or masked because a word always relates strongly to itself. What matters is the off-diagonal -- the cross-word influence.
Key property: Self-attention eliminates the need for recurrent connections. Every word directly interacts with every other word. All outputs can be computed simultaneously. Parallelism is finally possible.
The professor emphasized: "In self-attention, you take the essence from every input. You compare query, key, and value within the same sequence. The sequential dependency is eliminated."
Self-attention is the engine of the Transformer. Every word sees every other word, and computation happens in parallel -- no more waiting for the previous timestep.
15.3.2 Multi-Headed Attention
One attention head is like one person reading a sentence and noticing only the grammar. But language is richer than that. What if you had several people reading simultaneously -- one spotting grammar, one tracking subject-verb agreement, one untangling who did what to whom?
Multi-headed attention runs separate self-attention heads in parallel. Each head has its own learned projection matrices . Each head learns to extract a different kind of relationship from the same input.
The process:
- Feed the same input to all heads.
- Each head independently computes self-attention using its own projections.
- Concatenate the outputs from all heads: .
- Multiply by an output projection matrix to compress back to the desired dimension:
Worked example: Suppose you have 3 heads, each producing a 4-dimensional output vector. Concatenation gives a 12-dimensional vector. The output matrix (shape ) compresses this back to 4 dimensions so the result can feed into the next layer.
The professor compared this to CNNs: "Each head is a pattern detector -- just like having multiple kernels or filters in a CNN. One head learns part-of-speech tags. Another learns subject-verb agreement. A third learns dependency parsing. They all run in parallel -- that is the beauty."
The number of heads is a hyperparameter you choose. Typical values: 8 heads (base Transformer), 12 or 16 heads (larger models). This is the architectural centerpiece of the Transformer.
15.3.3 Cross-Attention
In cross-attention, the query comes from one sequence and the keys and values come from a different sequence. The query is from the decoder (what you are generating). The keys and values are from the encoder (the input you are processing).
where is the decoder hidden state at the previous timestep (the query), and are the encoder hidden states (both keys and values).
Imagine translating a document. The decoder has just produced the French word "pieds." Now it needs to produce the next word. It looks back at the English source sentence and asks: "which English words relate most to what I just said?" The query is the French word you just generated. The keys and values are the English source words from the encoder. Cross-attention aligns target-language generation with source-language information.
Cross-attention is the bridge in any sequence-to-sequence task: machine translation, text summarization, question answering, dialogue systems. Wherever two distinct sequences interact, cross-attention is the link.
15.3.4 Masked Attention
Masked attention is a technique, not a separate architecture. It prevents the model from seeing future words during training, which would be cheating. Before applying Softmax, you set the attention scores of all future positions to . After Softmax, , so those positions contribute nothing.
Without masking, the model can copy the answer directly from the future during training. It learns nothing about prediction. Masking forces the model to predict each word using only what came before.
Example: For the sentence "the customer was very happy with the service," consider the word "very" at position 4. When computing attention at position 4, all positions beyond 4 get masked. The words "happy," "with," "the," and "service" are hidden. The model sees only "the," "customer," "was," and "very."
This is essential for decoder-only models like GPT, where text generation is autoregressive -- each new word is predicted from all previous words only. The model never gets to peek ahead.
15.3.5 Comparison of Attention Types
| Type | Query source | Key/Value source | Masking? | Used for |
|---|---|---|---|---|
| Self-Attention | Same sequence | Same sequence | No | Encoding, classification, relationship learning within one text |
| Multi-Headed | Same sequence (h copies) | Same sequence (h copies) | No | Learning multiple relationship types in parallel |
| Cross-Attention | Decoder (target) | Encoder (source) | No | Sequence-to-sequence tasks (translation, summarization) |
| Masked Attention | Same sequence | Same sequence | Yes (future positions) | Autoregressive generation (GPT-style models) |
When to pick which: Use self-attention when working within one sequence. Add multiple heads when you need to capture different relationship types. Use cross-attention when you have two distinct sequences to align. Apply masking whenever generation must be autoregressive.
15.3.6 Visual Intuition
Draw an attention grid. For self-attention, both axes are the same sentence: ["the", "bank", "is", "near"]. Every cell is filled because every word attends to every other word. The diagonal is brightest (self-attention).
For cross-attention, the y-axis is the target sentence being generated and the x-axis is the source sentence. The pattern is not square -- it shows alignment between languages.
For masked attention, the grid is triangular. All positions above the diagonal are blacked out (masked). Each position can only see itself and everything to its left.
15.3.7 Assumptions, Scope, and Pitfalls
Assumptions:
- Self-attention assumes that the relevant relationships among words can be captured by dot-product similarity in the projected space.
- Multi-headed attention assumes that different relationship types live in different subspaces that can be learned independently.
Common pitfalls:
- Confusing self-attention (within one sequence) with cross-attention (between two sequences). Self = same source. Cross = different sources.
- Thinking multi-headed attention is just multiple copies of the same thing. Each head learns different projections through its own matrices.
- Forgetting to apply masking during training of autoregressive models. Without masking, the model sees answers and learns nothing.
- Setting the number of heads too high relative to the model dimension. Each head operates in a dimensional subspace. If this is too small, heads cannot learn meaningful patterns.
15.3.8 Recap and Bridge
Self-attention lets every word see every other word in parallel. Multi-headed attention runs several self-attention operations simultaneously, each learning different patterns. Cross-attention connects two distinct sequences. Masked attention enforces autoregressive generation by hiding the future. Together, these four variants form the attention toolkit that powers the Transformer.
Real-world connection: These attention types are not just theoretical. Every time you use ChatGPT, masked multi-headed self-attention runs across your prompt and the model's ongoing generation. Every time Google Translate processes a sentence, cross-attention aligns source and target languages. In vision Transformers (ViT), self-attention lets every image patch attend to every other patch, replacing convolution with attention entirely.
15.4 Positional Encoding
15.4.1 Why Position Matters
Self-attention processes all words at once. That is its superpower. But it also means word order disappears. Scramble the words "The cat sat on the mat" into "mat the on sat cat The" and self-attention gives the same scores. The model is blind to position. How do you tell the model that "cat" comes before "sat"?
RNNs never had this problem. Words were fed in one by one -- order came for free. Transformers throw away the sequential processing and must add position information back explicitly.
The solution: create a positional encoding for each position in the sequence. Add this encoding to the word embedding element-wise. The combined vector carries both what the word is (semantic) and where it sits (positional).
The result is the input to the Transformer block.
Think of a class roll call. Each student has a name (word embedding). But you also need to know who spoke first, second, and third. You could assign each seat a number (position 1, 2, 3...) and pair the name with the seat number. The positional encoding is that seat number -- but in vector form so the neural network can work with it mathematically.
15.4.2 Sinusoidal Encoding Formula
The original Transformer paper (Vaswani et al., 2017) used a sinusoidal positional encoding. For position and dimension index :
where:
- is the word's position in the sequence (0-indexed)
- is the dimension index (pairs of dimensions: )
- is the model's embedding dimension
How the frequencies work: The denominator controls the wavelength. When is small (early dimensions), the exponent is near 0, so the denominator is near 1 -- the sine and cosine oscillate slowly across positions. When is large (later dimensions), the denominator grows large -- the sine and cosine oscillate rapidly across positions.
This creates a pattern where each position gets a unique vector, and positions that are nearby in the sequence have similar encodings in the low-frequency dimensions. The model can learn to interpret these patterns as relative positions.
The professor described it simply: "It is purely mathematical -- nothing related to the word or the application. It just takes the position and transforms it into an embedding." The encoding is fixed, not learned (in the original design). You just compute it once from the formula.
Key property -- relative position: The sinusoidal encoding has a useful mathematical property. For any fixed offset , the encoding at position can be expressed as a linear transformation of the encoding at position . This means the model can learn to attend to relative positions (e.g., "the word three positions before the current one") by learning simple linear functions of the positional encoding.
15.4.3 Worked Example -- Positional Encoding with Two-Dimensional Vectors
Consider the sentence "The bank is near." Each word gets a 2-dimensional word embedding. Here .
Step 1 -- Word embeddings (given):
| Word | Word Embedding |
|---|---|
| the | (2, 5) |
| bank | (-3, 1) |
| is | (0, 5) |
| near | (1, 2) |
Step 2 -- Compute positional encodings. With , we have only (one pair of dimensions). The denominator simplifies: . So and .
| Position | PE | ||
|---|---|---|---|
| 0 | (0, 1) | ||
| 1 | (0.841, 0.540) | ||
| 2 | (0.909, -0.416) | ||
| 3 | (0.141, -0.990) |
Step 3 -- Professor's approximate values (for illustration). The professor used simplified values to make the example easy to follow by hand. These are the values used in class:
| Position | Word | Prof's Approx PE |
|---|---|---|
| 0 | the | (0, 1) |
| 1 | bank | (0, 0) |
| 2 | is | (0, 0) |
| 3 | near | (1, 1) |
Step 4 -- Add word embeddings and positional encodings element-wise (professor's approximate values):
| Position | Word | Combined (Prof) |
|---|---|---|
| 0 | the | (2+0, 5+1) = (2, 6) |
| 1 | bank | (-3+0, 1+0) = (-3, 1) |
| 2 | is | (0+0, 5+0) = (0, 5) |
| 3 | near | (1+1, 2+1) = (2, 3) |
Step 5 -- Now permute the sentence to "bank is near the" and recompute:
| Position | Word | Word Emb | Prof PE | Combined |
|---|---|---|---|---|
| 0 | bank | (-3, 1) | (0, 1) | (-3, 2) |
| 1 | is | (0, 5) | (0, 0) | (0, 5) |
| 2 | near | (1, 2) | (0, 0) | (1, 2) |
| 3 | the | (2, 5) | (1, 1) | (3, 6) |
Sense-check: Notice that "bank" had combined vector in the original order but after reordering. The word embedding for "bank" never changed -- only its position changed. This is exactly how the model distinguishes word order. Same word, different position → different combined embedding → different processing by the network.
Exam note: Positional encoding and self-attention are the two main components of the Transformer. Any Transformer architecture problem will involve both. You should be able to compute positional encodings given the formula and a small value.
15.4.4 Visual Intuition
Imagine a heatmap where rows are positions (0 to ) and columns are encoding dimensions (0 to ). Each cell is colored by the sine or cosine value at that position and dimension.
In the first few columns (low frequency), the colors change gradually as you move down rows -- like a slow wave. In later columns (high frequency), the colors alternate rapidly between rows. This gives each row a unique "barcode" pattern. Two nearby rows have similar patterns in the slow-changing columns, encoding their proximity.
15.4.5 Assumptions, Scope, and Pitfalls
Assumptions:
- The positional encoding uses a fixed sinusoidal pattern. This assumes that position relationships can be captured by continuous sinusoidal functions.
- Adding (rather than concatenating) PE to word embeddings assumes the two types of information combine additively.
Scope: Sinusoidal encoding works well for sequences up to a few thousand tokens. For very long sequences, learned positional encodings or relative position encodings (like RoPE) often work better.
Common pitfalls:
- Forgetting to add positional encoding entirely. Without it, the Transformer sees a bag of words.
- Confusing positional encoding (fixed sinusoidal formula) with learned position embeddings (trainable lookup table). Both are valid, but the exam likely tests the sinusoidal formula.
- Thinking PE replaces word embeddings. It is added to them, not substituted.
- Treating PE as learnable by default. In the original Transformer, it is fixed. Modern variants may learn it.
15.4.6 Recap and Bridge
Without positional encoding, the Transformer cannot tell word order apart. The sinusoidal formula adds a unique position-dependent vector to each word embedding. When the sentence order changes, the combined vectors change -- giving the model the order information it needs. Next, we work through a full self-attention computation with real numbers.
Real-world connection: Positional encoding is not unique to text. In vision Transformers, image patches need 2D positional encodings to encode row and column. In audio Transformers, time steps need 1D position information. The same principle -- add a position-dependent signal to the input -- applies across modalities. Modern large models like GPT-4 use learned positional embeddings, while some newer architectures like Llama use rotary position embeddings (RoPE), which encode relative position directly into the attention computation.
15.5 Self-Attention -- Worked Numerical Example (Dot-Product Scoring)
15.5.1 Setup -- Two Words: "playing" and "outside"
We will work through a full self-attention computation for a part-of-speech tagging task with two words. The goal: produce a context-aware representation (essence vector) for each word that captures how it relates to all other words in the sentence.
Each word starts with a pre-trained embedding. These embeddings are then multiplied by learned projection matrices to produce the query, key, and value vectors. This is step one of any attention computation -- you never use raw embeddings directly.
15.5.2 Computing Query, Key, and Value Representations
For each word, we apply three learned linear projections to its embedding:
These are the core idea: every word gets a query (what it is looking for), a key (how it identifies itself), and a value (what information it carries). The projections are learned during training.
For our example, assume the projection step has already been done, yielding these vectors:
- For "playing":
- For "outside":
15.5.3 Scaled Dot-Product Scoring -- First Timestep (query = "playing")
At timestep 1, the query is (what "playing" is looking for). We compare this query against the key vectors of all words, including "playing" itself.
Scaled dot-product attention score:
where is the dimension of the key vectors. The scaling factor prevents the dot products from growing too large when the vectors are high-dimensional, which would push the Softmax into regions with tiny gradients.
Why scale by ? Assume each element of and is drawn independently with mean 0 and variance 1. Their dot product has variance . Without scaling, for large , the dot products become very large in magnitude. After exponentiation in Softmax, a few elements dominate, and gradients vanish. Dividing by keeps the variance at 1 regardless of dimension.
Score computation for timestep 1:
In this example, , so each dot product is divided by .
15.5.4 Softmax and Weighted Context Vector
The raw scores pass through Softmax to become attention weights (a probability distribution summing to 1):
where is the attention weight from query to key .
The weights tell you the proportional influence of each word. Then compute the weighted sum of values:
This context vector is the customized essence for "playing." It captures both what "playing" itself means and how "outside" relates to it. This context feeds into a classification layer that predicts the part-of-speech tag (e.g., verb).
Second timestep (query = "outside"): The process is identical. The query is now . The keys and values are reused -- same vectors, different query. New scores, new Softmax weights, new weighted sum. The resulting context captures the essence for "outside."
The professor emphasized: "This is the same reasoning for every word. For every timestep, the current word becomes the query and all words act as keys and values. This is how self-attention works -- and you can compute all timesteps in parallel."
Exam note: Expect numerical problems on scaled dot-product self-attention in the EC3 exam. Practice with a small concrete example using explicit vector values. Also practice the same problem using Bahdanau's additive attention (Section 15.6) as an alternative scoring method.
15.5.5 Visual Intuition
Draw a 2x2 grid. Columns are keys ("playing", "outside"). Rows are queries ("playing", "outside"). Each cell holds the raw score between that query-key pair.
Below the grid, show the Softmax-then-weighted-sum pipeline: arrows from each cell to the Softmax nodes, then to the weighted values, then summed into the context vectors. Two context vectors emerge -- one per query -- and each feeds into its own part-of-speech classifier.
15.5.6 Assumptions, Scope, and Pitfalls
Scope: Scaled dot-product attention assumes queries and keys have the same dimension. When they differ, you need either a learned matrix to align them or you switch to additive (Bahdanau) attention.
Common pitfalls:
- Forgetting the scaling factor . Without it, gradients can vanish for large , and training stalls.
- Confusing the role of . The query is from the word whose context you are computing. Keys are what you match against. Values are what you aggregate.
- Thinking the keys and values change per timestep in self-attention. They are fixed for the entire input. Only the query changes per timestep.
- Applying Softmax before dividing by . The scaling happens to the raw scores, before Softmax.
- Forgetting that self-attention includes the word itself in the computation. A word attends to every word, including itself.
15.5.7 Recap and Bridge
Scaled dot-product self-attention works by computing query-key scores, scaling by , applying Softmax to get weights, and taking the weighted sum of values. Every word gets a custom context that captures its relationship to the entire sequence. The next section covers Bahdanau's additive attention -- an alternative scoring function used when queries and keys have different dimensions.
Real-world connection: The scaled dot-product attention is the exact mechanism used in every transformer block of GPT, BERT, and all modern LLMs. The scaling factor is one of those small but critical details -- remove it, and training large models becomes unstable. The same mechanism also appears in recommendation systems (user embeddings as queries, item embeddings as keys/values) and graph neural networks (node features attending to neighbor features).
15.6 Additive (Bahdanau) Attention
15.6.1 Definition and Difference from Dot-Product Attention
What if the query and the key live in spaces of different dimensions? A dot product between them would not even be defined. You need a different way to compare them.
Additive attention, also called Bahdanau attention after the researcher who proposed it (Bahdanau et al., 2014), replaces the dot product with a small neural network that learns how to compare queries and keys. Given a query and a key :
where:
- projects the query into a hidden space of dimension
- projects the key into the same hidden space
- is a learned weight vector that maps the hidden representation to a scalar score
- is the activation function
How it works: The query and key are each transformed by their own weight matrices into a common hidden space of dimension . They are added together (hence "additive"), passed through , and then projected to a single scalar by . This scalar is the attention score. It then goes through Softmax to produce attention weights, just like in dot-product attention.
Think of two people who speak different languages (different dimensions). A dot product would be meaningless -- you cannot multiply a French vector by a Chinese vector. Additive attention is like having a translator who first converts both statements into a common language (the hidden space), then compares them.
When to use additive vs. dot-product attention:
| Dot-Product (Scaled) | Additive (Bahdanau) | |
|---|---|---|
| Query and key dimensions | Must be equal () | Can differ () |
| Computational cost | Lower (just a dot product) | Higher (two matrix multiplies + tanh) |
| Scalability | Better for large with scaling | Works regardless of dimension |
| Usage today | Default in Transformers | Historical; dot-product dominates in modern models |
The standard form in the literature writes the score as . The professor writes the same using -- identical in structure, just with different notation for the weight vector.
15.6.2 Visual Intuition
Picture a two-branch network. The left branch takes the query and multiplies it by . The right branch takes the key and multiplies it by . Both branches feed into a sum node -- the "additive" part. The sum passes through tanh (squashing values between -1 and 1), then through a final learned vector that compresses the result into a single number. That number is the score.
15.6.3 Assumptions, Scope, and Pitfalls
Scope: Additive attention handles queries and keys of different dimensionalities. In modern Transformers, queries and keys are typically designed to have the same dimension (both ), so scaled dot-product attention is used instead. Additive attention is primarily of historical and exam importance.
Common pitfalls:
- Forgetting that additive attention still needs Softmax afterward. The score formula gives raw scores, not weights.
- Confusing additive attention with multi-headed attention. Additive is a scoring function. Multi-headed is an architectural pattern of running multiple attention heads.
- Thinking additive attention is fundamentally different from dot-product. Both are just scoring functions. The difference is how they compute the score -- dot product vs. small neural network.
15.6.4 Recap and Bridge
Additive (Bahdanau) attention uses a learnable neural network () to score query-key pairs instead of a dot product. It handles different-dimensional queries and keys at the cost of extra computation. The professor expects you to practice the same self-attention numerical problem from Section 15.5 using Bahdanau's scoring. Next, we introduce the full Transformer architecture.
Real-world connection: Bahdanau attention was the mechanism that first showed attention's power in machine translation (2014). It inspired the "Attention Is All You Need" paper three years later. While scaled dot-product attention now dominates, additive attention remains an important historical milestone and a useful alternative when dimensionality mismatch makes dot products impossible.
15.7 Introduction to Transformers
15.7.1 Why Transformers
What if you could throw away recurrent connections entirely and still process sequences better than any RNN ever could? In 2017, a paper titled "Attention Is All You Need" showed exactly how.
The Transformer architecture was built on three key insights, each fixing a fundamental weakness of RNNs.
Three advantages of Transformers over RNNs:
- Parallelism. Self-attention and multi-headed attention have no temporal dependency. All words are processed simultaneously. RNNs must proceed step by step. This makes training Transformers on massive datasets feasible.
- Long-range dependencies. In a Transformer, every word attends directly to every other word. The path length between any two positions is -- constant, regardless of how far apart they are. RNNs have path length between distant positions, and information degrades along the way.
- Scalability. The architecture scales to deep stacks. GPT-3 uses 96 decoder blocks. BERT-large uses 24 encoder blocks. Each block refines the representations further. RNNs become unstable and hard to train beyond a few layers due to vanishing/exploding gradients.
Think of three ways to summarize a long document. An RNN is like one person reading aloud from start to finish, trying to remember everything -- slow and error-prone. A Transformer is like distributing one page to each of a hundred people simultaneously. Each person reads their page and compares notes with everyone else. Everyone finishes at the same time with a complete picture.
Transformers are the basis for all modern AI systems. GPT, ChatGPT, Copilot, Gemini, Claude, Llama, Mistral -- plus vision Transformers, audio Transformers, and video generators. Everything works on Transformer principles. The core component is always attention.
15.7.2 Three Variants of Transformer Architecture
Transformers come in three architectural flavors, depending on whether you need to understand text, generate text, or transform text from one form to another.
Encoder-Only Models (e.g., BERT):
- Process the entire input bidirectionally -- every word sees every other word, left and right.
- Produce rich contextual representations for each token.
- Best for: classification (sentiment analysis, topic categorization), named entity recognition, question answering where the answer is a span within the text.
- No masking needed -- the model sees full context in both directions.
- Example: BERT (base: 12 encoder blocks, large: 24 encoder blocks).
Decoder-Only Models (e.g., GPT):
- Generate text autoregressively. Given a prompt, predict the next word, then the word after that, and so on.
- Use masked (causal) attention -- each position only sees itself and previous positions.
- Best for: text generation, code generation, conversational AI.
- Examples: GPT-3/GPT-4, Claude, Gemini, Llama, Mistral.
Encoder-Decoder Models (e.g., T5):
- Full architecture with both an encoder and a decoder stack.
- The encoder processes the input sequence. The decoder generates the output sequence, using cross-attention to pull information from the encoder.
- Best for: machine translation, text summarization, question answering with generated answers.
- Example: T5 (Text-to-Text Transfer Transformer).
The professor noted: "Not every application requires both encoder and decoder. For classification, an encoder alone is enough. For text generation from a prompt, a decoder alone is enough." The choice depends on whether your task is understanding, generation, or transformation.
15.7.3 Visual Intuition
Encoder-only: Draw a stack of arrowed boxes (encoder blocks). An input sentence enters from the left. Every box processes all words bidirectionally. An output vector emerges from the top. The diagram is simple and symmetrical -- just a vertical stack.
Decoder-only: Same vertical stack, but each box has a triangular mask drawn over the attention connections. Input words enter from the left, and output words are generated one at a time from the top. An arrow loops back from the output to serve as the next input -- autoregressive generation.
Encoder-decoder: Two stacks, side by side. The left stack (encoder) feeds into the right stack (decoder) through cross-attention connections -- shown as horizontal arrows between the two stacks at every layer.
15.7.4 Assumptions, Scope, and Pitfalls
Scope: The Transformer assumes that all relationships in a sequence can be captured by attention alone -- no recurrence, no convolution. This assumption works remarkably well in practice for most NLP tasks. It can be expensive for very long sequences because self-attention cost grows quadratically () with sequence length .
Common pitfalls:
- Picking the wrong variant for the task. Classification needs an encoder, not a decoder-only model. Text generation needs a decoder.
- Assuming all Transformers are GPT. Many students conflate "Transformer" with "decoder-only generative model." BERT (encoder-only) and T5 (encoder-decoder) are Transformers too.
- Overlooking the quadratic cost. A Transformer that works beautifully on 512-token sequences may become unusably slow at 4096 tokens.
- Thinking Transformers "understand" language. They learn powerful statistical patterns but have no genuine comprehension.
15.7.5 Recap and Bridge
Transformers eliminate recurrence by relying entirely on attention. The three architectural variants -- encoder-only, decoder-only, and encoder-decoder -- map to three task families: understanding, generation, and transformation. The next section dives into the internal details of the Transformer encoder block, showing exactly how input embeddings, positional encoding, multi-headed attention, layer normalization, residual connections, and feed-forward layers fit together.
Real-world connection: By 2018, Transformers had become the default architecture for NLP. By 2021, vision Transformers (ViT) had matched CNNs on image classification. By 2023, Transformer-based models -- GPT-4, Claude, Gemini -- were driving the generative AI revolution. The architecture that started as a machine translation model now underpins text generation, image generation (via diffusion Transformers), code completion, protein folding prediction, and robotic control. The same core idea -- attention over tokens -- scales across modalities.
15.8 Transformer Encoder Architecture
15.8.1 Input Embedding and Positional Encoding
The input sentence is tokenized into words (or subwords). Each token gets a dense vector representation -- a word embedding -- of dimension . These embeddings are learned during training via an embedding lookup table.
The embedding alone is not enough. Self-attention loses word order. To inject position information, you compute a positional encoding vector (sinusoidal or learned) of the same dimension and add it element-wise:
The result carries both what the token is (semantic) and where it sits (positional). This combined vector enters the first encoder block.
In practice, the embedding values are multiplied by before the positional encoding is added. This rescales the embeddings because positional encoding values are always between -1 and 1, and without scaling the embedding contribution would be too small relative to the positional contribution.
15.8.2 Layer Normalization
Before entering the attention block, the input passes through layer normalization.
Layer normalization normalizes across all features for a single instance -- different columns, same row. For an input vector :
where and are learnable parameters that scale and shift the normalized values back to a useful range, and is a small constant (e.g., ) to prevent division by zero.
Layer norm vs. batch norm analogy: Batch normalization is like grading on a curve -- you compare each student to the class average on one exam (normalize across the batch for one feature). Layer normalization is like computing each student's GPA -- you average across all their exam scores (normalize across features for one sample). Batch norm depends on the batch; layer norm does not. This makes layer norm better for NLP, where sequence lengths vary and batch sizes are often small.
Layer normalization stabilizes learning by keeping values from growing too large or too small as data flows through deep stacks. It is applied at multiple points in each encoder block.
15.8.3 Multi-Headed Attention Block
The layer-normalized input feeds into a multi-headed self-attention block with heads. Each head has its own projection matrices:
where is the dimension per head.
Each head independently computes scaled dot-product self-attention. The outputs (each of dimension ) are concatenated and mapped back to :
where .
The professor emphasized: "Each head learns a distinct pattern. One head may learn part-of-speech. Another learns subject-verb agreement. A third learns dependency parsing. One block of multi-headed attention is one pattern-extraction step."
15.8.4 Residual Connections
After the multi-headed attention output, a residual (skip) connection adds the input back, followed by layer normalization:
The residual connection provides a direct path for gradients to flow backward, solving the vanishing gradient problem in deep stacks. A second residual connection wraps the feed-forward network (see below). This is the same idea as ResNet in CNNs.
The residual connection requires the attention output and input to have the same dimension (). The projection matrix ensures this by mapping the concatenated head outputs back to .
15.8.5 Feed-Forward Network
After the attention sublayer and its residual connection, the data passes through a positionwise feed-forward network. This is where non-linearity and transformation logic are introduced. The attention mechanism does scoring, weighting, and summing -- all linear operations apart from Softmax. The FFN provides the non-linear computation:
where , , and typically .
A second residual connection wraps the FFN:
The professor put it memorably: "Nowhere in the attention block do you see actual classification logic or non-linearity. You are just doing scoring, creating context vectors, and producing an outcome. The feed-forward network is where the intelligence for the task lives."
Why positionwise? The same two-layer MLP is applied independently to each position in the sequence. Every token position goes through the same weights . This is why it is called "positionwise" -- the network is shared across positions.
15.8.6 Stacking Encoder Blocks
One encoder block contains these stages, in order:
- LayerNorm → Multi-Head Self-Attention → Add residual → LayerNorm
- → Feed-Forward Network → Add residual
One block is not enough. Like stacking hidden layers in a deep neural network, Transformers stack multiple encoder blocks. The output of one block becomes the input to the next. Lower blocks capture local patterns (word-level relationships). Higher blocks capture global, abstract patterns (semantic and discourse-level relationships).
Real-world stacks:
- BERT-base: 12 encoder blocks
- BERT-large: 24 encoder blocks
- GPT-3: 96 decoder blocks
15.8.7 Dimension Tracking and Parameter Summary
Let be the embedding dimension. Track the dimensions through one encoder block:
Input: (N tokens, D-dimensional) After embeddings + PE: (same shape) After LayerNorm: (normalization preserves shape)
Multi-head attention (h heads, each d_v = D/h):
- : each → per head: parameters
- Total QKV across h heads: parameters
- : parameters
- Total attention sublayer: parameters
Feed-forward network:
- : parameters
- : parameters
- Total FFN sublayer: parameters
Total per encoder block: parameters
The professor stated total parameters per block are about . This is reference information -- understand the architecture and how dimensions flow, but do not memorize the formula for the exam.
15.8.8 Visual Intuition
Draw one encoder block as a vertical pipeline:
- Arrow enters from top: (N × D)
- First sublayer: Split into two paths -- one goes through LayerNorm then Multi-Head Attention, the other skips straight ahead (residual). They merge at an "Add" node, then through another LayerNorm.
- Second sublayer: Same pattern -- one path through LayerNorm then FFN, the other skips through. They merge at an "Add" node.
- Arrow exits at bottom, same shape (N × D), feeding into the next block.
Stack several such blocks vertically. Data flows downward, preserving shape through every block. This shape-preserving property is what makes stacking possible -- you can add as many blocks as you want without the dimensions changing.
15.8.9 Assumptions, Scope, and Pitfalls
Scope: The encoder processes the entire sequence bidirectionally. Each token attends to every token. This is ideal for understanding tasks. For generation tasks where autoregressive masking is needed, the decoder variant (with masked self-attention + cross-attention) is used instead.
Common pitfalls:
- Confusing the order of operations: LayerNorm comes first (pre-norm), then attention, then residual add. The residual adds the input from before the LayerNorm.
- Setting independently of and . The constraint is -- the concatenated output must have dimension D for the residual connection.
- Forgetting the second residual connection around the FFN. Every sublayer in the Transformer has a residual connection.
- Thinking the FFN operates across positions. It is positionwise -- same weights, applied independently to each position.
- Neglecting that W_O is essential. Without it, concatenated heads would have dimension h×d_v, which may not equal D. W_O maps back to D for the residual connection and next block.
15.8.10 Recap and Bridge
The Transformer encoder block is a carefully designed pipeline: embeddings + positional encoding → layer norm → multi-head self-attention with residual → layer norm → positionwise FFN with residual. Every sublayer preserves shape, enabling deep stacking. The attention sublayer costs parameters, the FFN , totaling per block. Next, we see a concrete application: how BERT uses this encoder stack for question answering and classification.
Real-world connection: The encoder architecture described here is not just a theoretical construct -- it is the exact design used in BERT, one of the most influential NLP models ever created. When BERT processes text for Google Search, every word in every webpage is run through these same encoder blocks to produce contextual understanding. The architecture has proven so effective that even multimodal models (text + image) often use a Transformer encoder as their backbone.
15.9 BERT -- A Transformer Application Example
15.9.1 Question Answering with BERT
How does a search engine find the exact answer to your question inside a paragraph of text, without generating a single new word? BERT shows how.
BERT (Bidirectional Encoder Representations from Transformers) is an encoder-only Transformer. It uses only the encoder stack -- no decoder. It is built for natural language understanding tasks, not text generation.
In a question-answering setup, the input has three parts:
- The question tokens
- A special [SEP] token (separator)
- The context paragraph tokens
The entire sequence (question + [SEP] + context) passes through all the stacked encoder blocks. Every token is processed bidirectionally with full visibility to every other token.
Think of BERT reading the question AND the paragraph together, word by word, letting every word inform every other word. It does not generate an answer one word at a time. Instead, it highlights where in the paragraph the answer starts and ends -- like using two colored highlighters.
A feed-forward classifier sits on top of the encoder output. It takes the final representation of each token in the paragraph and predicts two things: (1) is this token the start of the answer? (2) is this token the end? The model outputs the span with the highest combined score.
The [CLS] token, placed at the very beginning of every BERT input, plays a special role. After all encoder blocks have processed the inputs bidirectionally, the output vector at the [CLS] position contains an aggregate of the entire sequence. This aggregate can feed into a classifier for tasks like sentiment analysis.
15.9.2 Sentence Classification with BERT
For sentence-level classification (topic labeling, sentiment analysis, spam detection), the workflow is:
- Tokenize the input sentence and prepend the [CLS] token.
- Add word embeddings and positional encodings.
- Pass through the stacked encoder blocks. Every token attends to every other token bidirectionally.
- Extract the output vector at the [CLS] position.
- Feed that vector through a feed-forward classification head.
- The head outputs a probability distribution over class labels.
The professor summarized: "BERT uses multiple encoder blocks stacked together. Every token is processed with the help of all other tokens. The [CLS] token acts as a designated position where the aggregate context can be extracted for classification."
15.9.3 Visual Intuition
For question answering: Draw the input as a long ribbon of tokens: [CLS] + question words + [SEP] + context words. Below it, draw the stack of encoder blocks (the BERT core). From the top, two small classifier blocks descend to the context tokens -- one predicting start positions, one predicting end positions. Highlight two tokens in the context where both scores are highest.
For classification: Same ribbon of tokens but with just one sentence. From the [CLS] position at the top, an arrow leads to a classification head producing labels like "positive" (0.87) and "negative" (0.13).
15.9.4 Assumptions, Scope, and Pitfalls
Scope: BERT's encoder-only architecture limits it to tasks that do not require text generation. You cannot use BERT to write an essay or have a conversation. For generation, you need a decoder (like GPT) or an encoder-decoder (like T5).
Common pitfalls:
- Thinking BERT generates text. It does not. It produces representations and span predictions.
- Forgetting the [CLS] and [SEP] tokens. BERT's input format is strict: [CLS] at the start, [SEP] between sentences. Skipping these breaks the model.
- Assuming BERT works out of the box for any task. BERT is typically fine-tuned on task-specific data after pretraining.
- Confusing the [CLS] token with the decoder's start-of-sequence token. The [CLS] token is an aggregation point for the encoder -- it does not trigger generation.
15.9.5 Recap and Bridge
BERT is an encoder-only Transformer that processes text bidirectionally. For question answering, it predicts answer spans rather than generating words. For classification, it uses the [CLS] token's output as an aggregate representation. BERT demonstrates that for understanding tasks, a stack of encoder blocks is all you need -- no decoder, no autoregressive generation.
Real-world connection: BERT variants (RoBERTa, DistilBERT, DeBERTa) power search engines, content moderation systems, and customer support automation worldwide. Google integrated BERT into its search ranking in 2019, affecting roughly 10% of all English-language queries. In healthcare, BioBERT and ClinicalBERT process medical literature and electronic health records. The encoder-only design pattern persists because many real-world tasks -- classifying emails, extracting entities from contracts, detecting hate speech -- are understanding tasks that do not need text generation.
15.10 Exam Guidance Summary
Exam note: EC3 examination format mirrors EC2. Same question types: numerical computation, conceptual reasoning, and code debugging. Application-based questions -- given a real-world scenario, identify which architecture fits best and explain why -- are new to EC3. Component-level questions ask for the purpose of a component (e.g., self-attention) in a given context rather than a direct definition. Expect architecture/code error-finding and dimension-tracking problems (trace dimensions through an encoder block). Open-book examination: understand the architecture, do not memorize parameter count formulas.
Key exam preparation checklist:
- Self-attention numerical problems. Practice scaled dot-product scoring with concrete numbers. Know how to compute query-key dot products, divide by , apply Softmax, and compute the weighted context vector. Also practice the same problem using Bahdanau's additive attention ().
- Positional encoding computation. Given and a set of positions, compute the sinusoidal positional encoding. Know the formula: and .
- Architecture identification. Given a task description (classification, translation, text generation), pick the right Transformer variant: encoder-only (BERT), decoder-only (GPT), or encoder-decoder (T5).
- Dimension tracking. Be able to follow input dimensions through an encoder block: embeddings (), position encoding (), attention sublayer (preserves ), FFN (preserves ). Know that attention parameters total and FFN parameters .
- Component understanding. Know the role of each piece: positional encoding (adds order), multi-headed attention (captures multiple relationships in parallel), layer normalization (stabilizes training), residual connections (enables deep stacking), FFN (adds non-linearity).
- Architecture error-finding. Given a diagram or description of a Transformer block with a deliberate error (missing residual, wrong order of operations, missing LayerNorm), identify and correct it.
Study resources: The PPT and reading material on the e-learning portal are sufficient. Go through all webinars and live session recordings. No external sources are needed.
15.11 Key Industry Applications
The Transformer architecture and its attention mechanisms are not just textbook concepts -- they power virtually every modern language AI system. Here are the major families:
Decoder-Only Models (text generation):
- GPT (Generative Pre-trained Transformer): The model family behind ChatGPT. GPT-3 (175B parameters, 96 decoder blocks) and GPT-4 power text generation, code completion, and conversational AI. These models use masked multi-headed self-attention and generate text autoregressively.
- Claude (Anthropic): A decoder-only Transformer focused on safe and helpful conversational AI.
- Gemini (Google): A multimodal decoder-only model that handles text, images, audio, and video.
- Llama (Meta) and Mistral (Mistral AI): Open-weight decoder-only Transformer models for research and deployment.
Encoder-Only Models (text understanding):
- BERT (Google): Encoder-only Transformer for NLP classification, question answering, and named entity recognition. BERT-base: 12 encoder blocks (110M parameters). BERT-large: 24 encoder blocks (340M parameters). Variants include RoBERTa, DistilBERT, and DeBERTa.
Encoder-Decoder Models (text transformation):
- T5 (Text-to-Text Transfer Transformer, Google): Full encoder-decoder Transformer that reframes every NLP task as text-to-text: input text in, output text out. Used for translation, summarization, and question answering.
Beyond Text:
- Vision Transformers (ViT): Apply the Transformer architecture to image data by splitting images into patches and treating them as tokens. Now competitive with CNNs for image classification, object detection, and segmentation.
- Audio Transformers: Process speech waveforms or spectrograms as token sequences for speech recognition and audio generation.
- Video Generators: Diffusion Transformers generate video frames autoregressively or via denoising diffusion in a Transformer backbone.
- Multimodal Models: Models like GPT-4V, Gemini, and Flamingo integrate text and vision by processing both modalities through a shared Transformer architecture.
Why Transformers dominate: The combination of parallel training, direct long-range attention, and scalable deep stacking means Transformers keep improving with more data and more compute. This is the architecture that launched the era of foundation models -- large pretrained models that can be adapted to hundreds of downstream tasks with minimal fine-tuning.
DNN Lecture 15 notes · Attention Mechanisms and Transformer Architecture
Sections Breakdown
Three RNN limitations: length mismatch, long-range memory, sequential bottleneck. Encoder-decoder solution and the context bottleneck problem.
Customized context per timestep using Query, Key, and Value vectors. Attention scoring, Softmax, and weighted value aggregation.
Self-attention, multi-headed attention, cross-attention, and masked attention. Comparison of all four types.
Why position matters in Transformers. Sinusoidal encoding formula with worked example.
Step-by-step scaled dot-product attention computation for part-of-speech tagging.
Neural-network-based scoring function. Comparison with dot-product attention.
Three advantages over RNNs: parallelism, long-range dependencies, scalability. Encoder-only, decoder-only, and encoder-decoder variants.
Input embedding, layer normalization, multi-headed attention, residual connections, feed-forward network, stacking, and dimension tracking.
Question answering with BERT, sentence classification, the [CLS] token role.
EC3 exam format, key preparation checklist: self-attention, positional encoding, architecture identification, dimension tracking.
GPT, BERT, T5, Vision Transformers, and multimodal models.
Exam Revision Notes
Below is the distilled, exam-ready core of this lecture. Every entry is built from the full textbook notes above. Use this section for rapid review — but if something doesn't make sense, go back to the full explanation in the main content.
RNN Limitations and Encoder-Decoder
Must-know: RNNs fail on three fronts: length mismatch (input must equal output length), long-range memory (hidden state forgets after ~100–200 tokens), and sequential bottleneck (no parallelism). The encoder-decoder architecture fixes the length problem by splitting the task into encoder (compresses input to a context vector) and decoder (generates output from that vector), but creates a new context bottleneck.
⚠️ Top pitfall: Thinking encoder and decoder are specific network types (they are roles, not implementations). Also assuming one fixed context vector can capture a long input sequence.
Self-check: Why can an RNN do part-of-speech tagging but not translation without architectural changes?
Connects to: Attention Mechanism, Transformer Architecture
Attention Mechanism
Must-know: Attention replaces one fixed context vector with a customized context per timestep. Uses Query (Q) — what the decoder is looking for, Key (K) — identifier for each input word, Value (V) — the information content. Score query against all keys, apply Softmax, take weighted sum of values.
⚠️ Top pitfall: Forgetting the Softmax step. Raw scores can be any real number — only after Softmax do they become a probability distribution summing to 1.
Self-check: What problem does attention solve that the basic encoder-decoder cannot?
Connects to: Self-Attention, Multi-Headed Attention, Transformer
Self-Attention and Multi-Headed Attention
Must-know: In self-attention, Q, K, V all come from the same sequence — every word attends to every other word in parallel. Multi-headed attention runs h separate self-attention heads in parallel, each learning different relationship types. Outputs are concatenated and projected back via W_O.
⚠️ Top pitfall: Confusing self-attention (same sequence) with cross-attention (different sequences). Also forgetting that multi-headed attention uses separate W_Q, W_K, W_V per head — not the same projections shared.
Self-check: How does self-attention eliminate the sequential dependency that limits RNNs?
Connects to: Cross-Attention, Masked Attention, Transformer Encoder
Positional Encoding
Must-know: Self-attention processes all words at once and loses word order. Positional encoding adds order information back via a fixed sinusoidal formula. The encoding is added to the word embedding element-wise.
⚠️ Top pitfall: Forgetting to add positional encoding — without it, the Transformer sees a bag of words. Also confusing positional encoding (fixed formula) with learned position embeddings (trainable lookup table).
Self-check: Why can't the Transformer infer word order from self-attention alone?
Connects to: Transformer Encoder, Self-Attention
Scaled Dot-Product Attention
Must-know: Score = dot product of Q and K divided by √d_k. The scaling factor prevents dot products from growing too large in high dimensions, which would push Softmax into regions with vanishing gradients.
⚠️ Top pitfall: Forgetting the √d_k scaling factor — without it, gradients vanish for large d_k and training stalls. Also applying Softmax before dividing by √d_k.
Self-check: Why do we divide the dot product by √d_k? What happens if we skip it?
Connects to: Additive Attention, Self-Attention
Additive (Bahdanau) Attention
Must-know: Alternative scoring function that uses a small neural network instead of a dot product. Useful when query and key have different dimensions.
⚠️ Top pitfall: Forgetting that additive attention still needs Softmax afterward (the formula gives raw scores, not weights). Also confusing it with multi-headed attention — additive is a scoring function, multi-headed is an architectural pattern.
Self-check: When would you choose additive attention over dot-product attention?
Connects to: Scaled Dot-Product Attention, Transformer
Transformer Encoder Block
Must-know: The encoder block follows: Input → LayerNorm → Multi-Head Self-Attention → Add residual → LayerNorm → FFN → Add residual. All operations preserve shape (N × D). Attention sublayer: 4D² parameters. FFN sublayer: 8D² parameters. Total: 12D² per block.
⚠️ Top pitfall: Confusing the order of operations — LayerNorm comes first (pre-norm), then attention, then residual add. Also forgetting the second residual connection around the FFN.
Self-check: Why must every sublayer in the Transformer preserve the shape N × D?
Connects to: BERT, Positional Encoding, Multi-Headed Attention
BERT and Encoder-Only Models
Must-know: BERT is an encoder-only Transformer for understanding tasks. Input format: [CLS] + tokens + [SEP]. Bidirectional self-attention — every token sees every other token. For QA, predicts answer span (start and end positions). For classification, extracts the [CLS] token's output.
⚠️ Top pitfall: Thinking BERT generates text. It does not — it produces representations and span predictions. Also forgetting the [CLS] and [SEP] tokens in BERT's strict input format.
Self-check: Why does BERT use an encoder-only architecture rather than an encoder-decoder?
Connects to: Transformer Encoder, GPT, T5
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.