Attention (machine learning)
Attention, in machine learning, is a method that determines how much weight each part of a sequence deserves relative to every other part. It expresses that importance through numbers called soft weights. When a trained network translates the phrase 'I love you' into French, those weights become visible. On the first pass of the decoder, 94% of the attention weight falls on the word 'I', and the network produces 'je'. On the second pass, 88% of the weight moves to 'you', yielding 't''. On the final pass, 95% concentrates on 'love', completing 'aime'. The model arrived at correct French word order without any explicit instruction about French syntax. It found the right source word at each step by attending to it directly. How did that idea develop from mid-century psychology into the mechanism behind models like BERT, T5, and GPT? And what made a 2017 paper titled 'Attention is All You Need' the pivot point for a field that had relied on recurrence for decades?
Recurrent neural networks process language one word at a time, passing context forward through a hidden state vector. Each new word updates that state, but earlier words grow harder to recall as the sequence lengthens. The network inherently favored information near the end of a sentence, treating recent words as more significant and attenuating earlier ones. In a long sentence, the first word could contribute almost nothing to the final representation.
The cocktail party effect, studied in psychology and biology research from the 1950s-1960s, described how humans focus on relevant signals while filtering noise. That observation pointed toward a computational version of selective attention. Sigma-pi units appeared in the 1980s. In 1992, fast weight controllers had one neural network produce the weights of another through outer products; that technique was later renamed linearized self-attention. The bilateral filter, introduced in image processing in 1998, showed that pairwise affinity matrices could propagate relevance across elements of a spatial structure. Non-local means, developed in 2005, extended that affinity-based approach to image denoising using Gaussian similarity kernels as fixed, attention-like weights.
The direct solution for language translation arrived in 2014, when researchers grafted attention onto an encoder-decoder architecture, with particular gains on long sentences. Attention gave each output token a direct path to any input token. The sequential hidden-state bottleneck was bypassed entirely.
By 2016, self-attention had been integrated into RNN-based models to capture dependencies within a single sequence. That step proved transitional: within a year, a paper would argue that recurrence could be removed from the architecture altogether.
'Attention is All You Need', published in 2017, introduced the Transformer: an architecture that removed recurrence and built its processing entirely around attention. Self-attention was the core operation: every element of the input sequence attends to every other element simultaneously. That parallel structure replaced the sequential RNN with a mechanism that could run across many hardware cores at once. Training became substantially faster.
Self-attention computes three vectors for each input position: a query, a key, and a value. Each position's query is compared against all positions' keys to produce a relevance score. Those scores determine how much of each position's value to include in the output. When all three vectors come from the same model, the result is self-attention. Every position has equal access to every other position's information in a single pass.
BERT, T5, and the generative pre-trained transformers known as GPT all emerged from the Transformer design. Each applied the same core mechanism to different tasks. Relation networks and set Transformers, developed in the same year as the original paper, applied attention to unordered sets and relational reasoning. The mechanism had spread beyond language before 2017 was out.
Bahdanau-style attention, also called additive attention, uses a learned weight matrix to combine encoder and decoder hidden states before computing an alignment score. It handled the task of matching source words to target words by treating alignment as a learnable function. Luong-style attention takes a multiplicative approach: a dot product between encoder and decoder states, scaled by a single learnable matrix. The two styles reflect different answers to the question of how to measure relevance between sequence elements.
Multi-head attention runs several attention operations in parallel, each with its own set of learned projections for queries, keys, and values. The outputs are concatenated and projected through another learned matrix. Running multiple heads lets the model capture different relationship types within the same sequence simultaneously.
For convolutional neural networks, spatial attention focuses on which regions of an input image contribute most to a prediction. Channel attention operates on a different axis: which feature maps deserve the most weight. The two can be combined so that a model is selective along both dimensions at once.
Masked attention imposes a hard constraint on autoregressive decoding. The mask is an upper-triangular matrix: weights above the diagonal are forced to zero. Each output position can only attend to prior outputs, not to positions it has yet to generate.
Flash attention addresses a fundamental scaling problem: the attention matrix grows proportional to the square of the number of input tokens. As sequences grow longer, that quadratic relationship consumes large amounts of GPU memory. Flash attention partitions the computation into blocks that fit in the chip's faster on-chip memory. This sidesteps the need to store large intermediate matrices while achieving the same mathematical result. Meta developed a related kernel called FlexAttention. It lets users modify attention scores before the softmax step, and dynamically selects the optimal algorithm for each configuration.
Non-local neural networks carried attention principles into computer vision in 2018, capturing long-range dependencies across spatial positions and time. Graph attention networks, also developed in 2018, applied the mechanism to data organized in irregular graph structures rather than fixed sequences.
AlphaFold applied Transformer attention to protein folding, carrying the architecture into structural biology. CLIP used it for vision-language pretraining, combining visual and textual processing in a single model. Dense segmentation models CCNet and DANet extended attention to pixel-level prediction across full images.
Vision transformers, abbreviated ViTs, achieved competitive results in image classification from 2019 onward. Question answering and text summarization in natural language processing both benefited from attention's capacity to hold global context across long inputs. Speech recognition also joined the list of tasks where attention improved performance.
Reformer, Linformer, and Performer, three efficient Transformer variants developed between 2019 and 2020, introduced scalable approximations of attention for long sequences. Each traded some mathematical precision for the ability to handle inputs that standard attention designs could not process economically. As these variants spread, researchers turned to a pressing question: does high attention weight reveal why a model made its decision?
Saliency maps, also called attention maps, became a standard inspection tool after the original vision transformer paper. To produce one, a researcher computes attention scores for a specific head and layer, then renders them as a heat map. Deeper layers of the network tend to yield more semantically meaningful visualizations: later-layer maps often highlight recognizable structures rather than low-level patterns.
Attention rollout combines scores from all layers into a single view. The algorithm is recursive. It computes the dot product of successive attention maps layer by layer, tracing how scores propagate from input to output across the full network.
Because vision transformers are typically trained in a self-supervised manner, their attention maps are generally not class-sensitive: they show what the model weighted, not which category it assigned. Class-discriminative attention maps, abbreviated CDAM, address that gap by combining attention scores with gradients computed for the class token. That gradient information focuses the visualization on regions relevant to the specific category the model predicted. GradCAM, originally developed for convolutional networks, achieves a similar result. It back-propagates gradients to the outputs of the final attention layer and can be applied to vision transformers as well.
Higher attention scores do not always correlate with greater impact on model performance, and this disconnect has generated ongoing debate. A position can receive high attention weight and yet have little measurable effect on the final output. Hopfield networks, originally conceived as associative memory systems, were reinterpreted after 2019 as attention mechanisms. Surveys by Niu et al. and Soydaner document this evolving picture: the boundary between associative memory and attention may be less fixed than the 2014 formulation implied.
Up next
Updated
Common questions
What is attention in machine learning?
Attention in machine learning is a method that assigns soft weights to each element in a sequence, reflecting how important each element is relative to the others. Unlike hard weights fixed during training, soft weights change at each step of the forward pass through the model, allowing the network to focus on different parts of the input at different moments.
How does the attention mechanism work in neural network translation?
In translation, an attention mechanism scores each source word against the current decoding step and forms a context vector weighted by those scores. When converting 'I love you' to French, 94% of the attention weight falls on 'I' for the first output word, 88% on 'you' for the second, and 95% on 'love' for the third, allowing the network to reorder words to match French grammar without an explicit rule.
When was the attention mechanism first introduced to machine learning?
An attention mechanism was grafted onto an encoder-decoder neural network translation system in 2014, with particular improvements for long sentences. A 1992 technique called fast weight controllers anticipated key elements: it had one network produce the weights of another through outer products, a scheme later renamed linearized self-attention.
What is the Transformer architecture and how does it use attention?
The Transformer, introduced in the 2017 paper 'Attention is All You Need', removed recurrent neural networks entirely and built its processing around scaled dot-product self-attention, where every position in the input sequence attends to every other position simultaneously. Transformers became the foundation for models including BERT, T5, and the generative pre-trained transformers known as GPT.
What is Flash attention and how does it improve attention computation?
Flash attention is an implementation that reduces GPU memory requirements for computing attention. The standard attention matrix grows proportional to the square of the number of input tokens; Flash attention partitions the computation into blocks that fit in the chip's faster on-chip memory, achieving the same mathematical result without storing large intermediate matrices.
What are attention maps in vision transformers and how are they interpreted?
Attention maps, also called saliency maps, are heat-map visualizations of attention scores used to inspect how vision transformer models weight different regions of their input. Deeper layers tend to produce more semantically meaningful maps. The technique called attention rollout combines scores across all layers by computing the dot product of successive attention maps, tracing how attention flows from input to output across the full network.
All sources
55 references cited across the entry
- 1A non-local algorithm for image denoisingAntoni Buades — 2005
- 2JournalA review on the attention mechanism of deep learningZhaoyang Niu et al. — 2021-09-10
- 3JournalAttention mechanism in neural networks: where it comes and where it goesDerya Soydaner — August 2022
- 4Neural Machine Translation by Jointly Learning to Align and TranslateDzmitry Bahdanau et al. — 2014
- 5Flash Attention: Revolutionizing Transformer EfficiencyAayush Mittal — 2024-07-17
- 7An Image is Worth 16x16 Words: Transformers for Image Recognition at ScaleAlexey Dosovitskiy et al. — 2021-06-03
- 8Quantifying Attention Flow in TransformersSamira Abnar et al. — 2020-05-31
- 9Class-Discriminative Attention Maps for Vision TransformersLennart Brocki et al. — 2024-10-25
- 10jacobgil/pytorch-grad-camJacob Gildenblat — 2025-07-21
- 11Explainable Prediction of Medical Codes from Clinical TextJames Mullenbach et al. — 2018-04-16
- 12Neural Machine Translation by Jointly Learning to Align and TranslateDzmitry Bahdanau et al. — 2016-05-19
- 13Is Attention Interpretable?Sofia Serrano et al. — 2019-06-09
- 14Set Transformer: A Framework for Attention-based Permutation-Invariant Neural NetworksJuho Lee et al. — 2018
- 16BookParallel Distributed Processing, Volume 1: Explorations in the Microstructure of Cognition: FoundationsDavid E. Rumelhart et al. — MIT Press — 1987-07-29
- 17JournalLearning to control fast-weight memories: an alternative to recurrent nets.Jürgen Schmidhuber — 1992
- 18Linear Transformers Are Secretly Fast Weight ProgrammersImanol Schlag et al. — Springer — 2021
- 19Massive Exploration of Neural Machine Translation ArchitecturesDenny Britz et al. — 2017-03-21
- 20Effective Approaches to Attention-Based Neural Machine TranslationMinh-Thang Luong — 2015-09-20
- 22VideoNYU Deep Learning course, Spring 20202021
- 24CBAM: Convolutional Block Attention ModuleSanghyun Woo et al. — 2018-07-18
- 25Multimodal Multi-Head Convolutional Attention with Various Kernel Sizes for Medical Image Super-ResolutionMariana-Iuliana Georgescu et al. — 2022-10-12
- 26Book2018 IEEE/CVF Conference on Computer Vision and Pattern RecognitionJie Hu et al. — 2018
- 27Book2019 IEEE/CVF International Conference on Computer Vision (ICCV)Xizhou Zhu et al. — 2019
- 28Learning Positional Attention for Sequential RecommendationFan Luo et al. — 3 July 2024
- 29JournalSome Experiments on the Recognition of Speech, with One and with Two EarsE. Colin Cherry — 1953
- 30BookPerception and CommunicationDonald E. Broadbent — Pergamon Press — 1958
- 31JournalThe control of saccadic eye movementsEileen Kowler — 1995
- 32JournalThe correlation theory of brain functionChristoph von der Malsburg — 1981
- 33JournalDynamic connections in neural networksJerome A. Feldman — 1982
- 34JournalConnectionist learning proceduresGeoffrey E. Hinton — 1989
- 35Long Short-Term Memory-Networks for Machine ReadingJianpeng Cheng — 2016
- 36A Deep Reinforced Model for Abstractive SummarizationRomain Paulus — 2017
- 37Show, Attend and Tell: Neural Image Caption Generation with Visual AttentionKelvin Xu et al. — 2015
- 382015 IEEE Conference on Computer Vision and Pattern Recognition (CVPR)Oriol Vinyals et al. — 2015
- 39Attention is All You NeedAshish Vaswani et al. — 2017
- 40Bilateral filtering for gray and color imagesCarlo Tomasi — 1998
- 41Attentional Neural Network: Feature Selection Using Cognitive FeedbackQian Wang — 2014
- 42Decomposable Attention Model for Natural Language InferenceAnees Parikh — 2016
- 43A Structured Self-Attentive Sentence EmbeddingZichao Lin — 2017
- 44Relation Networks for Relational ReasoningAdam Santoro — 2017
- 45Set Transformer: A Framework for Attention-based Permutation-Invariant Neural NetworksJuho Lee — 2019
- 46Non-Local Neural NetworksXiaolong Wang — 2018
- 47Graph Attention NetworksPetar Veličković — 2018
- 48Reformer: The Efficient TransformerNikita Kitaev — 2020
- 49Linformer: Self-Attention with Linear ComplexitySalah Wang — 2020
- 50Rethinking Attention with PerformersKrzysztof Choromanski — 2020
- 51Hopfield Networks is All You NeedJohannes Ramsauer — 2021
- 52An Image is Worth 16×16 Words: Transformers for Image Recognition at ScaleAleksander Dosovitskiy — 2021
- 53JournalHighly accurate protein structure prediction with AlphaFoldJohn Jumper — 2021
- 54Learning Transferable Visual Models from Natural Language SupervisionAlec Radford — 2021
- 55CCNet: Criss-Cross Attention for Semantic SegmentationXiangyu Huang — 2019
- 56Dual Attention Network for Scene SegmentationJing Fu — 2019