← Back to Cooldecode
AI Watch · LLM concepts explained

Temperature, top-p and the dial that is disappearing

Every word a model writes is a weighted dice roll. Temperature and top-p decide how loaded the dice are. Here is how they work, the myths around them, and why the newest Claude models no longer let you touch the temperature knob at all.

1. The next token is a draw, not a lookup

You already know from the tokens lesson that a model writes one token at a time. At each step, its last layer produces a raw score, called a logit, for every token in its vocabulary. Logits can be negative or large and do not add up to anything. A function called softmax turns them into probabilities that sum to 100%.

Then the model has to pick one. The simplest strategy, greedy decoding, always takes the top token. It sounds safe, but research going back to Holtzman et al. (ICLR 2020) showed greedy output on open-ended text tends to loop and repeat itself. So most systems sample: they draw a token at random, weighted by its probability. Temperature and top-p are the controls on that draw.

Analogy: picture a jar of marbles where each color is a candidate word and the number of marbles is its probability. Sampling is reaching in blind. Temperature changes how many marbles of each color are in the jar. Top-p throws the rare colors out before you reach in.

2. Temperature: a contrast dial

Temperature (T) divides every logit before softmax. Below 1, the gaps between scores grow, so the favorite becomes even more likely. Above 1, the gaps shrink and the distribution flattens. Think of the contrast slider on a photo: low contrast washes everything to gray, high contrast pushes bright pixels whiter and dark ones to black.

Here is the worked example from Let's Data Science, for the prompt "The mouse ate the…" (I re-checked the math):

TokenLogitT = 0.2T = 1.0T = 2.0
cheese3.099.3%68.6%50.6%
crumb2.00.7%25.3%30.7%
cable0.5~0%5.6%14.5%
moon-2.0~0%0.5%4.2%

Try it yourself with the same four logits:

Temperature1.0

The key detail: temperature only reweights, it never removes. Even at a very low temperature, "moon" still has a tiny non-zero chance. That is why truncation methods exist.

In code, the whole idea fits in a few lines (plain JavaScript, no library):

function softmaxWithTemperature(logits, T) {
  const scaled = logits.map(l => l / T);
  const max = Math.max(...scaled);              // subtract max for numeric stability
  const exps = scaled.map(s => Math.exp(s - max));
  const sum = exps.reduce((a, b) => a + b, 0);
  return exps.map(e => e / sum);
}

softmaxWithTemperature([3, 2, 0.5, -2], 0.2); // ≈ [0.993, 0.007, 0.000, 0.000]
softmaxWithTemperature([3, 2, 0.5, -2], 2.0); // ≈ [0.506, 0.307, 0.145, 0.042]

3. Top-k, top-p, min-p: trimming the long tail

Truncation methods cut unlikely tokens out of the pool, then rescale the survivors back to 100%.

MethodWhat it changesMain weakness
TemperatureShape of the whole distributionNever removes bad candidates
Top-kFixed number of candidatesSame k is wrong for confident and uncertain steps
Top-pCandidates covering p of the massLets lots of noise in when the model is unsure
Min-pCutoff relative to the top tokenNot offered by most hosted APIs

4. Four myths worth dropping

"Temperature 0 means deterministic"

Not quite. T = 0 is effectively greedy decoding, but hosted models run on batched GPU hardware where tiny floating-point differences can flip a near-tie. Expect "much more consistent," not "identical every time."

"Low temperature = more accurate"

Temperature changes how often the model picks its own favorite. If the favorite is wrong, low temperature just makes it wrong more consistently. This links back to the hallucinations lesson: a confident guess is still a guess.

"More knobs = more control"

Temperature and top-p interact. A high temperature flattens the distribution; a low top-p then cuts most of that new variety away. One guide calls this the two settings quietly cancelling each other. Tune one at a time.

"Same numbers, same behavior everywhere"

Runtimes apply the steps in different orders (llama.cpp applies temperature last in its default chain; Hugging Face Transformers applies it first), and some providers remap the value internally. Defaults also differ: per Let's Data Science, Claude and OpenAI default to temperature 1.0, while Gemini also sets top-p 0.95 and top-k 40.

5. Why reasoning models are taking the dial away

This is the part that changed recently. Anthropic's own API primer (read directly on platform.claude.com, October 2026) now says:

Before that, developers already hit a smaller version of this. Starting with Claude Sonnet 4.5 and Opus 4.1, sending both temperature and top_p returns a 400 error ("cannot both be specified for this model"), as AWS Bedrock's docs and several open-source bug reports confirm. Many tools broke because their defaults sent both.

