Dev.to AI 🤖 Ai 👁 0 📖 10 min read

Deconstructing the Attention Mechanism: What Exactly Do Q, K, and V Do?

This article was originally published on my blog. For the latest version and future updates, please visit the original post: https://jaketao.com/language/en/attention-mechanism Let’s Start with Finding a Book in the L

Deconstructing the Attention Mechanism: What Exactly Do Q, K, and V Do?

This article was originally published on my blog. For the latest version and future updates, please visit the original post: https://jaketao.com/language/en/attention-mechanism

Let’s Start with Finding a Book in the Library

In the previous article, we discussed how the attention mechanism enables AI to learn “translation with reference to the source text”: for every word it writes, it looks back at the source text, assigns a “relevance score” to each word, and then integrates the information based on those scores. But how exactly is the relevance score calculated? And what does the model use to express “what information I need”?

In this post, we’ll break down this process using the three sets of vectors: Q, K, and V.

Let’s Start with Finding a Book

Suppose you’ve never written code before and want to learn Python from scratch. With that in mind, you walk into the library. You wouldn’t flip through every one of the tens of thousands of books in the library; instead, you’d head straight to the “Computing/Programming” section.

The books on the shelf are arranged by programming language and difficulty: Introduction to Python Programming, Python Data Analysis, Introduction to Java Programming… Sandwiched in the middle is a copy of A Modern History of the World (probably slipped in by someone returning a book or misplaced by a librarian).

You’ll mentally compare these books one by one: Introduction to Python Programming is the best fit — it matches both the language and your learning stage; Python Data Analysis also uses Python, but its focus is on data analysis; Introduction to Java Programming is similarly aimed at beginners, but teaches a different language; and A History of the Modern World, sitting right next to it, has absolutely nothing to do with programming.

You pull out the most relevant books, read through the text to learn how to declare variables, write conditional statements, and use loops, and casually flip through the examples on data processing in the text.

The entire process of finding and reading books revolves around three pieces of information: the question in your mind (“How do I get started with Python from scratch?”), the book titles on the shelf used for evaluation, and the text you’re reading — which correspond exactly to the three sets of vectors Q, K, and V calculated at the same attention layer.

Table 1: Correspondence Between the Book-Search Process and the Attention Mechanism

During Book Search Attention Mechanism Meaning\
Your question Q (Query) What you want right now\
Book titles on the shelf K (Key) Clues used to determine if a book meets your needs\
The book’s content V (Value) The information it actually provides

Separating these elements is the first step toward understanding the attention mechanism.

Many people, upon first seeing Q, K, and V, have a question: K and V seem to be the same thing — why split them into two?

What helps you find the book and what you actually take from it are inherently different. The book’s title helps you determine whether it’s worth opening and whether it matches your needs, while the text itself contains the knowledge that helps you understand the problem. Finding the book Introduction to Python Programming is only the first step; you still have to read it.

The same applies to the model: K is responsible for “matching,” while V is responsible for “retrieving.” By separating them, the model can learn, respectively, “which features to use for matching” and “what content to pass after a match” — and the optimal solutions for these two tasks are often different.

Replacing Book Search with Computation

If we translate the process of finding a book in a library into numerical terms, we can understand how attention in large models is computed.

Prerequisites: Converting the query, book titles, and content into vectors

A computer cannot directly compare the phrase “Learn Python from Scratch” with a book title; it must first represent both as strings of numbers — that is, vectors. In this example, we use three types of vectors:

  • Q: Your query — “Learn Python from Scratch.”
  • K: The features of each book used to match the query.
  • V: The information each book provides.

Q and K are used to calculate the match score, while V is saved for last and aggregated based on the degree of match.

Step 1: Scoring

The most common scoring method is called the dot product: multiply corresponding elements in the two sequences, then sum the results.

Here’s a simple example:

