Measure how focused each attention row is with entropy
When you inspect a trained model, a common check is how spread out each query's attention is. Entropy near 0 means a head looks at one token; entropy near log(n) means it spreads evenly over n tokens.
Write attention_entropy(weights). weights is an array of shape (..., n) whose last axis holds probabilities that sum to 1 (rows of an attention matrix, possibly with masked zeros). Return an array of shape (...) with the entropy of each row in nats: -sum p * ln(p), where terms with p = 0 count as 0.
def attention_entropy(weights)Example
attention_entropy([[1.0, 0.0], [0.5, 0.5]]) gives [0.0, 0.693147] (the second value is ln 2).
Understand the idea
Entropy tells you how spread out a probability row is. If an attention row puts all its weight on one token, entropy is 0. If it spreads evenly over n tokens, entropy is ln(n), the largest possible. It is a quick way to see whether a head is focused or diffuse. Worked example: row [0.5, 0.25, 0.25]. Terms: 0.5 * ln 0.5 = -0.3466, and 0.25 * ln 0.25 = -0.3466 twice. Entropy = 0.3466 + 0.3466 + 0.3466 = 1.0397 nats. Row [1, 0] gives 0, and [0.5, 0.5] gives ln 2 = 0.6931. Rule: H = -sum over the last axis of p * ln(p), with 0 * ln 0 treated as 0, so masked keys add nothing and never produce nan. Use natural log, not log base 2, because the answer is in nats. The output drops the last axis, so an input of shape (heads, queries, keys) gives (heads, queries). Used in interpretability work to find heads that attend to a single token versus heads that average broadly.