v9.1.1
Menu

Scaled Dot-Product Attention

hardPRONLP FundamentalsMachine Learning 2

Implement Scaled Dot-Product Attention from the Transformer architecture.

Given query matrix QQ, key matrix KK, and value matrix VV:

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

where dkd_k is the dimension of the keys (number of columns in K).

Steps:

  1. Compute QKTQK^T (matrix multiplication)
  2. Scale by 1dk\frac{1}{\sqrt{d_k}}
  3. Apply softmax row-wise (each row sums to 1)
  4. Multiply by VV

Return the attention output matrix, rounded to 4 decimal places.

Example

Input
Q = [[1, 0]]
K = [[1, 0], [0, 1]]
V = [[1, 2], [3, 4]]
Output
[[1.6605, 2.6605]]
Reasoning
  • We start by computing the matrix product QKTQK^T, which is [[1,0]]⋅[[1,0],[0,1]]T=[[1,0]]⋅[[1,0],[0,1]]=[[1,0]][[1, 0]] \cdot [[1, 0], [0, 1]]^T = [[1, 0]] \cdot [[1, 0], [0, 1]] = [[1, 0]].
  • Then, we scale this result by 1dk=12\frac{1}{\sqrt{d_k}} = \frac{1}{\sqrt{2}}, yielding [[12,0]][[\frac{1}{\sqrt{2}}, 0]].
  • Next, we apply the softmax function row-wise: since [[12,0]][[\frac{1}{\sqrt{2}}, 0]] is a single row, this results in [[11+e−12,11+e0]]≈[[0.7311,0.2689]][[\frac{1}{1+e^{-\frac{1}{\sqrt{2}}}}, \frac{1}{1+e^{0}}]] \approx [[0.7311, 0.2689]] after normalization, but because we apply softmax to [12,0][\frac{1}{\sqrt{2}}, 0] we actually calculate softmax([[12,0]])=[[e12e12+e0,e0e12+e0]]=[[e12e12+1,1e12+1]]\text{softmax}([[\frac{1}{\sqrt{2}}, 0]]) = [[\frac{e^{\frac{1}{\sqrt{2}}}}{e^{\frac{1}{\sqrt{2}}} + e^{0}}, \frac{e^{0}}{e^{\frac{1}{\sqrt{2}}} + e^{0}}]] = [[\frac{e^{\frac{1}{\sqrt{2}}}}{e^{\frac{1}{\sqrt{2}}} + 1}, \frac{1}{e^{\frac{1}{\sqrt{2}}} + 1}]], which then gets multiplied by V.
  • Finally, multiplying this result by VV yields $[[\frac{e^{\frac{1}{\sqrt{2}}}}{e^{\frac{1}{\sqrt{2}}} + 1}, \frac{1}{e^{\frac{1}{\sqrt{2}}} + 1}]] \cdot [[1, 2], [3, 4]] = [[\frac{e^{\frac{1}{\sqrt{2}}}}{e^{\frac{1}{\sqrt{2}}} + 1} \cdot 1 + \frac

Constraints

  • Q: 2D list (n x d_k)
  • K: 2D list (m x d_k)
  • V: 2D list (m x d_v)
  • Return 2D list (n x d_v) rounded to 4 decimal places
  • Use numerical stability trick for softmax

Learn this in

More from Machine Learning 2

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.