Junior interview questionAsked at Amazon · interview write-up
Using only plain Python loops, implement a numerically stable sigmoid, a stable softmax and single-head scaled dot-product attention.
Model answer
import math
def sigmoid(x):
if x >= 0:
return 1 / (1 + math.exp(-x))
e = math.exp(x) # x is negative: no overflow
return e / (1 + e)
def softmax(xs):
m = max(xs) # shift so the largest exp is 1
es = [math.exp(x - m) for x in xs]
s = sum(es)
return [e / s for e in es]
def attention(Q, K, V):
d = len(Q[0])
out = []
for q in Q:
scores = []
for k in K:
dot = 0.0
for a, b in zip(q, k):
dot += a * b
scores.append(dot / math.sqrt(d))
w = softmax(scores)
row = [0.0] * len(V[0])
for wi, v in zip(w, V):
for j in range(len(v)):
row[j] += wi * v[j]
out.append(row)
return out
The trap is overflow: exp of a large number blows up. Branch sigmoid on the sign, and subtract the max before softmax, which leaves the result unchanged. Attention is then dot products, scaled by √d, a softmax per query, and a weighted sum of values.
Practise the rest
20 Attention questions, 492 in all, each with a model answer. Free.
More from Amazon 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.