Why Does Self-Attention Split into Three Linear Transformations for Q, K, and V?

    This article explains why Self-Attention uses three separate linear transformations to produce Query (Q), Key (K), and Value (V) instead of a single shared projection. It frames attention as a soft retrieval system, uses an everyday analogy to clarify the division of roles, and walks through the core computation, scaling, masking, and multi-head design. It also covers dimension choices, engineering pitfalls, and practical deployment considerations, helping readers design and implement attention mechanisms more effectively.

    1. The Real Question: Not “Can They Be Merged?” but “Why Decouple Them?”

    In Transformer-style models, the core operation of Self-Attention is straightforward: each position passes its own representation through three linear transformations to obtain a Query (Q), a Key (K), and a Value (V). Q and K are combined via a dot product to produce relevance scores. After scaling and normalization, these scores become weights that are applied to V in a weighted sum.

    Many beginners ask a natural question: since there is only one input, why not use a single transformation to do all the work?

    The answer is not that merging makes computation impossible. The issue is that merging forces two fundamentally different semantics into the same representation: the basis for matching, and the content being retrieved. Once these are bound together, the model loses the freedom to “retrieve using one feature while fetching another.” Both expressiveness and interpretability tend to degrade.

    2. An Everyday Analogy: Three Things When Borrowing a Charger

    Imagine your phone is at 2% battery and you need to find “someone who can charge an iPhone.” Your brain is actually handling three things in parallel:

    • Your current need: “I need someone who can charge an iPhone.” This is Q, representing your current retrieval intent.
    • The matchable tags each person carries: who has an Android cable, who has an iPhone cable, who has a power bank. This is K, representing the features that can be matched against.
    • What you actually take: a charging cable, the location of an outlet, or even a “I also have a fast charger.” This is V, representing the content being retrieved.

    The key point is that the basis used to “select someone” and the thing you “take from them” are naturally not the same. If you force one representation to serve as the address, the key, and the package contents all at once, the system becomes clumsy: the retrieval dimension and the content dimension constrain each other and become hard to optimize together.

    3. A Retrieval-System View of Self-Attention

    It is clearer to treat attention as a “soft retrieval” process. Let the input sequence representation be a matrix X (shape n×d, where n is the sequence length and d is the model dimension). The three linear transformations are:

    1. Q = X @ Wq # (n, dk) query: what am I looking for
    2. K = X @ Wk # (n, dk) key: am I matchable
    3. V = X @ Wv # (n, dv) value: the content I actually provide
    4. scores = Q @ K.transpose(-1, -2) / (dk ** 0.5) # relevance scoring
    5. weights = softmax(scores + mask) # normalize into weights
    6. output = weights @ V # retrieve content by weight

    There are three key points here:

    1. Q and K only decide “who to look at”; they do not directly decide “what you get.” The scoring semantics is similarity, while the content is carried independently by V.
    2. The scaling factor 1/√dk controls the variance of the dot product as dimensions grow, preventing softmax from entering a saturated region that causes vanishing gradients.
    3. The mask blocks future positions in decoding scenarios to preserve the autoregressive property; it also blocks invalid tokens at padding positions to avoid polluting the weights.

    If you set Wq = Wk = Wv, the model still runs, but “the basis for retrieval” and “the retrieved content” are locked into the same subspace: you can only use “the content itself” to retrieve “the content itself.” This is not optimal for many tasks. Syntactic dependency, coreference resolution, and positional relationship modeling often require “retrieving with role/position features but fetching semantic features.”

    4. Why Decoupling Improves Expressiveness

    • Subspace division of labor: the Q/K subspace focuses on “matchability,” while the V subspace focuses on “information transfer.” Different tasks can be optimized in different subspaces without interfering with each other.
    • Asymmetric matching: it allows the “query” and the “answer” to live in different representation spaces while the dot product still measures relevance. This is a common approach in question-answering retrieval.
    • Parallel multi-head attention: multi-head attention lets different heads execute different retrieval strategies (local, global, syntactic, positional, etc.) in different subspaces, then concatenates and fuses them.
    • Controllability and interpretability: you can reduce the dimensionality or sparsify V alone without breaking the matching logic; you can also visualize the Q·K distribution to analyze attention patterns.

    5. Dimension and Multi-Head Design

    • Dimension choice: a common practice is dk = dv = d / h (where h is the number of heads), so that after concatenation the dimension returns to d, making residual connections and subsequent layers easier.
    • Head-count trade-off: too many heads dilute the per-head dimension and limit expressiveness; too few heads make retrieval strategies monotonous. Tuning should consider the task and data scale.
    • Parameter efficiency: the three projection matrices add extra parameters and computation, but the gains are significant in practice, making this a standard configuration in general architectures.

    6. Engineering Implementation and Common Pitfalls

    • Numerical stability: scale before softmax; in mixed precision, watch the numerical range of softmax and normalization.
    • Correct masking: decoders need a causal mask; encoders need a padding mask; the two must not be mixed.
    • Complexity awareness: standard attention has time and memory complexity of O(n²); long sequences require general approaches such as sparse, chunked, or linear attention.
    • Common pitfalls: assuming “the same input means the same transformation”; ignoring the independent role of V; treating the scaling factor as an optional detail.

    7. Practical Suggestions on Baidu AI Cloud

    When deploying this type of model on Baidu AI Cloud, you can containerize training and inference tasks and use a container platform for elastic scheduling; use object storage to store datasets and checkpoints; track loss, throughput, and latency through log and monitoring services; and on the inference side, combine batching and caching strategies to optimize cost. These are general capability categories; refer to the official documentation for specific interfaces and parameters.

    8. Summary

    Self-Attention uses three linear transformations because it decouples “retrieval intent (Q),” “matchable tags (K),” and “retrieved content (V).” This preserves the differentiable and parallel advantages of soft retrieval while giving the model the freedom to “retrieve by one feature and fetch another.” Understanding this helps you design dimensions, head counts, and masks more reasonably and build more robust implementations.