KatInterview

Self-Attention Deep Dive: Q, K, V Roles and Transformer Design Trade-offs

Machine LearningModel answer
MediumModel answerMachine Learningtransformersself-attentionqkv

Last updated

Explain how self-attention builds queries, keys and values, what the value vectors do, and why Transformers handle long-range context better than recurrent models.

Imagine you are asked to walk a teammate through how a Transformer works, concentrating on the self-attention layer.

Cover the following in your answer:

  1. Q, K and V construction. Starting from a matrix of input token embeddings, show how the query, key and value matrices are produced. State the shapes involved, and say what kind of information each of the three is meant to carry.
  2. The role of V. What do the value vectors represent, and how are they used once the attention weights are known?
  3. From scores to outputs. Describe at a high level how similarity scores turn into attention weights and then into the layer's output. Mention any scaling or masking you would apply and why.
  4. Comparison with recurrent models. Contrast Transformers with RNNs and LSTMs. Explain how Transformers deal with sequential dependency and with long-range context, and name the costs they introduce.
  5. Multi-head attention and positional encoding. Briefly outline both, and explain when each matters at inference time.

Aim for a structured answer that a colleague could follow, with formulas where they help and a few concrete numbers or trade-offs.

Hints

Hint 1

Write the single-head formula first: softmax(QKᵀ / √d_k + mask) V. Then attach shapes to every term and walk through it left to right.

Hint 2

Separate 'where to look' from 'what to retrieve'. Q and K decide the weights; V is the payload that is actually mixed into the output. Ask yourself why one projection for both jobs would be limiting.

Hint 3

For the RNN comparison, think in terms of path length between two tokens, parallelism during training, and memory at inference. For the inference part, think about the KV cache, grouped-query attention, and what happens past the trained context length.