Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin
The dominant sequence transduction models are based on complex recurrent or convolutional neural networks that include an encoder and a decoder. The best performing models also connect the encoder and decoder through an attention mechanism. We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two machine translation tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task, improving over the existing best results, including ensembles, by over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training costs of the best models from the literature. We show that the Transformer generalizes well to other tasks by applying it successfully to English constituency parsing both with large and limited training data.
The dominant sequence transduction models are based on complex recurrent or convolutional neural networks that include a...
This abstract is announcing a paradigm shift in how we build neural networks for sequence-to-sequence tasks (like translation). Instead of the architectures that dominated the field in 2016, which relied heavily on recurrence (processing sequences one element at a time) and convolutions (looking at local patterns), the authors propose a radically simpler alternative: build everything using only attention mechanisms.
The abstract makes three key claims:
Let me break down what this means and why it matters.
"The dominant sequence transduction models are based on complex recurrent or convolutional neural networks that include an encoder and a decoder."
What is sequence transduction? It means transforming one sequence into another—the canonical example is machine translation (English → German). Mathematically, we're learning a function:
where represents sequences of any length from an input vocabulary (like English words) and represents output sequences (like German words).
What are the old approaches?
Recurrent Neural Networks (RNNs): Process sequences step-by-step:
Convolutional Neural Networks (CNNs): Use fixed-size local windows
Encoder-Decoder Architecture:
The attention mechanism improvement: Previous state-of-the-art models added attention to the encoder-decoder framework:
where the context varies at each decoding step, computed as a learned weighted average over the input:
Here:
This was an improvement, but it still required the complexity of RNNs or CNNs for the encoder and decoder.
"We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely."
The radical idea: What if we could build the encoder and decoder using only attention, with no recurrence or convolution at all?
Why is this significant?
The Transformer architecture (which we'll see later in the paper) uses "multi-head self-attention" to:
"Experiments on two machine translation tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time to train."
What are BLEU scores? BLEU (Bilingual Evaluation Understudy) is a metric for machine translation quality, ranging from 0 to 100:
Where:
The concrete results:
| Task | Model | BLEU Score | Training Cost |
|---|---|---|---|
| WMT 2014 EN→DE | Transformer | 28.4 | Lower |
| WMT 2014 EN→FR | Transformer | 41.8 | 3.5 days on 8 GPUs |
Why is this impressive?
"We show that the Transformer generalizes well to other tasks by applying it successfully to English constituency parsing both with large and limited training data."
What is constituency parsing? It's a different NLP task: identifying the grammatical structure of sentences.
Why mention this? It shows the Transformer isn't just good for machine translation—it's a general architecture that works across different sequence-to-sequence and structured prediction tasks. This suggests the core insight (using attention for everything) is broadly applicable.
| Aspect | Old Approaches | Transformer |
|---|---|---|
| Main components | RNN/CNN + Attention | Attention only |
| Parallelization | Limited (sequential) | Full (all positions at once) |
| Training speed | Slow | Fast (3.5 days for best EN-FR result) |
| Performance | State-of-the-art at the time | Better on benchmark tasks |
| Generality | Task-specific tuning | Generalizes across tasks |
The abstract is essentially claiming: "We found a simpler, faster, and better architecture. Here's the proof."
The rest of the paper reveals how the Transformer achieves this through the careful design of attention mechanisms—which we'll explore in subsequent sections.
Recurrent neural networks, long short-term memory [13] and gated recurrent [7] neural networks in particular, have been ...
This introduction section sets up the problem that the paper is solving and explains why existing approaches are limited. The authors are arguing that current state-of-the-art methods for sequence tasks (like machine translation) rely on recurrent neural networks, which have a fundamental computational constraint: they must process sequences one element at a time. The Transformer paper proposes to solve this by replacing recurrence entirely with attention mechanisms.
Think of it this way: imagine you're translating a book from English to French. Current methods read the English word-by-word, keeping a "memory" (hidden state) that updates at each step. The problem? You can't parallelize this—you can't read word 5 until you've read words 1-4. The Transformer says: "What if we could look at all words at once and figure out which ones matter for understanding each other?"
The section begins by noting that Recurrent Neural Networks (RNNs), particularly:
...have been the dominant approach for sequence modeling and sequence transduction problems.
Key definitions:
The paper describes RNNs with this critical observation:
"Recurrent models typically factor computation along the symbol positions of the input and output sequences."
This is saying that RNNs break up the computation into steps corresponding to positions in the sequence. Mathematically, at each time step , an RNN computes:
Where:
Why is this a problem?
This sequential dependency means:
The paper states this explicitly:
"This inherently sequential nature precludes parallelization within training examples, which becomes critical at longer sequence lengths, as memory constraints limit batching across examples."
What does this mean?
The paper acknowledges that recent work has tried to improve RNN efficiency through:
While these help, the paper emphasizes:
"The fundamental constraint of sequential computation, however, remains."
Translation: "Nice try, but you can't escape the fact that the architecture itself is inherently sequential."
Attention mechanisms have emerged as a way to help models handle long-range dependencies. The key insight is that a model doesn't need to process information sequentially if it can "attend to" (focus on) relevant parts of the input regardless of distance.
Simple intuition: When translating "The bank executive visited the river bank," you need to understand that "bank" means different things in each context. An attention mechanism lets the model look at the entire sentence at once and figure out: "When I'm processing the second 'bank', I should pay special attention to the word 'river' nearby."
The paper notes:
"Attention mechanisms have become an integral part of compelling sequence modeling and transduction models in various tasks, allowing modeling of dependencies without regard to their distance in the input or output sequences."
Key phrase: "without regard to their distance"—meaning the model can directly connect words that are far apart in the sequence, not just neighboring positions.
However, here's the critical limitation:
"In all but a few cases, however, such attention mechanisms are used in conjunction with a recurrent network."
What does this mean?
Existing approaches use attention as an add-on to RNNs. A typical architecture looks like:
The bottleneck remains—you still have to run the RNN sequentially first.
The authors propose a radical departure:
"In this work we propose the Transformer, a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output."
"Eschewing recurrence" = completely removing RNNs from the architecture
Key insight: If attention can model dependencies between any two positions in a sequence, then you don't need recurrence at all. You can replace sequential processing with parallel attention computations.
Instead of computing:
The Transformer computes something more like:
Where the attention mechanism considers all input positions simultaneously to compute the output for position , without any sequential dependency.
Computational advantage: All positions can be computed in parallel, not sequentially.
The paper concludes the introduction with a bold claim supported by empirical results:
"The Transformer allows for significantly more parallelization and can reach a new state of the art in translation quality after being trained for as little as twelve hours on eight P100 GPUs."
What they're saying:
| Aspect | RNN/LSTM | Transformer |
|---|---|---|
| Processing | Sequential: depends on | Parallel: all positions computed simultaneously |
| Memory bottleneck | Yes: can't batch many examples | No: can batch efficiently |
| Long-range dependencies | Difficult (gradient vanishing) | Natural via attention |
| Training speed | Slow (weeks) | Fast (hours) |
| Architecture complexity | Complex (gates, cells) | Simple (mostly matrix multiplications) |
The fundamental thesis: By replacing sequential recurrence with parallel attention, we can build faster, simpler, and more powerful models.
The goal of reducing sequential computation also forms the foundation of the Extended Neural GPU [16], ByteNet [18] and ...
This section is setting up the intellectual foundation for why the Transformer is important. The authors are essentially saying: "Previous models tried to solve the sequential computation problem using convolutions. Here's why that approach has limitations, and here's why self-attention is better."
The key tension being resolved:
Let's unpack each piece.
The authors reference three models that tried to replace RNNs with convolutional neural networks:
All of these could compute representations for all input and output positions in parallel—a huge advantage over RNNs.
Here's where the problem emerges. When you want to connect two distant positions in a sequence, convolutional networks have a fundamental limitation:
In ConvS2S:
In ByteNet:
When you have a network with layers, and information must travel through all layers to connect distant positions:
For ByteNet specifically:
The intuition: Each convolutional layer has a fixed receptive field (it can only "see" a local window of the input). To aggregate information from far away, you need many layers. Even with logarithmic scaling, this adds complexity.
The Transformer reduces this to a constant:
This is the game-changer. No matter how far apart two positions are, the Transformer can relate them with a single attention operation. But—and this is important—there's a trade-off:
"reduced effective resolution due to averaging attention-weighted positions"
What does this mean? When you compute attention, you're essentially taking a weighted average of all positions. This averaging process can lose some fine-grained information. The authors will address this with Multi-Head Attention (Section 3.2), which we'll see later.
Definition: Self-attention (also called intra-attention) is an attention mechanism that relates different positions within the same sequence to compute a representation.
Let's unpack this:
Consider the sentence: "The cat sat on the mat because it was comfortable."
For the word "it":
Previous work showed self-attention succeeds in many tasks:
The key insight: Self-attention works well because it can capture long-range dependencies directly, without the distance penalty that convolutions have.
The authors mention end-to-end memory networks:
The distinction here is subtle but important:
"To the best of our knowledge, however, the Transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequence-aligned RNNs or convolution."
Let's break down what makes this unique:
"Transduction model": A model that maps from one sequence to another (like machine translation: English → German)
"Relying entirely on self-attention":
"Without sequence-aligned RNNs": Unlike memory networks that apply RNNs at each step, the Transformer bypasses RNNs entirely
The Transformer optimizes both dimensions simultaneously:
This section establishes:
In the next section (3.2), the authors will show you exactly how self-attention works mathematically, and how Multi-Head Attention helps overcome the "reduced effective resolution" issue mentioned here.
Most competitive neural sequence transduction models have an encoder-decoder structure [5, 2, 35]. Here, the encoder map...
Before diving into the mathematical details, let's understand what this section is establishing:
The authors are presenting the overall structural blueprint of the Transformer. The key insight is that while the Transformer is revolutionary in how it processes information (through attention rather than recurrence), it maintains a familiar high-level structure: an encoder-decoder architecture. Think of this as saying "we're keeping the tried-and-true organizational pattern, but replacing the internal machinery."
This section does two important things:
Let's work through it carefully.
Sequence transduction is the task of converting one sequence into another. Examples include:
The passage describes the traditional encoder-decoder pattern that was dominant before the Transformer:
Input sequence:
Encoder processing:
Why "continuous representations"?
Decoder generation:
Visual intuition: Think of it like a translator working with notes: they read the entire source text first (encoder), take notes (), then write the translation word-by-word (decoder), always remembering what they've written so far.
Now here's the crucial claim:
"The Transformer follows this overall architecture using stacked self-attention and point-wise, fully connected layers for both the encoder and decoder"
"Follows this overall architecture"
"Stacked self-attention"
"Point-wise, fully connected layers"
The key architectural difference from previous models:
Old approach (RNNs, LSTMs): Process sequentially, position-by-position, where each position depends on previous ones
New approach (Transformer): All positions can be processed in parallel using attention
The passage mentions:
"shown in the left and right halves of Figure 1, respectively"
What Figure 1 shows:
Left side: The encoder architecture
Right side: The decoder architecture
The "stacked" nature is visible in the diagram—you'll see repeated blocks of layers, one on top of another.
| Aspect | Traditional Models | Transformer |
|---|---|---|
| Encoder mechanism | RNN/LSTM (sequential) | Stacked Self-Attention |
| Decoder mechanism | RNN/LSTM (sequential) | Stacked Self-Attention + Cross-Attention |
| Parallelization | Limited (sequential) | Excellent (parallel-friendly) |
| Overall structure | Encoder → Decoder | Encoder → Decoder (same pattern!) |
The profound insight: you don't need recurrence to model sequences effectively. Pure attention is enough, and it's faster to train.
The remainder of Section 3 will elaborate on:
Each of these builds on the architectural blueprint you've now seen.
Encoder: The encoder is composed of a stack of $N = 6$ identical layers. Each layer has two sub-layers. The first is a m...
This section describes the fundamental building blocks of the Transformer architecture. Rather than using recurrent connections (like LSTMs) or convolutional layers, the Transformer stacks multiple identical layers, each containing attention mechanisms and feed-forward networks. The key innovations here are:
Let's break each component down.
The encoder consists of N = 6 identical layers stacked on top of each other. Think of this like building a tower where each floor has the same architecture but processes information slightly differently as it flows upward.
Each layer has two sub-layers:
Here's the critical formula for the encoder:
Let me break down what's happening:
What each component means:
Why the residual connection matters:
In earlier deep neural networks, when you stack many layers, gradients computed during backpropagation would become vanishingly small in early layers. This is called the vanishing gradient problem. The residual connection solves this by creating a direct shortcut: instead of forcing all information to flow through , we add it to the original input .
Think of it this way:
Layer Normalization:
Layer normalization normalizes the activations across the feature dimension for each sample independently. Given an output vector of dimension :
Where:
Intuition: Layer normalization centers and scales each sample's activations to have mean 0 and variance 1, which stabilizes training and allows higher learning rates.
The paper specifies that all sub-layers and embedding layers produce outputs of dimension . This is crucial because:
The decoder is more complex than the encoder because it must:
Each of the N = 6 decoder layers contains:
All three are wrapped with the same residual connection + layer normalization pattern:
Here's where the decoder differs fundamentally. The paper states:
"We modify the self-attention sub-layer in the decoder stack to prevent positions from attending to subsequent positions."
Why is this necessary?
During training, we have the ground truth output sequence available. But during inference, we generate one token at a time. To train the model realistically for inference, we must simulate the inference condition during training: position can only attend to positions .
How masking works mathematically:
Recall from Section 3 that attention is computed as:
The masking is applied before the softmax. For each position , we set attention scores to for all positions :
When you apply softmax to , it becomes , completely zeroing out the future positions.
The offset mechanism:
"The output embeddings are offset by one position"
This means:
Here's how a single sample flows through the Transformer:
Input → embedding layer → produces sequence of vectors, each of dimension 512
Encoder layer 1 → attention sees all input positions → feed-forward → output (512 dimensions)
Encoder layers 2-6 → same process, each seeing outputs from previous layer, progressively refining representations
Decoder layer 1 →
Decoder layers 2-6 → same process, refining output predictions
Final layer → project to vocabulary size → softmax → predict next token
| Aspect | Encoder | Decoder |
|---|---|---|
| Number of layers | N = 6 | N = 6 |
| Sub-layers per layer | 2 (attention + feed-forward) | 3 (masked attention + cross-attention + feed-forward) |
| Self-attention type | Full attention (all-to-all) | Masked attention (causal) |
| Cross-attention | None | Yes (to encoder) |
| Output dimension | 512 | 512 |
| Purpose | Process input once | Generate output sequentially |
The elegance of this design is that both encoder and decoder use the same fundamental building blocks (attention + feed-forward + residual + norm), but with strategic modifications (masking in decoder) to handle the directional nature of generation.
We call our particular attention "Scaled Dot-Product Attention" (Figure 2). The input consists of queries and keys of di...
This section introduces the core computational mechanism that powers the entire Transformer architecture. Think of attention as a way for the model to selectively focus on different parts of the input when processing information.
Previously (in Section 2), the paper mentioned that RNNs process sequences sequentially (slow for parallel computation) while CNNs struggle to relate distant positions efficiently. The authors are now proposing a better alternative: Scaled Dot-Product Attention, which relates any two positions with constant computational cost.
The key innovation here is deceptively simple: use dot products to measure relevance, scale them to prevent numerical problems, and use softmax to create attention weights.
Let me start with the intuitive definition before the math:
Attention is a mechanism for computing a weighted sum of values, where the weights depend on how "compatible" or "relevant" each value is to a query.
Imagine you're skimming a document to answer a specific question (the query). You don't read every word equally—you focus on (assign higher weight to) words relevant to your question. Attention works similarly:
The output is a blend of all values, weighted by how well each key matches the query.
The paper gives us the formula for Scaled Dot-Product Attention:
Let me break down every component and dimension:
| Symbol | What it represents | Dimensions | Explanation |
|---|---|---|---|
| Query matrix | Contains all queries packed as rows; is the query dimension | ||
| Key matrix | Keys for each position; same dimension as queries for dot product compatibility | ||
| Value matrix | Actual values we'll average; can have different dimension than keys | ||
| Key dimension | scalar | Dimension of key vectors (e.g., 64 in the paper's implementation) | |
| Value dimension | scalar | Dimension of value vectors (e.g., 64) | |
| Output | Attention output | Weighted combination of values, same dimension as values |
Key insight about matrix shapes: The multiplication gives us an matrix—essentially a compatibility score between every query and every key.
Let me walk through the computation:
This matrix multiplication computes dot products between each query and each key. The entry at position is:
where is the -th query vector and is the -th key vector.
Why dot product? The dot product measures geometric similarity: parallel vectors (pointing the same direction) have large positive dot products, while orthogonal vectors have dot products near zero. This naturally captures relevance.
Why scale? This is crucial. The paper explains:
Analogy: Imagine softmax as a temperature control—dividing by cools down hot (large) dot products.
The softmax function converts scores to probabilities. For a vector :
Applied to each row of our matrix, this gives us attention weights:
So each query gets a probability distribution over all keys, representing "how much should I attend to each position?"
Matrix dimensions:
Each output query vector is a weighted average of all value vectors, with weights from the attention distribution.
The paper mentions two main approaches:
Uses a learned neural network to compute compatibility:
where are learned weight matrices.
Pros: Theoretically expressive (can learn complex compatibility functions) Cons: Slower (requires forward passes through a small neural network for each pair)
Pros:
Cons:
This deserves special attention because it's critical:
When is large, say :
The softmax derivative is:
When softmax inputs are large, the output is nearly 0 or 1, making the gradient term vanish.
Result: Gradients disappear, training stalls.
By dividing by , we keep dot products at comfortable magnitudes. If we assume and are normalized:
The paper emphasizes practical benefits:
Matrix Implementation: We don't compute attention separately for each query-key pair. Instead, we pack everything into matrices and compute:
This is three matrix multiplications, which can be:
| Step | Operation | Purpose | Dimensions |
|---|---|---|---|
| 1 | Compute | Measure query-key compatibility | |
| 2 | Divide by | Keep values in reasonable range | |
| 3 | Apply softmax | Convert to probability weights | |
| 4 | Multiply by | Compute weighted sum of values |
Remember from Section 3.1 that the Transformer has:
Scaled Dot-Product Attention makes this possible and practical. It's elegant, efficient, and—as the experimental results show—remarkably effective.
Three key properties of softmax:
Sums to 1 () — produces valid probability distributions for weighted sums
Differentiable everywhere — enables backpropagation through attention
Preserves ordering — larger scores get higher weights (monotonic)
The paper mentions that this basic attention is used in Multi-Head Attention, which runs the attention computation times in parallel:
where each head:
This allows the model to attend to different representation subspaces—for example, one head might focus on word positions, another on semantic relationships. It's like having multiple parallel filters.
| Aspect | Insight |
|---|---|
| Core operation | Weighted combination of values, where weights come from comparing queries to keys |
| Scaling factor | Prevents saturation of softmax; normalizes dot products' variance to 1 regardless of dimension |
| Softmax choice | Produces normalized weights; smooth gradients enable training |
| Parallelization | All queries and keys processed simultaneously via matrix multiplication (efficient) |
| Design elegance | Simple, differentiable, and interpretable—weights show what the model attends to |
This mechanism is the foundation of transformers and explains why they excel at capturing long-range dependencies and parallel processing.
Visualize sigmoid saturation (related to softmax gradient problem)



Show that sigmoid gradient vanishes at extremes




Computing QK^T matrix multiplication for concrete example


Computing softmax manually for understanding



Calculate softmax values numerically
![N[{exp(0.707)/(exp(0.707) + 1), 1/(exp(0.707) + 1)}]](/api/wolfram-image?url=https%3A%2F%2Fpublic6.wolframalpha.com%2Ffiles%2FGIF_595okpmufs.gif)

Softmax with unscaled dot product (moderate values)



Softmax with large scaled scores (saturation problem)



Verify softmax sums to 1

Instead of performing a single attention function with $d_{\text{model}}$-dimensional keys, values and queries, we found...
You've just learned about Scaled Dot-Product Attention in the previous section—a single attention mechanism that lets the model look at different positions and compute a weighted combination of values based on relevance (query-key matches).
Multi-Head Attention takes this idea further by asking: Why look at the data in just one way?
The core insight is that different aspects of your data might be more relevant when viewed through different "lenses" or representations. A single attention head might conflate multiple types of relationships. By using multiple heads in parallel, each with its own learned perspective on the data, the model can simultaneously attend to different types of information—grammatical structure, semantic meaning, word relationships, etc.—all at once.
This is analogous to how humans use different cognitive processes simultaneously: you might parse syntax, recognize semantic meaning, and track discourse structure all in parallel when reading a sentence.
Instead of using queries, keys, and values directly at their full dimension , the model linearly projects them times (where in this work) into lower-dimensional spaces.
For each head (where ):
Let me break down what each component represents:
, , : These are the original query, key, and value matrices (defined in section 3.2.1). Each has shape related to sequence length and dimensionality.
, , : These are learned projection matrices with dimensions:
Different subscripts mean these are different matrices for each head—this is how each head learns its own "lens."
What happens geometrically: Matrix multiplication takes each of the rows of (representing positions in your sequence) and transforms them into a new vector space of dimension . This is a linear transformation that the model learns during training.
For each head, you apply the Scaled Dot-Product Attention formula (Equation 1 from the previous section):
This produces an output of shape —a -dimensional representation for each of the positions.
Key point: All heads do this in parallel on their own projected versions of the data. They don't interfere with each other.
After all heads finish their attention computations, you have 8 outputs, each of shape :
You concatenate these along the dimension axis:
This gives you a matrix where each position has information from all 8 different attention perspectives stacked together.
Finally, you apply one more learned linear projection to combine all this information back to the original dimension:
Where:
Shape tracking:
Putting it all together:
where
The paper makes a crucial observation:
"Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this."
What does "averaging inhibits this" mean?
Intuition: Imagine you're trying to understand a word in context. You might need to:
With a single attention head, the softmax must create one probability distribution that balances all these considerations simultaneously. The weighted average blurs together these different types of relationships.
With multiple heads, each head can specialize:
The model can learn these specializations because each head has its own set of parameters () that are optimized independently during training.
The paper notes an important practical point:
"Due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality."
The math:
Single-head attention would compute: with
Multi-head (8 heads):
Same computational cost, but with the benefits of multiple representation subspaces. This is why multi-head attention is such a powerful design choice.
The authors made specific choices:
| Parameter | Value | Why? |
|---|---|---|
| (number of heads) | 8 | Balances model capacity with computational efficiency |
| Keeps per-head dimension manageable while using full model dimension across all heads | ||
| 512 | Standard choice for this model size |
These aren't magical constants—they're design choices that work well empirically. Researchers could experiment with other values (e.g., 16 heads with ).
In the Transformer architecture:
This design—combining insights from multiple representation subspaces—is a major reason the Transformer became so successful and influential.
Elegant result! The computational savings factor is exactly 8, which is the number of heads. Here's why:
Since , we have:
But we compute 8 heads in parallel, each costing , for total: , which is the cost of a single full-dimension head.
Architecture: Multi-head attention performs the same attention mechanism in parallel across different learned subspaces, then combines the results.
Why it works: Different heads can specialize in different types of relationships (syntax, semantics, positions, etc.), whereas a single head must average all patterns together.
Efficiency: By splitting the dimension across heads, computation remains tractable. Computing attention on 8 separate 64-dimensional spaces costs the same as computing attention on a single space (ignoring the final projection, which is negligible).
Dimensional elegance: The design maintains constant dimensionality through the pipeline—inputs and outputs are both dimensional, with only the intermediate heads being in reduced dimensions.
Learned specialization: Each head gets its own set of weight matrices (, , ), allowing the model to learn different ways to project information into each subspace during training.
This simple yet powerful design has proven to be the foundation of modern transformer-based language models, enabling them to capture diverse types of linguistic and semantic patterns simultaneously.
Verify the relationship between model dimension and head dimension in the original Transformer




Visualize how a single attention head (which performs weighted averaging) might mix multiple peaks, whereas multiple heads can focus on different patterns



Show how the first projection works dimensionally



Calculate the output dimension after projecting queries to dimension dk




Verify concatenated dimension equals model dimension




Calculate total computational operations for 8 heads with dk=64 each




Calculate computational operations for single-head attention with dk=512




Calculate the computational savings ratio




The Transformer uses multi-head attention in three different ways: • In "encoder-decoder attention" layers, the queries ...
This section is the practical payoff of everything discussed so far. We've learned how attention works (Scaled Dot-Product Attention from 3.2.1) and how to make it more powerful (Multi-Head Attention from 3.2.2). Now we need to understand where these attention mechanisms are actually used in the Transformer architecture.
The key insight: attention can be used in fundamentally different ways depending on what you feed into it. By changing where the queries, keys, and values come from, we can implement three distinct types of information flow, each serving a different purpose in translating a sentence from one language to another.
Purpose: Allow the decoder to look back at the entire input sequence while generating output.
How it works:
Intuition: Imagine you're translating English to German. The decoder is deciding what to write next in German, and it needs to look at the entire English sentence to figure out what word to generate. This attention mechanism does exactly that—it lets each position in the decoder "look at" all positions in the input.
Mathematical interpretation: When we compute using equation (1):
We're computing a weighted sum of the encoder's output values (), where the weights depend on how well the decoder's current query () matches each encoder position's key (). The softmax ensures these weights sum to 1 (a probability distribution).
Why this matters: This is the bridge between encoder and decoder—without it, the decoder would have no way to access the input sequence. The paper notes this "mimics the typical encoder-decoder attention mechanisms in sequence-to-sequence models," meaning this is how previous neural machine translation systems also worked, but now it's implemented via the elegant attention mechanism.
Purpose: Allow each position in the encoder to integrate information from all other positions at the previous layer.
How it works:
The key word: "Self" means queries, keys, and values all come from the same source.
Intuition: Consider the word "bank" in English—it could mean a financial institution or the side of a river. To understand which meaning is intended, you need to look at surrounding words. Self-attention allows each word position to attend to (look at) all other word positions in the same layer. This way, the representation of "bank" can be refined based on context from neighboring words like "river" or "account."
How it propagates information:
This is how context propagates through the encoder—each layer builds richer, more contextually-aware representations.
Purpose: Allow each position in the decoder to look at previously generated tokens, but not future tokens (preserving autoregressive generation).
How it works:
The critical constraint - Autoregressive property: In machine translation, you generate words sequentially: first word, then second word, then third, etc. When generating the second word, you should only have access to the first word—you can't "cheat" by looking at words you haven't generated yet.
How masking works mathematically:
The paper states: "We implement this inside of scaled dot-product attention by masking out (setting to ) all values in the input of the softmax which correspond to illegal connections."
Let's unpack this. Recall the attention computation:
The matrix has shape where is the sequence length. The entry at position represents how much position should attend to position .
Before softmax, for each query position , we set all entries corresponding to "illegal" future positions (where ) to :
When we apply softmax to each row:
Any entry with becomes , so the softmax weights for future positions become exactly zero. This completely eliminates the "look at future" contribution.
Concrete example: Imagine you're generating a 4-word translation and you're at position 2 (generating the second word). The attention mask looks like this:
Position 2 (second row) can only attend to positions 1 and 2—positions 3 and 4 are blocked.
Why this matters: This constraint is essential for training. During training, the ground truth words are available, but the model must still learn to generate word-by-word without "looking ahead." During inference (actual translation), you generate one word at a time anyway, so this constraint matches the actual deployment scenario.
These three attention mechanisms work in concert:
This is why the Transformer is elegant—by simply controlling where queries, keys, and values come from and applying masking when needed, we get three fundamentally different but complementary behaviors from the same underlying attention mechanism.
In addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully connected feed-forwa...
You might be wondering: "We just spent all this time on attention mechanisms—why do we need feed-forward networks too?"
Here's the key insight: attention mechanisms are great at figuring out which positions should talk to each other, but they don't inherently add expressive power to transform the information itself. The feed-forward networks in this section are the Transformer's solution to this problem. They act as "information processors" that can apply learned transformations to each piece of information independently, adding nonlinearity and computational power beyond what attention alone provides.
In traditional deep learning, you alternate between mixing information (like attention does) and transforming it (like these feed-forward networks do). The Transformer does exactly this pattern: attention → feed-forward → attention → feed-forward, and so on.
Each layer in both the encoder and decoder contains:
The word "position-wise" is crucial. It means: the same feed-forward network is applied independently to each position in the sequence. There's no interaction between positions within this feed-forward layer—each token gets processed by identical transformation rules.
This is different from the attention layer, where every position can "look at" every other position. Here, position 1's transformation doesn't depend on position 2, position 3, etc. The transformation is purely local to each position.
Let me break down each part:
Variables and their meanings:
Walking through the computation step by step:
First linear transformation:
Activation function: (ReLU)
Second linear transformation:
The overall data flow: (expand, apply nonlinearity, contract)
The architecture expands from 512 → 2048 (4x larger) and then contracts back to 512. Why?
The expansion creates a "hidden layer" with much higher dimensionality. This increased dimension allows the network to learn richer, more complex transformations. Think of it like having more "capacity" to express ideas.
The contraction brings it back to 512 so the output can be fed into the next layer (which expects inputs of dimension 512, matching )
The factor of 4 (since ) is a design choice in this paper. It's one of the hyperparameters they selected. Different values could work, but this ratio seems to balance expressiveness with computational cost.
The ReLU activation is essential for introducing nonlinearity. Here's why:
Consider two linear transformations stacked together:
Mathematically, composing two linear operations still gives you a linear operation! Specifically:
This is still just a linear transformation (with a combined weight matrix ). You haven't gained any extra expressiveness.
But with ReLU in between:
The operation is nonlinear, so you can no longer simplify this to a single linear transformation. The network can now learn much more complex functions—this is what gives it expressive power.
The paper mentions: "Another way of describing this is as two convolutions with kernel size 1."
This might seem odd if you're thinking of traditional convolutions, so let me clarify:
A 1×1 convolution is a convolution operation where the filter has spatial size 1×1. In the context of processing sequences with a channel dimension:
This framing is just another way to think about the same operation—it emphasizes that each position is processed independently (there's no interaction across positions within this layer). In the literature, 1×1 convolutions are sometimes called "pointwise convolutions" for exactly this reason.
Here's an important practical note: the same parameters , , , are used for every position.
This means:
This is actually implementable very efficiently because you can:
where is a matrix with shape for a sequence of length . Then:
You compute this all at once using optimized matrix operations rather than looping over positions—that's why it's efficient.
The feed-forward network serves as a per-position transformation mechanism that:
In the full Transformer architecture, you see a repeating pattern:
This interleaving of "communication" (attention) and "transformation" (feed-forward) is what gives the Transformer its power.
Gradient of ReLU:
$ \frac{d}{dx}\max(0, x) =
This is critical for training:
This selective activation is called the "dying ReLU" problem in very deep networks—if a neuron always outputs values , its gradient is always 0 and it stops learning. However, in the Transformer context, this is typically not a major issue due to the architecture's design.
The FFN equation is a position-wise, two-layer fully connected network that:
Applied independently at each sequence position, it provides capacity for complex transformations while maintaining computational efficiency. The 4× expansion factor is empirically optimal for transformer models of this scale.
Visualizing the ReLU activation function to show how it zeroes out negative values



Computing the first linear transformation xW_1 + b_1


Applying ReLU activation (zeroing negative values)



Understanding how gradients flow through ReLU during backpropagation

Similarly to other sequence transduction models, we use learned embeddings to convert the input tokens and output tokens...
This section describes how the Transformer converts discrete input tokens (words) into continuous vectors that the neural network can process, and how it converts the network's output back into predictions about which token should come next. While this might sound like a simple bookkeeping detail, the authors make two clever design choices here:
These choices have subtle but important effects on how the model learns. Let's break down what's happening.
The Transformer works entirely with real-valued vectors (as you've seen in the attention and feed-forward layers). But language is inherently discrete—we have a finite vocabulary of tokens (words, subwords, or characters). We need a way to convert each token into a real-valued vector.
The paper says: "we use learned embeddings to convert the input tokens and output tokens to vectors of dimension ."
What does this mean mathematically?
Let's say our vocabulary has possible tokens. An embedding layer is defined by an embedding matrix:
Here:
How it works in practice:
When we encounter token in our input sequence (where token is represented as an integer from to ), we look up row of the embedding matrix:
This is essentially a lookup table operation. The values in are learned parameters—they're updated during training via backpropagation to make the model better at its task.
Why learn embeddings?
Initially, all token embeddings are random. But as the model trains on thousands or millions of examples, it learns to position tokens in this high-dimensional space such that:
For example, the embedding for "king" minus the embedding for "man" plus the embedding for "woman" will be close to the embedding for "queen"—a famous property of word embeddings.
Here's where it gets interesting. The paper states: "In the embedding layers, we multiply those weights by ."
After looking up the embedding vector, we multiply every component by :
\text{scaled\_embedding}(t) = \sqrt{d_{\text{model}}} \cdot E_{\text{input}}[t, :] **Why do this?** This is somewhat of a technical trick related to how the model combines embeddings with positional encodings (which are mentioned in the context but not the main focus here). Here's the intuition: 1. **Embeddings and positional encodings have different scales**: The embedding vectors have one typical scale, while positional encodings (vectors that indicate where in the sequence a token appears) have a different scale. 2. **Matching scales matters**: When you add two vectors together, you want them to contribute relatively equally. If one is much larger than the other, it dominates. By scaling up the embeddings by $\sqrt{d_{\text{model}}}$, the authors ensure that the embedding and positional encoding contributions are roughly balanced in magnitude. 3. **Empirical motivation**: The authors mention this works well in practice—it's an engineering choice that improves training stability and model performance, though the exact mechanism is somewhat empirical. **A rough analogy:** Imagine you're mixing two ingredients in a recipe—one measured in grams, one in ounces. If you want them to contribute roughly equally, you need to scale them appropriately before mixing. That's what this factor does. --- ## Part 2: The Output Layer - From Continuous Back to Discrete ### Converting to Token Probabilities The paper says we use *"the usual learned linear transformation and softmax function to convert the decoder output to predicted next-token probabilities."* **What does this mean mathematically?**At the end of the decoder stack, after passing through all the attention and feed-forward layers, we have a vector representing the model's "understanding" of what should come next.
where:
Instead of having three separate weight matrices:
Then:
So we have:
Why share weights?
Fewer parameters: This reduces the total number of learnable parameters, which can improve generalization and reduce computational cost. In a model with a vocabulary of 50,000 tokens, this saves million parameters.
Geometric interpretation: It creates a symmetry in the model. The same embedding space is used for both interpreting input tokens and predicting output tokens. This encourages the model to learn a shared representation space where:
Initialization: Shared weights provide a better initialization. The embeddings start with meaningful random values rather than zeros.
| Component | Dimension | Purpose |
|---|---|---|
| Input embeddings | Convert input tokens to vectors | |
| Output embeddings | Same as input | Used in softmax layer (transpose) |
| Scaling factor | Balance embedding with positional encoding | |
| Softmax output | Probability distribution over tokens |
Remember from earlier sections:
This section completes the pipeline: the embeddings get the input into the model, and the softmax gets the model's output back into a format humans can understand (predicted tokens).
Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequen...
The Transformer is fundamentally different from previous sequence models. Traditional approaches like RNNs (Recurrent Neural Networks) process sequences one token at a time, naturally capturing order information through their sequential processing. Transformers, by contrast, process the entire sequence in parallel using attention mechanisms.
The core problem: If you feed all tokens into the model simultaneously, how does the model know which token comes first, second, third, etc.? Without some way to encode position information, the sentence "The cat ate the mouse" would be treated identically to "The mouse ate the cat" — just a jumbled collection of tokens with no inherent order.
The solution: Positional encodings inject information about token positions directly into the input representations. This allows the attention mechanism to leverage both the semantic meaning of tokens AND their sequential positions.
Positional encodings are vectors of dimension (which equals 512 in this model) that get added to the token embeddings. Think of it like this:
Since both have the same dimension, element-wise addition is straightforward. The positional encoding is designed to:
The authors mention they experimented with learned positional embeddings — treating positions like learnable parameters, similar to token embeddings. These performed nearly identically (Table 3, row E). However, they chose the sinusoidal version for one key reason: extrapolation to longer sequences. A learned embedding might not generalize well to sequences longer than training examples, while sinusoidal encodings can theoretically extend infinitely.
The positional encoding at position and dimension is defined by:
Let me break down every component:
| Symbol | Meaning | Notes |
|---|---|---|
| The positional encoding at position in dimension | This is a scalar value that gets added to the embedding | |
| The position in the sequence | where is sequence length | |
| A dimension index | ||
| The embedding dimension | Set to 512 in this paper | |
| A frequency scaling constant | Determines the wavelength range |
Notice the clever construction:
For a sequence position , you compute the full -dimensional positional encoding by evaluating these formulas for .
Example: If and :
Each dimension oscillates at a different frequency. Think of tuning knobs on different radio stations:
The denominator term controls the wavelength (or period) of each sinusoid:
The wavelengths form a geometric progression from to .
Imagine stacking sine and cosine waves of increasing wavelengths:
Together, these create a unique "fingerprint" for each position in the sequence.
Here's the critical claim from the paper: "for any fixed offset , can be represented as a linear function of ."
This is saying: the positional encoding at position can be computed as a linear combination of the encoding at position .
Let me prove why this works for a single dimension:
Using the angle addition formulas from trigonometry:
With and (where is the frequency):
In matrix form for the pair of sine-cosine dimensions:
This is a rotation matrix! The encoding at position is a linear transformation (specifically, a rotation) of the encoding at position .
This property means:
The constant 10000 is somewhat arbitrary but chosen to be large enough that:
You could use other constants; 10000 just happens to work well empirically.
Using both sine and cosine (in alternating dimensions) is elegant because:
| Aspect | Details |
|---|---|
| What it does | Adds position information to token embeddings so the Transformer knows token order |
| How it works | Uses sine/cosine functions of different frequencies, one unique encoding per position |
| Key property | Relative positions are encoded as linear transformations (rotations) |
| Why not learned? | Sinusoids generalize to longer sequences better than learned embeddings |
| Integration | Simply added to embeddings: |
The elegance of this approach lies in its simplicity and mathematical structure — without any learnable parameters or sequence length limitations, it provides the order information essential for making the parallel, attention-based Transformer architecture work.
Perfect! Now I have all the information I need to provide a comprehensive analysis. Let me synthesize this into a clear explanation.
The positional encoding (PE) equation is a clever mechanism to inject position information into the Transformer model. Since Transformers lack recurrence or convolution, they don't inherently understand sequence order—all positions are processed in parallel. These sinusoidal encodings solve that problem by adding position-dependent signals to the embeddings.
The equation has two interleaved components:
Where:
Each dimension pair produces a sinusoid at a different frequency. This is crucial: the model encodes position through multiple oscillating patterns, from very slow (low frequency) to very fast (high frequency).
The frequency scaling factor creates a geometric progression of wavelengths. Here's what this means numerically in a 512-dimensional model:
This exponential spacing allows:

The plot shows three sine waves with vastly different frequencies. Notice how the lowest-frequency wave (leftmost, oscillating slowly) completes only one cycle in the window, while the highest-frequency wave (rightmost, oscillating rapidly) completes many cycles. Each dimension in the actual embedding pairs responds to a different frequency in between these extremes.
The paper makes a crucial claim: any fixed offset can be represented as a linear function of the base position. This is the genius of sinusoids.
Using the angle addition formulas (which Wolfram confirmed):
Applied to positional encoding:
Translation: The PE at position depends only on:
This means the attention mechanism can learn the offset directly from the relative encoding, without needing absolute position labels! The model sees pairs of positions and their encodings, and can deduce their distance.
For a 512-dimensional model at different positions and frequencies:
| Position | Dimension | Value | Notes |
|---|---|---|---|
| pos=0, i=0 (lowest freq) | sin component | Starting point | |
| pos=100, i=0 | sin component | Low frequency: slow oscillation | |
| pos=100, i=256 (mid freq) | sin component | Medium frequency: balanced oscillation | |
| pos=100, i=255 (highest freq) | sin component | High frequency: rapid oscillation |
The key insight: at the same position (pos=100), different dimension pairs have completely different values, creating a unique signature for that position.
By pairing sine (dimension ) and cosine (dimension ), the model gets both the amplitude and phase of each oscillation:
This is equivalent to an encoding as a unit circle point , which captures 2D information from a 1D phase angle. The model can interpret this geometrically: neighboring positions have nearby encodings, distant positions have orthogonal encodings.
The paper claims this allows extrapolation to longer sequences than those seen during training. Here's why:
The sinusoidal encoding is a pure mathematical function independent of training data length. If trained on sequences of length 1000, the same PE formula works for length 10,000 or 100,000. Learned embeddings, by contrast, are lookup tables limited to seen positions.
The geometric wavelength progression ( to ) means:
| Feature | Effect |
|---|---|
| Sine + Cosine pair | Captures phase and amplitude; creates 2D signature per position |
| Different values | Different frequencies capture position info at multiple scales |
| Geometric progression | Smooth coverage from short to long-range positional patterns |
| Angle addition formula | PE(pos+k) is a linear combo of PE(pos); enables relative position learning |
| Fixed formula | No parameters to learn; works for any sequence length |
This elegant design ensures the Transformer can "understand" position without explicit architectural support for sequencing.
Visualizing how positional encodings have different frequencies across dimensions - showing low frequency (i=0), mid frequency, and high frequency components



Deriving the linear relationship property: showing PE(pos+k) can be represented as a linear combination of PE(pos)




Recalling angle addition formulas needed to show the linear relationship




Computing concrete PE values at position 0 and 100 for dimension i=0 (lowest frequency)




Computing PE values at the middle frequency (i=256 in 512-dim model)




Computing PE values at the highest frequency (i=255 in 512-dim model)




Understanding the wavelength scaling: 10000 appears as the base in the exponent




Computing the wavelength progression from lowest to highest dimension




In this section we compare various aspects of self-attention layers to the recurrent and convolutional layers commonly u...
This section is the justification for why the Transformer uses self-attention instead of recurrent neural networks (RNNs) or convolutional neural networks (CNNs). The authors need to convince us that their architectural choice is fundamentally sound.
Think of it this way: The paper has proposed something radical—a neural network with no recurrence and no convolutions. That's unusual! So they need to explain: "Why is self-attention actually better than what people were using before?"
The answer comes down to three key metrics:
The authors identify three criteria for comparing layer types. Let me break each down:
When processing a sequence of length where each element has dimension :
This is subtle but crucial: Even if two operations have the same total complexity, one might require many sequential steps while the other can run in parallel.
Example: Suppose you need to do 1,000 multiplications.
Modern GPUs are incredibly fast at parallel operations but can't hide sequential bottlenecks.
This is perhaps the deepest insight. Consider a neural network as a directed graph where:
The path length between position and position is the minimum number of hops needed for information from position to influence position .
Why does this matter?
When you train a neural network with backpropagation, gradients flow backward through the network. If there's a long path between two positions, the gradient signal gets weaker as it flows (this is the "vanishing gradient" problem). Mathematically, when you multiply many matrices together during backpropagation, small eigenvalues compound, making gradients exponentially smaller:
If each partial derivative is less than 1, the product shrinks exponentially with path length.
Shorter paths = easier learning of long-range dependencies.
Now let's examine the actual comparisons in Table 1. I'll walk through each type:
Maximum path length: (constant)
Per-layer complexity:
Minimum sequential operations: (constant)
Maximum path length: (linear in sequence length)
Per-layer complexity:
Minimum sequential operations: (linear)
Maximum path length: with a single layer (more with multiple layers)
Per-layer complexity:
Minimum sequential operations: (constant per layer, but you need many layers)
Here's the crucial comparison from the text:
"self-attention layers are faster than recurrent layers when the sequence length is smaller than the representation dimensionality "
Let's understand this with numbers. Suppose (100 words in a sentence) and (standard in Transformer):
Self-attention per-layer complexity:
RNN per-layer complexity:
Self-attention actually wins! The quadratic dependence on is outweighed by the quadratic dependence on in the RNN.
And critically: self-attention can do all operations in parallel, while the RNN must do them sequentially.
The authors acknowledge one weakness:
"To improve computational performance for tasks involving very long sequences, self-attention could be restricted to considering only a neighborhood of size "
If your sequences are very long, you can modify self-attention to only attend to nearby positions—say, only look at the 50 closest words instead of all 1000 words:
This reduces:
The authors note an elegant property:
"self-attention could yield more interpretable models... individual attention heads clearly learn to perform different tasks"
When you visualize which words the model is paying attention to, you get a direct window into the model's reasoning. A word's attention pattern shows what other words influenced its representation.
This is genuinely useful for understanding model behavior—a major advantage over RNNs where information is hidden in high-dimensional hidden states.
| Property | Self-Attention | RNN | CNN |
|---|---|---|---|
| Path length | ✓ | ✗ | ~ |
| Per-layer work | ✓ | ||
| Parallelizable? | YES ✓ | NO ✗ | YES ✓ |
| Interpretable? | YES ✓ | NO ✗ | NO ✗ |
The self-attention mechanism hits a sweet spot:
This is why, despite being theoretically more complex per layer, self-attention is practically superior for sequence modeling.
We trained on the standard WMT 2014 English-German dataset consisting of about 4.5 million sentence pairs. Sentences wer...
Before we can train a neural network to translate languages, we need to decide what data to train on and how to organize that data during training. This section describes the practical details of how the authors prepared their training pipeline for the Transformer model. This might seem like a minor technical detail, but it's actually crucial because:
Let's break down each component:
Dataset: WMT 2014 English-German dataset
Vocabulary Encoding: Byte-pair encoding (BPE)
Let me explain what "shared vocabulary" means mathematically. Normally, you might have:
But the Transformer uses:
This single shared vocabulary has several advantages:
What is Byte-Pair Encoding (BPE)? It's a tokenization strategy that breaks words into subword units. For example:
["play", "ing"] or even ["p", "l", "ay", "ing"]Dataset: WMT 2014 English-French dataset
The vocabulary here is slightly smaller (32,000 vs 37,000) but applied to a much larger dataset. Word-piece is similar to BPE but has some technical differences in how it selects which subword units to create.
This is where the practical training logistics come in. When training neural networks, we don't process one example at a time. Instead, we group multiple examples into batches and process them together. This is more computationally efficient.
Key principle: Sentence pairs were batched together by approximate sequence length.
What does this mean? Let's define some notation:
Why group by sequence length? The Transformer processes variable-length sequences through attention operations. Consider the attention computation from Section 3.2 (the mathematical detail we don't repeat here, but you computed something like ).
The computational cost grows quadratically with sequence length because:
By grouping short sentences together and long sentences together, you avoid having to pad short sequences to match long ones. Padding means adding dummy tokens to make all sequences in a batch the same length.
"Each training batch contained a set of sentence pairs containing approximately 25,000 source tokens and 25,000 target tokens."
Let's parse this carefully with mathematical notation:
For a batch :
where denotes the length (number of tokens) of sentence pair .
Why these specific numbers?
Memory constraints: Each batch must fit in GPU memory. The authors had 8 GPUs available (mentioned in the abstract: "training for 3.5 days on eight GPUs")
Computational efficiency vs. Gradient quality tradeoff:
Flexibility in batch composition: Using a token count (not a sentence count) is clever because:
The sorting operation creates an approximate ordering:
This minimizes wasted computation from padding zeros and maximizes the useful computation done by the attention mechanism.
| Aspect | English-German | English-French |
|---|---|---|
| Sentence pairs | ~4.5M | ~36M |
| Encoding method | Byte-pair | Word-piece |
| Vocabulary size | ~37K | ~32K |
| Batch token count | ~25K source + ~25K target | Same |
The batching strategy is particularly important for the Transformer because:
No recurrence — Unlike RNNs (which process sequences sequentially), the Transformer can process all positions in parallel. This means batching 100 examples of length 250 is nearly as fast as 10 examples of length 2,500. The batching strategy lets us leverage this parallelization advantage.
Quadratic attention complexity — The cost per layer means length matters a lot. Smart batching keeps the effective manageable.
The "approximately" caveat — They say "approximately 25,000" because you can't hit this exactly when grouping by sentence pairs. You batch complete sentence pairs and stop when adding another pair would exceed ~25,000 tokens. This small flexibility doesn't matter in practice.
We trained our models on one machine with 8 NVIDIA P100 GPUs. For our base models using the hyperparameters described th...
Before diving into the numbers, let's understand why this section is important for the paper's contribution. The authors are making two major claims about the Transformer:
This section provides the empirical evidence for claim #2 by being transparent about exactly what hardware they used and exactly how long training took. This transparency is crucial for reproducibility and for understanding the practical advantages of the Transformer architecture.
The authors trained on "one machine with 8 NVIDIA P100 GPUs."
Let me unpack what this means:
Why is this important? Recall from Section 4 that self-attention has a major advantage: all positions in the sequence can be processed in parallel (constant number of sequential operations). The 8 GPUs enable the Transformer to take full advantage of this parallelization potential, whereas recurrent architectures (which process sequentially) would struggle to utilize multiple GPUs effectively.
The authors provide two key metrics for their "base" models:
What's a training step? In neural network training, one "step" typically means:
Recall from Section 5.1 that each batch contained approximately 25,000 source tokens and 25,000 target tokens for the English-German task.
Let's verify this makes sense: ✓ (The ~12 hours includes some overhead for validation, checkpointing, etc.)
### Big Model Training For larger versions of the Transformer ("big models"), the computational demand increases:
Let's verify: ✓
To appreciate the significance, you need to understand what was typical before the Transformer. The abstract mentions:
"a small fraction of the training costs of the best models from the literature"
Previous state-of-the-art sequence transduction models (based on RNNs with attention) typically required:
The Transformer achieved better results in 3.5 days on a single machine.
This is a practical revolution, not just an academic one. It makes the technology accessible to researchers with limited computational budgets.
Though not explicitly stated in this section, there's an important relationship implied:
For neural networks, computational cost per step generally scales with the number of parameters. If we denote:
The ratio tells us the big model is roughly 2.5× more computationally expensive per step, likely meaning it has significantly more parameters.
This is worth emphasizing: The efficiency here isn't just about the hardware—it's about the synergy between:
The Transformer architecture's parallelizability (from Section 4):
Hardware that can exploit parallelism:
A recurrent architecture (like an LSTM) with 8 GPUs would see much less speedup because the recurrent dependencies force sequential computation—you must compute the hidden state at position before computing position .
| Metric | Base Models | Big Models |
|---|---|---|
| Time per step | 0.4 sec | 1.0 sec |
| Total steps | 100,000 | 300,000 |
| Total training time | 12 hours | 3.5 days |
| Hardware | 8 P100 GPUs on 1 machine | 8 P100 GPUs on 1 machine |
The practical implication: Researchers with access to a single modern GPU machine could train these models overnight or over a weekend, compared to previous approaches requiring distributed systems and weeks of compute time.
We used the Adam optimizer [20] with $\beta_1 = 0.9$, $\beta_2 = 0.98$ and $\epsilon = 10^{-9}$. We varied the learning ...
Before diving into the math, let's understand what we're doing here. Training a neural network is fundamentally an optimization problem: we want to find the set of model parameters (weights and biases) that minimize our loss function. The optimizer is the algorithm that guides this search.
In the context of the Transformer paper, the choice of optimizer and learning rate schedule is crucial because:
The authors chose to use the Adam optimizer with a carefully designed learning rate schedule. This section explains both pieces.
Adam (short for "Adaptive Moment Estimation") is an optimization algorithm that builds on simpler methods like stochastic gradient descent (SGD). Instead of using a fixed learning rate for all parameters, Adam maintains separate learning rates for each parameter, adapting them based on historical gradient information.
The key idea: Some parameters might need larger steps, others smaller steps. Adam figures this out automatically by tracking:
Let me explain what these parameters control:
: This is the exponential decay rate for the first moment (momentum term)
: This is the exponential decay rate for the second moment
: A small constant added for numerical stability
This is the novel and clever part. Rather than keeping the learning rate constant throughout training, the authors use a schedule that changes the learning rate based on the training step.
This looks complex, so let's break it down into pieces.
This is the scaling factor based on model dimension:
This minimum function selects between two different behaviors depending on where we are in training. Let me define a helpful shorthand:
So we're choosing between:
Warmup Phase (early training, when ):
During warmup, the right term is smaller, so the learning rate follows:
Let's rewrite this more intuitively:
Why is warmup necessary?
When you start training a neural network, the initialization of parameters is essentially random. The gradients can be very noisy. Starting with a small learning rate and gradually increasing it gives the optimizer time to get oriented before taking large steps. Think of it like slowly accelerating your car rather than suddenly flooring the accelerator.
Decay Phase (later training, when ):
After warmup ends (around step 16 million for this schedule, or about 4000 steps if we think about the crossover), the left term becomes smaller, so:
Why does this decay help?
Early in training, we're far from a good solution and can afford to take larger steps. As we get closer to a good solution (indicated by having trained for many steps), we need smaller steps to avoid overshooting the optimal parameters. The inverse square root decay is gentler than linear decay, allowing continued improvement even late in training.
The two terms are equal when:
Wait, that's not quite right. Let me recalculate. Setting them equal:
Hmm, actually they're equal at ? Let me verify by checking which term is smaller on each side of this point:
Actually, the crossover is not exactly at . Let me be more careful. The two functions cross where:
But for practical purposes, with , the warmup clearly dominates for the first thousands of steps, and then the decay dominates.
[Figure: Imagine a graph with step number on the x-axis and learning rate on the y-axis]
The learning rate schedule has a distinctive shape:
With :
So the peak learning rate (at step 4000) is approximately in relative terms.
The authors don't explicitly justify every design choice, but we can infer:
The factor makes the learning rate scale-invariant with model size. Larger models automatically get smaller learning rates.
The warmup phase is essential for Transformers because:
The square-root decay is gentler than exponential decay, allowing continued learning throughout training while gradually stabilizing as parameters converge.
This schedule has become standard in modern deep learning and is used in many subsequent Transformer-based models (BERT, GPT, etc.).
| Aspect | Value | Meaning |
|---|---|---|
| Optimizer | Adam | Adaptive learning rates for each parameter |
| 0.9 | Strong momentum in gradient direction | |
| 0.98 | Conservative variance-based scaling | |
| Warmup steps | 4000 | Linear increase for first 4000 steps |
| Decay schedule | Inverse square root decrease thereafter |
The combination of Adam's per-parameter adaptation with this carefully designed learning rate schedule creates a robust training procedure that balances exploration (early, with larger steps) and exploitation (later, with smaller steps).
Perfect! Now I have the key insights. Let me create a comprehensive analysis.
The equation defines how the learning rate evolves during training:
This is a clever two-phase schedule that balances rapid initial learning with careful, measured progress later:
Phase 1 (Warmup): Linear increase — For the first steps, the learning rate increases linearly with the step number, warming up the model gradually.
Phase 2 (Decay): Inverse square root decay — After warmup, the learning rate decreases proportionally to , allowing the optimizer to settle into minima.
This is a scaling constant that depends on the embedding dimension. For (used in the original Transformer):
This factor ensures that the learning rate scales inversely with model size. Larger models use smaller learning rates. This is critical because larger models have different gradient magnitudes due to their different attention head structure and embedding dimensions.
The function selects between two competing schedules:
Wolfram Alpha found a beautiful property: the two curves intersect exactly at .
This is no accident—it's by design. At the end of warmup, both terms are equal, ensuring a smooth transition without a discontinuity.
Using and :
This is surprisingly small—but it works because the optimizer makes many updates across a large batch.
| Training Step | Phase | Learning Rate | Interpretation |
|---|---|---|---|
| 1000 | Warmup | 0.000175 | Still ramping up linearly |
| 4000 | Transition | 0.000699 | Peak rate—fully warmed up |
| 10000 | Decay | 0.000221 | Half the peak (inverse sqrt decay) |
| 100000 | Late decay | 0.000140 | Very conservative, fine-tuning territory |
The learning rate at step is roughly times the peak rate, showing the graceful power-law decay.
1. Stability during warmup: Neural networks (especially Transformers) can be unstable early in training due to random initialization. Linear warmup gradually scales up the gradient signal, preventing chaotic behavior.
2. Efficiency: The inverse square root decay means the optimizer doesn't waste iterations with a too-large learning rate, but also doesn't unnecessarily freeze at tiny rates too early.
3. Scale invariance across model sizes: The factor means you can apply this same schedule formula to Transformers of different dimensions—larger models automatically get proportionally smaller learning rates.
4. Smooth transition: Because the curves meet at , there's no jarring jump between phases—the model transitions naturally.
The decay phase follows a power law: . This is a standard choice in optimization theory because:
The inverse square root is particularly elegant: it means the expected "noise" in gradient estimates (which scales like ) remains relatively constant throughout training, allowing the effective step size to remain balanced.
Compute the maximum learning rate at the transition point




Find where the warmup and decay curves meet



Compute the peak learning rate value
![N[1/sqrt(512)×1/sqrt(4000)]](/api/wolfram-image?url=https%3A%2F%2Fpublic6.wolframalpha.com%2Ffiles%2FGIF_5acpwhmueo.gif)


Compute learning rate at step 100,000
![N[1/sqrt(512)×1/sqrt(100000)]](/api/wolfram-image?url=https%3A%2F%2Fpublic5c.wolframalpha.com%2Ffiles%2FGIF_5acul1mctk.gif)


We employ three types of regularization during training: Residual Dropout: We apply dropout [33] to the output of each ...
Before we dive into the details, let's understand what regularization is doing in this context. The Transformer model has many parameters (especially the "big" model trained for 3.5 days mentioned in section 5.2), which means it could potentially memorize the training data rather than learn generalizable patterns.
Regularization techniques are methods that intentionally add constraints or noise during training to prevent this memorization and improve generalization to unseen data. Think of it like a teacher making exams slightly harder or ambiguous on purpose—not to be cruel, but to force students to understand concepts deeply rather than just memorize facts.
Section 5.4 introduces two complementary regularization techniques used in the Transformer. Let's break each one down.
Dropout is a regularization technique where we randomly "turn off" neurons during training. In the Transformer, the authors apply this in a specific way: they drop outputs before they're added to residual connections.
Recall from the paper's architecture that sub-layers in the Transformer use residual connections—the output of a sub-layer is added back to its input before normalization. The structure looks roughly like:
Dropout is applied to the term before the addition happens.
By applying dropout before the residual connection, rather than after, the authors ensure that:
This is clever: the residual connection acts like a "bypass highway" that always works, while the learned path gets selective dropout.
When we apply dropout with rate , we're essentially multiplying random elements by a mask. For a vector representing a sub-layer's output:
where:
This scaling is crucial: without it, dropping random elements would reduce the overall magnitude of activations, and the model would have to learn to compensate. By scaling, we preserve the expected value mathematically.
The authors apply residual dropout in three places:
For the base model: , meaning 10% of units are dropped each forward pass.
In typical classification tasks (which machine translation is—selecting the next word from a vocabulary), the training target is a one-hot vector. For example, if the correct next word is token #42 out of 37,000:
where only position 42 has a 1, and all others are 0.
Label smoothing modifies this hard target to be softer—instead of absolute certainty (1.0) for the correct class and zero for others, we assign:
This prevents the model from becoming overconfident.
For a vocabulary of size , the smoothed label is computed from the one-hot label as:
where:
Let's say the correct token is at position 42 in a vocabulary of 37,000:
Before smoothing (one-hot):
After smoothing with :
For the correct class (position 42):
For any incorrect class (say position ):
Notice that the probabilities still sum to 1:
The authors note an important trade-off:
The Bad: Label smoothing hurts perplexity during training. Perplexity is a measure of how "surprised" the model is by the correct answer—lower is better. By telling the model "even the wrong tokens have a 0.0000027 probability of being correct," we're asking it to assign probability mass to incorrect answers, which increases perplexity.
The Good: Despite higher perplexity, label smoothing improves both BLEU score and accuracy on test data. Why?
This is a beautiful example of why we don't always optimize for the metric we measure during training (perplexity) if we care about a different metric at test time (BLEU score).
| Technique | Where Applied | What It Does | Effect |
|---|---|---|---|
| Residual Dropout | Layer outputs, before residual connections | Randomly zeroes 10% of activations | Prevents co-adaptation of neurons; improves robustness |
| Label Smoothing | Training targets | Softens one-hot labels | Prevents overconfidence; improves generalization |
Together, they form a dual approach:
This combination helps the Transformer avoid memorizing the training data and instead learn robust, generalizable representations for machine translation.
These regularization techniques are particularly important for the Transformer because:
On the WMT 2014 English-to-German translation task, the big transformer model (Transformer (big) in Table 2) outperforms...
This section is the payoff of the entire Transformer paper. After proposing a novel neural network architecture (the Transformer) and explaining all its technical details, the authors now show that it actually works better than existing systems—and does so more efficiently. This is where theory meets practice: we see concrete numerical evidence that the Transformer's design choices were sound.
The key message: The Transformer achieves state-of-the-art machine translation results while training faster and cheaper than previous best models.
BLEU (BiLingual Evaluation Understudy) is the metric used to measure machine translation quality. Think of it this way:
Intuition: BLEU compares a machine-translated sentence to one or more human reference translations. It measures how many sequences of words (n-grams) in the machine translation match sequences in the references.
Mathematical Definition:
Where:
In simple terms: A BLEU score of 28.4 means the Transformer's English-to-German translations matched human reference translations quite well—better than any previous system.
The claim: Transformer (big) achieves 28.4 BLEU, beating the previous best by >2.0 BLEU points.
Why this matters:
Practical significance: 2+ BLEU point improvements on WMT (a prestigious benchmark) are considered substantial in the machine translation community.
The claim: Transformer (big) achieves 41.0 BLEU, outperforming all previous single models.
Key detail: The authors used dropout rate (not 0.3). Recall from Section 5.4 that dropout is a regularization technique where we randomly disable neurons during training to prevent overfitting. The different dropout rate suggests task-specific tuning—French translation apparently needed less aggressive regularization.
Training efficiency: The previous state-of-the-art required 4× more training time than the Transformer.
The authors used a technique called checkpoint averaging—instead of using the final trained model, they averaged multiple saved checkpoints:
Intuition: This is an ensemble-like technique that's cheaper than training multiple models separately. The idea is that different training steps capture different "good" solutions, so averaging them gives a more robust final model.
During the translation process (inference), the authors used:
Beam search with beam size = 4
Length penalty
Maximum output length: Input length + 50
These hyperparameters were "chosen after experimentation on the development set"—meaning the authors tested different values and picked the ones that worked best on a validation set.
The authors estimate floating-point operations (FLOPs) used to train a model:
Why this matters: FLOPs is a more hardware-independent metric than raw time. A model trained on 8 expensive GPUs for 1 hour might be equivalent to a model trained on 4 cheaper GPUs for 2 hours.
From Section 5.2, we know:
Key insight: The big model trains longer and takes longer per step, but achieves better quality. The question is: is the quality improvement worth the extra cost? The authors show (via Table 2) that yes—previous models needed even more training to reach worse quality.
Recall from Section 5.4 that the authors used three regularization techniques:
These regularization choices were empirically tuned, and the results show they worked:
The learning rate formula in Equation 3:
This schedule (warm up for first 4000 steps, then decay) helps stabilize training for a model as large as Transformer (big), which is why it can be trained effectively.
| Aspect | Key Takeaway |
|---|---|
| Performance | Transformer beats previous state-of-the-art on two major benchmarks (WMT 2014) |
| Quality metric | 28.4 BLEU (En-De) and 41.0 BLEU (En-Fr) represent >2 point improvements over ensembles |
| Efficiency | Achieves this with less training time than competitors, despite larger models |
| Methods | Checkpoint averaging, beam search, and careful hyperparameter tuning enable these results |
| Generality | Later sections (not shown here) prove Transformers work beyond translation, suggesting they're genuinely useful |
The authors are essentially saying: "Here's a simpler, more parallelizable architecture (no recurrence, only attention). Not only is it more elegant, it actually works better and trains faster. This is a meaningful advance."
To evaluate the importance of different components of the Transformer, we varied our base model in different ways, measu...
Before we conclude that the Transformer architecture as presented is optimal, we need to ask: Which components actually matter? This section is the authors' systematic answer to that question. They take their base model and methodically change different parts to measure how each component contributes to performance.
Think of this like engineering a car: you have a working design, but you want to understand whether you really need that expensive turbocharger, or if a cheaper carburetor would work just as well. By testing variations, the authors identify which design choices are genuinely important and which might be interchangeable.
This matters because:
The authors use a controlled methodology:
This is good experimental practice—by changing one thing at a time and measuring the impact, they can isolate cause and effect.
The Question: How many "attention heads" should we have? What dimensions should each head work with?
Background (from Section 3.2.2): The Transformer uses multi-head attention, where instead of computing a single attention mechanism, it computes parallel attention mechanisms. Each head has:
The total "model dimension" is (which is 512 for the base model). If we want to keep computation constant while varying heads, we must reduce the per-head dimensions proportionally. For example:
The Findings:
What This Means:
The Transformer benefits from having multiple perspectives simultaneously. A single attention head can't capture all the different ways tokens might relate to each other. However, there's a sweet spot (the authors find 8 heads is good for the base model), and beyond that, you're dividing the attention space too thinly—each individual head becomes too narrow to be useful.
The Intuition: Think of it like committee decision-making. One person (single head) might miss nuances. Eight diverse panelists (eight heads) can each focus on different aspects simultaneously. But 64 panelists (too many heads) where each only hears a tiny slice of information becomes unwieldy.
The Question: How important is the dimension (the size of each attention head's "key" and "query" vectors)?
Background: In the attention mechanism, the compatibility between a query and key is computed as:
The term produces a matrix where each element measures similarity between a query and a key. Both and have dimension (the depth of each query/key vector).
The Experiment: They reduce while keeping everything else constant.
The Finding: Reducing hurts model quality.
Why This Matters:
When is smaller, each query and key vector has fewer dimensions—they carry less information. The authors interpret this as evidence that "determining compatibility is not easy." In other words:
The Takeaway: The authors speculate that "a more sophisticated compatibility function than dot product may be beneficial." They're saying: the dot product works, but maybe a more complex function could do better—but they didn't implement that here.
The Question: Does bigger = better?
The Experiment: They vary (the overall embedding dimension), which affects:
The Finding: As expected, bigger models are better.
Why This Is Mentioned: This is somewhat of a "control check"—it's validating the obvious. Larger models with more parameters generally fit the data better (though with more risk of overfitting). This gives us confidence the experimental setup is working as intended: we see the expected pattern.
The Question: How important is regularization via dropout?
Background (from Section 5.4): The base model uses (10% dropout). Dropout is a regularization technique that randomly removes 10% of activations during training, forcing the network to not rely on any single pathway. This prevents overfitting.
The Experiment: They increase (more aggressive regularization) or remove it entirely.
The Finding: Dropout is very helpful in avoiding overfitting.
What This Reveals:
The Transformer, despite being a very powerful model, benefits significantly from regularization. This tells us that:
The Question: Does the choice of how to encode position information matter?
Background (from earlier sections): The Transformer adds positional information to token embeddings. The base model uses sinusoidal positional encodings, a fixed mathematical formula:
Where:
The Alternative: Learned positional embeddings treat position like another vocabulary—each position gets a learnable embedding vector, optimized during training.
The Experiment: Replace sinusoidal with learned embeddings.
The Finding: Nearly identical results to the base model.
Why This Is Interesting:
This is a negative result (no difference), which is surprisingly informative:
Across all these variations, a pattern emerges:
| Component | Impact of Change | Interpretation |
|---|---|---|
| Attention heads | Single head loses 0.9 BLEU | Multiple perspectives matter; one view isn't enough |
| Key dimension | Smaller hurts | Capacity for nuanced compatibility matching is important |
| Model size | Bigger is better | Standard scaling relationship (more capacity → better) |
| Dropout | More dropout hurts | The model tends to overfit without regularization |
| Positional encoding | Learned ≈ sinusoidal | Mathematical design works as well as learning |
The Big Lesson: The Transformer's design choices aren't accidents—they've been validated. The multi-head structure, the dimension sizes, and the regularization are all pulling their weight. The only true alternative (learned positions) works equally well, but doesn't offer advantages.
By showing these ablations, the authors are:
Building scientific credibility: This isn't just "we threw this together and it worked." They systematically validated design choices.
Providing design guidance: If someone in 2018 wanted to build a Transformer variant, they now know: "multi-head attention is crucial," "you need sufficient dimensionality," and "regularization matters."
Demonstrating the method: This establishes a pattern that future researchers can follow—test variations systematically to understand what components matter.
This is why you see ablation studies like this in good machine learning papers: they transform a paper from "here's a system that works" to "here's why it works" to "here's how to improve it."
To evaluate if the Transformer can generalize to other tasks we performed experiments on English constituency parsing. T...
The authors have just demonstrated that their Transformer architecture achieves state-of-the-art results on machine translation tasks. Now comes a critical question: Is the Transformer a general-purpose architecture, or is it only good for translation?
This section answers that question by testing the Transformer on a completely different task: English constituency parsing. This is important because it shows whether the fundamental architectural innovations (attention mechanisms without recurrence or convolutions) work beyond their original application.
Before diving into the results, let's understand what this task actually is:
Constituency parsing means breaking down a sentence into its grammatical tree structure. For example:
Input: "The cat sat on the mat"
Output: A tree structure showing how words group:
(S (NP (DET the) (NOUN cat))
(VP (VERB sat)
(PP (PREP on) (NP (DET the) (NOUN mat)))))
The output is a parse tree where:
This is fundamentally different from machine translation because:
The authors created a 4-layer Transformer with the following specifications:
This is a deliberate choice: by reusing parameters, they're testing whether the architecture naturally generalizes without task-specific engineering.
The authors tested in two different settings:
Here's what makes this experiment elegant: minimal task-specific tuning
The authors explicitly state they:
Modified only 3 hyperparameters on the development set (Section 22):
Left everything else unchanged from the translation model
Adjusted inference parameters for the longer output:
Why this matters: By keeping 95% of parameters the same, they're proving the architecture is robust, not that they engineered a perfect solution for parsing.
Though not explicitly formalized in this section, parsing in the Transformer works as follows:
The model learns a mapping from input tokens to output parse tree tokens:
where:
The decoder produces output tokens autoregressively (one at a time), conditioned on:
[Table 4 shows the parsing results]
The key findings:
"The Transformer outperforms the BerkeleyParser even when training only on the WSJ training set of 40K sentences"
This is remarkable because:
The comparison to "all previously reported models with the exception of the Recurrent Neural Network Grammar" shows:
This shows the architecture scales from data-poor to data-rich settings.
Returning to the paper's narrative:
This transforms the contribution from "we have a better translator" to "we have a new fundamental architecture for sequence problems" — which is why the Transformer became so influential.
The fact that minimal modification was needed is the key insight: the attention mechanism is sufficiently general that it solves diverse linguistic structure problems without problem-specific engineering.
In this work, we presented the Transformer, the first sequence transduction model based entirely on attention, replacing...
The conclusion section serves a crucial function in academic papers: it summarizes the main contributions, highlights the achievements, and outlines future research directions. In the context of this paper, the authors are:
Let's break this down into digestible pieces.
"In this work, we presented the Transformer, the first sequence transduction model based entirely on attention, replacing the recurrent layers most commonly used in encoder-decoder architectures with multi-headed self-attention."
What does this mean?
A sequence transduction model is any neural network that transforms one sequence (like words in English) into another sequence (like words in German). Before the Transformer, these models almost universally used:
The breakthrough here is replacing these with multi-headed self-attention (discussed extensively in Sections 3 and earlier sections of the paper).
The key difference comes down to how information flows:
This creates a sequential dependency chain that cannot be parallelized—you must compute , then , then , etc.
where , , (Query, Key, Value matrices) are computed from all positions in parallel.
The fundamental advantage: You can compute attention for all positions at once, unlike recurrence which must process sequentially. This enables massive parallelization.
The authors reference their results from Section 6.1:
English-to-German (WMT 2014)
English-to-French (WMT 2014)
BLEU (Bilingual Evaluation Understudy) measures translation quality by comparing machine translations to human reference translations. The score ranges from 0 to 100, where higher is better. An improvement of 2 BLEU points is substantial in machine translation research—this represents a meaningful jump in translation quality.
Beyond quality, the paper emphasizes computational efficiency:
The authors achieved better quality with significantly lower computational cost. This is crucial because:
From Section 6.3, the authors show the Transformer works on English constituency parsing (a completely different task):
Generalization is a critical property in machine learning. A model that only works well on one specific task has limited value. By demonstrating strong performance on a structurally different problem, the authors show that:
The authors identify four promising research avenues:
"Apply them to problems involving input and output modalities other than text"
Currently the model processes text sequences. But what about:
This requires no fundamental change to the attention mechanism—just different preprocessing.
"Investigate local, restricted attention mechanisms to efficiently handle large inputs and outputs such as images, audio and video"
The problem: Full self-attention has computational complexity of where is sequence length.
For an image with 1,000,000 pixels, computing attention across all pairs would require:
This is prohibitively expensive.
The solution: Sparse attention patterns where each position only attends to nearby positions (like a window):
"Making generation less sequential is another research goal of ours"
Current approach: During inference (generation), the model produces output tokens one at a time:
This is inherently sequential because each token depends on previous tokens (due to the causal mask discussed in earlier sections).
Alternative approaches to explore:
The benefit: Faster inference on hardware accelerators that excel at parallelism.
"The code we used to train and evaluate our models is available at https://github.com/tensorflow/tensor2tensor"
This seemingly simple statement is actually crucial for scientific impact:
In practice, this code release was transformative—it enabled rapid adoption and the explosion of Transformer-based models we see today (BERT, GPT, etc.).
| Aspect | Significance |
|---|---|
| Architecture | First purely attention-based sequence model; eliminates recurrence |
| Performance | State-of-the-art on multiple benchmarks with lower computational cost |
| Generalization | Works on diverse tasks beyond translation |
| Efficiency | Parallelizable, trains faster, cheaper than alternatives |
| Future Potential | Opens multiple research directions (modalities, efficiency, generation) |
The conclusion effectively communicates that the Transformer is not just an incremental improvement, but a fundamental shift in how we approach sequence-to-sequence learning—with clear practical benefits and significant future research opportunities.