Query–key products
×Score every key for every query within each head.
- in
- [B batch, 64 heads, T positions, 64 d_h] [B batch, 64 heads, T positions, 64 d_h]
- out
- [B batch, 64 heads, T queries, T keys]
Sources
In codetorch.einsum("qhmd,khmd->hmqk", Q, K) · 166
Direct evidence
The attention arithmetic: keys and values repeated to the query heads of their group; a causal mask and, for a window, every key 128 or more positions before the query masked too; scores scaled; each head’s sink appended to every row as one more column; softmax; the sink’s column dropped; values mixed by the weights; heads joined.
model.py 153–173 ↗ · openai/gpt-oss @ 5681a6b65526
Excerpt
def sdpa(Q, K, V, S, sm_scale, sliding_window=0):
# sliding_window == 0 means no sliding window
n_tokens, n_heads, q_mult, d_head = Q.shape
assert K.shape == (n_tokens, n_heads, d_head)
assert V.shape == (n_tokens, n_heads, d_head)
K = K[:, :, None, :].expand(-1, -1, q_mult, -1)
V = V[:, :, None, :].expand(-1, -1, q_mult, -1)
S = S.reshape(n_heads, q_mult, 1, 1).expand(-1, -1, n_tokens, -1)
mask = torch.triu(Q.new_full((n_tokens, n_tokens), -float("inf")), diagonal=1)
if sliding_window > 0:
mask += torch.tril(
mask.new_full((n_tokens, n_tokens), -float("inf")), diagonal=-sliding_window
)
QK = torch.einsum("qhmd,khmd->hmqk", Q, K)
QK *= sm_scale
QK += mask[None, None, :, :]
QK = torch.cat([QK, S], dim=-1)
W = torch.softmax(QK, dim=-1)
W = W[..., :-1]
attn = torch.einsum("hmqk,khmd->qhmd", W, V)
return attn.reshape(n_tokens, -1)