Ever wondered why asking the same question to a large language model (LLM) can produce entirely different responses each time? The secret lies not in randomness, but in two key concepts: temperature and sampling.
LLMs work by predicting the next token (word or subword) based on a probability distribution over all possible tokens. The model assigns a probability to each token, and the next token is chosen according to that distribution. However, how exactly that choice is made dramatically affects output variability.
Greedy Decoding: The Simplest Approach
Greedy decoding always selects the token with the highest probability. This yields deterministic, often repetitive results. While it might work for simple tasks, it fails in creative or open-ended scenarios because it eliminates diversity. Greedy decoding is like always ordering the most popular dish at a restaurant—safe, but boring.
Sampling: Adding Randomness for Creativity
Sampling introduces randomness by drawing from the probability distribution rather than always picking the top token. Even tokens with low probability have a chance to be selected. This leads to varied, more natural outputs. A helpful analogy: imagine a restaurant where you pick a dish based on its popularity, but you might occasionally try something unique. Sampling works similarly, enabling LLMs to generate creative and diverse responses.
Temperature: Controlling Randomness
Temperature adjusts the sharpness of the probability distribution. A low temperature (e.g., 0.1) makes the distribution more peaked, favoring high-probability tokens—producing focused, conservative outputs. A high temperature (e.g., 1.5) flattens the distribution, giving low-probability tokens a better chance—resulting in more random, creative, but potentially incoherent text. Temperature essentially tunes the "creativity knob" of the model.
Why It Matters
Understanding temperature and sampling is crucial for anyone working with LLMs. For factual tasks, low temperature with greedy decoding minimizes mistakes. For storytelling or brainstorming, higher temperature with sampling unlocks creative possibilities. By mastering these parameters, users can guide LLMs to produce exactly the kind of output they need—whether predictable or surprising.
This episode of Tab 47 by upGrad dives deeper into next-token prediction, probability distributions, and practical examples of how temperature and sampling shape LLM behavior. Check out the full video for a detailed breakdown.