# Day 05: Temperature, top-p, and the myth of creative settings

*Same file, same prompt, temperature pinned at zero, three runs. All three failed the same way: three repair attempts each, every one reporting that the reply was not JSON.*

*It was not bad JSON. It was no JSON. The model I use is a reasoning model: it thinks in hidden tokens before it answers, and those tokens come out of the same `max_tokens` budget. It spent all 2048 thinking and was cut off before writing a character. From the outside, an answer that never arrived looks exactly like a wrong one.*

*Every request carried settings I had never written down, and one decided whether I got an answer at all. The belief underneath, that `temperature=0` means the same input gives the same output, turned out to be wrong in a quieter way.*

*So today adds two things, and only one of them is a setting.*

---

## The Short Version

**Code for this day:** [cartographer at day-05](https://github.com/Harshavardhan17/cartographer/tree/day-05)

- `temperature` **rescales the scores before the softmax**. It is not a creativity dial, which is why most advice about it is unfalsifiable.
- **Greedy decoding is not determinism.** It fixes how a token is chosen from a distribution, not whether you get the same distribution twice.
- `top_p` is **a different mechanism** — it truncates the tail rather than reshaping it. Move both and two knobs are fighting over one distribution.
- **Send the values explicitly even when they equal the default**, and omit `seed` entirely when unset. The default is not yours and can change under you; `seed` is best effort, not a contract.
- The fix for repeatability is **not a parameter**. It is a schema, a validator, and a harness that reports how much the output moved.

---

## What the two knobs actually do

At every step the model emits a vector of scores, one per token in its vocabulary. A softmax turns those into probabilities and a sampler picks one. Both knobs act on that vector, differently.

Temperature divides the scores before the softmax. Above 1 the distribution flattens and unlikely tokens get a real chance; below 1 it sharpens; at 0, implementations stop dividing and simply take the top-scoring token.

Top-p leaves the scores alone. It sorts the distribution, keeps the smallest set of tokens whose probabilities sum to `p`, throws the rest away, and renormalises — the nucleus sampling idea from [Holtzman et al., 2019](https://arxiv.org/abs/1904.09751). Different mechanism, same target.

Which is why the widely copied advice to "set temperature to 0.2 and top-p to 0.9 for factual work" is unattributable by construction. Two mechanisms, one distribution: when the output changes you cannot say which of them did it, so you cannot tune either. Move one. This project leaves `top_p` at 1.0.

For a high temperature, in brainstorming rather than mapping, there is a better cut-off than a fixed `p`. Min-p keeps only tokens whose probability is at least a fraction of the top token's, so the cut adapts to the model's confidence ([Roush and Mahajani on min-p](https://www.thoughtworks.com/en-in/insights/blog/generative-ai/Min-p-sampling-for-LLMs)). Cartographer does not send it: at temperature 0 it changes nothing, and the free model here does not list `min_p` among its supported parameters.

And "creative" is the wrong word for both. Neither invents anything — the candidate tokens and their scores were fixed by the forward pass, the model's computation of those scores, before either knob was consulted. What you adjust is your willingness to accept the model's lower-ranked guesses. In prose that reads as variety. In a tool that reports symbol names and line numbers, it reads as making things up.

## Greedy decoding is not determinism

Temperature 0 gives you greedy decoding, always taking the top-scoring token, and that pins only the last step of a long pipeline. Everything above it can still differ between two identical requests, and none of it is a parameter.

Your request is batched with whatever else arrived at the same moment, and the batch changes the order the arithmetic is done in. Floating-point addition is not associative, so a different order gives a slightly different score vector. A router in front of many providers may also place two identical requests on two different backends.

Two score vectors differing in the seventh decimal place produce the same top token almost every time. Almost. Where two candidates are near-tied the tie breaks the other way, and everything generated after that point is conditioned on a different token. One flipped tie is enough to change a symbol list, which is why the runs below are measured, not assumed.

![Five candidate tokens for def ask( shown at temperatures 0.2, 0.7, 1.0 and 1.5: the leader holds 99.6 percent of the mass at 0.2 and 48 percent at 1.5](https://cdn.hashnode.com/uploads/covers/69eb0bc51e45c4e0da9b9f00/c9308880-3b45-4c3c-a6d5-7fe33f05e333.png)

## Send the config, do not inherit it

The settings live in one small new module, `src/cartographer/config.py`, so that "what produced this map" is answerable by reading one file. A frozen dataclass holds the five values with their defaults, `payload()` turns them into request fields, and a `from_environment()` function lets an environment variable override each one.

```python
from dataclasses import dataclass
from typing import Any

@dataclass(frozen=True)
class Sampling:
    temperature: float = 0.0
    top_p: float = 1.0
    max_tokens: int = 2048
    seed: int | None = None
    reasoning: bool = False

    def payload(self) -> dict[str, Any]:
        fields: dict[str, Any] = {
            "temperature": self.temperature,
            "top_p": self.top_p,
            "max_tokens": self.max_tokens,
            "reasoning": {"enabled": self.reasoning},
        }
        if self.seed is not None:
            fields["seed"] = self.seed
        return fields
```

`temperature` and `top_p` are sent even though both equal the common default. You do not own that default, and nobody will tell you when it moves.

`seed` is left out of the body entirely when unset, rather than sent as `null`. A provider may honour it, ignore it, or never see it; different output with a seed is not a bug you can file.

`max_tokens` belongs in the same object, because truncation is a reproducibility problem in costume: the repair loop from earlier cannot tell bad JSON from good JSON that got cut off, and you will spend an afternoon on the wrong one. `reasoning` sits beside it for the reason in the opening: sent as `{"enabled": false}`, the same file fits in under a thousand tokens. Asking for low reasoning effort changed nothing.

Then the merge, the one new line in `post` in `src/cartographer/agent.py`, in the one order that works:

```python
payload: dict[str, Any] = {"model": MODEL, "messages": messages}
payload.update(SAMPLING.payload())
if max_tokens is not None:
    payload["max_tokens"] = max_tokens
```

`update` copies the config into the body, then an explicit argument overwrites it. Swap those two lines and the token-calibration call from earlier silently asks for two thousand output tokens instead of one. `tests/test_config.py` asserts on the body that leaves the process, so that swap turns red.

## Measure what you cannot remove

The second half of the day is a harness rather than a setting. Run the same analysis N times and ask what survived all N.

```python
import collections

def agreement(runs: list[set[str]]) -> tuple[list[str], list[str]]:
    counts: collections.Counter[str] = collections.Counter()
    for names in runs:
        counts.update(names)
    stable = sorted(name for name, seen in counts.items() if seen == len(runs))
    variable = sorted(name for name, seen in counts.items() if seen < len(runs))
    return stable, variable
```

It lives in `src/cartographer/repeat.py`, a command that analyses one file N times and keeps each run's symbol names as a set. A `Counter` tallies how many runs found each name; names found in every run are stable, the rest variable, and `tests/test_repeat.py` pins that split. [Today's dev notes](https://github.com/Harshavardhan17/cartographer/blob/main/docs/devnotes/day-05.md) explain every line.

The weakness is worth stating plainly, because it is large. This compares sets of names. Two runs can agree perfectly here and still disagree about every line number and every role sentence. Scoring content needs known-good answers, a bigger job later in the series.

On `src/cartographer/budget.py`, temperature 0 found the same 13 names in eight runs out of eight. At 1.0, one run in three dropped `Meter.__str__`, so 92%, and the next five agreed. A seed of 42 changed nothing visible, because there was nothing to remove. One small file, one model, one day: a measurement, not a guarantee. They are in `docs/sampling.md` with the model id, temperature and run count.

## Three things people reach for, and what each one is worth

| | `temperature=0` | A `seed` | Schema, validator, repeat harness |
|---|---|---|---|
| **Gives you** | the top-scoring token at every step | a request for the same draw, best effort | a number for how much the output moved |
| **Defeated by** | different scores from batching or a different backend | a provider that ignores it, or a router that switches backend | nothing, because it does not try to control anything |
| **Right when** | always, as the floor under everything else | one pinned model, one provider, and you verified it holds | always, and it is the only one that keeps working as the agent grows |

## What I'd do

1. **Send every sampling parameter explicitly**, including the ones that match the default.
2. **Move one knob.** Leave `top_p` at 1.0 and change temperature, or the reverse. Never both, or you can attribute nothing.
3. **Treat `seed` as a hint.** Omit it when unset, and never write a test that would fail if a provider ignored it.
4. **Keep `max_tokens` and reasoning beside temperature.** Truncation and instability arrive in your logs wearing the same costume.
5. **Stop arguing about determinism and measure agreement.** A set comparison over three runs turns a belief into a number you can watch move.

---

*If this was useful, a clap helps other people find it. I am curious where other people landed: have you ever got a genuinely repeatable multi-call run out of a hosted model, and what did you have to pin down to get it?*

---

*All views in this post are my own. The scenarios are illustrative composites, and code examples are not drawn from any specific codebase.*

