Attention Mechanism Variants in Large Language Models: Evolution and Engineering Trade-offs

    This article explains what attention mechanisms solve in sequence modeling, how self-attention works through its four-step computation, and why the design choices behind attention are shaped by both modeling quality and hardware parallelism.

    What Problem Does Attention Solve?

    When sequence models process text, the representation at each position often depends on information from other positions. For example, the noun that a pronoun refers to may appear much earlier in the text. Early recurrent neural networks read information step by step in temporal order, so distant information must travel through many steps to reach the current position, which makes it prone to fading along the way. Training also cannot be parallelized effectively.

    The attention mechanism allows a model, when computing the representation at a given position, to directly access all relevant positions in the sequence. Distance is no longer the main obstacle. At its core, attention is a weighted aggregation: the model assigns a score to each position, and the higher the score, the greater that position’s contribution to the current output. Both scoring and aggregation can be expressed as matrix operations, which makes them well suited to parallel execution on modern accelerators.

    The Basic Computation of Self-Attention

    Self-attention applies three groups of learnable linear transformations to the same input, producing three sets of vectors: Query, Key, and Value. Their roles can be understood as follows: the query represents what the current position is looking for, the key represents the matching label each position can offer, and the value represents the content each position actually carries.

    The computation proceeds in four steps:

    1. Take the dot product of the query with all keys to obtain similarity scores.
    2. Divide the scores by the square root of the key vector dimension. This step suppresses the problem where, as the dimension grows, dot product values become too large and softmax gradients approach saturation.
    3. Apply softmax to each row of scores to obtain weights that sum to 1.
    4. Use the weights to compute a weighted sum of the value vectors, producing the new representation at that position.

    Written as a formula: Attention(Q, K, V) = softmax(QK^T / √d_k) V, where d_k is the dimension of the key vectors.