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:

  1. Linear projections (row-vector layout): weights maps "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"], and V = value @ weights["wv"].
  2. Head partitioning: Each head has width d_k = d_model // num_heads (raise a ValueError if d_model is not divisible by num_heads). Head h (0 <= h < num_heads) owns feature columns h * d_k through (h + 1) * d_k - 1 of Q, K, and V.
  3. 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). When mask is provided (broadcastable to (batch, L_q, L_k)), True indicates an allowed (query, key) pair and False blocks that key so its post-softmax weight is 0.0. If every key for a query position is False, assign 0.0 weight to all keys so the head produces an all-zero vector rather than NaN.
  4. Head combination and output projection: Multiply the numerically stable softmax weights along the key axis by V_h, concatenate all num_heads slices along the last axis back to width d_model, right-multiply by weights["wo"], and return the result as nested Python lists of floats.

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, and num_heads >= 1.
  • d_model % num_heads == 0 for valid calls (raise ValueError otherwise).
  • weights["wq"], weights["wk"], weights["wv"], and weights["wo"] each have shape (d_model, d_model).
  • mask is either None or 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

  1. Understand the inputs, outputs, and conventions

    Multi-head attention lets every query position gather information from allowed key/value positions across num_heads parallel subspaces:

    • query has shape (batch, L_q, d_model) — L_q query token vectors of width d_model.
    • key and value have shape (batch, L_k, d_model) — L_k context token vectors (L_q == L_k in self-attention, while L_q and L_k can differ in cross-attention).
    • weights holds four (d_model, d_model) projection matrices: "wq", "wk", "wv", and "wo".
    • num_heads divides d_model evenly, giving each head width d_k = d_model // num_heads.
    • mask is either None (every query sees every key) or a boolean tensor of shape (batch, L_q, L_k).

    Before coding, state the three core conventions explicitly:

    1. Right-multiplication (x @ W): each token is a row vector, so projecting query uses q_in @ w_q.
    2. Mask polarity (True = allowed): mask[b][i][j] == True means query i may attend to key j; False gives key j zero weight.
    3. All-blocked query rows: if every key for a query has mask == False, all keys receive zero weight, producing an all-zero vector rather than NaN.
  2. Plan every tensor shape before writing code

    Almost every bug in multi-head attention comes from mixing up the num_heads axis 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 h sits at axis 1 (ahead of L_q and d_k): NumPy's @ operator performs matrix multiplication on the last two axes and runs every leading axis (batch and h) in parallel with zero Python loops.

  3. Split and merge attention heads without scrambling tokens

    Inside projected_q of shape (batch, seq_len, d_model), head 0 owns columns 0 .. d_k - 1 of each token, head 1 owns columns d_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's d_model vector into (num_heads, d_k), and only then transpose(0, 2, 1, 3) to swap seq_len and num_heads. Look at what happens with 1 batch, 2 tokens [a0, a1, a2, a3] and [b0, b1, b2, b3], and 2 heads (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_heads performs the exact reverse: transpose(0, 2, 1, 3) puts each token's head slices back next to each other in memory before reshape(batch, seq_len, num_heads * d_k) glues them into d_model columns.

    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)
    
  4. Score query-key pairs and scale by sqrt(d_k)

    Inside each head, we measure how strongly query i matches key j by taking their dot product (sum_c q[i, c] * k[j, c]). Swapping the last two axes of k_heads from (L_k, d_k) to (d_k, L_k) lets q_heads @ k_transposed compute all L_q * L_k dot products at once.

    Why divide by np.sqrt(d_k)? If the entries of q and k have mean 0 and variance 1, each product q_c * k_c has variance 1, and adding d_k independent products gives variance d_k (standard deviation sqrt(d_k)). Without scaling, larger d_k produces huge dot products that push softmax into extreme 0/1 saturation where gradients vanish. Dividing by sqrt(d_k) — using the per-head dimension d_k, not d_model — restores unit variance.

  5. Write a numerically stable masked softmax

    Turning each score row (L_k,) into non-negative weights requires handling three numerical hazards:

    1. Blocked keys must get exact 0.0 weight: setting disallowed scores to -np.inf before exponentiating makes np.exp(-np.inf) == 0.0. (Multiplying scores by 0 would fail because exp(0) = 1!)
    2. Large scores overflow np.exp: np.exp(710) overflows float64 to inf. Subtracting each row's maximum row_max from every score in that row multiplies top and bottom by exp(-row_max), leaving the probabilities identical while ensuring every exponent is <= 0.
    3. Fully masked rows must not produce NaN: if every key in a row is False, row_max is -inf, and -inf - (-inf) evaluates to NaN! Replacing non-finite row_max values with 0.0 keeps every entry at -inf, so exps becomes all 0.0. Then replacing zero row_sums with 1.0 turns 0.0 / 0.0 into 0.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
    
  6. Assemble the full multi-head attention pass

    Now every piece snaps together cleanly. When mask is 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 all num_heads heads without duplicating memory.

    After masked_softmax, attention_weights @ v_heads computes each query's weighted average of the value vectors, merge_heads concatenates all heads back to width d_model, and @ w_o applies 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()
    
  7. Trace Example 1 by hand

    In Example 1, batch = 1, num_heads = 2, d_model = 2 (d_k = 1, so sqrt(d_k) = 1.0), mask = None, and all four weight matrices are 2x2 identity 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.

  8. 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):

  1. Splitting along columns gives Head 0 (Q_0 = [[2], [0]], K_0 = [[1], [0]], V_0 = [[10], [20]]) and Head 1 (Q_1 = [[0], [1]], K_1 = [[2], [2]], V_1 = [[5], [15]]).
  2. In Head 0 (sqrt(d_k) = 1.0), query 0 gets scores [2.0, 0.0] and softmax weights [0.8808, 0.1192], blending V_0 into 0.8808 * 10 + 0.1192 * 20 = 11.1920, while query 1 gets equal scores [0.0, 0.0] and averages 10 and 20 to 15.0.
  3. In Head 1, both keys equal 2, so both queries assign [0.5, 0.5] weights and blend V_1 to 10.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). Projecting Q and the final output each multiply (b, L_q, d) by (d, d) in O(b * L_q * d^2) operations, while projecting K and V each take O(b * L_k * d^2). Computing all h heads' 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 cost O(b * h * L_q * L_k * d_k) = O(b * L_q * L_k * d) — notice that splitting d into h heads of width d / h keeps total arithmetic identical to a single d-wide head!
  • Space: O(b * h * L_q * L_k + b * (L_q + L_k) * d). Storing the projected Q, K, V, and merged outputs uses O(b * (L_q + L_k) * d) numbers, while materializing the (b, h, L_q, L_k) scores and attention_weights tensors uses O(b * h * L_q * L_k) memory. Using broadcasting (stretching a size-1 tensor axis across h heads virtually without copying data) avoids duplicating the boolean mask across heads.

