GeekCoding101 make your way to geek

Attention Is All You Need, Explained: Intro & Background

A line-by-line walkthrough of the Introduction and Background of "Attention Is All You Need": why RNNs hit a wall and how self-attention replaced them.

13 min read
Daily 2 20241229
On this pageDay 2 at a glance

The Introduction and Background sections of “Attention Is All You Need” make one argument. Recurrent neural networks process a sentence one step at a time, and that sequential computation limits both how fast they train and how well they connect distant words. The Transformer drops recurrence and convolution entirely and relies on attention alone. As a result, any two positions in a sequence can be related in a constant number of operations, and training can run in parallel.

About this series: I’m working through “Attention Is All You Need” one section a day, line by line. For each sentence I explain the idea in plain words, unpack the technical terms and the math, look at the papers it cites, and add analogies and further reading. If you’re curious about Transformers or modern AI, read along.

Day 2 at a glance

What the paper says
The old standardRNNs, LSTMs and GRUs were state of the art for language modeling and machine translation.
The core problemThey compute step by step, so work inside one training example can’t run in parallel. Memory limits also restrict batching on long sequences.
Earlier fixesFactorization tricks and conditional computation made RNNs faster, but the sequential constraint remained. Convolutional models (Extended Neural GPU, ByteNet, ConvS2S) computed in parallel, but relating distant positions still cost more operations the farther apart they were.
The Transformer’s answerUse attention only. Relating any two positions takes a constant number of operations, and Multi-Head Attention offsets the resolution lost to averaging.

1. Introduction

Sentence 1

Recurrent neural networks, long short-term memory [13] and gated recurrent [7] neural networks in particular, have been firmly established as state of the art approaches in sequence modeling and transduction problems such as language modeling and machine translation [35, 2, 5].

In plain words: Recurrent Neural Networks (RNNs) are AI models that remember earlier things while working on something new. Long Short-Term Memory (LSTM) networks and Gated Recurrent Units (GRUs) are improved versions of RNNs. At the time, these were the best performers (state of the art) on tasks that process sequences. Examples include predicting the next word in a sentence (language modeling) and translating text from one language to another (machine translation).

Key terms

  • Recurrent Neural Networks (RNNs): models designed for sequential data such as sentences or time series.
    • Analogy: reading a book where each sentence depends on the one before it. An RNN reads one sentence at a time and remembers the earlier ones.
    • Further reading: RNNs on Wikipedia
  • Long Short-Term Memory (LSTM): a type of RNN that addresses the problem of forgetting important past information.
    • Analogy: a memory-keeper who knows what to remember and what to forget.
    • Further reading: LSTM on Wikipedia
  • Gated Recurrent Units (GRUs): a simpler version of the LSTM, with fewer memory-related functions.
  • Sequence modeling: tasks like predicting the next word in a sentence.
  • Sequence transduction: tasks that turn one sequence into another, like translating a sentence or converting text to speech.

References

RefPaperWhat it contributedLink
[13]Hochreiter & Schmidhuber (1997)Introduced LSTMsLSTM Original Paper
[7]Chung et al. (2014)Evaluated GRUsGRU Evaluation Paper
[35, 2, 5]—Machine translation and language modeling with RNNs—

Sentence 2

Numerous efforts have since continued to push the boundaries of recurrent language models and encoder-decoder architectures [38, 24, 15].

In plain words: Researchers kept working to make RNNs better, focusing on two areas:

  • Recurrent language models: making RNNs predict words more accurately.
  • Encoder-decoder architectures: one part (the encoder) processes the input, and another (the decoder) generates the output, as in translation.

Key term: encoder-decoder architecture

  • The encoder compresses the input into a smaller representation, like a summary.
  • The decoder uses that compressed information to generate the output.
  • Analogy: translating English to French. First you understand the English text, then you write the French version.
  • Further reading: Sequence to Sequence Learning with Neural Networks

References

RefPaperWhat it contributedLink
[38]Wu et al. (2016)Google’s Neural Machine Translation (GNMT), an encoder-decoder systemGNMT Paper
[24]Luong et al. (2015)Effective approaches to attention in neural machine translationLuong Attention Paper
[15]Jozefowicz et al. (2016)Explored the limits of language modelingLanguage Model Study

Sentence 3

Recurrent models typically factor computation along the symbol positions of the input and output sequences.

In plain words: RNNs handle input and output one step at a time.

  • Symbols: the letters, words or word pieces in a sentence.
  • Factor computation along positions: the RNN computes each part of the sequence (for example, one word) in a fixed order.

Sentence 4

Aligning the positions to steps in computation time, they generate a sequence of hidden states hth_t, as a function of the previous hidden state ht−1h_{t-1} and the input for position tt.

