Skip to content

← JAX Stochasticity step 8 of 25

Easy Primitives

Decoding Temperature

Jump to the task

Why this matters

Logits are scores before normalization. Temperature changes the gaps between these scores before softmax turns them into probabilities.

For positive temperature T, calculate softmax(logits / T). A smaller temperature concentrates probability on the highest scores. A larger temperature makes the distribution more uniform. At T = 1, you get the original softmax distribution.

This changes sampling probabilities, not the model's knowledge or factual reliability. It does not guarantee creative or coherent text.

Worked mini-example

import jax
import jax.numpy as jnp

logits = jnp.array([1.0, 2.0, 3.0])
baseline = jax.nn.softmax(logits)        # approximately [0.090, 0.245, 0.665]
sharper = jax.nn.softmax(logits / 0.5)   # approximately [0.016, 0.117, 0.867]
flatter = jax.nn.softmax(logits / 2.0)   # approximately [0.186, 0.307, 0.506]

Index two remains the most likely choice. Temperature changes how often sampling selects other indices; it does not select an index itself.

Common pitfalls

  • Dividing probabilities by T after softmax is not temperature scaling. Their sum becomes 1 / T; renormalizing that vector simply recovers the original probabilities.
  • From exact positive probabilities, raising each to 1 / T and renormalizing is mathematically equivalent. Working from logits is usually preferable because tiny probabilities may already have rounded to zero.
  • Zero temperature is outside this formula. Use argmax for greedy selection. As positive temperature approaches zero, equal maximum logits still share probability.
  • Positive scaling preserves score order mathematically. Equal logits stay equal; uniform logits stay uniform.
  • Use the stable softmax implementation rather than directly exponentiating large scores. Extremely small temperatures can still overflow the preceding division.

Problem

Implement temperature_softmax(logits, temperature) as jax.nn.softmax(logits / temperature).

logits is a nonempty one-dimensional float32 array of finite scores. temperature is a finite positive scalar; test inputs keep the scaled scores finite. Return a float32 array with the same shape, summing to one within floating-point tolerance.

For equal scores [0, 0], return [0.5, 0.5] at any valid temperature. This function returns probabilities, not a sample.