Merge and project

Merge heads

×

Concatenate the 64 heads into 4,096 features.

[B, 64, T, 64][B,\,64,\,T,\,64]
→  [B, T, 64, 64]\to\;[B,\,T,\,64,\,64]
→  [B, T, 4096]\to\;[B,\,T,\,4096]
in
HH [B batch, 64 heads, T positions, 64 d_h]
out
oo [B batch, T positions, 4096 heads × d_h]
Explanation

Heads are concatenated in order: head ii fills features 64i,…,64i+63{64i},\dots,{64i+63}.

Sources

In codeattn.reshape(n_tokens, -1) · 173

Open pinned code ↗

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)