0Pricing
AI Prompt Engineering · 课时

LLM 中的温度是什么?

温度用于控制创造性:0 表示确定性,2 表示混沌,其他取值则介于两者之间。

LLM 中的温度是什么? 是 CoddyKit 上的免费 AI Prompt Engineering 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Prompt Engineering 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Prompt Engineering 课程共包含 4 节课。

LLM 如何选择下一个令牌

在每一步中,LLM 都会针对其词汇表中的所有令牌输出一个概率分布(GPT 约有 50,000 个令牌)。模型会为每个令牌分配一个称为对数几率的分数——这是一个原始的、未经归一化的数值。对数几率越高,令牌出现的可能性越大。

温度是一个参数,用于控制这些原始对数几率在采样前如何转换为概率。

softmax 函数

对数几率通过 softmax 函数转换为概率。softmax 接收一个对数几率向量,并输出一个总和为 1 的概率分布。

下面是一个包含 4 个令牌的小型词汇表示例:

import numpy as np

# Raw logits from the model
logits = np.array([2.0, 1.0, 0.5, -1.0])  # scores for 4 tokens

# Standard softmax (temperature = 1)
def softmax(logits, temperature=1.0):
    scaled = logits / temperature
    exp_scaled = np.exp(scaled - np.max(scaled))  # subtract max for numerical stability
    return exp_scaled / exp_scaled.sum()

probs = softmax(logits, temperature=1.0)
print('Probabilities:', np.round(probs, 3))
# [0.567, 0.208, 0.129, 0.095]
# Token 0 is most likely at 56.7%

温度 = 0:贪心解码

当温度趋近于 0 时,softmax 分布会收缩:对数几率最高的令牌获得约 1.0 的概率,其他令牌的概率都趋近于 0。模型始终选择概率最高的单个令牌。

这称为贪心解码。它是确定性的——相同的提示词始终会生成相同的输出。没有随机性,也没有创造性。

# Temperature = 0 (greedy)
probs_temp0 = softmax(logits, temperature=0.01)  # near-zero
print('Probs at T=0.01:', np.round(probs_temp0, 4))
# [~1.0, ~0.0, ~0.0, ~0.0]

# In practice, temperature=0 is implemented as argmax:
def greedy_sample(logits):
    return np.argmax(logits)  # always returns the index of the highest logit

token_idx = greedy_sample(logits)
print(f'Selected token index: {token_idx}')  # always 0

温度 = 1:标准采样

温度 = 1 表示直接应用 softmax,不进行缩放——概率分布反映模型自然的置信度。模型根据这些概率进行采样:可能性高的令牌经常出现,可能性低的令牌很少出现,但偶尔也会出现。

这是大多数对话使用场景的默认设置。它能在保持连贯性的同时,生成多样且自然的输出。

# Temperature = 1 (standard)
probs_temp1 = softmax(logits, temperature=1.0)
print('Probs at T=1.0:', np.round(probs_temp1, 3))
# [0.567, 0.208, 0.129, 0.095]

# Sampling from this distribution:
def sample_token(probs):
    vocab = ['the', 'a', 'an', 'is']
    return np.random.choice(vocab, p=probs)

# Run 10 times to see variation
for _ in range(10):
    print(sample_token(probs_temp1), end=' ')
# Output varies each time, but 'the' appears most often

温度 = 2:混沌采样

高温度(> 1)会使概率分布变得平坦——所有令牌出现的可能性趋于相等。模型会变得不可预测,并且输出通常缺乏连贯性。

温度 > 1.5 在实践中很少使用。它可能生成富有创意且出人意料的输出,但通常会生成无意义的内容。

# Temperature = 2 (chaotic)
probs_temp2 = softmax(logits, temperature=2.0)
print('Probs at T=2.0:', np.round(probs_temp2, 3))
# [0.385, 0.261, 0.211, 0.143]
# Much flatter — the 4th token (logit=-1.0) now has 14.3% chance
# (vs 9.5% at T=1.0)

# Visualization: compare distributions
for temp in [0.1, 0.5, 1.0, 1.5, 2.0]:
    probs = softmax(logits, temperature=temp)
    print(f'T={temp}: {np.round(probs, 3)}')

温度作为分布尖锐度控制

从概念上说,温度控制分布的尖锐度:

  • 低温度(0.1–0.4):峰值尖锐——模型信心较高,会选择稳妥或常见的令牌
  • 中等温度(0.6–1.0):形状自然——在创造性和连贯性之间取得平衡
  • 高温度(1.2–2.0):分布平坦——模型会自由探索可能性较低的令牌

可以把它想象成一个创造性旋钮:低温度意味着精确,高温度意味着大胆。

import matplotlib
# Conceptual: what distribution shape looks like at different temps
temps = {'T=0.2 (sharp)': 0.2, 'T=1.0 (normal)': 1.0, 'T=2.0 (flat)': 2.0}
for label, temp in temps.items():
    probs = softmax(logits, temp)
    bar = '#' * int(probs[0] * 40)
    print(f'{label}: top token = {probs[0]:.1%} |{bar}|')
# T=0.2: top token = 97.2% |########################################|
# T=1.0: top token = 56.7% |######################|
# T=2.0: top token = 38.5% |###############|

温度与确定性

