np.swapaxes(k, -1, -2) trades only the last two axes, so each key becomes a column and the batch and head axes stay in front. @ multiplies over the last two axes and repeats for every axis in front. So q times that flip gives the scores as batch, heads, queries, keys, (2, 4, 3, 5), for one sequence or a whole (batch, heads) stack, with no Python loop.
Expression
Shape
What moved
k
(2, 4, 5, 8)
batch, heads, keys, d
k.swapaxes(-1, -2)
(2, 4, 8, 5)
only the last two trade places
k.T
(8, 5, 4, 2)
every axis reversed
k.T reverses every axis, so it only works on a plain 2-D matrix. The name swapaxes is not the point. Any call that swaps the last two axes works, for example np.moveaxis(k, -1, -2).
In the editor, write scores(q, k) for any number of leading axes. The editor prints the shape for a batch of 2 with 4 heads, which should be (2, 4, 3, 5).
Pick an answer above to see the rest
Instructions
1
Write scores(q, k): entry [i, j] is query i dotted with key j. No scaling yet.
2
It must work with batch and head axes in front, so swap only the last two axes of k.