Multi-Head Self-Attention Layer
Updated
Problem statement
A language model reads a sequence of n tokens. Token i is stored as row x[i], a vector of d numbers. Compute what one multi-head self-attention layer returns for this sequence: an n x d matrix, built in the steps below.
- Make three
n x dmatrices from the tokens.Q[i][c]is the sum overtofx[i][t] * wq[t][c].Kis built the same way fromwk, andVfromwv. We call them queries, keys and values. - Let
w = d / heads. Split thedcolumns intoheadsblocks ofwneighbouring columns: head 0 owns columns0tow - 1, head 1 owns columnswto2w - 1, and so on. Each head only ever reads and writes its own columns. - Inside head
h, decide which tokens tokenimay look at. Whencausalisfalse, it may look at allntokens. Whencausalistrue, it may look only at tokens0toi, that is, itself and the tokens before it. - For each token
jthat tokenimay look at, multiplyQ[i][c]byK[j][c]for every columncof the head, add these products up, and divide bysqrt(w). The result is the score ofj. - Turn those scores into weights with softmax: the weight of
jisexp(score of j), divided by the total ofexp(score)across every token thatimay look at. The weights are positive and add up to 1. - On the head's columns, row
iof the mixed matrixMis the weighted sum of the rowsV[j], using those weights. Once every head has filled its columns,Mis a fulln x dmatrix. - Return
Mmultiplied bywo, built the same way as in step 1.
A score can be in the tens of thousands, and exp of such a number does not fit in a double. Subtracting the largest score that token i may look at from each of those scores before calling exp leaves the weights unchanged and avoids the overflow.
Answers are compared with a small tolerance. A returned entry passes when it is within 10^-6 of the expected entry, or, for an expected entry whose absolute value is above 1, within 10^-6 times that absolute value.
Function
selfAttentionLayer(x: double[][], wq: double[][], wk: double[][], wv: double[][], wo: double[][], heads: int, causal: boolean) → double[][]Examples
Example 1
x = [[1.0],[2.0],[-1.0]]wq = [[1.0]]wk = [[0.5]]wv = [[1.0]]wo = [[-1.0]]heads = 1causal = truereturn = [[-1.0],[-1.7310585786300048],[0.11681905525743641]]Here d = 1, so Q = x = [1, 2, -1], K = 0.5 * x = [0.5, 1, -0.5] and V = x. There is one head of width 1, so scores are not rescaled.
Token 0 may only look at itself, so its mixed value is 1. Token 1 looks at tokens 0 and 1 with scores 2 * 0.5 = 1 and 2 * 1 = 2. Softmax gives weights of about 0.269 and 0.731, so its mixed value is about 0.269 * 1 + 0.731 * 2 = 1.731. Token 2 looks at all three tokens with scores -0.5, -1 and 0.5. The weights are about 0.231, 0.140 and 0.629, and the weighted sum of the values 1, 2 and -1 is about -0.117.
Finally wo = [[-1]] flips every sign.
Example 2
x = [[1.0,2.0],[0.0,-1.0]]wq = [[1.0,0.0],[1.0,1.0]]wk = [[0.0,1.0],[1.0,0.0]]wv = [[1.0,0.0],[0.0,0.5]]wo = [[1.0,1.0],[0.0,1.0]]heads = 1causal = falsereturn = [[0.9995813993860604,1.998953498465151],[0.05580721920716973,-0.36048195198207567]]The projections give Q = [[3, 2], [-1, -1]], K = [[2, 1], [-1, 0]] and V = [[1, 1], [0, -0.5]]. There is one head of width 2, so every dot product is divided by sqrt(2), about 1.414.
Token 0 gets scores 8 / 1.414 (about 5.66) and -3 / 1.414 (about -2.12). Nearly all the weight, about 0.99958, goes to token 0, so its mixed row is very close to [1, 1]. Token 1 gets scores of about -2.12 and 0.71, so token 0 gets a weight of only about 0.056 and the mixed row is about [0.056, -0.416].
Multiplying a row [a, b] by wo gives [a, a + b].
Example 3
x = [[1.0,-1.0],[2.0,1.0]]wq = [[1.0,0.0],[0.0,-1.0]]wk = [[0.5,0.0],[0.0,1.0]]wv = [[1.0,0.0],[0.0,1.0]]wo = [[1.0,0.0],[0.0,1.0]]heads = 2causal = falsereturn = [[1.6224593312018545,0.7615941559557649],[1.7310585786300048,-0.7615941559557649]]The projections give Q = [[1, 1], [2, -1]], K = [[0.5, -1], [1, 1]] and V = x. With 2 heads, each head has width 1: head 0 owns column 0 and head 1 owns column 1, and each head runs its own softmax.
- Head 0: token 0 has scores
0.5and1, giving weights of about0.378and0.622on the values1and2, so about1.622. Token 1 has scores1and2, giving about0.269 * 1 + 0.731 * 2 = 1.731. - Head 1: token 0 has scores
-1and1, giving weights of about0.119and0.881on the values-1and1, so about0.762. Token 1 has scores1and-1, so the weights swap and the result is about-0.762.
The two heads fill the two columns, and wo leaves the rows unchanged.
Constraints
1 <= n <= 30, wherenis the number of rows ofx.1 <= d <= 12, and every row ofxhas exactlydentries.- Each of the four weight matrices (
wq,wk,wv,wo) is square, withdrows ofdentries. 1 <= heads <= d(soheads <= 12), anddis a multiple ofheads.-10 <= x[i][j] <= 10- Every entry of the four weight matrices is between
-1and1. causalis eithertrueorfalse.
More OpenAI Onsite Interview questions
- Sparse Plant Infection SimulationPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Rectangle Point Coverage CountsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Message Event AggregationPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- 15-Minute Chat Session TrackerPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Segmented Durable Key-Value StorePHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Durable Work Queue OperationsPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Versioned Social NetworkPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Budgeted API Inference with Out-of-Order FeedbackONSITE INTERVIEW · Seen Oct 2026
- Plant Infection Simulation, Part 4: Death CountdownPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Count Friend CirclesPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Implement Circular PaddingApple · ONSITE INTERVIEWApple interview questions
- Robot Survival ProbabilityInMobi · ONSITE INTERVIEWInMobi interview questions
- Grouped-Query Attention with a KV CacheAmazon · ONSITE INTERVIEW
- Transformer Attention and SwiGLU Forward PassGoogle · ONSITE INTERVIEWGoogle interview questions
- Logistic Regression DiagnosticsLinkedIn · PHONE SCREENLinkedIn interview questions
- Scaled Dot-Product AttentionMeshy · OA
- Column and Row Parallel Linear LayersNVIDIA · PHONE SCREENNVIDIA interview questions
- Flip Rows and Columns, Count ZerosNutanix · OANutanix interview questions
- Orthogonal Neighbor Grid TotalIMC Trading · OAIMC Trading interview questions
- Spiral MatrixAthenahealth · ONSITE INTERVIEW