1D Softmax Probabilities From Raw Logits

Basics
BasicsDecodingSoftmaxOpenAIAnthropicGoogle

Problem

Implement softmax_1d(logits) converting a 1D list or array of raw logits zz into a numerically stable probability distribution pi=ezi−max⁡(z)∑jezj−max⁡(z)p_i = \frac{e^{z_i - \max(z)}}{\sum_j e^{z_j - \max(z)}} summing to 1.0.

Why It Matters: Softmax turns raw LLM vocabulary logits into sampling probabilities—and subtracting max(z) is the classic numerical-stability trick that prevents exp(1000) -> inf overflow.

Function Signature

import numpy as np

def softmax_1d(logits) -> np.ndarray:
    """Convert 1D logits into probabilities summing to 1."""

Sample Input & Output

Example 1: Equal Logits

Input:

logits = [1.0, 1.0, 1.0]

Expected Output:

array([0.33333333, 0.33333333, 0.33333333])

Explanation: Identical logits produce a uniform probability distribution [1/3, 1/3, 1/3].

Example 2: Large Logits (Overflow Stability Check)

Input:

logits = [1000.0, 1000.0, 998.0]

Expected Output:

array([0.46831053, 0.46831053, 0.06337894])

Explanation: Subtracting max(z) = 1000.0 shifts logits to [0.0, 0.0, -2.0], avoiding inf / inf = NaN.

Constraints & Edge Cases

  • Return a 1D float NumPy array summing to 1.0.
  • Always subtract np.max(z) before calling np.exp.
  • Returned np.ndarray entries must be non-negative and sum to 1.0.

Constraints & Evaluation Criteria

  • Return a 1D float NumPy array summing to `1.0`.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
[1.0, 1.0, 1.0]
Expected Output / Criteria
[0.3333, 0.3333, 0.3333]