LLM Sampling Parameters: How Temperature, Top-P, and Top-K Control Creativity
Temperature, Top-P (nucleus sampling), and Top-K are stochastic hyper-parameters that calibrate the probability distribution over next-token logits, allowing developers to balance deterministic precision (for code and JSON) against creative divergence.
1.Logits, Softmax, and Temperature Scaling
2.Top-P (Nucleus Sampling) vs. Top-K Filtering
3.Production Parameter Presets for Different Use Cases
from openai import OpenAI
client = OpenAI(
base_url="https://api.apihundred.com/v1",
api_key="your_api100_key"
)
# For code generation, use temperature=0 for zero randomness
code_response = client.chat.completions.create(
model="claude-3-5-sonnet",
messages=[
{"role": "user", "content": "Write a regex that validates ISO-8601 UTC timestamps."}
],
temperature=0.0,
top_p=1.0
)
print("Deterministic Output:", code_response.choices[0].message.content)Frequently Asked Questions
Should I alter both temperature and top_p simultaneously?
It is standard engineering practice to tune either temperature or top_p, leaving the other at default (e.g. adjust temperature with top_p=1.0, or set temperature=1.0 and adjust top_p).
Does setting temperature=0 guarantee 100% identical outputs?
In theory yes, but GPU non-deterministic floating-point math across parallel threads can occasionally produce slight variations unless seed pinning and dedicated deterministic engines are enforced.
What happens if temperature is set above 1.5?
High temperatures flatten the probability curve so heavily that the model begins sampling nonsensical, out-of-context tokens and grammatical gibberish.

