AI Prompt Engineering · 课时

Top-p 核采样

了解 top-p 如何将采样范围限制在概率最高的词元集合中。

第 2 / 4 课13 个步骤

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

什么是 Top-p 采样?

Top-p 采样(也称为核采样)是一种将采样限制在词汇表动态子集中的技术。模型不从所有词元中采样,而只考虑累计概率至少为 p 的最小词元集合。

该方法由论文《神经文本退化的奇特案例》(Holtzman 等,2019)提出;与简单的温度缩放相比,它能生成更多样且连贯的文本。

Top-p 的工作原理

算法:

  1. 计算完整词汇表上的 softmax 概率
  2. 按概率对词元排序(从最高到最低)
  3. 沿着排序后的列表依次处理并累加概率,直到累计总和达到 p
  4. 这组词元就是核
  5. 仅从核中采样(重新归一化概率,使总和为 1)
import numpy as np

def top_p_sample(logits, p=0.9):
    probs = softmax(logits, temperature=1.0)

    # Sort by probability descending
    sorted_indices = np.argsort(probs)[::-1]
    sorted_probs = probs[sorted_indices]

    # Find nucleus: smallest set with cumulative prob >= p
    cumulative = np.cumsum(sorted_probs)
    nucleus_size = np.searchsorted(cumulative, p) + 1
    nucleus_indices = sorted_indices[:nucleus_size]
    nucleus_probs = sorted_probs[:nucleus_size]

    # Renormalize
    nucleus_probs = nucleus_probs / nucleus_probs.sum()

    # Sample
    chosen = np.random.choice(nucleus_indices, p=nucleus_probs)
    return chosen

token = top_p_sample(logits, p=0.9)

动态核

Top-p 的关键洞见在于:核的大小是动态的。当模型非常确定时(某个词元以 0.95 的概率占据绝对优势),核只包含 1 个词元。当模型不确定时(许多词元的概率相近),核会扩展以包含更多词元。

这会根据模型的置信度自动调整——置信度高 → 词汇表较小 → 输出集中。置信度低 → 词汇表较大 → 探索更多。

# High-confidence situation: model strongly prefers 'the'
high_confidence_logits = np.array([5.0, 1.0, 0.5, 0.1, -0.5])
hc_probs = softmax(high_confidence_logits)
print('High confidence probs:', np.round(hc_probs, 3))
# [0.974, 0.018, 0.011, 0.007, 0.004]
# Top-p=0.9 nucleus: just 1 token (cumulative after token 0 = 97.4% > 90%)

# Low-confidence situation: model unsure
low_confidence_logits = np.array([1.1, 1.0, 0.9, 0.8, 0.7])
lc_probs = softmax(low_confidence_logits)
print('Low confidence probs:', np.round(lc_probs, 3))
# [0.218, 0.208, 0.199, 0.190, 0.181]
# Top-p=0.9 nucleus: all 5 tokens (need all to reach 90%)

OpenAI API 中的 Top-p

在 API 调用中设置 top_p。有效范围是 0.0–1.0。默认值为 1.0(使用完整词汇表,不限制核)。

OpenAI 建议:如果您更改该参数,请将温度保持为 1.0,反之亦然。同时调整两者会使实际的采样行为难以预测。

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

# Nucleus sampling: top 90% of probability mass
resp = client.chat.completions.create(
    model='gpt-4o',
    messages=[{'role': 'user', 'content': 'Tell me an interesting fact about the ocean.'}],
    temperature=1.0,   # leave temperature at default
    top_p=0.9          # sample from top 90% nucleus
)
print(resp.choices[0].message.content)

p=1.0:不受限制的采样

当 top_p=1.0 时,核包含所有词元,即完整词汇表。这等同于不受 Top-p 限制的纯温度采样。每个词元无论概率多低,都有非零的被选中机会。

如果您希望获得最大多样性,请使用 p=1.0。在 p=1.0 时,只有温度会控制分布的形状。

# p=1.0: all tokens in nucleus
resp_full = client.chat.completions.create(
    model='gpt-4o',
    messages=[{'role': 'user', 'content': 'Generate a creative story opening.'}],
    temperature=1.0,
    top_p=1.0  # no nucleus restriction
)

# p=0.5: very focused nucleus
resp_focused = client.chat.completions.create(
    model='gpt-4o',
    messages=[{'role': 'user', 'content': 'Generate a creative story opening.'}],
    temperature=1.0,
    top_p=0.5  # only top 50% probability mass
)

权衡:Top-p 与温度

两个参数都控制输出多样性,但方式不同:

  • 温度重塑整个分布——某个词元相对于所有其他词元的概率都会发生变化
  • Top-p截断分布——如果某个词元位于核之外,无论其相对概率如何,都会被直接排除

Top-p 可以防止“尾部采样”问题:温度较高时,概率极低的词元(胡言乱语或不相关的词语)偶尔也会被采样。Top-p 会将这些词元完全排除在候选范围之外。

# The tail problem with temperature alone
high_temp_logits = np.array([3.0, 2.0, 1.0, 0.0, -1.0, -5.0, -10.0])
probs_high_temp = softmax(high_temp_logits, temperature=2.0)
print('High temp probs:', np.round(probs_high_temp, 4))
# The last token (logit=-10) still has a small probability
# With many tokens in a real vocab, these rare tokens accumulate
# and occasionally get sampled, producing incoherent output

# Top-p=0.9 cuts these off entirely
# ensuring only tokens contributing to the top 90% are considered

结合温度与 Top-p

同时使用两个参数时,会先应用温度(重塑分布),再将 Top-p 应用于得到的概率(截断到核)。

