Real lesson · Machine learning

This is a real Nodebook lesson.

Nothing below was written for this website. It is a row out of the product’s own database — compiled on 9 August 2026 from 7 sources, fact-checked against them, and drawn here by the same reader a subscriber uses. The only things missing are the ones that would need an account to be worth anything.

  • 7 concepts
  • 7 cited sources
  • 4 code-rendered figures
  • 14 quiz questions
  • 12 flashcards
7 sources✓ VerifiedIntermediate

Self-Attention in Transformer Models: Queries, Keys, and Values

Self-attention in a transformer uses Query, Key, and Value vectors to dynamically determine relevance between sequence tokens, enabling the model to focus on important contextual information. For each token, a Query vector seeks information, a Key vector offers information, and a Value vector holds the actual content. This mechanism is enhanced by multi-head attention for diverse perspectives, positional encoding for sequence order, and attention masks for controlled processing.

The process of Scaled Dot-Product Attention, transforming input embeddings into an output by using Queries, Keys, and Values.
Concepts · 7
  1. Self-Attention's Purpose
    Definition

    How can a computer understand a word whose meaning changes based on surrounding words?

    When you read a sentence, your brain doesn't just process words one by one; it constantly relates each word to others to build a coherent meaning. Self-attention aims to mimic this human ability in machines.

    Traditional models struggled to understand how words relate across long sentences, often treating each word in isolation. Self-attention solves this by allowing each word to dynamically weigh the importance of every other word in the input sequence, creating a richer, context-aware representation.

    WHAT IT ISSelf-attention is a core mechanism within transformer models.

    WHAT IT DOESIt enables a model to process a sequence of data, like a sentence, by considering the relationships between all elements (tokens) in that sequence simultaneously. For each token, self-attention computes an output representation that is a weighted sum of all Value vectors in the sequence, where the weights are dynamically determined by how relevant each token's Query is to every other token's Key. For instance, when processing 'it' in 'The animal didn't cross the street because it was too tired,' self-attention helps the model understand that 'it' refers to 'animal.'

    WHY IT MATTERSThis mechanism is crucial for understanding context and long-range dependencies, vital in tasks like language translation, text summarization, and question answering. It allows the model to focus on relevant parts of the input, regardless of their position, leading to more nuanced and accurate interpretations of sequential data.

    Not to be confused with: Self-attention is just a simple weighted average of words. - Self-attention is not merely a simple weighted average of words without considering their relationships, but rather it dynamically calculates specific relevance scores between each word and every other word in the sequence, allowing the model to focus on the most pertinent contextual information for each token's representation.

    WHY THIS MATTERSWithout self-attention, transformer models would struggle to capture intricate contextual nuances and dependencies within long sequences, severely limiting their performance on complex language tasks. This mechanism is fundamental to how transformers achieve state-of-the-art results in understanding and generating human-like text.

  2. Queries, Keys, Values
    Definition

    How does a transformer decide which words in a sentence are most important to understand another word?

    Just as a search engine uses your query to find relevant documents based on their keywords, self-attention uses Query, Key, and Value vectors to find relevant parts of an input sequence.

    Self-attention mechanisms in a transformer use three distinct types of vectors—Queries, Keys, and Values—to determine how much focus each part of an input sequence should place on other parts. These vectors are not separate inputs; instead, they are dynamically generated from the same initial input embedding for each token through independent learned linear transformations.

    WHAT IT ISQuery, Key, and Value vectors are specialized vector representations derived from an input token's embedding within a transformer's self-attention layer.

    WHAT IT DOESThe Query vector (Q) represents the information a token is 'seeking' from other tokens. The Key vector (K) represents the information a token 'offers' to be found by others. The Value vector (V) holds the actual content or semantic information of the token, which is then weighted and aggregated based on the attention scores calculated from Query-Key similarities. For instance, if 'bank' is the current token, its Query might look for 'financial' or 'river-edge' context, its Key would advertise its own 'bank' identity, and its Value would carry the full meaning of 'bank'.

    WHY IT MATTERSThese distinct roles enable the self-attention mechanism to dynamically weigh the relevance of every other token to the current token, allowing the model to build a rich, context-aware representation. This mechanism is crucial for understanding long-range dependencies and nuances in sequential data, as it allows each token's representation to be informed by the most pertinent parts of the entire input, rather than just its immediate neighbors.

    Process of a Single Attention Head in a Transformer Model.jpg · Shuang Zhang, Rui Fan, Yuti Liu, Shuang Chen, Qiao Liu, Wanwen Zeng / CC BY 4.0

    Not to be confused with: A common misconception is that Query, Key, and Value vectors are entirely separate, distinct inputs that the model receives. - This is incorrect; Q, K, and V are not separate inputs, but rather learned transformations of the same initial input embedding for each token, allowing the model to project the same information into different representational spaces for comparison and aggregation.

    WHY THIS MATTERSUnderstanding the distinct roles of Queries, Keys, and Values is fundamental to grasping how transformers dynamically model relationships between tokens, enabling sophisticated contextual understanding. This mechanism allows the model to selectively focus on relevant information, which is critical for tasks like translation, summarization, and question answering.

  3. Scaled Dot-Product Attention
    Process

    How does a transformer decide which words in a sentence are most important for understanding another word?

    Just as a search engine matches your query to relevant documents (keys) and then presents snippets (values) from the best matches, self-attention uses Queries to find relevant Keys and combine their Values.

    Scaled Dot-Product Attention is the core calculation within a transformer's self-attention mechanism, determining how much focus each part of an input sequence should give to other parts. It computes similarity scores between a query and all keys, scales these scores, and then uses them as weights to sum the corresponding values, producing a context-aware output for each input token.

    WHAT IT ISScaled Dot-Product Attention is a fundamental computational block within the self-attention layer of transformer models.

    WHAT IT DOESIt quantifies the relevance between a given Query vector and all Key vectors in the input sequence using a dot product, then scales these raw scores to prevent vanishing gradients during training. These scaled scores are transformed into a probability distribution via a softmax function, yielding attention weights. Finally, these weights are applied to the corresponding Value vectors, summing them to produce a new, context-rich representation for the original Query's position. For example, if the query is 'bank' in 'river bank', it calculates how much 'river' and 'bank' itself relate to 'bank'.

    WHY IT MATTERSThis mechanism allows the transformer to dynamically weigh the importance of different input elements when processing each token, enabling it to capture complex dependencies regardless of their distance in the sequence. This ability to 'attend' selectively is crucial for tasks like machine translation and text summarization, where understanding context is paramount.

    The computational flow of Scaled Dot-Product Attention.
    Walk through an example

    A transformer processing 'it' in 'The cat sat on the mat. It purred.' We want to calculate the attention output for 'it'.

    1. Calculate the dot product between the Query vector for 'it' and each Key vector (for 'The', 'cat', 'sat', 'on', 'the', 'mat', 'It', 'purred').
      This step quantifies the raw similarity or relevance of 'it' to every other word in the sequence. A higher dot product means greater alignment in their vector spaces.
    2. Divide each dot product by the square root of the dimension of the Key vectors (scaling factor √dₖ).
      This scaling step prevents the dot products from becoming too large, which could push the softmax function into regions with extremely small gradients, hindering stable model training, as discussed in 'The Scaling Factor (√dₖ)'.
    3. Apply the softmax function to these scaled scores.
      Softmax converts the scaled scores into a probability distribution, ensuring that all attention weights are positive and sum to one. This makes them interpretable as 'how much attention' to pay to each word.
    4. Multiply each attention weight by its corresponding Value vector.
      Each Value vector carries the contextual information of its original word. Multiplying by the attention weight means we're selectively emphasizing the information from words that are highly relevant to 'it'.
    5. Sum all these weighted Value vectors.
      This final sum creates a new, context-aware representation for 'it', incorporating information from all other words, weighted by their relevance. This new vector is the output of the attention head for 'it'.

    So: The resulting vector for 'it' is a rich, context-aware representation that emphasizes its relationship with 'cat' and 'purred' more than other words, reflecting its role as a pronoun, as shown in the worked example.

    Not to be confused with: Using the raw dot product of Query and Key vectors directly as attention weights. - The dot product does not directly yield the attention weights without further processing; it's not a probability distribution. Instead, the raw dot-product scores must be scaled by √dₖ and then passed through a softmax function to produce stable, normalized attention weights that sum to one, ensuring a proper distribution of focus across the sequence.

    WHY THIS MATTERSThis precise calculation is what allows transformers to dynamically focus on relevant parts of the input, enabling them to capture long-range dependencies and understand complex language structures. Without it, the model would struggle to weigh information effectively, limiting its ability to generate coherent and contextually appropriate outputs.

    TRY IT

    Given a Query vector Q, two Key vectors K1, K2, and two Value vectors V1, V2. If Q·K1 = 8, Q·K2 = 2, and √dₖ = 2, what are the attention weights after scaling and softmax?

    Hint

    First, scale the dot products. Then, apply the softmax function: e^x / (e^x + e^y).

  4. The Scaling Factor (√dₖ)
    Math

    Why do we need to divide attention scores by a seemingly arbitrary number like the square root of a dimension?

    You've seen how 'Scaled Dot-Product Attention' calculates similarity between queries and keys using a dot product. This scaling factor directly modifies those dot-product results.

    When calculating attention, the raw similarity scores between queries and keys can become extremely large, especially with high-dimensional vectors. The scaling factor acts as a crucial dampener, reducing these scores to a more stable range before they are converted into probability distributions by the softmax function.

    WHAT IT ISThe scaling factor (√dₖ) is a normalization constant applied in scaled dot-product attention.

    WHAT IT DOESIt divides the raw dot-product scores between a query vector and all key vectors before the softmax function is applied. This division counteracts the tendency of dot products to grow proportionally with the dimension of the key vectors (`d_k`), preventing the scores from becoming excessively large. For instance, if `d_k` is 64, the scores are divided by 8.

    WHY IT MATTERSThis scaling is vital for stabilizing the training of transformer models by preventing the softmax function from saturating. Without it, large input values to softmax would push outputs towards extreme values (0 or 1), leading to vanishing gradients and significantly hindering the model's ability to learn effectively.

    The softmax function's output becomes very flat (saturates) for large positive or negative inputs, leading to near-zero gradients. Scaling prevents scores from
    Walk through an example

    A transformer processes a sequence, and for one query, it calculates raw dot-product scores against several keys. The dimension of the key vectors (`d_k`) is 64. One raw score is 100, and another is 10.

    1. Calculate the scaling factor.
      The scaling factor is determined by the square root of the key vector dimension, `d_k`, which is 64. This value is constant for all scores within a given attention head.
    2. Apply the scaling factor to the raw dot-product scores.
      Each raw score is divided by the calculated scaling factor. This reduces their magnitude, bringing them into a range where the softmax function behaves more predictably.
    3. Observe the impact on subsequent softmax calculation.
      The scaled scores (12.5 and 1.25) are now much smaller than the original (100 and 10). When these scaled values are fed into the softmax function, the output probabilities will be more nuanced and less prone to extreme values, ensuring gradients are not vanishingly small.

    So: The scaling factor transforms potentially large raw attention scores into a more stable range, crucial for the softmax function to produce meaningful probability distributions and maintain gradient flow.

    Not to be confused with: Treating the scaling factor as an optional hyperparameter to be tuned, or a simple way to make numbers smaller. - The scaling factor is not an arbitrary constant or a minor optimization without significant impact, but rather a mathematically derived necessity to counteract the increasing variance of dot products in high dimensions. It's specifically designed to prevent the softmax function from saturating, which would otherwise lead to vanishing gradients and render model training ineffective, rather than merely reducing numerical values for convenience.

    WHY THIS MATTERSWithout the scaling factor, the dot products between high-dimensional query and key vectors can become very large, causing the softmax function to output probabilities that are extremely close to 0 or 1. This 'saturation' leads to vanishing gradients during backpropagation, effectively halting learning for parts of the model and making stable training impossible.

    TRY IT

    A new transformer architecture uses key vectors with a dimension (`d_k`) of 256. What value should the scaling factor be, and what problem does it primarily solve?

    Hint

    Recall the formula for the scaling factor and its main purpose related to gradients.

  5. Multi-Head Attention
    Comparison

    How can a transformer model understand multiple, distinct connections between words in a single sentence simultaneously?

    Scaled Dot-Product Attention calculates how much each word in a sequence relates to every other word. Multi-Head Attention builds on this by performing that calculation not just once, but many times in parallel.

    Multi-Head Attention allows a transformer to process different aspects of relationships within a sequence simultaneously. Instead of calculating attention once, it performs several independent attention calculations in parallel, each focusing on a unique part of the input information.

    WHAT IT ISMulti-Head Attention is a mechanism in transformer models that runs multiple self-attention operations in parallel.

    WHAT IT DOESEach 'head' independently projects the input queries, keys, and values into different learned subspaces, then performs scaled dot-product attention. For instance, one head might focus on syntactic dependencies, while another captures semantic relationships. The outputs from these individual attention heads are then concatenated and linearly transformed to produce the final output.

    WHY IT MATTERSThis parallel processing enhances the model's ability to capture diverse types of relationships and dependencies within the input sequence, which a single attention mechanism might miss. It allows the model to attend to information from different representation subspaces at different positions, leading to a richer and more comprehensive understanding of the input.

    Not to be confused with: A common misconception is that Multi-Head Attention merely repeats the same attention calculation multiple times. - This is incorrect because each attention head uses different learned linear projections for its Query, Key, and Value vectors. This means each head operates in a distinct representation subspace, allowing it to focus on different types of relationships, not just re-evaluating the same ones.

    WHY THIS MATTERSMulti-Head Attention is critical for the transformer's ability to grasp complex linguistic nuances, like polysemy or long-range dependencies, by considering various interpretations concurrently. This parallel processing of different 'perspectives' leads to more robust and contextually rich representations, which is vital for tasks like machine translation or text summarization.

  6. Positional Encoding
    Definition

    How does a transformer know the difference between 'cat chases dog' and 'dog chases cat' if it processes all words at once?

    Just as a word's meaning is captured by its embedding vector, a word's position in a sentence needs its own numerical representation.

    Transformers process all tokens in a sequence simultaneously, meaning self-attention alone doesn't inherently understand the order of words. Positional encoding adds numerical information to each token's embedding, indicating its position within the sequence, so the model can learn from word order.

    WHAT IT ISPositional encoding is a technique used in transformer models.

    WHAT IT DOESIt injects information about the relative or absolute position of tokens in the input sequence into their corresponding embeddings. For example, 'bank' in 'river bank' receives a different positional signal than 'bank' in 'money bank' if their positions differ, allowing the model to distinguish their context based on order. This positional information is added to the token's initial vector representation before it enters the self-attention layers.

    WHY IT MATTERSThis mechanism is crucial because self-attention, by design, treats all tokens as an unordered set, unable to inherently distinguish between 'dog bites man' and 'man bites dog'. Positional encoding allows the model to leverage sequence order, which is vital for understanding grammar, context, and meaning in natural language processing tasks.

    Not to be confused with: Self-attention inherently understands the order of tokens in a sequence. - This is incorrect because self-attention calculates relationships between all tokens simultaneously, treating them as an unordered set. It does not inherently know which token comes before or after another; positional encoding explicitly provides this crucial sequence order information.

    WHY THIS MATTERSWithout positional encoding, transformers would struggle with tasks requiring an understanding of syntax, grammar, or temporal relationships, like machine translation or text summarization. It ensures that the model can differentiate between sentences with the same words but different meanings due to word order.

  7. Attention Masks: Practical Control
    Process

    How do transformers manage sequences of different lengths, or generate text one word at a time without 'peeking' at the answer?

    Just as a human reader ignores blank space at the end of a line or only reads up to the current word when predicting the next, transformers need mechanisms to control what information is considered relevant or available.

    Self-attention mechanisms need precise control over which parts of an input sequence a token can 'see' or attend to. Attention masks provide this control by selectively modifying attention scores, preventing unwanted interactions and ensuring correct information flow.

    WHAT IT ISAttention masks are binary matrices applied to the raw attention scores (the result of the Query-Key dot product) within a transformer's self-attention mechanism.

    WHAT IT DOESThey modify specific attention scores, typically by setting them to a very large negative number (like negative infinity), which, after the softmax function, effectively turns those attention weights into zero. For instance, a padding mask ensures that tokens representing filler or 'padding' do not influence the attention calculation for meaningful tokens.

    WHY IT MATTERSMasks are critical for two main practical scenarios: handling variable-length input sequences efficiently (padding masks) and enabling autoregressive sequence generation where tokens can only attend to preceding tokens (causal or look-ahead masks). This ensures the model processes information logically and avoids 'cheating' by seeing future data.

    The process of applying an attention mask within the self-attention mechanism.
    Walk through an example

    You are training a transformer model. First, it translates the sentence 'The cat sat [PAD] [PAD]' (where [PAD] fills unused sequence length). Second, it generates the next word in 'The quick brown'.

    1. During translation, apply a padding mask to the attention scores.
      This prevents any token in 'The cat sat' from attending to the meaningless `[PAD]` tokens, ensuring attention is focused only on relevant words and preventing computational waste.
    2. During text generation, apply a causal (look-ahead) mask.
      This ensures that when the model predicts 'fox' after 'The quick brown', it can only attend to 'The', 'quick', and 'brown', mimicking real-time generation and preventing it from 'seeing' 'fox' prematurely.
    3. The mask modifies the raw attention scores before the softmax function.
      The mask sets the scores for forbidden connections to negative infinity, which become zero after softmax, effectively blocking attention.

    So: The transformer correctly processes variable-length inputs and generates sequences autoregressively, focusing attention only on permissible tokens.

    Not to be confused with: Assuming that a transformer's self-attention mechanism always allows every token to attend to every other token in the sequence without any restrictions. - This is incorrect; attention masks are specifically designed to restrict attention, not enable unrestricted access. They are crucial for preventing attention to padding tokens or future tokens in autoregressive tasks, ensuring the model's behavior is appropriate for the task at hand.

    WHY THIS MATTERSWithout attention masks, transformers would struggle with variable-length inputs, wasting computation on padding tokens, and could not perform autoregressive tasks like text generation correctly. They are fundamental for building robust and efficient transformer models for real-world applications.

    TRY IT

    You're building a chatbot that generates responses word-by-word. What type of mask is essential for its decoder, and why?

    Hint

    The order in which a chatbot generates text and what information it should have access to at each step.

Sources · 7
Practice

Reading it is the easy half.

In the app this lesson does not stop here. Each of the 7 concepts ends with a prompt you answer from memory before you are shown the answer, and behind them sit 14 quiz questions and 12 flashcards. What you get shaky on comes back on a schedule built from how you actually did — which is the whole point, and the reason it needs an account: your answers and your review dates have to live somewhere.

3 free lessons a month. No card.

Two more, in other subjects