Skip to content

← Attention 101 step 1 of 5

Hard Primitives

Implement Scaled Dot-Product Attention

Attention builds an output for each query by taking a weighted average of value vectors. A query's dot products with the keys determine those weights. This exercise implements one attention head without batching, masking or dropout.

Scores, weights and values

Compute these three arrays in order:

scores = (Q @ K.T) / sqrt(d_k)
weights = softmax(scores, axis=-1)
output = weights @ V

Each score row belongs to one query; each column belongs to one key. Softmax normalizes across the keys, so each row's weights sum to one. The matching rows of V supply the vectors to average. Query and key vectors have width d_k, but the values can have a different width d_v.

The scale uses the query/key width, not the number of tokens or value width. For independent zero-mean, unit-variance components, a dot product's variance grows with d_k; dividing by its square root keeps that scale from growing in the same way. It is not a guarantee against numerical overflow.

For Q = [[1, 0]], identity rows in K, and V = [[10, 0], [0, 10]], the scores are approximately [0.707107, 0]. The weights are about [0.669762, 0.330238], giving output [[6.697615, 3.302385]].

Your task

Implement scaled_dot_product_attention(Q, K, V) using matrix products and a row-wise softmax. Do not call a built-in attention function. For a stable softmax, subtract each row's maximum before exponentiating.

  • Q: a floating-point tensor of shape (seq_len_q, d_k).
  • K: a floating-point tensor of shape (seq_len_k, d_k).
  • V: a floating-point tensor of shape (seq_len_k, d_v).

Dimensions are positive. The number of queries need not equal the number of keys. Inputs use compatible dtypes and, in PyTorch, the same device.

Output

Return a tensor of shape (seq_len_q, d_v), leaving the inputs unchanged. Return the weighted values, not the score matrix or attention weights.

The grid below shows which query/key pairs a mask would allow, not their learned weights. Full attention corresponds to this task; the other patterns are comparisons for masked variants.

Loading visualization…