Why would a provider remove a knob? Anthropic does not explain it in the primer, so what follows is my interpretation, not an official reason. A reasoning model is tuned to think and then answer under one sampling setup. Its quality comes from the reasoning, not from how sharply the last word is picked. Lowering temperature on the thinking can make it repetitive or get it stuck; raising it can derail a long chain. Locking the dial removes a setting that mostly let people make the model worse, and moves control to levers that act on the behavior itself: effort, prompts, and schemas.

In practice: if old code sends temperature: 0 to a current Claude model, expect an error, not a "safer" answer. Remove the parameter rather than fighting it.

6. What to use instead

  1. Consistency of format: use structured outputs or strict tool schemas, so the shape is guaranteed regardless of sampling.
  2. Consistency of content: show examples in the prompt and state the rules explicitly (the few-shot lesson from October 9 applies directly).
  3. Depth vs. speed: adjust effort (or pick a smaller, faster model) instead of lowering temperature.
  4. Reliability on a hard question: ask several times and compare or vote. Variety between runs becomes a signal: if answers disagree, the model is unsure.
  5. Open or older models where the knobs still exist: a common starting point is temperature 0–0.3 for code and extraction, around 0.7 for chat, around 1.0+ for brainstorming, and only one truncation method at a time. Test on your own prompts; no single setting wins everywhere.

Sources

Note: category rotation pointed to "LLM concepts explained"; no Anthropic/Claude announcement dated today was found. The reason providers lock the temperature dial on reasoning models is my interpretation, not an official statement.

IA Watch · Conceitos de LLMs explicados

Temperature, top-p e o botão que está sumindo

Cada palavra que um modelo escreve é um sorteio com dado viciado. Temperature e top-p decidem o quanto o dado está viciado. Como eles funcionam, os mitos em volta deles e por que os modelos Claude mais recentes nem deixam mais você mexer na temperatura.

1. O próximo token é um sorteio, não uma consulta

Você já viu na lição sobre tokens que o modelo escreve um token por vez. A cada passo, a última camada gera uma nota bruta, chamada logit, para cada token do vocabulário. Logits podem ser negativos ou grandes e não somam nada em especial. Uma função chamada softmax transforma essas notas em probabilidades que somam 100%.

Aí o modelo precisa escolher um. A estratégia mais simples, decodificação gulosa (greedy), sempre pega o primeiro colocado. Parece seguro, mas pesquisas desde Holtzman et al. (ICLR 2020) mostraram que, em texto aberto, ela tende a entrar em loop e se repetir. Por isso a maioria dos sistemas amostra: sorteia um token, com peso proporcional à probabilidade. Temperature e top-p são os controles desse sorteio.

Analogia: imagine um pote de bolinhas em que cada cor é uma palavra candidata e a quantidade de bolinhas é a probabilidade dela. Amostrar é enfiar a mão sem olhar. A temperature muda quantas bolinhas de cada cor estão no pote. O top-p joga fora as cores raras antes de você pegar.

2. Temperature: um botão de contraste

A temperature (T) divide cada logit antes do softmax. Abaixo de 1, as diferenças entre as notas aumentam, então o favorito fica ainda mais provável. Acima de 1, as diferenças diminuem e a distribuição achata. Pense no controle de contraste de uma foto: pouco contraste deixa tudo cinza; muito contraste deixa o claro mais branco e o escuro preto.

Este é o exemplo do Let's Data Science para o início "The mouse ate the…" ("O rato comeu o…"); conferi as contas:

TokenLogitT = 0,2T = 1,0T = 2,0
cheese (queijo)3,099,3%68,6%50,6%
crumb (farelo)2,00,7%25,3%30,7%
cable (cabo)0,5~0%5,6%14,5%
moon (lua)-2,0~0%0,5%4,2%

Teste você mesmo com os mesmos quatro logits:

Temperature1.0

O detalhe principal: temperature só redistribui o peso, nunca elimina. Mesmo com temperatura muito baixa, "moon" ainda tem uma chance minúscula. É por isso que existem os métodos de corte.

Em código, a ideia inteira cabe em poucas linhas (JavaScript puro, sem biblioteca):

function softmaxWithTemperature(logits, T) {
  const scaled = logits.map(l => l / T);
  const max = Math.max(...scaled);              // subtrai o máximo para estabilidade numérica
  const exps = scaled.map(s => Math.exp(s - max));
  const sum = exps.reduce((a, b) => a + b, 0);
  return exps.map(e => e / sum);
}

softmaxWithTemperature([3, 2, 0.5, -2], 0.2); // ≈ [0.993, 0.007, 0.000, 0.000]
softmaxWithTemperature([3, 2, 0.5, -2], 2.0); // ≈ [0.506, 0.307, 0.145, 0.042]

