← Questions

Implement a transformer block with SwiGLU

0
GoogleCodingLast asked Dec 2025

A coding interview question asked in Google's first round (coding), last asked Dec 2025. It tests transformers, attention and pytorch.

Write one transformer block from scratch in NumPy (or PyTorch tensors without the built-in attention or feed-forward modules). The input x has shape (batch, seq_len, hidden); the output has the same shape. The block is pre-norm:

y   = x + MultiHeadSelfAttention(LN1(x))
out = y + SwiGLUFeedForward(LN2(y))

Be ready to state the tensor shape after every step, how the mask works, and what attention costs in time and memory.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • transformer_block(x, num_heads, w_q, w_k, w_v, w_o, w_gate, w_value, w_ffn_out, gamma1, beta1, gamma2, beta2, mask=None) -> array — no biases, no dropout.
  • w_q, w_k, w_v, w_o are (hidden, hidden). w_gate and w_value are (hidden, ffn); w_ffn_out is (ffn, hidden).
  • Attention: project to Q, K, V, split hidden evenly into num_heads heads, compute softmax(Q K^T / sqrt(head_dim)) per head, apply the optional (seq_len, seq_len) mask before the softmax (0 = blocked), weight V, concatenate the heads and multiply by w_o.
  • SwiGLU: gate = h @ w_gate, value = h @ w_value (both from the same normalised input), hidden = gate * sigmoid(gate) * value, output hidden @ w_ffn_out.
  • Layer norm over the last axis only: (t - mean) / sqrt(var) * gamma + beta. Leave out epsilon so results are exact; every token has non-zero variance.

Example

One sequence of two tokens, hidden = 2, one head, all four attention weights the identity, all three feed-forward weights zero, gamma = [1, 1], beta = [0, 0]:

x = [[[1, 0], [0, 1]]]
mask = None          ->  [[[1.888386, -0.888386], [-0.888386, 1.888386]]]
mask = [[1, 0],
        [1, 1]]      ->  [[[2.0, -1.0], [-0.888386, 1.888386]]]

LN turns the tokens into [1, -1] and [-1, 1]. Each attends mostly to itself (score 2/sqrt(2) against -2/sqrt(2)). With the mask, token 0 sees only itself and adds exactly [1, -1]. The zero feed-forward adds nothing.

Constraints

  • 1 <= batch <= 10, 1 <= seq_len <= 30, 1 <= hidden <= 64, hidden % num_heads == 0.
  • If a mask is given, every query position has at least one unmasked key.

Clarifying questions

  • Pre-norm or post-norm? Is there an epsilon in the layer norm?
  • Is the mask causal, padding, or arbitrary? Which value means blocked?
  • Do the projections have biases? Is there dropout?
  • NumPy or PyTorch, and will the output be compared to a tolerance?

What a strong answer covers

  • Reshape (B, T, D) to (B, T, H, D/H) and transpose to (B, H, T, D/H) so every head runs in one batched matmul; undo it before w_o.
  • A numerically stable softmax (subtract the row max) and masking with a large negative number before it.
  • SwiGLU as gate times value: why the gate helps, and why ffn is often set near 8/3 * hidden to keep parameters equal to a 4x GELU MLP.
  • Cost: O(B · H · T² · d) time and O(B · H · T²) memory for the score matrix; the projections are O(B · T · D²).
  • Shape checks and a tiny hand-computed test like the example.

Follow-ups

  • Turn the mask into a causal mask and add a KV cache for decoding one token at a time.
  • Swap layer norm for RMSNorm. What changes?
  • How would you avoid materialising the T x T score matrix for long sequences?

Where it's asked

  • Google · First round: coding · Last asked Dec 202545 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI

What it tests

transformers · attention · pytorch

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding