KatInterview

Build a Pre-Norm Transformer Layer with a Gated SiLU Feed-Forward

Machine LearningModel answer
MediumModel answerMachine Learningtransformermulti-head-attentionswiglu

Last updated

Write a Transformer layer with masked multi-head self-attention, a gated Swish feed-forward network, residual paths and layer norm, and explain its shapes, masking and complexity.

Implement a single Transformer layer in Python, using either PyTorch or NumPy.

Attention sublayer

  • The input has shape (batch_size, sequence_length, hidden_dim).
  • Divide hidden_dim among num_heads heads.
  • Compute scaled dot-product attention in each head.
  • Accept an optional attention mask.
  • Join the heads back together and apply a final linear projection.

Gated feed-forward sublayer

  • Use the SwiGLU form: SwiGLU(x) = Swish(x W_gate) * (x W_value), followed by a projection back to hidden_dim.
  • Compute the gate and value projections in parallel, not as two separate sequential steps.
  • Define Swish(z) = z * sigmoid(z).

Layer structure

  • Add residual connections around both sublayers.
  • Apply layer normalization.
  • The output must have the same shape as the input.

What to be ready to discuss

  • The tensor shape at each step.
  • How the mask is applied and how it broadcasts, including causal and padding masks.
  • The time and memory complexity of multi-head attention.

Hints

Hint 1

Project once into a tensor of width 3*D for queries, keys and values, then reshape to (B, T, 3, H, d_h) and permute so each of q, k, v is (B, H, T, d_h). Divide scores by sqrt(d_h).

Hint 2

Apply the mask to the scores before the softmax by filling disallowed positions with a very large negative number. Think about what happens to a row where every position is masked, and make sure it cannot produce NaN.

Hint 3

After attention, the head axis must be moved next to the feature axis (transpose(1, 2)) before reshaping to (B, T, D). For the feed-forward, one linear layer can output 2F features that you split into gate and value halves. Decide between pre-norm and post-norm and be able to justify it.