Apply Temperature Scaling to 1D Logits

Basics
BasicsDecodingTemperatureOpenAIAnthropicGoogle

Problem

Implement temperature_softmax(logits, temperature=1.0) that scales raw 1D logits by 1 / temperature and returns the resulting numerically stable softmax probability distribution. Lower temperature (< 1) sharpens the peak; higher temperature (> 1) flattens probabilities toward uniform.

Why It Matters: Temperature is the primary creativity knob in every LLM API—low temperatures (0.0–0.2) stabilize factual Q&A and JSON output, while higher values (0.7–1.0) diversify brainstorming.

Function Signature

import numpy as np

def temperature_softmax(logits, temperature: float = 1.0) -> np.ndarray:
    """Return softmax(logits / temperature)."""

Sample Input & Output

Example 1: Sharpening With Low Temperature (T = 0.5)

Input:

logits = [2.0, 1.0, 0.0], temperature = 0.5

Expected Output:

array([0.866813, 0.117310, 0.015876])

Explanation: Dividing by 0.5 doubles logit gaps to [4.0, 2.0, 0.0], concentrating 86.7% mass on token 0.

Example 2: Flattening With High Temperature (T = 2.0)

Input:

logits = [2.0, 1.0, 0.0], temperature = 2.0

Expected Output:

array([0.50648039, 0.30719589, 0.18632372])

Explanation: Dividing by 2.0 halves logit gaps to [1.0, 0.5, 0.0], spreading mass more evenly.

Constraints & Edge Cases

  • temperature > 0.
  • Return a 1D float NumPy probability array.
  • temperature is guaranteed strictly positive (> 0).
  • Subtract np.max(z) after dividing by temperature to maintain numerical stability.

Constraints & Evaluation Criteria

  • `temperature > 0`.
  • Return a 1D float NumPy probability array.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
[2.0, 0.0], T=0.5
Expected Output / Criteria
softmax([4.0, 0.0])