Mask illegal moves out of a policy head's softmax

Why it matters Chess, Go and card-game agents, and constrained decoding in LLMs, all apply a legal-action mask before sampling.

A game-playing network outputs a logit for every possible move, but in each position only some moves are legal. Illegal moves must get exactly zero probability.

Write masked_policy(logits, legal). logits is a (B, A) float array, legal a (B, A) boolean array. Set illegal logits to minus infinity and take a stable softmax per row. If a row has no legal move at all, return a row of zeros for it (never NaN). Return a (B, A) numpy array.

Signaturedef masked_policy(logits, legal)

Example

masked_policy([[1.0, 2.0, 3.0]], [[True, False, True]]) gives array([[0.1192, 0., 0.8808]]).

Understand the idea

A policy network for a board game has a fixed output size, one logit per move it could ever make. In a given position many of those moves are illegal. If we sample from the raw softmax, the agent wastes probability on impossible moves or even plays them. The fix is to remove illegal moves before the softmax by setting their logits to minus infinity, which turns into probability 0.

Example: logits [1, 2, 3] with move 1 illegal. Only 1 and 3 remain: e^1 = 2.72 and e^3 = 20.09, so the policy is [0.119, 0, 0.881].

Rule: p = softmax(where(legal, logits, -inf)), using the max over legal logits for stability.

The same idea powers constrained decoding in LLMs (JSON mode, grammar sampling), where tokens that would break the format are masked out at each step.

Shapes and data flow

logits, legal: (B, A) -> probs: (B, A), each row sums to 1 or is all zeros
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplemasked_policy([[1.0, 2.0, 3.0]], [[True, False, True]])
  • Sample 2: no legalmasked_policy([[0.5, 0.5], [1.0, -1.0]], [[False, False], [False, True]])
  • Test 3: huge logitsmasked_policy([[1000.0, 999.0, 5000.0]], [[True, True, False]])
  • Test 4: all legalmasked_policy([[0.0, 0.0, 0.0, 0.0]], [[True, True, True, True]])