In plain words: An RNN keeps a hidden memory state, hth_t, that stores what it has learned so far. At each position tt, it takes the previous memory ht−1h_{t-1} and adds the new input for position tt.

The math

ht=f(ht−1,xt)h_t = f(h_{t-1}, x_t)

SymbolMeaning
hth_tHidden state at step tt
ht−1h_{t-1}Hidden state from the previous step
xtx_tInput at step tt
ffThe function that combines them

Analogy: hth_t is a diary. You write today’s entry based on yesterday’s memories plus what happened today. You can’t write Wednesday’s entry until Tuesday’s is done.

Sentence 5

This inherently sequential nature precludes parallelization within training examples, which becomes critical at longer sequence lengths, as memory constraints limit batching across examples.

In plain words: Each step needs the result of the step before it, so an RNN can’t compute several steps at once. There is no parallelization within a single example. This hurts most on long sequences:

  • Time cost: processing each step one after another is slow.
  • Memory limits: long sequences use a lot of memory, so fewer of them can be trained together in a batch.

Analogy: reading a book one sentence at a time versus scanning many pages at once. RNNs are stuck with the first method, which is slow and memory-hungry for big books.

Why it matters: in real tasks like translation, sentences and documents can be long, which makes RNNs inefficient.

Sentence 6

Recent work has achieved significant improvements in computational efficiency through factorization tricks [21] and conditional computation [32], while also improving model performance in case of the latter.

In plain words: Researchers found clever ways to make RNNs faster, and in one case better:

  • Factorization tricks: simplify the calculations to save time.
  • Conditional computation: activate only the parts of the model that are needed for a given input, skipping unnecessary work.

References

RefWhat it contributedLink
[21]Factorization tricks that simplify LSTM computations for faster trainingFactorization Tricks Paper
[32]Sparsely gated mixture-of-experts layers, improving efficiencyConditional Computation Paper

Sentence 7

The fundamental constraint of sequential computation, however, remains.

In plain words: Even with these improvements, RNNs still process sequences step by step. This is their biggest limitation, and it is the problem the rest of the paper sets out to remove.

Sentence 8

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 [2, 19].

In plain words: Attention works like a smart highlighter. It lets a model focus on the most relevant parts of the input. Its big advantage is that distance doesn’t matter. The first and last words of a long sentence can be connected as easily as two neighbors.

References

RefPaperWhat it contributedLink
[2]Bahdanau et al. (2014)Introduced attention in neural machine translationBahdanau Attention Paper
[19]Kim et al. (2017)Structured attention networksStructured Attention Networks Paper

Sentence 9

In all but a few cases [27], however, such attention mechanisms are used in conjunction with a recurrent network.

In plain words: Most models used attention as an add-on to an RNN rather than as a replacement for it.

Reference

RefPaperWhat it contributedLink
[27]Parikh et al. (2016)A decomposable attention model without recurrenceDecomposable Attention Model Paper

Sentence 10

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.

In plain words: The Transformer is a new model that:

  • Removes recurrence: no RNNs at all.
  • Uses only attention: attention does all the work of relating input and output sequences.

Why it’s exciting: the design removes the RNN’s sequential bottleneck and its memory problems. It also keeps attention’s ability to connect words that are far apart.

Sentence 11

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 […] GPUs.

In plain words: Because the Transformer processes positions in parallel, it trains much faster. In the paper’s experiments, it reached top translation quality after as little as 12 hours of training on 8 GPUs.

Key takeaway: the Transformer is faster to train and gets better translation results than the recurrent models before it.


2. Background

Sentence 1

The goal of reducing sequential computation also forms the foundation of the Extended Neural GPU [16], ByteNet [18] and ConvS2S [9], all of which use convolutional neural networks as basic building block, computing hidden representations in parallel for all input and output positions.

In plain words: The Transformer wasn’t the first attempt to escape step-by-step processing. Three earlier models used convolutional neural networks (CNNs) instead of recurrence, which let them compute all positions in parallel:

  • Extended Neural GPU: a convolutional model built for parallel computation.
  • ByteNet: uses convolutions to process sequences in parallel.
  • ConvS2S: uses convolutions for sequence-to-sequence learning.

Why they matter: they showed that parallel sequence processing could work, which paved the way for the Transformer.

References

RefModelLink
[16]Extended Neural GPUExtended Neural GPU Paper
[18]ByteNetByteNet Paper
[9]ConvS2SConvS2S Paper

Sentence 2

In these models, the number of operations required to relate signals from two arbitrary input or output positions grows in the distance between positions, linearly for ConvS2S and logarithmically for ByteNet.

In plain words: In these convolutional models, the farther apart two words are, the more operations it takes to connect them.

  • ConvS2S: operations grow linearly with distance. Twice as far means roughly twice the work.
  • ByteNet: operations grow logarithmically. That is better, but cost still depends on distance.

