v9.1.1
Menu

Temperature Sampler

easyFREEText Generation & AdvancedNLP 3: Advanced

Given a list of logits (raw scores) for vocabulary words and a temperature value, apply temperature scaling and compute the resulting probability distribution using softmax.

Temperature scaling divides each logit by the temperature before applying softmax: pi=ezi/T∑jezj/Tp_i = \frac{e^{z_i / T}}{\sum_j e^{z_j / T}}

Input: temperature_sample(pairs, T)

  • pairs: a list of (word, logit) tuples, e.g. [("cat", 2.0), ("dog", 1.0), ("fish", 0.5)]
  • T: the temperature (float, T>0T > 0)

Output: A list of strings, one per word, each formatted as "word probability", sorted by probability descending (ties: alphabetical). The probability is rounded to 4 decimal places and written as that rounded number, without padding trailing zeros (e.g. 0.5, 0.982, 0.6285).

Example

Input
cat:2.0,dog:1.0,fish:0.5
1.0
Output
cat 0.6285
dog 0.2312
fish 0.1402
Reasoning
  • Input: pairs holds each word with its logit, a raw unnormalised score: cat 2.02.0, dog 1.01.0, fish 0.50.5. T =1.0= 1.0 is the temperature that every logit is divided by.
  • Scale: with T=1T = 1 the scaled logits stay 2.0, 1.0, 0.52.0,\ 1.0,\ 0.5.
  • Exponentiate: e2.0≈7.3891e^{2.0} \approx 7.3891, e1.0≈2.7183e^{1.0} \approx 2.7183, e0.5≈1.6487e^{0.5} \approx 1.6487, and their total is ≈11.7561\approx 11.7561.
  • Normalise: pcat=7.3891/11.7561≈0.6285p_{cat} = 7.3891 / 11.7561 \approx 0.6285, pdog≈0.2312p_{dog} \approx 0.2312, pfish≈0.1402p_{fish} \approx 0.1402. The three sum to 11, and the words are listed from most to least likely.
  • Notice: TT controls sharpness. At T=2T = 2 the scaled logits become 1.0, 0.5, 0.251.0,\ 0.5,\ 0.25 and the distribution flattens to roughly 0.481, 0.2918, 0.22720.481,\ 0.2918,\ 0.2272; at T=0.5T = 0.5 the scaled logits become 4.0, 2.0, 1.04.0,\ 2.0,\ 1.0 and the mass shifts sharply toward cat, to roughly 0.8438, 0.1142, 0.0420.8438,\ 0.1142,\ 0.042.

Constraints

  • Temperature T > 0
  • Apply softmax after dividing logits by T
  • Round probabilities to 4 decimal places
  • Output sorted by probability descending (ties: alphabetical)

Learn this in

More from NLP 3: Advanced

solution.py

Test results

Sign in to run your code against the test cases.