Technology

How Does the Transformer Attention Mechanism Work? (Queries, Keys & Values Explained)

Executive Direct Answer (BLUF)

A computer science deep dive into the 2017 "Attention Is All You Need" architecture: how Scaled Dot-Product Attention, Query-Key-Value ($Q, K, V$) projections, and Multi-Head Attention replaced RNNs to power all modern LLMs.

Alcuin Archival Research Group·September 7, 2026·10 min read·7 Verified Sources
Abstract matrix mathematical equations and self-attention computational graph flow
The Transformer attention mechanism: computing dynamic pairwise contextual relationships across all tokens in parallel via $\text{Softmax}(QK^T / \sqrt{d_k})V$.

The Bottleneck of RNNs: The Road to "Attention Is All You Need" (2017)

Prior to 2017, the state of the art in Natural Language Processing (NLP) relied on Recurrent Neural Networks (RNNs) and Long Short-Term Memory (LSTM) networks [1,2]. These architectures processed text sequentially, token by token from left to right [1,2].

Sequential processing created two fatal bottlenecks [1,2]:

1. Information Vanishing: As sentences grew longer (over 50 to 100 words), earlier contextual information was compressed into a fixed-size hidden state vector, causing the model to forget distant words [1,2].

2. No GPU Parallelization: Because step $t$ depended strictly on the hidden state of step $t-1$, training could not be parallelized across thousands of GPU cores [1,3].

In June 2017, a team of eight Google Brain and Google Research scientists (Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan Gomez, Lukasz Kaiser, and Illia Polosukhin) published the landmark paper: Attention Is All You Need [1,3]. They eliminated recurrence entirely, introducing the Transformer—an architecture where every word attends directly to every other word simultaneously in parallel [1,3].

"The 2017 Transformer eliminated sequential recurrence entirely, allowing neural networks to process all words in parallel with direct pairwise attention."

The Core Equation: Scaled Dot-Product Attention

At the heart of the Transformer is Scaled Dot-Product Attention, defined by the fundamental mathematical equation [1,3,4]:

$$\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V$$

For any input token embedding $X$, the network learns three distinct weight projection matrices ($W_Q, W_K, W_V$) to generate three vectors [1,3,4]:

1. Query ($Q$): "What am I looking for?" (e.g., the pronoun "it" searching for its antecedent) [1,4].

2. Key ($K$): "What is my identity and content?" (every word advertising its semantic attributes) [1,4].

3. Value ($V$): "What informative content do I provide if matched?" [1,4].

"In self-attention, Query matrices ask what information is needed, Key matrices broadcast identity, and Value matrices deliver content."

Why Scale by $\sqrt{d_k}$? Preventing Gradient Vanishing in Softmax

The dot product $Q \cdot K^T$ computes a raw cosine-like similarity score between every pair of tokens in the sequence [1,3,5]. For large vector dimensions (such as $d_k = 64$ or $128$), dot products grow large in magnitude, pushing the softmax function into regions with extremely small gradients (gradient saturation) where learning stalls [1,3,5].

Dividing by the scaling factor $\sqrt{d_k}$ normalizes the variance back to 1.0, ensuring smooth gradients during backpropagation [1,3,5]. The resulting softmax probabilities represent an Attention Map—a probability distribution indicating how much weight token $A$ should assign to token $B$ when updating its representation [1,4,5].

Multi-Head Attention & The Foundation of Modern LLMs

Rather than computing a single attention function, Transformers use Multi-Head Attention [1,3,6]. By splitting the queries, keys, and values into $h$ independent subspaces (typically 8, 32, or 128 heads), each head specializes in different linguistic relationships in parallel [1,3,6]:

- Head 1 might track direct syntactic subject-verb agreements ("The cat ... sits").

- Head 2 might resolve pronoun coreferences ("it" $\to$ "the bank").

- Head 3 might track long-range temporal markers and causal relationships across paragraphs [1,6,7].

Concatenating the outputs of all attention heads with Feed-Forward Networks (FFNs) and residual layer normalization enables the massive emergent reasoning and in-context learning capabilities of modern frontier models (GPT-4, Claude 3.5, Gemini 1.5) [1,3,7].

Key Chronology & Milestones

2014

Bahdanau, Cho, and Bengio introduce additive attention for neural machine translation in recurrent networks.

2017 (Jun)

Vaswani et al. publish "Attention Is All You Need", introducing the pure Transformer architecture.

2018 (Oct)

Google introduces BERT (Bidirectional Encoder Representations from Transformers).

2020 (May)

OpenAI publishes GPT-3, demonstrating that decoder-only Transformers exhibit emergent few-shot learning.

2024–2026

Long-context Transformers scale to 10-million-token context windows and multimodal video/audio streams.

Cited Primary & Academic Sources

7 Verified Records

Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, & Illia Polosukhin (NeurIPS 2017) · arxiv.org

The historic paper that introduced the Transformer architecture, scaled dot-product attention, and multi-head attention.

Dzmitry Bahdanau, Kyunghyun Cho, & Yoshua Bengio (ICLR 2015) · arxiv.org

Original paper introducing soft attention mechanisms to overcome fixed-length vector compression in RNNs.

Alexander Rush & Harvard NLP Group · nlp.seas.harvard.edu

Line-by-line PyTorch implementation and mathematical walkthrough of the 2017 Transformer architecture.

Thomas Wolf, Lysandre Debut, et al. (Hugging Face / EMNLP 2020) · arxiv.org

Comprehensive open-source documentation of self-attention matrices, positional encodings, and causal masking.

Ian Goodfellow, Yoshua Bengio, & Aaron Courville (MIT Press) · deeplearningbook.org

Foundational textbook covering softmax gradient saturation, backpropagation through time, and matrix calculus.

Kevin Clark, Urvashi Khandelwal, Omer Levy, & Christopher D. Manning (Stanford / ACL 2019) · arxiv.org

Empirical probe revealing how specific multi-head attention heads specialize in direct objects, delimiters, and coreference.

Tri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra, & Christopher Ré (NeurIPS 2022) · arxiv.org

GPU SRAM tiling optimization enabling 3x faster attention execution and multi-million-token context scaling.

Frequently Asked Inquiries

Click any inquiry to research

What is self-attention in artificial intelligence?

Self-attention is a mathematical mechanism that allows a neural network to examine all words in a sentence simultaneously and calculate how much every word relates to every other word, creating rich contextual representations that capture grammar, meaning, and references in parallel.

What are Queries, Keys, and Values in Transformers?

Queries ($Q$) represent what information a word is looking for, Keys ($K$) represent what information a word possesses, and Values ($V$) represent the actual semantic content. Computing the dot product between Queries and Keys determines how much Value each word contributes to the other words in the sentence.

Why did Transformers replace RNNs and LSTMs?

Recurrent networks had to process words one by one in order, which made training slow and caused them to forget distant words in long texts. Transformers process all words in parallel on GPUs and allow direct connections between any two words regardless of distance.

The Sunday Codex

Research delivered once a week.

One deeply investigated historical, scientific, or economic mystery grounded in primary sources. Pure evidence, zero noise.

Free weekly archival digest. Unsubscribe at any time.
Connected Curiosity

Explore the Question Graph

Every investigation opens further avenues of historical and scientific inquiry. Select a connected question to research it immediately:

Investigate Any Subject

Have a question of your own?

Alcuin researches primary historical records, academic journals, and peer-reviewed archives with zero hallucinations.