Q = [1, 2], and a book’s K = [3, 1]. Matching score = 1 × 3 + 2 × 1 = 5

This is the specific algorithm for “comparing Q and K.” It is influenced by both the direction and magnitude of the vectors; through training, the model ensures that this calculation reflects matching relationships useful for the current task.

Returning to the four books, we compute the dot product of the same Q with each of their Ks, then apply scaling (explained later), resulting in the scores shown in the table below.

Table 2: Matching Scores for the Four Books

Book Matching Score\
Introduction to Python Programming 3.0\
Python Data Analysis 1.5\
Introduction to Java Programming 1.0\
Modern World History 0

Introduction to Python Programming best meets the requirements; the other two programming books are each partially relevant; the history book is largely irrelevant.

Step 2: Convert Scores to Weights

With the scores in hand, we need to convert them into weights that add up to 100% to determine how much weight each book’s information carries.

Softmax handles this step. It first raises each score to a power, then divides it by the sum of all results:

A book’s weight = e raised to the power of “that book’s score” ÷ the sum of the exponents of all four books

Here, e is approximately 2.718. No need to calculate this by hand — just remember: the higher the score, the greater the weight; and the total of all weights adds up to 100%.

Referring to the scores of each book above, we obtain the corresponding information weights.

Table 3: Converted Information Weights

Book Information Weight\
Introduction to Python Programming 71.0%\
Python Data Analysis 15.8%\
Introduction to Java Programming 9.6%\
Modern World History 3.5%

The most relevant book accounts for the largest share, partially relevant books account for a portion, and irrelevant books account for very little. Standard Softmax typically does not set the weights of irrelevant items directly to zero.

Step 3: Aggregate Content by Weight

Finally, it’s time for each book’s V vector to take center stage.

V is the “content card” for each book’s text within the model. Since the model cannot read the text, it first converts the text into a string of numbers, with each number representing the abundance of a specific type of content. This string of numbers is V.

Output ≈ 71.0% × V Python Data Analysis\
+9.6% × V Introduction to Java Programming\
+3.5% × V Modern World History

The percentage of information weight determines “how much of each book is read”; V is the “content card” for each book. Combining the four cards proportionally into one is a weighted sum.

Q and K determine how to allocate the weights, while V provides the information to be aggregated. This is the division of labor among the three.

Self-Attention: Querying Within the Same Text Segment

In the library example, a single query involves multiple books. In self-attention, both the query and the information come from the same text segment.

The text is first split into individual tokens — which could be a character, a word, or even a part of a word. Each position has its own numerical representation, which is used to generate Q, K, and V.

The following calculation is performed separately for each position:

  1. Score using its own Q and the Ks from the positions it is allowed to read;
  2. Convert the scores into weights;
  3. Aggregate the V from those positions according to the weights.

In other words, each position can both initiate a query and provide information to other positions. The aggregated information is used to update the representation of that position for subsequent processing.

Different models allow for varying scopes of “viewing”: bidirectional self-attention can read both preceding and following context; models like GPT typically use causal self-attention, where each position can only read itself and the preceding context. However, the core computation remains these three steps: scoring → scaling → weighted aggregation.

Making Attention Work Effectively: Scaling and Training

Scaling: Why Divide by the Square Root of $d$

If you’ve read the relevant papers, you’ll have come across this famous formula:

Attention(Q, K, V) = softmax( Q·Kᵀ / √d ) · V

Comparing this to the three steps mentioned earlier:

  • $QK^{\mathsf{T}}$: Score Q against all K;
  • $\mathrm{softmax}$: Convert to a ratio;
  • $V$: Collect $V$ proportionally.

The only part that hasn’t been explained is the ÷ √d in the middle. Here, $d$ is more accurately written as dₖ, referring to the length of the $Q$ and $K$ vectors within a single attention head, which is not necessarily equal to the length of the $V$ vector or the model’s overall representation.

