4 hidden checks
Implement the attention function at the heart of every transformer.
softmax(x, axis=-1): numerically stable softmax along an axis. It must handle-np.infentries (they get weight 0).attention(Q, K, V, causal=False): return(out, weights)whereweights = softmax(Q @ K.T / sqrt(d_k))andout = weights @ V. Withcausal=True, set scores above the diagonal to-np.inffirst (usenp.triu(..., k=1)). AssumeQandKhave the same number of rows when causal.
- softmax is stable and handles -infnot run
- attention matches the formulanot run
- causal attention never looks aheadnot run
- changing a future token doesn't change earlier outputsnot run