I4MediumPart I · Inference, Decoding & Quantization
Beam Search Decoding with Length Penalty
Maintain top-B partial decoding hypotheses scored with GNMT length penalty normalization.
⏱️ Time:
O(T * B * V)💾 Space:
O(B * T)🎯 Interactive Self-Practice Loop (Attempt Before Peeking)
Practice in 4 steps: recall mechanism, complete core lines, check edge cases, and log mastery locally.
Step 1 · Mechanism Recall & Stability Self-Check
Step 2 · Complete Key Implementation Lines
import numpy as np
def simple_beam_search_step(
current_beams: list, # [(score, [token_ids])] 长度为 B 的当前候选路径
next_token_log_probs: np.ndarray, # (B, V) 各路径扩展下一词的对数概率
beam_width: int = 3,
alpha: float = 0.6
) -> list:
all_candidates = []
# 遍历当前每条活跃的 Beam
for b_idx, (prev_score, seq) in enumerate(current_beams):
log_probs =
for token_id, lp in enumerate(log_probs):
new_seq = seq + [token_id]
new_raw_score = prev_score + lp
# 计算长度惩罚
length = len(new_seq)
lp_factor = ((5.0 + length) / 6.0) ** alpha
normalized_score =
all_candidates.append((new_raw_score, normalized_score, new_seq))
# 按归一化分数降序排序,仅截取前 beam_width 条
all_candidates.sort(key=lambda x: x[1], reverse=True)
best_beams = [(raw, seq) for raw, norm, seq in all_candidates[:beam_width]]
return best_beams
Step 3 · Verify Boundary Cases & Assertions
Step 4 · Follow-Up Drill & Review Outcome
Q1: Why does Best-of-N (sampling + verifier) outperform Beam Search for code generation and math reasoning?
💡
Core Mental Anchor / Mnemonic
Expand B beams across vocab V, normalize scores by length penalty, prune back to top B.
📐 Mathematical Derivation & Core Formula
### Heuristic Beam Width & Length Normalization
Greedy decoding is shortsighted, while exact decoding costs . Beam Search retains the top highest-scoring partial hypotheses per step.
Because summed token log-probabilities decrease monotonically with sequence length , unnormalized scores favor overly short outputs. Length penalty divides cumulative log-prob so longer coherent sequences remain competitive.
Greedy decoding is shortsighted, while exact decoding costs . Beam Search retains the top highest-scoring partial hypotheses per step.
Because summed token log-probabilities decrease monotonically with sequence length , unnormalized scores favor overly short outputs. Length penalty divides cumulative log-prob so longer coherent sequences remain competitive.
🔄 Tensor Dimensions & Shape Flow
B beams -> expand B*V candidates -> score / length_penalty -> keep top B hypotheses
🛡️ Numerical Stability & Pitfalls Checklist
- Move hypotheses hitting
[EOS]into completed beams while continuing search on active beams. - Open-ended chat models generally prefer stochastic Top-P / Min-P sampling to avoid repetitive beam output.
💻 Reference Code Implementation
import numpy as np
def simple_beam_search_step(
current_beams: list, # [(score, [token_ids])] 长度为 B 的当前候选路径
next_token_log_probs: np.ndarray, # (B, V) 各路径扩展下一词的对数概率
beam_width: int = 3,
alpha: float = 0.6
) -> list:
all_candidates = []
# 遍历当前每条活跃的 Beam
for b_idx, (prev_score, seq) in enumerate(current_beams):
log_probs = next_token_log_probs[b_idx] # (V,)
for token_id, lp in enumerate(log_probs):
new_seq = seq + [token_id]
new_raw_score = prev_score + lp
# 计算长度惩罚
length = len(new_seq)
lp_factor = ((5.0 + length) / 6.0) ** alpha
normalized_score = new_raw_score / lp_factor
all_candidates.append((new_raw_score, normalized_score, new_seq))
# 按归一化分数降序排序,仅截取前 beam_width 条
all_candidates.sort(key=lambda x: x[1], reverse=True)
best_beams = [(raw, seq) for raw, norm, seq in all_candidates[:beam_width]]
return best_beams
🧪 Runnable Assertions & Validation
Copy and run directly in Python / Jupyter:
import numpy as np
init_beams = [(0.0, [101])] # [CLS]
# 假设词表大小 3
next_lps = np.array([[-0.1, -2.0, -5.0]])
step1 = simple_beam_search_step(init_beams, next_lps, beam_width=2)
assert len(step1) == 2
# 概率最高的词 0 应排在第 1 位
assert step1[0][1][-1] == 0
print("✓ Beam Search 束搜索自测通过")🎯 Core Follow-up Inquiries & Reference Answers
Q1:Why does Best-of-N (sampling + verifier) outperform Beam Search for code generation and math reasoning?
Beam Search prunes greedily step-by-step and cannot recover if a valid solution starts with a low-probability reasoning setup, whereas Best-of-N samples diverse complete chains and scores them end-to-end with compilers or test verifiers.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
中文速览与面试要点
Beam Search 束搜索(束宽更新与长度惩罚)
机器翻译与语音识别经典确定性搜索,保持前 Beam_Width 个最高累计对数似然候选路径。
核心要点
- ### 启发式路径搜索与长度归一化 贪心搜索每步只选局部最优,容易因一步走错导致后续全盘皆输;全量穷举搜索在词表为 V 时复杂度为 O(V^T),计算不可行。 Beam Search 折中方案: 每一步仅保留累计对数概率最高的 B(Beam Width,如 4 或 5)条最优候选路径。 长度惩罚(Length Penalty)的必要性: 由于对数概率 P 0 是负数,路径越长累计累加的负数越多。如果不做长度归一化,Beam Search 会强烈偏向于生成极短的断句。 GNMT 提出长度惩罚公式( 通常取 0.6 ~ 0.8): LP(t) = (5 + t)^ (5 + 1)^ 打分调整为累计对数概率除以 LP(t)。
- 当前 B 条路径 -> 乘积扩展为 B*V 种可能 -> 计算带 LP 分数 -> 排序取 Top B
- 一旦候选生成 [EOS] 终止符,需将其移入已完成序列集合(Completed Beams),剩余活跃 Beam 继续向下扩展
- 在大模型开放式自由对话中,Beam Search 容易造成复读机单调重复,现代大模型更倾向于使用 Top-P / Min-P 采样
- 为什么在代码生成与数学推理(DeepSeek-R1 / OpenAI o1)中,Best-of-N 往往比 Beam Search 表现更好?:Beam Search 在早期局部搜索时剪枝不可逆,一步剪掉未来潜在优质解答便彻底错失;而 Best-of-N(Rejection Sampling / Pass@k)通过独立随机采样生成 N 条完整长思维链,配合外部代码执行器或验证器做全局评判,更能探索复杂的多步解题路径。
参考实现
import numpy as np
def simple_beam_search_step(
current_beams: list, # [(score, [token_ids])] 长度为 B 的当前候选路径
next_token_log_probs: np.ndarray, # (B, V) 各路径扩展下一词的对数概率
beam_width: int = 3,
alpha: float = 0.6
) -> list:
all_candidates = []
# 遍历当前每条活跃的 Beam
for b_idx, (prev_score, seq) in enumerate(current_beams):
log_probs = next_token_log_probs[b_idx] # (V,)
for token_id, lp in enumerate(log_probs):
new_seq = seq + [token_id]
new_raw_score = prev_score + lp
# 计算长度惩罚
length = len(new_seq)
lp_factor = ((5.0 + length) / 6.0) ** alpha
normalized_score = new_raw_score / lp_factor
all_candidates.append((new_raw_score, normalized_score, new_seq))
# 按归一化分数降序排序,仅截取前 beam_width 条
all_candidates.sort(key=lambda x: x[1], reverse=True)
best_beams = [(raw, seq) for raw, norm, seq in all_candidates[:beam_width]]
return best_beams