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):
| Token | Logit | T = 0.2 | T = 1.0 | T = 2.0 |
| cheese | 3.0 | 99.3% | 68.6% | 50.6% |
| crumb | 2.0 | 0.7% | 25.3% | 30.7% |
| cable | 0.5 | ~0% | 5.6% | 14.5% |
| moon | -2.0 | ~0% | 0.5% | 4.2% |
Try it yourself with the same four logits:
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%.
- Top-k (Fan et al., 2018): keep the k most likely tokens, period. Simple but rigid. For "The capital of France is…", k = 50 keeps 49 useless options. For "My favorite food is…", k = 50 cuts perfectly good answers.
- Top-p, or nucleus sampling (Holtzman et al., 2020): sort tokens, add probabilities until the running total reaches p (say 0.9), drop the rest. The pool adapts: if "Paris" alone is 95%, the pool is one token; if the top food is only 1%, the pool may hold hundreds.
- Min-p (Nguyen et al., ICLR 2025): keep any token whose probability is at least a fraction of the top token's. With min_p = 0.1 and a top token at 90%, the cutoff is 9%; with a top token at 5%, the cutoff is 0.5%. It is popular in open-model runtimes. A later re-analysis argues its edge over top-p shrinks once quality and diversity are measured together, so treat it as a good option, not a solved problem.
| Method | What it changes | Main weakness |
| Temperature | Shape of the whole distribution | Never removes bad candidates |
| Top-k | Fixed number of candidates | Same k is wrong for confident and uncertain steps |
| Top-p | Candidates covering p of the mass | Lets lots of noise in when the model is unsure |
| Min-p | Cutoff relative to the top token | Not 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:
- Temperature must be 1 (or unset) whenever thinking is enabled, on all models.
- On Claude 4.7 and later (which includes the current Opus 5.5, Sonnet 5.5 and Haiku 5.5),
temperature is deprecated and only its default value is accepted, even with thinking off.
- On Claude 5 and later, thinking is on by default. Depth is steered with the
effort parameter, not with sampling settings.
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
- Consistency of format: use structured outputs or strict tool schemas, so the shape is guaranteed regardless of sampling.
- Consistency of content: show examples in the prompt and state the rules explicitly (the few-shot lesson from October 9 applies directly).
- Depth vs. speed: adjust
effort (or pick a smaller, faster model) instead of lowering temperature.
- 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.
- 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
- Claude Platform Docs — "API usage primer for Claude" (read directly, Oct 15, 2026): temperature rules with thinking, deprecation on Claude 4.7+, effort parameter
- Let's Data Science — "LLM Sampling: Temperature, Top-K, Top-P, and Min-P Explained" (Feb 11, 2026, updated Sep 6, 2026; read directly): worked example, method history, sampler order, provider defaults
- AWS Bedrock — Anthropic Claude Messages API parameters (via search summary): Sonnet 4.5 / Haiku 4.5 accept only one of temperature or top_p
- GitHub — BrowserOS issue #208 (via search summary): "temperature and top_p cannot both be specified for this model"
- F22 Labs — "What are temperature, top_p and top_k in AI" (2026, via search summary): starting ranges and the temperature-0 caveat
- Original papers, cited via Let's Data Science: Holtzman et al., "The Curious Case of Neural Text Degeneration" (ICLR 2020); Fan et al. (ACL 2018); Nguyen et al., min-p (ICLR 2025).
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:
| Token | Logit | T = 0,2 | T = 1,0 | T = 2,0 |
| cheese (queijo) | 3,0 | 99,3% | 68,6% | 50,6% |
| crumb (farelo) | 2,0 | 0,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:
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.
- Top-k (Fan et al., 2018): fica com os k tokens mais prováveis e pronto. Simples, mas rígido. Em "A capital da França é…", k = 50 mantém 49 opções inúteis. Em "Minha comida favorita é…", k = 50 corta respostas perfeitamente boas.
- Top-p, ou nucleus sampling (Holtzman et al., 2020): ordena os tokens, vai somando probabilidades até chegar a p (digamos 0,9) e descarta o resto. O tamanho se adapta: se "Paris" sozinho tem 95%, sobra um token; se a comida favorita mais provável tem só 1%, podem sobrar centenas.
- Min-p (Nguyen et al., ICLR 2025): mantém qualquer token cuja probabilidade seja pelo menos uma fração da do primeiro colocado. Com min_p = 0,1 e o favorito em 90%, o corte é 9%; com o favorito em 5%, o corte é 0,5%. É popular em runtimes de modelos abertos. Uma reanálise posterior argumenta que a vantagem sobre o top-p diminui quando se mede qualidade e diversidade juntas, então trate como boa opção, não como problema resolvido.
| Método | O que muda | Principal fraqueza |
| Temperature | Formato da distribuição inteira | Nunca remove candidatos ruins |
| Top-k | Número fixo de candidatos | O mesmo k erra em passos confiantes e incertos |
| Top-p | Candidatos que cobrem p da massa | Deixa entrar muito ruído quando o modelo está em dúvida |
| Min-p | Corte relativo ao favorito | A 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:
- A temperature precisa ser 1 (ou não ser enviada) sempre que o thinking estiver ligado, em todos os modelos.
- No Claude 4.7 em diante (o que inclui os atuais Opus 5.5, Sonnet 5.5 e Haiku 5.5),
temperature está depreciada e só o valor padrão é aceito, mesmo com thinking desligado.
- No Claude 5 em diante, o thinking vem ligado por padrão. A profundidade é controlada pelo parâmetro
effort, não por ajustes de amostragem.
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
- Consistência de formato: use structured outputs ou schemas de ferramenta estritos, para o formato ser garantido independentemente da amostragem.
- 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).
- Profundidade vs. velocidade: ajuste o
effort (ou escolha um modelo menor e mais rápido) em vez de baixar a temperatura.
- 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.
- 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
- Claude Platform Docs — "API usage primer for Claude" (lido diretamente em 15/10/2026): regras de temperature com thinking, depreciação no Claude 4.7+, parâmetro effort
- Let's Data Science — "LLM Sampling: Temperature, Top-K, Top-P, and Min-P Explained" (11/02/2026, atualizado em 06/09/2026; lido diretamente): exemplo numérico, histórico dos métodos, ordem dos samplers, padrões dos provedores
- AWS Bedrock — parâmetros da Messages API do Anthropic Claude (via resumo de busca): Sonnet 4.5 / Haiku 4.5 aceitam só um entre temperature e top_p
- GitHub — issue #208 do BrowserOS (via resumo de busca): "temperature and top_p cannot both be specified for this model"
- F22 Labs — "What are temperature, top_p and top_k in AI" (2026, via resumo de busca): faixas de partida e a ressalva sobre temperature 0
- Artigos originais, citados via Let's Data Science: Holtzman et al., "The Curious Case of Neural Text Degeneration" (ICLR 2020); Fan et al. (ACL 2018); Nguyen et al., min-p (ICLR 2025).
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.