Let a=softmax(s) be attention weights over scores s. Derive the Jacobian ∂ai/∂sj and the backward rule ∂L/∂s=a⊙(g−(a⊤g)1) where g=∂L/∂a. For a=(0.7,0.2,0.1) and g=(1,0,−1), compute ∂L/∂s, and again for the peaky a=(0.98,0.01,0.01). What does this say about saturated attention?

Sequence models and transformers, Attention
Level L3 Intermediate. Length Long. Nature Mat Mathematical.

What's being asked

Whether you can derive the softmax Jacobian and apply it to see that peaky attention gives small gradients to the scores.

Key idea

∂ai∂sj=ai(δij−aj), so J=diag(a)−aa⊤ and ∂L∂s=J⊤g=a⊙g−a (a⊤g).

Steps

  1. Write ai=esi/Z with Z=∑kesk.
  2. For j=i: ∂ai/∂si=ai−ai2=ai(1−ai). For j≠i: ∂ai/∂sj=−esiesj/Z2=−aiaj.
  3. In matrix form J=diag(a)−aa⊤. It is symmetric, so the backward pass is ∂L/∂sj=∑igiJij=aj(gj−a⊤g).
  4. Case 1: a⊤g=0.7−0.1=0.6. So ∂L/∂s=(0.7×0.4,  0.2×(−0.6),  0.1×(−1.6))=(0.28, −0.12, −0.16). The entries sum to 0 because softmax ignores a constant shift of s.
  5. Case 2: a⊤g=0.98−0.01=0.97. So ∂L/∂s=(0.98×0.03,  0.01×(−0.97),  0.01×(−1.97))=(0.0294, −0.0097, −0.0197).
  6. The gradient magnitudes drop by about a factor of 10. When a is nearly one-hot, every entry aj(⋅) is small, so scores (and hence WQ,WK) receive almost no gradient. This is why large score magnitudes (no 1/dk scaling) slow learning.

Common mistakes

How long your answer should be

Half a page; 5–6 minutes.

Last checked on 4 December 2026.

Read this

Previous in Sequence models and transformers: For a vanilla RNN with ht=tanh⁡(Wht−1+Uxt), show that ∥∂hT/∂h0∥≤(σmax⁡(W))T, where σmax⁡ is the largest singular value. What does this say for σmax⁡=0.9 and 1.1 over T=50 steps? How does gradient-norm clipping help, for example when the gradient norm is 25 and the threshold is 5?
Next in Sequence models and transformers: A decoder has 32 layers, 32 query heads of dimension 128 (dmodel=4096) and stores keys and values in 16-bit floats (2 bytes). How large is the KV cache for one sequence of 4096 tokens with multi-head attention (MHA), grouped-query attention with 8 KV heads (GQA), and multi-query attention (MQA, one KV head)? How many parameters does GQA save in the K and V projections?