一个重要的细节:温度 = 0 会使采样具有确定性。对于温度 > 0,每次运行都会产生不同的输出,因为采样是一个随机过程。分布是固定的,但采样结果会变化。

要在测试中获得可复现的输出,请始终将温度设为 0。在生产环境中需要变化时,如果 API 支持,请使用随机种子。

import openai
client = openai.OpenAI(api_key='sk-...')

# Deterministic: temperature=0
resp1 = client.chat.completions.create(
    model='gpt-4o',
    messages=[{'role': 'user', 'content': 'What is the capital of France?'}],
    temperature=0
)
resp2 = client.chat.completions.create(
    model='gpt-4o',
    messages=[{'role': 'user', 'content': 'What is the capital of France?'}],
    temperature=0
)
print(resp1.choices[0].message.content == resp2.choices[0].message.content)  # True (usually)

温度如何与 Top-p 交互

温度和 Top-p(核采样)都会影响采样分布,但作用阶段不同:

  • 温度:在 softmax 之前缩放对数几率——改变完整分布的形状
  • Top-p:在 softmax 之后将分布截断到前 p 的概率质量——仅从概率最高的词元集合中采样

同时使用两者可以实现精细控制。通常建议一次只调整一个。若同时更改两者,效果将难以预测。

# Using temperature with top_p in OpenAI API
resp = client.chat.completions.create(
    model='gpt-4o',
    messages=[{'role': 'user', 'content': 'Write a one-line haiku about code.'}],
    temperature=0.9,  # moderately diverse distribution
    top_p=0.95        # sample from top 95% of probability mass
)

按任务划分的实用温度值

常见任务类型的快速参考:

  • 事实问答:0——必须准确,无需变化
  • 代码生成:0–0.2——语法必须正确
  • 摘要生成:0.3–0.5——允许一定变化
  • 聊天 / 对话:0.7–0.9——回复自然且多样
  • 创意写作:0.9–1.2——需要多样性
  • 头脑风暴 / 创意构思:1.0–1.5——探索出人意料的选项
TEMPERATURE_PRESETS = {
    'factual_qa': 0.0,
    'code_generation': 0.1,
    'summarization': 0.4,
    'chat': 0.8,
    'creative_writing': 1.1,
    'brainstorming': 1.3
}

def call_with_preset(task_type, prompt):
    temp = TEMPERATURE_PRESETS.get(task_type, 0.7)
    return client.chat.completions.create(
        model='gpt-4o',
        messages=[{'role': 'user', 'content': prompt}],
        temperature=temp
    )

API 中的温度

所有主要 LLM API 都接受温度参数。OpenAI 的有效范围是 0–2,Anthropic Claude 的有效范围是 0–1。超过最大值会引发错误。

# OpenAI: temperature 0 to 2
client.chat.completions.create(
    model='gpt-4o',
    messages=[{'role': 'user', 'content': prompt}],
    temperature=1.2  # Valid for OpenAI
)

# Anthropic Claude: temperature 0 to 1
import anthropic
claude = anthropic.Anthropic(api_key='sk-ant-...')
claude.messages.create(
    model='claude-opus-4-5',
    max_tokens=1024,
    temperature=0.8,  # Max is 1.0 for Claude
    messages=[{'role': 'user', 'content': prompt}]
)

温度不足时

仅靠温度并不总能产生您所需的多样性或精确性。当温度=0 仍会产生不同的输出时(某些模型可能因浮点数非确定性而出现这种情况),请使用 seed 以实现真正的可复现性。当高温度产生无意义的内容时,请使用 Top-p 或 Top-k 限制词汇表,而不要继续提高温度。

# Seed for reproducibility (OpenAI API)
resp = client.chat.completions.create(
    model='gpt-4o',
    messages=[{'role': 'user', 'content': prompt}],
    temperature=0,
    seed=42  # Guarantees same output across calls on same model version
)

# Note: same output only guaranteed with same model version
# A model update can change outputs even with the same seed

知识检查

当温度设置为非常高的值(例如 2.0)时,词元上的概率分布会发生什么变化?

回顾:LLM 中的温度

温度通过在 softmax 之前缩放对数几率来控制词元采样的随机性:

  • T=0:贪心——始终选择概率最高的词元,具有确定性
  • T=1:标准——按照自然概率分布进行采样
  • T>1:混沌——使分布变平,随机性更高,连贯性更低

事实型任务和代码任务使用低温度,聊天使用中等温度,创意任务使用高温度。一次只调整温度或 Top-p,不要同时调整两者。下一课:Top-p 核采样。

常见问题解答

「LLM 中的温度是什么?」课时是免费的吗?

是的 — 「LLM 中的温度是什么?」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Prompt Engineering 课程的其余内容,请升级到 CoddyKit PRO。 AI Prompt Engineering 课程共包含 4 节课。

「LLM 中的温度是什么?」这节课中我会学到什么?

温度用于控制创造性:0 表示确定性,2 表示混沌,其他取值则介于两者之间。 你通过在浏览器中直接运行的动手代码来练习 AI Prompt Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Prompt Engineering 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Prompt Engineering 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「LLM 中的温度是什么?」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Prompt Engineering 课中编写并运行代码吗?

能。每节 AI Prompt Engineering 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. LLM 中的温度是什么?
  2. Top-p 核采样
  3. Top-k 采样
  4. 为您的使用场景选择参数
← 返回 AI Prompt Engineering