Why scale? The longer the Q and K vectors are, the more terms there are in the dot-product sum, and scores tend to fluctuate more significantly. Softmax has a characteristic: once the score gap becomes too large, the weight distribution becomes extremely skewed.

For example, if we multiply the scores of the four books mentioned earlier by 4 before applying Softmax, the weight for Introduction to Python Programming would change from approximately 71.0% to approximately 99.7%. Focusing intensely on a single book isn’t necessarily a problem; however, if the score scale is simply too large, it causes the distribution to approach “choosing only one” too early, which can make it harder for the model to adjust these weights during training.

Dividing by √d effectively “cools down” the scores after they’re calculated, mitigating the score fluctuations caused by increased dimensionality and making training more stable. This does not require attention to be distributed evenly at all times: the model can still focus intensely on a specific location when necessary.

Training: Learning to Generate Appropriate Q, K, and V

We already know how Q, K, and V are used in the calculations. But how are they initially generated, and why do they produce useful matches?

The answer is that these values aren’t manually entered one by one; instead, the model learns them during training.

In standard self-attention, a single input vector is transformed by three distinct sets of parameters to produce Q, K, and V. These three sets of parameters are called projection matrices.

You can think of them as three processing machines: with the same input, different machine settings yield different outputs. Training adjusts the parameters of these machines, so the generated Q, K, and V also change accordingly.

Different positions within the same layer and the same attention head share these three sets of parameters; different layers and different heads typically have their own projection parameters.

When training from scratch, these projection parameters are usually initialized randomly and initially cannot consistently produce useful matches.

Then, the model begins training on a large corpus of text. Training tasks vary by model: bidirectional models can practice filling in missing words; a fundamental task for generative language models like GPT is to predict the next token.

Taking the prediction of the next token as an example, training calculates a “loss” based on the probability the model assigns to the correct answer, and then uses backpropagation and an optimizer to adjust the parameters — including these three sets of projection matrices. Even if the correct answer is already ranked first, as long as its probability is not high enough, updates are typically still generated.

After extensive training, some attention heads may learn patterns related to reference, modification, subject-predicate relationships, and so on. However, not every head corresponds to a clear grammatical rule; understanding a sentence typically requires the collaborative effort of multiple heads across multiple layers.

In this type of text pre-training, there is no need to write grammatical rules one by one; the model can learn many patterns of “where to look” from the data and training objectives.

Conclusion: The Intuition Behind a Formula

Let’s recap this article:

  • Q is “what I’m looking for,” K is “what features I have available for matching,” and V is “what I can provide”;
  • The attention calculation involves three steps: scoring, scaling, and weighted aggregation;
  • Dividing by √d prevents the scores from becoming too extreme;
  • The parameters that generate Q, K, and V are learned by the model during training.

At this point, you’ve likely grasped the core formula behind the attention mechanism.

But the story doesn’t end there. In many large models, attention isn’t performed just once; instead, multiple attention heads compute in parallel, with multiple layers stacked on top of each other — the exact number depends on the model. Standard full attention requires computing relationships between a vast number of position pairs; even with causal attention — which only allows looking at the current position and preceding text — long texts still incur a massive computational cost.

In 2017, the paper Attention Is All You Need elevated attention from a supplementary module to the backbone of the system, ushering in the era of today’s large language models.

Looking back, a grand architectural framework is essentially no different from searching for a book in a library — it’s simply repeating the process of “asking what, comparing what, and selecting what” countless times.

References

[1] Vaswani A., et al. Attention Is All You Need. 2017: Sections 3.1–3.2, scaled dot-product attention, multi-head attention, residual connections, and causal masking. https://arxiv.org/html/1706.03762v7

[2] PyTorch Documentation: CrossEntropyLoss; the loss depends on the predicted probability of the correct class, rather than simply determining whether the guess was correct. https://docs.pytorch.org/docs/2.14/generated/torch.nn.CrossEntropyLoss.html

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.