Stable Masked Softmax
Implement masked_softmax(scores, allowed). scores is a list of numeric attention logits and allowed is an equally long list of booleans. Return probabilities rounded to six decimals. Masked positions must be exactly 0.0; unmasked probabilities sum to one before rounding. If no position is allowed, return zeros. Use only Python's standard library. Subtract the maximum allowed score before exponentiating so large logits do not overflow.
Explore the underlying concept with illustrative inputs. This experiment is separate from the problem’s test cases.
Causal attention
Inspect query-key scores, masking and normalized attention weights.
Rows: queries · columns: keys
Synthetic unscaled scores are [1, 2, 4, 0] × √dₖ. The mask is applied before normalization.
Change the experiment
scores = Q @ K.T / sqrt(d_k)
scores[future_positions] = -inf
weights = softmax(scores)
output = weights @ VTry it yourself
Select the last query, increase the key dimension and disable scaling. Watch the distribution sharpen.
Query 1 attends to 1 allowed positions. Future weights are zero.
Apply the causal mask before softmax. Scaling controls score magnitude; masked positions retain exactly zero weight.
Playback pauses in hidden tabs and offscreen. With reduced motion enabled, use the timeline or Next step.Examples
A guided view of the published example, not a trace of your code.
[[1000,1000,5],[true,true,false]][0.5,0.5,0]Start with the input values shown in this example.
Input: scores = [1000,1000,5], allowed = [true,true,false]
Output: [0.5,0.5,0]
Explanation: large logits
Input: scores = [1,999,1], allowed = [true,false,true]
Output: [0.5,0,0.5]
Explanation: masked maximum
Hint 1
Find the maximum among allowed positions only.
Hint 2
Never exponentiate a masked score.