MLCrack

    LLMS & TRANSFORMERS · INTERVIEW QUESTION

    Explain the self-attention mechanism in detail. What are Q, K, V and why do we use scaled dot-product attention?

    🟡 intermediate · Transformer Architecture

    Hint: Think about the analogy of information retrieval and why we divide by √d_k.

    Answer

    Self-attention allows each token to attend to every other token in the sequence, computing contextual representations.

    The Mechanism

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

    • Q (Queries): "What am I looking for?"
    • K (Keys): "What do I contain?"
    • V (Values): "What information do I provide?"

    All three are linear projections of input embeddings: Q=XWQQ = XW_Q, K=XWKK = XW_K, V=XWVV = XW_V.

    Why Scale by dk\sqrt{d_k}?

    For large dkd_k, under independent zero-mean, unit-variance query/key components, dot-product variance grows as dkd_k and standard deviation as dk\sqrt{d_k}, pushing softmax into regions with vanishing gradients. Scaling keeps variance at ~1.

    Multi-Head Attention

    Runs hh parallel attention functions with different projections, allowing the model to attend to different aspects simultaneously. Outputs are concatenated and projected.

    Complexity

    O(n2d) where n=sequence lengthO(n^2 d) \text{ where } n = \text{sequence length}

    This quadratic cost in nn is the key bottleneck for long sequences, motivating approaches like FlashAttention and sparse attention.