InferenceAI

Enter at least two characters to search.

Start free

Stable Masked Softmax

hardAttention35 min50 XP

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.

INTERACTIVE ENGINEERING · TEACHING MODEL

Causal attention

Inspect query-key scores, masking and normalized attention weights.

Rows: queries · columns: keys

Key 1
100.0%
Key 2
0.0%
Key 3
0.0%
Key 4
0.0%

Synthetic unscaled scores are [1, 2, 4, 0] × √dₖ. The mask is applied before normalization.

Change the experiment

Core calculation
scores = Q @ K.T / sqrt(d_k)
scores[future_positions] = -inf
weights = softmax(scores)
output = weights @ V
Try 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.

Open the full explainer and practice links

Examples

EXAMPLE WALKTHROUGHlarge logits

A guided view of the published example, not a trace of your code.

INPUT[[1000,1000,5],[true,true,false]]
TASKmasked_softmax()
EXPECTED OUTPUT[0.5,0.5,0]

Start with the input values shown in this example.

Example 1 of 2

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.

Topics

PythonAttentionNumerical Stability