3. Top-k, top-p, min-p: cortando a cauda longa

Métodos de corte tiram do sorteio os tokens improváveis e reescalam os sobreviventes para somar 100% de novo.

MétodoO que mudaPrincipal fraqueza
TemperatureFormato da distribuição inteiraNunca remove candidatos ruins
Top-kNúmero fixo de candidatosO mesmo k erra em passos confiantes e incertos
Top-pCandidatos que cobrem p da massaDeixa entrar muito ruído quando o modelo está em dúvida
Min-pCorte relativo ao favoritoA maioria das APIs hospedadas não oferece

4. Quatro mitos para abandonar

"Temperature 0 é determinístico"

Não exatamente. T = 0 equivale à decodificação gulosa, mas modelos hospedados rodam em GPUs com processamento em lote, onde diferenças minúsculas de ponto flutuante podem desempatar um quase-empate para o outro lado. Espere "bem mais consistente", não "idêntico sempre".

"Temperatura baixa = mais correto"

A temperature muda com que frequência o modelo escolhe o próprio favorito. Se o favorito está errado, temperatura baixa só faz ele errar com mais consistência. Isso conversa com a lição sobre alucinações: chute confiante continua sendo chute.

"Mais botões = mais controle"

Temperature e top-p interagem. Uma temperature alta achata a distribuição; um top-p baixo depois corta quase toda essa variedade nova. Um guia descreve isso como os dois ajustes se anulando em silêncio. Ajuste um de cada vez.

"Mesmos números, mesmo comportamento em todo lugar"

Runtimes aplicam as etapas em ordens diferentes (o llama.cpp aplica a temperature por último na cadeia padrão; o Hugging Face Transformers aplica primeiro), e alguns provedores remapeiam o valor internamente. Os padrões também mudam: segundo o Let's Data Science, Claude e OpenAI usam temperature 1,0 por padrão, enquanto o Gemini também define top-p 0,95 e top-k 40.

5. Por que modelos de raciocínio estão tirando o botão

Esta é a parte que mudou recentemente. O próprio primer da API da Anthropic (lido diretamente em platform.claude.com, outubro de 2026) agora diz:

Antes disso, desenvolvedores já tinham esbarrado numa versão menor da mudança. A partir do Claude Sonnet 4.5 e do Opus 4.1, enviar temperature e top_p juntos retorna erro 400 ("cannot both be specified for this model"), como confirmam a documentação do AWS Bedrock e vários relatos de bug em projetos open source. Muitas ferramentas quebraram porque mandavam os dois por padrão.

Por que um provedor tiraria um botão? A Anthropic não explica isso no primer, então o que segue é interpretação minha, não motivo oficial. Um modelo de raciocínio é ajustado para pensar e depois responder sob uma configuração de amostragem específica. A qualidade vem do raciocínio, não de quão "afiada" é a escolha da última palavra. Baixar a temperatura no pensamento pode deixá-lo repetitivo ou travado; subir pode descarrilar uma cadeia longa. Travar o botão elimina um ajuste que, na maior parte das vezes, só servia para piorar o modelo, e move o controle para alavancas que agem no comportamento: effort, prompt e schemas.

Na prática: se um código antigo manda temperature: 0 para um modelo Claude atual, espere um erro, não uma resposta "mais segura". Remova o parâmetro em vez de brigar com ele.

6. O que usar no lugar

  1. Consistência de formato: use structured outputs ou schemas de ferramenta estritos, para o formato ser garantido independentemente da amostragem.
  2. Consistência de conteúdo: mostre exemplos no prompt e escreva as regras explicitamente (a lição de few-shot de 9 de outubro se aplica direto).
  3. Profundidade vs. velocidade: ajuste o effort (ou escolha um modelo menor e mais rápido) em vez de baixar a temperatura.
  4. Confiabilidade numa pergunta difícil: pergunte várias vezes e compare ou faça votação. A variação entre execuções vira sinal: se as respostas discordam, o modelo está em dúvida.
  5. Modelos abertos ou antigos, onde os botões ainda existem: um ponto de partida comum é temperature 0–0,3 para código e extração, perto de 0,7 para conversa, 1,0 ou mais para brainstorming, e um único método de corte por vez. Teste nos seus próprios prompts; nenhum ajuste vence em tudo.

Fontes

Nota: a rotação apontava para "Conceitos fundamentais de LLMs explicados"; não foi encontrado anúncio da Anthropic/Claude datado de hoje. O motivo de provedores travarem a temperatura em modelos de raciocínio é interpretação minha, não declaração oficial.