At every step, the model gives probabilities for every possible next token. But which one should it actually pick? That choice is called decoding, and a few settings control it.
Greedy decoding always picks the most likely token. It's steady, but can be boring, and repetitive. Sampling picks randomly, using the probabilities, so likely tokens win more often. Temperature changes how random sampling is. Low is careful. High is wild. And top p only samples from the most likely tokens, that together make up, for example, ninety percent.
We sample from the same start, three times, with three temperatures. Set seed makes the random choices repeatable. We only decode the new tokens, by slicing off the input. Run it. At zero point two, the text is sensible. At one, it's more surprising. At one point eight, it falls apart.
app.pypython
from transformers import AutoTokenizer, AutoModelForCausalLM, set_seedname = "HuggingFaceTB/SmolLM2-135M"tok = AutoTokenizer.from_pretrained(name)model = AutoModelForCausalLM.from_pretrained(name)inputs = tok("My favourite kind of book is", return_tensors="pt")for temp in [0.2, 1.0, 1.8]: set_seed(1) out = model.generate(**inputs, max_new_tokens=10, do_sample=True, temperature=temp) new = out[0][inputs["input_ids"].shape[1]:] print(f"temperature {temp}: {tok.decode(new, skip_special_tokens=True)!r}")
Output
temperature 0.2: ' the one that I read when I was a kid'
temperature 1.0: ' the kind with good grammar, the kind where people'
temperature 1.8: ' if an actor would perform\ntwo things at a'
For tasks with one right answer, like pulling data out of a message, use greedy decoding. You want the same answer every time. For creative writing, use sampling, with a temperature around zero point seven. In this course, our task has right answers, so we'll mostly use greedy.
Let's recap. Decoding chooses the next token. Greedy picks the top one. Sampling picks randomly, and temperature controls how random. Use greedy for tasks with right answers. Next, base models, and instruct models.