Mid-level interview questionAsked at Applied Intuition · interview write-up
Implement sinusoidal or learned positional encodings in PyTorch, explain the equations and tensor shapes, and say what you'd see if positional information were missing.
Model answer
import math
import torch
def sinusoidal_pe(T, d):
pos = torch.arange(T).float()[:, None] # (T, 1)
i = torch.arange(0, d, 2).float() # (d/2,)
freq = torch.exp(-math.log(10000.0) * i / d)
pe = torch.zeros(T, d) # d even
pe[:, 0::2] = torch.sin(pos * freq)
pe[:, 1::2] = torch.cos(pos * freq)
return pe
# x: (B, T, d); x = x + sinusoidal_pe(T, d).to(x)
# learned: x = x + nn.Embedding(max_len, d)(pos_ids)
Dimension pair 2i gets sin and cos of pos divided by 10000 to the power 2i/d. A learned table is simpler but can't go past max_len.
Without positions, attention is permutation-equivariant: an encoder sees a bag of words, so shuffled inputs give shuffled outputs and order-dependent tasks fail. A causal decoder recovers some position from its mask.
Practise the rest
20 Attention questions, 492 in all, each with a model answer. Free.
More from Applied Intuition interview questions.
More Attention interview questions
- Walk me through scaled dot-product attention. What are queries, keys and values, and why divide by the square root of d?
- What's inside one transformer block, and where do most of its parameters sit?
- What does the causal mask do, and what does it imply for a decoder model reading 'The ladder did not reach the window because it was too short'?
- A teammate shows you a GPT-2 head that puts most of a pronoun's attention on the right noun and concludes that the head resolves pronouns. How do you respond?
- Product wants to double the context you support, from 1,000 to 2,000 tokens. From the attention side, what gets more expensive, and what families of fixes would you weigh?
- Implement batched multi-head self-attention with a causal mask.