常见的生产环境配置:

  • 创意写作:温度=1.0,Top-p=0.95
  • 聊天:温度=0.8,Top-p=0.9
  • 代码:温度=0.2,Top-p=1.0(低温度下 Top-p 不具有限制作用)
def combined_sample(logits, temperature=1.0, top_p=0.9):
    # Step 1: apply temperature
    probs = softmax(logits, temperature=temperature)

    # Step 2: apply top-p nucleus
    sorted_idx = np.argsort(probs)[::-1]
    sorted_probs = probs[sorted_idx]
    cumulative = np.cumsum(sorted_probs)
    nucleus_size = np.searchsorted(cumulative, top_p) + 1
    nucleus_idx = sorted_idx[:nucleus_size]
    nucleus_probs = probs[nucleus_idx]
    nucleus_probs = nucleus_probs / nucleus_probs.sum()

    return np.random.choice(nucleus_idx, p=nucleus_probs)

Top-p 与重复

较低的 Top-p 值可能导致重复。当核非常小时(例如 p=0.5),模型会反复从一个很小的词元集合中采样。输出会变得重复且可预测——这与预期的创意效果相反。

如果 Top-p 对当前任务设置得过低,请注意观察重复现象。一个实用的诊断方法是:如果模型不断重复相同的短语,请提高 Top-p 或温度。

def detect_repetition(text, window=20):
    words = text.split()
    if len(words) < window * 2:
        return False
    # Check if any window of words repeats within the text
    for i in range(len(words) - window):
        phrase = ' '.join(words[i:i + window])
        rest = ' '.join(words[i + window:])
        if phrase in rest:
            return True
    return False

response = call_llm(prompt)
if detect_repetition(response):
    print('Warning: repetition detected — consider increasing top_p or temperature')

Top-p 与 Top-k:预览

Top-p 和 Top-k 都会在采样前截断词汇表,但方式不同:

  • Top-p:动态核大小——模型不确定时扩展,模型确定时缩小
  • Top-k:固定核大小——无论模型的置信度如何,始终只考虑恰好 k 个词元

通常更推荐 Top-p,因为它会根据模型的置信度进行调整。下一课将详细介绍 Top-k,以及它与 Top-p 的区别。

# Top-k equivalent for comparison
def top_k_sample(logits, k=50):
    probs = softmax(logits)
    # Keep only top-k tokens
    top_k_indices = np.argsort(probs)[::-1][:k]
    top_k_probs = probs[top_k_indices]
    top_k_probs = top_k_probs / top_k_probs.sum()
    return np.random.choice(top_k_indices, p=top_k_probs)

# Key difference: k is always 50, regardless of model confidence
# Top-p nucleus size varies from 1 to thousands depending on confidence

默认值以及何时更改

API 默认值:top_p = 1.0(不限制核)。什么时候应该更改它?

  • 降低 Top-p(0.7–0.9):当输出感觉不连贯或包含无意义的词语时——尾部采样过多
  • 保持为 1.0:当温度已经较低时——低温度下分布已经很尖锐,Top-p 实际上也不会产生限制作用
  • 不要降低到 0.5 以下:这会导致重复并损失多样性
# Guidance: what to adjust based on symptoms
TROUBLESHOOTING = {
    'output is incoherent or contains random words': {
        'fix': 'lower top_p to 0.9 or 0.85',
        'or': 'lower temperature'
    },
    'output is repetitive and looping': {
        'fix': 'increase top_p or temperature',
        'also': 'try adding frequency_penalty or presence_penalty'
    },
    'output is too predictable and boring': {
        'fix': 'increase temperature to 0.9-1.2',
        'keep': 'top_p at 0.95'
    },
    'output needs to be deterministic': {
        'fix': 'set temperature=0, top_p=1.0'
    }
}

Anthropic Claude 中的 Top-p

Anthropic 的 Claude API 也将 top_p 作为参数公开。其行为相同:模型会构建一个核,该核包含累计概率达到阈值 p 的最小词元集合,然后从这个核中采样。

将它与温度结合可以实现精细控制:使用温度塑造分布,再使用 Top-p 限制可以从该分布中选择哪些词元。

import anthropic
claude = anthropic.Anthropic(api_key='sk-ant-...')

# Creative writing with nucleus sampling
message = claude.messages.create(
    model='claude-opus-4-5',
    max_tokens=256,
    temperature=1.0,
    top_p=0.95,
    messages=[{
        'role': 'user',
        'content': 'Write a short poem about the ocean.'
    }]
)
print(message.content[0].text)

知识检查

与 Top-k 采样相比,Top-p(核)采样的主要优势是什么?

回顾:Top-p 核采样

Top-p 采样会构建一个动态核,即覆盖至少 p 的总概率的最小词元集合:

  • p=1.0:完整词汇表,不受限制
  • p=0.9:前 90% 的概率质量——典型的创意设置
  • p=0.5:非常集中——有重复风险

模型不确定时,核会扩展;模型确定时,核会收缩。这可以防止尾部采样(从概率极低的词元中采样出胡言乱语),同时保留多样性。下一课:Top-k 采样及其与 Top-p 的区别。

免费开始

用 AI 导师学习 AI Prompt Engineering — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
53
课程
199

常见问题解答

「Top-p 核采样」课时是免费的吗?

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

「Top-p 核采样」这节课中我会学到什么?

了解 top-p 如何将采样范围限制在概率最高的词元集合中。 你通过在浏览器中直接运行的动手代码来练习 AI Prompt Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

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

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

「Top-p 核采样」课时需要多长时间?

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

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

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

此课程中的所有课时

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