FastPrepMulti-Head Self-Attention Layer
Problems/Multi-Head Self-Attention Layer

Multi-Head Self-Attention Layer

OpenAI logoOpenAI● MediumFULLTIMEONSITE INTERVIEW

Updated Nov 2026

QuestionFunctionExamplesConstraints

Problem statement

Source note: A report from April 2026 says an OpenAI onsite for a member of technical staff included a coding round on multi-head attention. It gives the topic only: no input format, weight layout, masking rule, limits or examples.

Here the task is one self-attention layer. It has query, key, value and output weight matrices. Each head takes an equal block of columns. Scores are divided by the square root of the head width. The softmax is numerically stable, and there is an optional causal mask. These choices, the limits and the tolerance are ours. The examples are our own.

Our version is about 40% the same as the reported question.

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.

  1. Make three n x d matrices from the tokens. Q[i][c] is the sum over t of x[i][t] * wq[t][c]. K is built the same way from wk, and V from wv. We call them queries, keys and values.
  2. Let w = d / heads. Split the d columns into heads blocks of w neighbouring columns: head 0 owns columns 0 to w - 1, head 1 owns columns w to 2w - 1, and so on. Each head only ever reads and writes its own columns.
  3. Inside head h, decide which tokens token i may look at. When causal is false, it may look at all n tokens. When causal is true, it may look only at tokens 0 to i, that is, itself and the tokens before it.
  4. For each token j that token i may look at, multiply Q[i][c] by K[j][c] for every column c of the head, add these products up, and divide by sqrt(w). The result is the score of j.
  5. Turn those scores into weights with softmax: the weight of j is exp(score of j), divided by the total of exp(score) across every token that i may look at. The weights are positive and add up to 1.
  6. On the head's columns, row i of the mixed matrix M is the weighted sum of the rows V[j], using those weights. Once every head has filled its columns, M is a full n x d matrix.
  7. Return M multiplied by wo, 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.5 and 1, giving weights of about 0.378 and 0.622 on the values 1 and 2, so about 1.622. Token 1 has scores 1 and 2, giving about 0.269 * 1 + 0.731 * 2 = 1.731.
  • Head 1: token 0 has scores -1 and 1, giving weights of about 0.119 and 0.881 on the values -1 and 1, so about 0.762. Token 1 has scores 1 and -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, where n is the number of rows of x.
  • 1 <= d <= 12, and every row of x has exactly d entries.
  • Each of the four weight matrices (wq, wk, wv, wo) is square, with d rows of d entries.
  • 1 <= heads <= d (so heads <= 12), and d is a multiple of heads.
  • -10 <= x[i][j] <= 10
  • Every entry of the four weight matrices is between -1 and 1.
  • causal is either true or false.

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

OpenAI interview experiences

  • OpenAI OA: What It Tests (2026)
All OpenAI interview questionsSee OpenAI hiring insights
Saved
class Solution {
    public double[][] selfAttentionLayer(double[][] x, double[][] wq, double[][] wk, double[][] wv, double[][] wo, int heads, boolean causal) {
        // Write your code here.
    }
}
Checking account…