19/25
Part 4 of 6 · A stable softmaxLearn

The softmax runs over the keys, the last axis

One choice is left: which axis the softmax runs over.

# 2 queries, 3 keys
s = np.array([[1.0, 2.0, 3.0],
              [1.0, 1.0, 1.0]])
print(softmax(s, axis=-1).sum(axis=-1))
print(softmax(s, axis=-2).sum(axis=-1).round(2))
[1. 1.]
[2.11 0.89]

Both lines run. Only the first gives each query weights that sum to 1.

Scores: a row for each query, a column for each key
scores (2, 3)
k1k2k3q11.02.03.0q21.01.01.0

Axis -1 runs along a row: one query's weights over the keys. Right. Axis -2 runs down a column: one key's weights over the queries. Wrong, and no error.

The scores are (T_q, T_k), one row per query. Each query needs its weights over the keys to sum to 1, so the softmax runs over the last axis, the keys.

Run it over axis -2 and each key's weights over the queries sum to 1 instead. The shapes still line up, nothing errors, and every output is wrong. Only a test that checks the actual numbers catches it. That's why interviewers like it.