Edge cases

  • Query row with every key masked ([False, ..., False]): guarding row_max against -inf and row_sums against 0.0 assigns 0.0 weight to every key, returning a clean all-zero output row instead of NaN.
  • Single key (L_k = 1): any unmasked query gives weight 1.0 to that sole key, returning value[:, 0] @ w_v @ w_o regardless of query.
  • Cross-attention (L_q != L_k): scores has rectangular shape (batch, h, L_q, L_k) and the output cleanly takes query length L_q.
  • Extreme head counts (num_heads = 1 or num_heads = d_model): both work through the exact same split_heads / merge_heads reshapes without special branches.
  • Large input magnitudes (e.g., 1000.0, scores ~7 * 10^5): subtracting safe_row_max caps every exponent at 0.0, preventing np.exp overflow.
  • Integer list inputs: np.asarray(..., dtype=float) converts integers up front so divisions and matrix products stay in floating point.
  • Invalid num_heads: raises ValueError immediately if d_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. Always reshape(batch, seq_len, num_heads, d_k) first, then transpose(0, 2, 1, 3).
  • Scaling by sqrt(d_model) instead of sqrt(d_k): invisible in 1-head unit tests (where d_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 to 1, not each key's weights over queries.
  • Zeroing masked scores (scores * mask) instead of setting -np.inf: exp(0.0) equals 1.0, so blocked keys still steal positive probability mass.
  • Using a finite mask constant like -1e9 on a fully masked row: if every key in a row gets -1e9, softmax gives every blocked key uniform weight 1 / L_k instead of 0.0.
  • Confusing x @ W with PyTorch's nn.Linear x @ 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 i only attends to positions 0..i and never peeks at future positions j > i) passes np.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) is True, 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) = NaN unless protected like masked_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_heads and v_heads tensors of all prior tokens, with shape (batch, h, t, d_k) after t steps). When step t + 1 arrives as (batch, 1, d_model), project only that single token into q_new, k_new, and v_new, append k_new and v_new along the sequence axis to reach length t + 1, and run attention between q_new (L_q = 1) and the cached t + 1 keys/values — cutting per-token work from O(t * d^2 + t^2 * d) down to O(d^2 + t * d).
  • 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? Although h heads of width d / h use the exact same parameter count (4 * d^2) and FLOPs as one d-wide head, a single head computes only one softmax weight vector per query (forcing one weighted sum to mix syntax, coreference, and semantics together), whereas h heads compute h independent softmax distributions across distinct feature subspaces at once. Multi-query attention (MQA) (retaining h query heads while sharing one key head and one value head across all of them) shrinks the KV cache by hx to relieve memory-bandwidth bottlenecks during decoding, while grouped-query attention (GQA) (dividing the h query heads into g groups 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: at L = 32,000, a single head's L * L matrix contains 1.024 * 10^9 floats (~4.1 GB in float32), so 16 heads consume ~65.5 GB per sequence for one layer's attention matrix — versus only ~131 MB for a (32,000, 1,024) activation tensor. You can eliminate this bottleneck exactly by processing queries in small blocks (chunk * L peak 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 full L * L matrix is never materialized in GPU HBM, reducing attention memory to O(L * d)), paired with bf16/fp16 precision and GQA or sliding-window attention where appropriate.

Follow-up questions

Similar questions

More ByteDance interview questions

All 160 ByteDance questions →