Batched Multi-Head Attention Forward Pass
Medium · Machine Learning · Applied Scientist · Technical Screen
Problem Statement
Write a vectorized NumPy implementation of batched multi-head scaled dot-product attention:
def multi_head_attention(
query: List[List[List[float]]],
key: List[List[List[float]]],
value: List[List[List[float]]],
num_heads: int,
weights: Dict[str, List[List[float]]],
mask: Optional[List[List[List[bool]]]] = None,
) -> List[List[List[float]]]:
Given query sequences of shape (batch, L_q, d_model) together with key and value sequences of shape (batch, L_k, d_model), compute the contextualized output tensor of shape (batch, L_q, d_model) across num_heads parallel attention subspaces. Both self-attention (L_q == L_k) and cross-attention (L_q != L_k) must work seamlessly.
Follow these exact rules and conventions:
- Linear projections (row-vector layout):
weightsmaps"wq","wk","wv", and"wo"to(d_model, d_model)matrices. Project inputs by multiplying on the right:Q = query @ weights["wq"],K = key @ weights["wk"], andV = value @ weights["wv"]. - Head partitioning: Each head has width
d_k = d_model // num_heads(raise aValueErrorifd_modelis not divisible bynum_heads). Headh(0 <= h < num_heads) owns feature columnsh * d_kthrough(h + 1) * d_k - 1ofQ,K, andV. - Scaled dot-product scoring and masking: Within each head, compute pairwise scores
(Q_h @ K_h^T) / sqrt(d_k)of shape(batch, num_heads, L_q, L_k). Whenmaskis provided (broadcastable to(batch, L_q, L_k)),Trueindicates an allowed(query, key)pair andFalseblocks that key so its post-softmax weight is0.0. If every key for a query position isFalse, assign0.0weight to all keys so the head produces an all-zero vector rather thanNaN. - Head combination and output projection: Multiply the numerically stable softmax weights along the key axis by
V_h, concatenate allnum_headsslices along the last axis back to widthd_model, right-multiply byweights["wo"], and return the result as nested Pythonlists offloats.
Examples
Example 1
Input:
query = [[[2.0, 0.0], [0.0, 1.0]]]
key = [[[1.0, 2.0], [0.0, 2.0]]]
value = [[[10.0, 5.0], [20.0, 15.0]]]
num_heads = 2
weights = {
"wq": [[1.0, 0.0], [0.0, 1.0]],
"wk": [[1.0, 0.0], [0.0, 1.0]],
"wv": [[1.0, 0.0], [0.0, 1.0]],
"wo": [[1.0, 0.0], [0.0, 1.0]],
}
mask = None
Output:
[[[11.192029220221174, 10.0], [15.0, 10.0]]]
Walk-through: With d_model = 2 and num_heads = 2, each head has width d_k = 1 (sqrt(d_k) = 1.0) and identity projections leave Q, K, and V unchanged.
- Head 0 (column 0): Q_0 = [[2], [0]], K_0 = [[1], [0]], V_0 = [[10], [20]]. Query 0 gets scores [2.0, 0.0], giving softmax weights [e^2 / (e^2 + 1), 1 / (e^2 + 1)] ≈ [0.880797, 0.119203] and output 0.880797 * 10 + 0.119203 * 20 ≈ 11.192029. Query 1 gets equal scores [0.0, 0.0], averaging 10 and 20 to 15.0.
- Head 1 (column 1): Q_1 = [[0], [1]], K_1 = [[2], [2]], V_1 = [[5], [15]]. Both queries assign equal scores to the two identical keys, averaging 5 and 15 to 10.0.
Example 2
Input:
query = [[[1.0, 0.0], [0.0, 1.0]]]
key = [[[2.0, 0.0], [0.0, 2.0], [2.0, 2.0]]]
value = [[[4.0, 0.0], [0.0, 6.0], [8.0, 10.0]]]
num_heads = 1
weights = {
"wq": [[1.0, 0.0], [0.0, 1.0]],
"wk": [[1.0, 0.0], [0.0, 1.0]],
"wv": [[1.0, 0.0], [0.0, 1.0]],
"wo": [[1.0, 1.0], [0.0, 1.0]],
}
mask = [[[True, False, False], [False, False, False]]]
Output:
[[[4.0, 4.0], [0.0, 0.0]]]
Walk-through: Cross-attention runs with L_q = 2 queries over L_k = 3 keys. Query 0 may only attend to key 0, so its pre-output vector is V[0] = [4.0, 0.0], which right-multiplied by wo = [[1.0, 1.0], [0.0, 1.0]] yields [4.0, 4.0]. Query 1 has every key blocked (False), producing [0.0, 0.0].
Constraints
batch >= 1,L_q >= 1,L_k >= 1,d_model >= 1, andnum_heads >= 1.d_model % num_heads == 0for valid calls (raiseValueErrorotherwise).weights["wq"],weights["wk"],weights["wv"], andweights["wo"]each have shape(d_model, d_model).maskis eitherNoneor a boolean nested list broadcastable to(batch, L_q, L_k).- Compute all heads and positions in batched NumPy tensor operations with no Python loops over batches, heads, queries, or keys, and without prebuilt framework attention functions.
- The softmax must remain numerically finite even on large score magnitudes or fully blocked query rows.
Step-by-step walkthrough
Understand the inputs, outputs, and conventions
Multi-head attention lets every query position gather information from allowed key/value positions across
num_headsparallel subspaces:queryhas shape(batch, L_q, d_model)—L_qquery token vectors of widthd_model.keyandvaluehave shape(batch, L_k, d_model)—L_kcontext token vectors (L_q == L_kin self-attention, whileL_qandL_kcan differ in cross-attention).weightsholds four(d_model, d_model)projection matrices:"wq","wk","wv", and"wo".num_headsdividesd_modelevenly, giving each head widthd_k = d_model // num_heads.maskis eitherNone(every query sees every key) or a boolean tensor of shape(batch, L_q, L_k).
Before coding, state the three core conventions explicitly:
- Right-multiplication (
x @ W): each token is a row vector, so projectingqueryusesq_in @ w_q. - Mask polarity (
True= allowed):mask[b][i][j] == Truemeans queryimay attend to keyj;Falsegives keyjzero weight. - All-blocked query rows: if every key for a query has
mask == False, all keys receive zero weight, producing an all-zero vector rather thanNaN.
Plan every tensor shape before writing code
Almost every bug in multi-head attention comes from mixing up the
num_headsaxis and the sequence-length axis. Writing down the exact shape at every line makes the whole forward pass straightforward (h = num_heads):q_in (batch, L_q, d_model) projected_q = q_in @ wq (batch, L_q, d_model) q_heads (split_heads) (batch, h, L_q, d_k) k_heads, v_heads (batch, h, L_k, d_k) k_transposed (batch, h, d_k, L_k) scores = Q @ K^T / √d_k (batch, h, L_q, L_k) <-- each row is 1 query over all L_k keys attention_weights (batch, h, L_q, L_k) <-- each row sums to 1 (or 0 if all masked) head_outputs = attn @ V (batch, h, L_q, d_k) merged_heads (batch, L_q, d_model) output = merged @ wo (batch, L_q, d_model)Notice why
hsits at axis1(ahead ofL_qandd_k): NumPy's@operator performs matrix multiplication on the last two axes and runs every leading axis (batchandh) in parallel with zero Python loops.Split and merge attention heads without scrambling tokens
Inside
projected_qof shape(batch, seq_len, d_model), head0owns columns0 .. d_k - 1of each token, head1owns columnsd_k .. 2*d_k - 1, and so on.To separate heads cleanly, we must first
reshape(batch, seq_len, num_heads, d_k)to slice each token'sd_modelvector into(num_heads, d_k), and only thentranspose(0, 2, 1, 3)to swapseq_lenandnum_heads. Look at what happens with1batch,2tokens[a0, a1, a2, a3]and[b0, b1, b2, b3], and2heads (d_k = 2):Correct: reshape(1, 2, 2, 2) then transpose(0, 2, 1, 3) head 0 gets [[a0, a1], [b0, b1]] (token a's first half, token b's first half) head 1 gets [[a2, a3], [b2, b3]] (token a's second half, token b's second half) WRONG: direct reshape(1, 2, 2, 2) without transpose! "head 0" gets [[a0, a1], [a2, a3]] (both halves of token a!) "head 1" gets [[b0, b1], [b2, b3]] (both halves of token b!)merge_headsperforms the exact reverse:transpose(0, 2, 1, 3)puts each token's head slices back next to each other in memory beforereshape(batch, seq_len, num_heads * d_k)glues them intod_modelcolumns.def split_heads(x: np.ndarray, num_heads: int) -> np.ndarray: """Split (batch, seq_len, d_model) into (batch, num_heads, seq_len, d_k).""" batch, seq_len, d_model = x.shape d_k = d_model // num_heads # Slice the last axis into (num_heads, d_k) per token FIRST, then move num_heads # ahead of seq_len; reshaping directly to (batch, num_heads, seq_len, d_k) would mix tokens. reshaped = x.reshape(batch, seq_len, num_heads, d_k) return reshaped.transpose(0, 2, 1, 3) def merge_heads(x: np.ndarray) -> np.ndarray: """Concatenate (batch, num_heads, seq_len, d_k) back into (batch, seq_len, d_model).""" batch, num_heads, seq_len, d_k = x.shape # Move seq_len back ahead of num_heads so each token's head slices sit side by side in memory. transposed = x.transpose(0, 2, 1, 3) return transposed.reshape(batch, seq_len, num_heads * d_k)Score query-key pairs and scale by sqrt(d_k)
Inside each head, we measure how strongly query
imatches keyjby taking their dot product (sum_c q[i, c] * k[j, c]). Swapping the last two axes ofk_headsfrom(L_k, d_k)to(d_k, L_k)letsq_heads @ k_transposedcompute allL_q * L_kdot products at once.Why divide by
np.sqrt(d_k)? If the entries ofqandkhave mean0and variance1, each productq_c * k_chas variance1, and addingd_kindependent products gives varianced_k(standard deviationsqrt(d_k)). Without scaling, largerd_kproduces huge dot products that push softmax into extreme0/1saturation where gradients vanish. Dividing bysqrt(d_k)— using the per-head dimensiond_k, notd_model— restores unit variance.Write a numerically stable masked softmax
Turning each score row
(L_k,)into non-negative weights requires handling three numerical hazards:- Blocked keys must get exact
0.0weight: setting disallowed scores to-np.infbefore exponentiating makesnp.exp(-np.inf) == 0.0. (Multiplying scores by0would fail becauseexp(0) = 1!) - Large scores overflow
np.exp:np.exp(710)overflowsfloat64toinf. Subtracting each row's maximumrow_maxfrom every score in that row multiplies top and bottom byexp(-row_max), leaving the probabilities identical while ensuring every exponent is<= 0. - Fully masked rows must not produce
NaN: if every key in a row isFalse,row_maxis-inf, and-inf - (-inf)evaluates toNaN! Replacing non-finiterow_maxvalues with0.0keeps every entry at-inf, soexpsbecomes all0.0. Then replacing zerorow_sumswith1.0turns0.0 / 0.0into0.0 / 1.0 = 0.0.
def masked_softmax(scores: np.ndarray, allowed: np.ndarray) -> np.ndarray: """Compute softmax over the last (key) axis with zero weight on disallowed keys.""" # Set disallowed positions to -inf so exp(-inf) produces exact 0.0 weight. masked_scores = np.where(allowed, scores, -np.inf) # Subtract each row's max so the largest exponent is exp(0) = 1.0 (prevents exp overflow). row_max = np.max(masked_scores, axis=-1, keepdims=True) # If every key in a row is disallowed, row_max is -inf; replace with 0.0 to avoid -inf - (-inf) = NaN. safe_row_max = np.where(np.isfinite(row_max), row_max, 0.0) exps = np.exp(masked_scores - safe_row_max) row_sums = np.sum(exps, axis=-1, keepdims=True) # Fully disallowed rows have row_sums == 0.0; divide by 1.0 so 0.0 / 1.0 stays 0.0 instead of NaN. safe_row_sums = np.where(row_sums > 0.0, row_sums, 1.0) return exps / safe_row_sums- Blocked keys must get exact
Assemble the full multi-head attention pass
Now every piece snaps together cleanly. When
maskis provided with shape(batch, L_q, L_k)(or a broadcastable shape like(1, L_q, L_k)), inserting a singleton head axis[:, np.newaxis, :, :]gives shape(batch, 1, L_q, L_k)so NumPy broadcasts the same mask across allnum_headsheads without duplicating memory.After
masked_softmax,attention_weights @ v_headscomputes each query's weighted average of the value vectors,merge_headsconcatenates all heads back to widthd_model, and@ w_oapplies the output projection before.tolist()converts back to Python lists.def multi_head_attention( query: List[List[List[float]]], key: List[List[List[float]]], value: List[List[List[float]]], num_heads: int, weights: Dict[str, List[List[float]]], mask: Optional[List[List[List[bool]]]] = None, ) -> List[List[List[float]]]: # Phase 1: convert nested lists to float64 arrays and validate dimensions. q_in = np.asarray(query, dtype=float) # shape: (batch, L_q, d_model) k_in = np.asarray(key, dtype=float) # shape: (batch, L_k, d_model) v_in = np.asarray(value, dtype=float) # shape: (batch, L_k, d_model) batch, len_q, d_model = q_in.shape len_k = k_in.shape[1] if d_model % num_heads != 0: raise ValueError("d_model must be divisible by num_heads") d_k = d_model // num_heads w_q = np.asarray(weights["wq"], dtype=float) # shape: (d_model, d_model) w_k = np.asarray(weights["wk"], dtype=float) # shape: (d_model, d_model) w_v = np.asarray(weights["wv"], dtype=float) # shape: (d_model, d_model) w_o = np.asarray(weights["wo"], dtype=float) # shape: (d_model, d_model) # Phase 2: project Q, K, V and split d_model into `num_heads` parallel subspaces of size d_k. projected_q = q_in @ w_q # shape: (batch, L_q, d_model) projected_k = k_in @ w_k # shape: (batch, L_k, d_model) projected_v = v_in @ w_v # shape: (batch, L_k, d_model) q_heads = split_heads(projected_q, num_heads) # shape: (batch, num_heads, L_q, d_k) k_heads = split_heads(projected_k, num_heads) # shape: (batch, num_heads, L_k, d_k) v_heads = split_heads(projected_v, num_heads) # shape: (batch, num_heads, L_k, d_k) # Phase 3: scaled dot-product scores across every (query, key) pair per head. # Scale by sqrt(d_k) — the per-head width, NOT sqrt(d_model) — to keep score variance near 1. k_transposed = k_heads.transpose(0, 1, 3, 2) # shape: (batch, num_heads, d_k, L_k) scale = np.sqrt(d_k) scores = (q_heads @ k_transposed) / scale # shape: (batch, num_heads, L_q, L_k) # Phase 4: prepare the boolean mask with a size-1 head axis so it broadcasts across all heads. if mask is None: allowed = np.ones((batch, 1, len_q, len_k), dtype=bool) else: # Convention: True means this query may attend to this key; False blocks the key. mask_array = np.broadcast_to(np.asarray(mask, dtype=bool), (batch, len_q, len_k)) allowed = mask_array[:, np.newaxis, :, :] # shape: (batch, 1, L_q, L_k) # Phase 5: convert scores to attention weights, mix V, concatenate heads, and project output. attention_weights = masked_softmax(scores, allowed) # shape: (batch, num_heads, L_q, L_k) head_outputs = attention_weights @ v_heads # shape: (batch, num_heads, L_q, d_k) merged_heads = merge_heads(head_outputs) # shape: (batch, L_q, d_model) output = merged_heads @ w_o # shape: (batch, L_q, d_model) return output.tolist()Trace Example 1 by hand
In Example 1,
batch = 1,num_heads = 2,d_model = 2(d_k = 1, sosqrt(d_k) = 1.0),mask = None, and all four weight matrices are2x2identity matrices:Inputs (single batch item): Q = [[2.0, 0.0], K = [[1.0, 2.0], V = [[10.0, 5.0], [0.0, 1.0]] [0.0, 2.0]] [20.0, 15.0]] 1. Split into 2 heads of width d_k = 1: Head 0 (col 0): Q_0 = [[2], [0]], K_0 = [[1], [0]], V_0 = [[10], [20]] Head 1 (col 1): Q_1 = [[0], [1]], K_1 = [[2], [2]], V_1 = [[ 5], [15]] 2. Scaled scores (Q_h @ K_h^T) / sqrt(1) and row-wise softmax: Head 0: Query 0 scores = [2.0, 0.0] -> weights = [e^2 / (e^2 + 1), 1 / (e^2 + 1)] ~ [0.880797, 0.119203] Query 1 scores = [0.0, 0.0] -> weights = [0.5, 0.5] Head 1: Query 0 scores = [0.0, 0.0] -> weights = [0.5, 0.5] Query 1 scores = [2.0, 2.0] -> weights = [0.5, 0.5] 3. Weighted sum of V_h per head, concatenated and multiplied by I_2: Query 0: [0.880797 * 10 + 0.119203 * 20, 0.5 * 5 + 0.5 * 15] = [11.192029, 10.0] Query 1: [0.5 * 10 + 0.5 * 20, 0.5 * 5 + 0.5 * 15] = [15.0, 10.0]That matches Example 1's expected output
[[[11.192029220221174, 10.0], [15.0, 10.0]]]to full floating-point precision.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import numpy as np def split_heads(x: np.ndarray, num_heads: int) -> np.ndarray: """Split (batch, seq_len, d_model) into (batch, num_heads, seq_len, d_k).""" batch, seq_len, d_model = x.shape d_k = d_model // num_heads # Slice the last axis into (num_heads, d_k) per token FIRST, then move num_heads # ahead of seq_len; reshaping directly to (batch, num_heads, seq_len, d_k) would mix tokens. reshaped = x.reshape(batch, seq_len, num_heads, d_k) return reshaped.transpose(0, 2, 1, 3) def merge_heads(x: np.ndarray) -> np.ndarray: """Concatenate (batch, num_heads, seq_len, d_k) back into (batch, seq_len, d_model).""" batch, num_heads, seq_len, d_k = x.shape # Move seq_len back ahead of num_heads so each token's head slices sit side by side in memory. transposed = x.transpose(0, 2, 1, 3) return transposed.reshape(batch, seq_len, num_heads * d_k) def masked_softmax(scores: np.ndarray, allowed: np.ndarray) -> np.ndarray: """Compute softmax over the last (key) axis with zero weight on disallowed keys.""" # Set disallowed positions to -inf so exp(-inf) produces exact 0.0 weight. masked_scores = np.where(allowed, scores, -np.inf) # Subtract each row's max so the largest exponent is exp(0) = 1.0 (prevents exp overflow). row_max = np.max(masked_scores, axis=-1, keepdims=True) # If every key in a row is disallowed, row_max is -inf; replace with 0.0 to avoid -inf - (-inf) = NaN. safe_row_max = np.where(np.isfinite(row_max), row_max, 0.0) exps = np.exp(masked_scores - safe_row_max) row_sums = np.sum(exps, axis=-1, keepdims=True) # Fully disallowed rows have row_sums == 0.0; divide by 1.0 so 0.0 / 1.0 stays 0.0 instead of NaN. safe_row_sums = np.where(row_sums > 0.0, row_sums, 1.0) return exps / safe_row_sums def multi_head_attention( query: List[List[List[float]]], key: List[List[List[float]]], value: List[List[List[float]]], num_heads: int, weights: Dict[str, List[List[float]]], mask: Optional[List[List[List[bool]]]] = None, ) -> List[List[List[float]]]: # Phase 1: convert nested lists to float64 arrays and validate dimensions. q_in = np.asarray(query, dtype=float) # shape: (batch, L_q, d_model) k_in = np.asarray(key, dtype=float) # shape: (batch, L_k, d_model) v_in = np.asarray(value, dtype=float) # shape: (batch, L_k, d_model) batch, len_q, d_model = q_in.shape len_k = k_in.shape[1] if d_model % num_heads != 0: raise ValueError("d_model must be divisible by num_heads") d_k = d_model // num_heads w_q = np.asarray(weights["wq"], dtype=float) # shape: (d_model, d_model) w_k = np.asarray(weights["wk"], dtype=float) # shape: (d_model, d_model) w_v = np.asarray(weights["wv"], dtype=float) # shape: (d_model, d_model) w_o = np.asarray(weights["wo"], dtype=float) # shape: (d_model, d_model) # Phase 2: project Q, K, V and split d_model into `num_heads` parallel subspaces of size d_k. projected_q = q_in @ w_q # shape: (batch, L_q, d_model) projected_k = k_in @ w_k # shape: (batch, L_k, d_model) projected_v = v_in @ w_v # shape: (batch, L_k, d_model) q_heads = split_heads(projected_q, num_heads) # shape: (batch, num_heads, L_q, d_k) k_heads = split_heads(projected_k, num_heads) # shape: (batch, num_heads, L_k, d_k) v_heads = split_heads(projected_v, num_heads) # shape: (batch, num_heads, L_k, d_k) # Phase 3: scaled dot-product scores across every (query, key) pair per head. # Scale by sqrt(d_k) — the per-head width, NOT sqrt(d_model) — to keep score variance near 1. k_transposed = k_heads.transpose(0, 1, 3, 2) # shape: (batch, num_heads, d_k, L_k) scale = np.sqrt(d_k) scores = (q_heads @ k_transposed) / scale # shape: (batch, num_heads, L_q, L_k) # Phase 4: prepare the boolean mask with a size-1 head axis so it broadcasts across all heads. if mask is None: allowed = np.ones((batch, 1, len_q, len_k), dtype=bool) else: # Convention: True means this query may attend to this key; False blocks the key. mask_array = np.broadcast_to(np.asarray(mask, dtype=bool), (batch, len_q, len_k)) allowed = mask_array[:, np.newaxis, :, :] # shape: (batch, 1, L_q, L_k) # Phase 5: convert scores to attention weights, mix V, concatenate heads, and project output. attention_weights = masked_softmax(scores, allowed) # shape: (batch, num_heads, L_q, L_k) head_outputs = attention_weights @ v_heads # shape: (batch, num_heads, L_q, d_k) merged_heads = merge_heads(head_outputs) # shape: (batch, L_q, d_model) output = merged_heads @ w_o # shape: (batch, L_q, d_model) return output.tolist()✅ Submit now — all tests should pass.
Intuition & how it works
Imagine researching a sentence in a library with a team of num_heads specialist assistants instead of a single reader. Every query word writes a search slip (Q), while every context word posts an index label on its spine (K) and keeps a content summary inside (V) — either within the same sequence (self-attention, where queries, keys, and values all come from one input) or across two sequences (cross-attention, where queries attend to a separate key/value memory). Each specialist projects Q, K, and V into a smaller d_k-dimensional lens (say, one head tracking pronouns, another tracking verb tense), measures query-key similarity via a dot product (multiplying matching coordinates and summing them up), converts those scores into probabilities that sum to 1 via softmax (a function exp(s_i) / sum_j exp(s_j) that turns arbitrary real numbers into non-negative weights), blends a weighted summary of V, and finally hands all specialists' summaries to a closing projection W_o to synthesize one unified vector per query.
Writing nested Python for loops over batches, heads, queries, and keys is thousands of times slower than batched tensor math and violates the prompt's vectorization constraint. Equally important, a naive textbook softmax without sqrt(d_k) scaling, row-maximum subtraction, and -inf masking overflows to inf on large inputs, gives nonzero weight to masked zero scores, or produces NaN whenever an entire query row is masked out.
Walk through Example 1 (2 tokens, 2 heads, d_model = 2 so d_k = 1, identity weights):
- Splitting along columns gives Head
0(Q_0 = [[2], [0]],K_0 = [[1], [0]],V_0 = [[10], [20]]) and Head1(Q_1 = [[0], [1]],K_1 = [[2], [2]],V_1 = [[5], [15]]). - In Head
0(sqrt(d_k) = 1.0), query0gets scores[2.0, 0.0]and softmax weights[0.8808, 0.1192], blendingV_0into0.8808 * 10 + 0.1192 * 20 = 11.1920, while query1gets equal scores[0.0, 0.0]and averages10and20to15.0. - In Head
1, both keys equal2, so both queries assign[0.5, 0.5]weights and blendV_1to10.0, producing[[11.1920, 10.0], [15.0, 10.0]].
Complexity
Let b be batch, h be num_heads, d be d_model (so h * d_k = d), L_q be the query length, and L_k be the key/value length.
- Time:
O(b * (L_q + L_k) * d^2 + b * L_q * L_k * d). ProjectingQand the final output each multiply(b, L_q, d)by(d, d)inO(b * L_q * d^2)operations, while projectingKandVeach takeO(b * L_k * d^2). Computing allhheads' dot-product scores ((b, h, L_q, d_k) @ (b, h, d_k, L_k)) and value mixtures ((b, h, L_q, L_k) @ (b, h, L_k, d_k)) each costO(b * h * L_q * L_k * d_k) = O(b * L_q * L_k * d)— notice that splittingdintohheads of widthd / hkeeps total arithmetic identical to a singled-wide head! - Space:
O(b * h * L_q * L_k + b * (L_q + L_k) * d). Storing the projectedQ,K,V, and merged outputs usesO(b * (L_q + L_k) * d)numbers, while materializing the(b, h, L_q, L_k)scoresandattention_weightstensors usesO(b * h * L_q * L_k)memory. Using broadcasting (stretching a size-1tensor axis acrosshheads virtually without copying data) avoids duplicating the boolean mask across heads.
Edge cases
- Query row with every key masked (
[False, ..., False]): guardingrow_maxagainst-infandrow_sumsagainst0.0assigns0.0weight to every key, returning a clean all-zero output row instead ofNaN. - Single key (
L_k = 1): any unmasked query gives weight1.0to that sole key, returningvalue[:, 0] @ w_v @ w_oregardless ofquery. - Cross-attention (
L_q != L_k):scoreshas rectangular shape(batch, h, L_q, L_k)and the output cleanly takes query lengthL_q. - Extreme head counts (
num_heads = 1ornum_heads = d_model): both work through the exact samesplit_heads/merge_headsreshapes without special branches. - Large input magnitudes (e.g.,
1000.0, scores~7 * 10^5): subtractingsafe_row_maxcaps every exponent at0.0, preventingnp.expoverflow. - Integer list inputs:
np.asarray(..., dtype=float)converts integers up front so divisions and matrix products stay in floating point. - Invalid
num_heads: raisesValueErrorimmediately ifd_model % num_heads != 0.
Common mistakes
- Reshaping straight to
(batch, num_heads, seq_len, d_k)without transposing: gives the expected shape while silently scrambling slices from different token positions into the same head. Alwaysreshape(batch, seq_len, num_heads, d_k)first, thentranspose(0, 2, 1, 3). - Scaling by
sqrt(d_model)instead ofsqrt(d_k): invisible in 1-head unit tests (whered_k == d_model) and subtly breaks multi-head attention scores. - Taking softmax along the query axis (
axis=-2) instead of the key axis (axis=-1): each query's weights over keys must sum to1, not each key's weights over queries. - Zeroing masked scores (
scores * mask) instead of setting-np.inf:exp(0.0)equals1.0, so blocked keys still steal positive probability mass. - Using a finite mask constant like
-1e9on a fully masked row: if every key in a row gets-1e9, softmax gives every blocked key uniform weight1 / L_kinstead of0.0. - Confusing
x @ Wwith PyTorch'snn.Linearx @ W.T: identity matrices in basic samples hide transposed weights, so verify and state the weight layout convention explicitly.
Follow-up questions
- How do you support autoregressive decoding with a look-ahead mask, and what occurs when every key for a given query position is disallowed? A causal mask (a lower-triangular boolean matrix ensuring position
ionly attends to positions0..iand never peeks at future positionsj > i) passesnp.tril(np.ones((L, L), dtype=bool))— combined via&with any padding mask. Pure causal self-attention never blocks an entire row because the diagonal(i, i)isTrue, so each token attends at least to itself; however, combining a causal mask with left-padding leaves leading pad positions with zero allowed keys, where an unguarded softmax evaluates-inf - (-inf) = NaNunless protected likemasked_softmax. - When generating tokens sequentially, how can you avoid recomputing key and value projections for all prior positions at every step? Keep a per-layer KV cache (buffers storing the projected
k_headsandv_headstensors of all prior tokens, with shape(batch, h, t, d_k)aftertsteps). When stept + 1arrives as(batch, 1, d_model), project only that single token intoq_new,k_new, andv_new, appendk_newandv_newalong the sequence axis to reach lengtht + 1, and run attention betweenq_new(L_q = 1) and the cachedt + 1keys/values — cutting per-token work fromO(t * d^2 + t^2 * d)down toO(d^2 + t * d). - What expressive benefit do multiple subspaces of width
d_model // num_headsoffer over a single full-width head, and how do MQA and GQA modify that design? Althoughhheads of widthd / huse the exact same parameter count (4 * d^2) and FLOPs as oned-wide head, a single head computes only one softmax weight vector per query (forcing one weighted sum to mix syntax, coreference, and semantics together), whereashheads computehindependent softmax distributions across distinct feature subspaces at once. Multi-query attention (MQA) (retaininghquery heads while sharing one key head and one value head across all of them) shrinks the KV cache byhx to relieve memory-bandwidth bottlenecks during decoding, while grouped-query attention (GQA) (dividing thehquery heads intoggroups that each share one key/value head) shrinks the KV cache by(h / g)x while preserving near-full multi-head quality. - At long context lengths such as 32k tokens, which intermediate tensor becomes the memory bottleneck, and which techniques mitigate it? The
(batch, h, L, L)score and weight tensors grow quadratically: atL = 32,000, a single head'sL * Lmatrix contains1.024 * 10^9floats (~4.1 GBinfloat32), so 16 heads consume~65.5 GBper sequence for one layer's attention matrix — versus only~131 MBfor a(32,000, 1,024)activation tensor. You can eliminate this bottleneck exactly by processing queries in small blocks (chunk * Lpeak memory) or using FlashAttention tiling with online softmax (maintaining a running row maximum and running normalization denominator across key tiles in fast on-chip SRAM so the fullL * Lmatrix is never materialized in GPU HBM, reducing attention memory toO(L * d)), paired withbf16/fp16precision and GQA or sliding-window attention where appropriate.
Follow-up questions
- How do you support autoregressive decoding with a look-ahead mask, and what occurs when every key for a given query position is disallowed?
- When generating tokens sequentially, how can you avoid recomputing key and value projections for all prior positions at every step?
- What expressive benefit do multiple subspaces of width `d_model // num_heads` offer over a single full-width head, and how do MQA and GQA modify that design?
- At long context lengths such as 32k tokens, which intermediate tensor becomes the memory bottleneck, and which techniques mitigate it?
Similar questions
- Selecting Precision, Recall, or F1 Across Moderation Classifier Tiers
- Monthly Top Spenders, Lifetime Value Design, and Conversion Modeling
- Semantic Text Similarity via Word Embeddings
- Group Relative Policy Optimization (GRPO) vs. PPO for LLM Post-Training
- Generational LLM Scaling, Vision-Language Architecture, and Activation Normalization
- Why XGBoost Generalizes Better Than an Unpruned Decision Tree
More ByteDance interview questions
- Platform PM Walkthrough: Flagship Projects, Trade-Offs, and Impact Medium
- Fixed-Capacity LRU Cache Simulation Hard
- Course Completion with Prerequisites Hard Pro
- Deriving Alphabet Order from Sorted Words Medium Pro
- Course Completion Feasibility with Prerequisites Medium Pro
- Sum of Root-to-Leaf Path Numbers Medium Pro
- Contiguous House Blocks After Removals Medium Pro
- Hardest Engineering Project and Technical Leadership Medium Pro
- Consolidate Overlapping Closed Intervals Medium Pro
- Career Narrative and Role Alignment for TikTok PM Medium Pro