Implement sparsemax

Why it matters Sparse attention and sparse routing papers use sparsemax to get exact zeros.

Sparsemax is like softmax but can output exact zeros: it is the Euclidean projection of the scores onto the probability simplex.

Write sparsemax(z) for a 1D array. Sort z descending into s, find the largest k with 1 + k * s_k > sum of the first k values of s (1-based k), set tau = (sum of first k - 1) / k, and return max(z - tau, 0).

Signaturedef sparsemax(z)

Example

sparsemax([2, 1, -1]) is [1, 0, 0]; sparsemax([0.5, 0.4]) is [0.55, 0.45].

Understand the idea

Softmax always gives every option some probability. Sparsemax also returns a probability vector, but it can set weak options to exactly zero. It works by finding one threshold tau, subtracting it from every score and clipping negatives to zero, with tau chosen so the survivors sum to 1. Worked example: z = [1.0, 0.8, 0.1]. Sorted s = [1.0, 0.8, 0.1] with prefix sums 1.0, 1.8, 1.9. Check k = 1: 1 + 1 * 1.0 = 2 > 1.0, yes. k = 2: 1 + 2 * 0.8 = 2.6 > 1.8, yes. k = 3: 1 + 3 * 0.1 = 1.3 > 1.9, no. So k = 2 and tau = (1.8 - 1) / 2 = 0.4. Output = max(z - 0.4, 0) = [0.6, 0.4, 0]. It sums to 1. Rule: sort descending, find the largest 1-based k with 1 + k * s_k > sum of the first k values, tau = (that sum - 1) / k, return max(z - tau, 0) in the original order. Used in: sparse attention, interpretable classifiers and some mixture-of-experts gates.

Shapes and data flow

z (n,) -> sort desc s (n,) -> cumsum cs (n,)
support size k -> tau scalar -> max(z - tau, 0) (n,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplesparsemax([2, 1, -1])
  • Sample 2: close scoressparsemax([0.5, 0.4])