Implement a Transformer Block with SwiGLU
GoogleMachine Learning Engineer · Technical ScreenLast updated
This question evaluates implementation and reasoning skills for Transformer internals, testing competency in multi-head self-attention, SwiGLU gated feed-forward layers, residual connections, and layer normalization within the Machine Learning / deep learning domain.
Implement a Transformer-style neural network block in Python using either NumPy or PyTorch.
Your implementation should include:
- Multi-head self-attention
- Input tensor shape:
(batch_size, sequence_length, hidden_dim). - Split the hidden dimension into
num_headsattention heads. - Compute scaled dot-product attention.
- Support an optional attention mask.
- Concatenate heads and apply an output projection.
- SwiGLU feed-forward network
- Implement a gated feed-forward layer using the SwiGLU formulation:
SwiGLU(x) = Swish(xW_gate) * (xW_value), followed by an output projection. - The gate and value projections should be computed in parallel.
- Use
Swish(z) = z * sigmoid(z).
- Transformer block structure
- Include residual connections.
- Include layer normalization.
- Return an output tensor with the same shape as the input.
Be prepared to explain tensor shapes, masking behavior, and the time and memory complexity of multi-head attention.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.