Build a Pre-Norm Transformer Layer with a Gated SiLU Feed-Forward
Machine LearningModel answerLast 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_dimamongnum_headsheads. - 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 tohidden_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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A Transformer layer is two sublayers, each wrapped with normalization and a residual connection. I would use the pre-norm arrangement:
x = x + Attn(LN(x), mask)
x = x + FFN(LN(x))
Pre-norm leaves the residual stream untouched, so gradients flow through the identity path. Deep stacks therefore train stably without delicate learning-rate warmup. Post-norm, LN(x + Sublayer(x)), is the layout from the original paper. It is acceptable, but it is harder to train when deep.
Shapes
Let B be batch size, T sequence length, D hidden size, H heads, d_h = D/H, and F the feed-forward inner width.
| Step | Shape |
|---|---|
| input | (B, T, D) |
| fused QKV projection | (B, T, 3D), viewed as (B, T, 3, H, d_h) |
| q, k, v after permute | (B, H, T, d_h) each |
scores q @ kᵀ | (B, H, T, T) |
softmax(scores) @ v | (B, H, T, d_h) |
| after transpose and reshape | (B, T, D) |
| gate and value projection | (B, T, 2F), split into two (B, T, F) |
| FFN output | (B, T, D) |
Masking
Use a boolean mask where True means "this key may be attended to". It must broadcast to (B, H, T, T):
- Causal: shape
(T, T), e.g.torch.tril(torch.ones(T, T, dtype=torch.bool)). - Padding: shape
(B, T)reshaped to(B, 1, 1, T), so every query ignores padded keys. - Both:
causal[None, None] & pad[:, None, None, :].
Fill disallowed scores with the dtype's most negative finite value (finfo.min) before the softmax. Using -inf is risky: a row that is fully masked (e.g. a padding query) becomes all -inf, the softmax returns NaN, and that propagates through the network. As an extra guard, zero the masked weights after the softmax so fully masked rows yield zero output rather than a uniform average.
Code
import math
import torch
import torch.nn as nn
class MultiHeadSelfAttention(nn.Module):
def __init__(self, hidden_dim, num_heads, dropout=0.0):
super().__init__()
if hidden_dim % num_heads != 0:
raise ValueError("hidden_dim must be divisible by num_heads")
self.h = num_heads
self.dh = hidden_dim // num_heads
self.qkv = nn.Linear(hidden_dim, 3 * hidden_dim)
self.out = nn.Linear(hidden_dim, hidden_dim)
self.drop = nn.Dropout(dropout)
def forward(self, x, mask=None):
B, T, D = x.shape
qkv = self.qkv(x).view(B, T, 3, self.h, self.dh)
q, k, v = qkv.permute(2, 0, 3, 1, 4) # (B, H, T, dh)
scores = q @ k.transpose(-2, -1) / math.sqrt(self.dh)
if mask is not None:
mask = mask.to(torch.bool)
if mask.dim() == 2:
mask = mask[None, None]
elif mask.dim() == 3:
mask = mask[:, None]
scores = scores.masked_fill(~mask, torch.finfo(scores.dtype).min)
attn = torch.softmax(scores, dim=-1)
if mask is not None:
attn = attn.masked_fill(~mask, 0.0)
attn = self.drop(attn)
out = (attn @ v).transpose(1, 2).reshape(B, T, D)
return self.out(out)
class SwiGLUFeedForward(nn.Module):
def __init__(self, hidden_dim, ffn_dim=None, dropout=0.0):
super().__init__()
if ffn_dim is None:
ffn_dim = 64 * math.ceil(int(8 * hidden_dim / 3) / 64)
self.gate_value = nn.Linear(hidden_dim, 2 * ffn_dim, bias=False)
self.out = nn.Linear(ffn_dim, hidden_dim, bias=False)
self.drop = nn.Dropout(dropout)
def forward(self, x):
gate, value = self.gate_value(x).chunk(2, dim=-1)
return self.drop(self.out(gate * torch.sigmoid(gate) * value))
class TransformerBlock(nn.Module):
def __init__(self, hidden_dim, num_heads, ffn_dim=None, dropout=0.0, eps=1e-5):
super().__init__()
self.norm1 = nn.LayerNorm(hidden_dim, eps=eps)
self.attn = MultiHeadSelfAttention(hidden_dim, num_heads, dropout)
self.norm2 = nn.LayerNorm(hidden_dim, eps=eps)
self.ffn = SwiGLUFeedForward(hidden_dim, ffn_dim, dropout)
self.drop = nn.Dropout(dropout)
def forward(self, x, mask=None):
x = x + self.drop(self.attn(self.norm1(x), mask))
x = x + self.ffn(self.norm2(x))
return x
A quick sanity check: with a causal mask, perturbing the last token must leave all earlier output positions unchanged. The output shape must equal the input shape.
Why the design choices matter
- Scaling by 1/sqrt(d_h): if q and k entries have unit variance, their dot product has variance
d_h. Without scaling, logits grow with head size, the softmax saturates and gradients vanish. - Multiple heads: each head works in its own subspace and can learn a different pattern, while total compute stays comparable to one head of width
D. - SwiGLU: a smooth, input-dependent gate multiplies the value path. It tends to outperform ReLU or GELU feed-forwards at equal parameter count. It has three weight matrices (gate, value, output) instead of two, so choose
Fnear8D/3to match the parameter count of a standard4Dfeed-forward. Rounding to a multiple of 64 helps hardware efficiency. - Fused projections: one matmul for Q, K, V and one for gate and value improve GPU utilization over several small matmuls.
Complexity
For one attention layer:
- Time: the QKV and output projections cost
O(B·T·D²). The score and weighted-sum matmuls costO(B·H·T²·d_h) = O(B·T²·D). The total isO(B·T·D² + B·T²·D), so quadratic in sequence length onceTexceeds aboutD. - Memory: the score matrix is
O(B·H·T²), the dominant activation for long sequences. Activations for projections areO(B·T·D). - Fused kernels such as FlashAttention compute exact attention without materializing the
T×Tmatrix, reducing extra memory toO(B·T·D)while time stays quadratic.
The feed-forward costs O(B·T·D·F) time, linear in T.
Common mistakes
- Reshaping
(B, H, T, d_h)straight to(B, T, D)withouttranspose(1, 2). It runs without error but mixes tokens across heads. - Using
-inffor masking and gettingNaNfrom fully masked rows. - Applying the mask after the softmax without renormalizing, or forgetting the
(B, 1, 1, T)reshape for padding masks. - Forgetting the
1/sqrt(d_h)scale, or usingDinstead ofd_h. - Checking
hidden_dim % num_headstoo late, or not at all. - Mixing pre-norm and post-norm unintentionally, for example normalizing the residual output and also the sublayer input.