Sentence 3

This makes it more difficult to learn dependencies between distant positions [12].

In plain words: Each extra operation between two distant words is another step where the signal can weaken. So the longer the path, the harder it is for the model to learn how those words relate.

Why it matters: in translation, a word at the start of a sentence can depend on a word near the end. A model that struggles to connect them makes mistakes.

Sentence 4

In the Transformer this is reduced to a constant number of operations, albeit at the cost of reduced effective resolution due to averaging attention-weighted positions, an effect we counteract with Multi-Head Attention as described in section 3.2.

In plain words: In the Transformer, connecting any two positions takes the same small number of operations, no matter how far apart they are. There is a trade-off. Attention blends many positions into a weighted average, and averaging can blur the details. The paper’s fix is Multi-Head Attention: several attention “heads” run side by side, each free to focus on different relationships. Section 3.2 explains it, and we’ll get there later in the series.

Analogy: one person summarizing a whole meeting loses detail. Eight people each tracking a different thread (decisions, deadlines, open questions) lose much less.

How the approaches compare

ModelBuilding blockOperations to relate two distant positions
RNN / LSTM / GRURecurrenceOne step per position, in sequence
ConvS2SConvolutionGrows linearly with distance
ByteNetConvolutionGrows logarithmically with distance
TransformerSelf-attentionConstant

Sentence 5

Self-attention, sometimes called intra-attention is an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence.

In plain words: Ordinary attention in translation lets the output look back at the input. Self-attention lets a sentence look at itself. Each word checks every other word in the same sentence to decide what it means in context.

Example: in “The animal didn’t cross the street because it was too tired,” self-attention can help the model link “it” to “animal” rather than “street.”

Sentence 6

Self-attention has been used successfully in a variety of tasks including reading comprehension, abstractive summarization, textual entailment and learning task-independent sentence representations [4, 27, 28, 22].

In plain words: Self-attention wasn’t new in 2017. It had already worked well in:

  • Reading comprehension: answering questions about a passage (Machine Reading paper).
  • Abstractive summarization: writing a summary in new words rather than copying sentences (Summarization paper).
  • Textual entailment: deciding whether one sentence follows from another.
  • Sentence representations: turning a sentence into a general-purpose vector that other tasks can reuse (Self-Attentive Embeddings paper).

Sentence 7

End-to-end memory networks are based on a recurrent attention mechanism instead of sequence-aligned recurrence and have been shown to perform well on simple-language question answering and language modeling tasks [34].

In plain words: End-to-end memory networks are another relative of the Transformer. They repeat attention over a memory several times. They do not step through the sequence word by word the way an RNN does. They did well on simple question answering and language modeling. (Memory Networks paper)

Sentences 8–9

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. In the following sections, we will describe the Transformer, motivate self-attention and discuss its advantages over models such as [17, 18] and [9].

In plain words: This is the paper’s main claim to novelty. Attention existed and self-attention existed. The Transformer was the first model for transduction tasks like translation that used only self-attention, with no RNN and no convolution underneath. The rest of the paper explains how it works and why that choice pays off.


Key takeaways from Day 2

  1. RNNs were the standard for language modeling and translation, but they compute one step at a time.
  2. Sequential computation was the bottleneck. It blocks parallel training and strains memory on long sequences, and speed-up tricks didn’t remove it.
  3. Convolutional models helped by computing in parallel, but connecting distant words still cost more the farther apart they were.
  4. Attention ignores distance, yet before the Transformer it was mostly bolted onto RNNs.
  5. The Transformer uses attention only. Any two positions connect in a constant number of operations, and Multi-Head Attention offsets the blurring from averaging.

FAQ

Why did Transformers replace RNNs? RNNs must process a sequence step by step, which blocks parallel training and makes long-range dependencies hard to learn. The Transformer relates all positions directly through attention. It trains in parallel and connects any two words in a constant number of operations.

Did the Transformer invent attention? No. Attention in neural machine translation goes back to Bahdanau et al. (2014), and self-attention had been used in reading comprehension, summarization and other tasks. What was new was a transduction model built entirely on self-attention, with no recurrence or convolution.

What is the difference between attention and self-attention? Attention generally lets one sequence focus on parts of another, such as a translation looking at the source sentence. Self-attention relates positions within a single sequence, so each word builds its meaning from the other words around it.

Why does the Transformer need Multi-Head Attention? A single attention step averages over many positions, which can blur detail. Multiple heads attend in parallel, each able to focus on different relationships, and this counteracts the loss. The paper describes it in Section 3.2.

What comes after the Background section? Section 3, Model Architecture, which describes how the Transformer is built.

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.

Keep reading

All posts