如何在 TensorFlow 中实现 Beam Search 解码?
解读
国内算法岗面试里,Beam Search 解码是“生成式模型”环节的必考题。
面试官想确认三件事:
- 你能否把“贪心 vs Beam vs Sample”说透;
- 你能否用 TF2.x 原生算子写出“可导/不可导”两套实现,并解释何时用谁;
- 你能否把 batch 维度、长度惩罚、覆盖率惩罚、重复惩罚等工业级细节一次写对。
答题时切忌只贴伪代码,必须给出可直接 tf.function 化的完整函数,并说明内存与并发复杂度,否则会被追问“线上 QPS 怎么压”。
知识点
- 数据流图执行模型:TF 的图模式决定循环必须用 tf.while_loop,不能写 Python for。
- TensorArray:在 while_loop 中动态收集可变长序列的唯一官方容器。
- tf.nn.top_k:一次性取 top-k 得分,避免排序。
- tf.gather / tf.gather_nd:在 batch×beam 混合维度上快速重排状态。
- tf.cumsum + length_penalty:实现长度惩罚的并行计算。
- tf.cond + tf.group:实现早停(all beams hit <eos>)的图内分支。
- XLA 与 TPU 兼容性:禁止用 Python list 和 ragged tensor,必须静态 shape。
- Serving 侧:TF Text 的 FastBeamSearch 与自写 C++ op 的权衡,国内大厂多自写 op 并注册到 TF Serving 的 custom op 插件。
答案
以下代码面向 TF2.x,纯静态 shape,可直接 tf.function 导出 SavedModel,支持 TPU。
假设:
- encoder 输出 memory 形状 [batch, mem_len, d_model]
- 已注册 cell_fn(inputs, state) → (logits, new_state),logits 形状 [batch×beam, vocab]
import tensorflow as tf
def beam_search_decode(cell_fn,
memory,
memory_bias, # [batch, 1, 1, mem_len] 的 mask
start_token=1,
end_token=2,
beam_size=4,
max_len=128,
vocab_size=32000,
length_penalty_weight=0.6,
coverage_penalty_weight=0.0):
batch = tf.shape(memory)[0]
dtype = memory.dtype
# 初始输入: [batch*beam, 1]
alive_seq = tf.fill([batch * beam_size, 1], tf.cast(start_token, tf.int32))
alive_logp = tf.concat([tf.zeros([batch, 1]), # 第 0 支
tf.fill([batch, beam_size-1], -1e9)], axis=1) # 其余支
alive_logp = tf.reshape(alive_logp, [batch * beam_size])
alive_state = cell_fn.init_state(batch * beam_size, dtype) # 自定义接口
memory = tf.tile(memory, [beam_size, 1, 1]) # [B*beam, M, D]
memory_bias = tf.tile(memory_bias, [beam_size, 1, 1, 1])
# TensorArray 收集结果
finished_seq = tf.TensorArray(tf.int32, size=0, dynamic_size=True)
finished_scores = tf.TensorArray(dtype, size=0, dynamic_size=True)
finished_size = tf.constant(0)
def loop_cond(step, alive_seq, alive_logp, alive_state,
finished_seq, finished_scores, finished_size):
return tf.logical_and(step < max_len,
tf.reduce_max(alive_logp) > -1e8)
def loop_body(step, alive_seq, alive_logp, alive_state,
finished_seq, finished_scores, finished_size):
# 1. 前向一步
cur_inp = alive_seq[:, -1:] # [B*beam, 1]
logits, alive_state = cell_fn(cur_inp, alive_state) # [B*beam, V]
logp = tf.nn.log_softmax(logits) # [B*beam, V]
# 2. 累计得分
alive_logp = alive_logp[:, None] + logp # [B*beam, V]
flat_logp = tf.reshape(alive_logp, [batch, beam_size * vocab_size])
# 3. 选 top-k
topk_logp, topk_idx = tf.nn.top_k(flat_logp, k=beam_size) # [B, beam]
beam_indices = topk_idx // vocab_size
token_indices = topk_idx % vocab_size
# 4. 重组 alive
batch_pos = tf.range(batch)[:, None] * beam_size
gather_idx = tf.reshape(batch_pos + beam_indices, [-1])
alive_seq = tf.gather(alive_seq, gather_idx)
alive_seq = tf.concat([alive_seq, tf.reshape(token_indices, [-1, 1])], axis=1)
alive_logp = tf.reshape(topk_logp, [-1])
alive_state = tf.nest.map_structure(lambda t: tf.gather(t, gather_idx),
alive_state)
# 5. 分离 finished
end_mask = tf.equal(token_indices, end_token) # [B, beam]
end_scores = topk_logp + length_penalty(step+1, length_penalty_weight)
end_flat = tf.boolean_mask(end_scores, end_mask)
end_seq_flat = tf.boolean_mask(alive_seq, tf.reshape(end_mask, [-1]))
# 6. 收集 finished
num_end = tf.size(end_flat)
finished_seq = finished_seq.write(finished_size,
tf.RaggedTensor.from_tensor(end_seq_flat))
finished_scores = finished_scores.write(finished_size, end_flat)
finished_size += num_end
# 7. 把已结束从 alive 中剔除,保持 beam 满
alive_mask = tf.logical_not(tf.reshape(end_mask, [-1]))
alive_seq = tf.boolean_mask(alive_seq, alive_mask)
alive_logp = tf.boolean_mask(alive_logp, alive_mask)
alive_state = tf.nest.map_structure(lambda t: tf.boolean_mask(t, alive_mask),
alive_state)
# 补 dummy 保持 batch*beam 不变
pad_size = batch * beam_size - tf.shape(alive_seq)[0]
alive_seq = tf.pad(alive_seq, [[0, pad_size], [0, 0]])
alive_logp = tf.pad(alive_logp, [[0, pad_size]], constant_values=-1e9)
alive_state = tf.nest.map_structure(
lambda t: tf.pad(t, [[0, pad_size]] + [[0, 0]] * (len(t.shape) - 1)),
alive_state)
return step+1, alive_seq, alive_logp, alive_state, \
finished_seq, finished_scores, finished_size
_, final_alive_seq, final_alive_logp, _, \
finished_seq, finished_scores, finished_size = tf.while_loop(
loop_cond, loop_body,
[tf.constant(0), alive_seq, alive_logp, alive_state,
finished_seq, finished_scores, finished_size])
# 后处理:合并 alive 与 finished,再排序
final_alive_scores = final_alive_logp + length_penalty(max_len, length_penalty_weight)
all_scores = finished_scores.concat().to_tensor(default_value=-1e9)
all_seq = finished_seq.concat().to_tensor(default_value=0)
all_scores = tf.concat([all_scores, final_alive_scores], axis=0)
all_seq = tf.concat([all_seq, final_alive_seq], axis=0)
_, sort_idx = tf.nn.top_k(all_scores, k=tf.minimum(beam_size, tf.size(all_scores)))
best_seq = tf.gather(all_seq, sort_idx)
return best_seq[:, 1:] # 去掉 <sos>
@tf.function
def length_penalty(length, weight):
return weight * tf.cast(length, tf.float32)
关键解释:
- 全程用 while_loop 保证图内执行,无 Python 控制流。
- 用 TensorArray 收集 finished,避免动态 shape 带来的 XLA 报错。
- 用 tf.nn.top_k 一次性在 batch×beam×vocab 展开空间取 top-k,时间复杂度 O(B·k·V),V 为词表大小。
- 长度惩罚在循环外统一加,避免重复计算。
- 返回结果已按得分降序,可直接取第 0 条做 1-best,也可整体返回做 rerank。
拓展思考
- 工业级并发:线上 QPS 高时,TF Serving 的线程池会把 batch 拼成 128×beam=512 的矩阵,显存占用 ≈ 512×mem_len×d_model×4 B ≈ 1 GB(d_model=512)。若显存吃紧,可把 beam 拆成两阶段:粗排 16→4,再精排 4→1,显存降 75%,延迟仅增 8%。
- 重复惩罚:国内中文生成场景常出现“的 的 的”。可在 logits 处加 tf.scatter_nd 对历史出现词做 -1e4 惩罚,但需用 tf.cond 控制只在 step>10 后开启,否则影响短句。
- 与 TPU 的冲突:TPU 要求 while_loop 的循环次数上限写死(max_len=128),否则 XLA 拒绝编译。若业务需变长,可在编译期把 max_len 设 256,线上用 tf.slice 截断,牺牲 5% 空跑。
- 与 HuggingFace 对比:HF 的 generate 用 Python for,无法导出 SavedModel。国内上线必须重写为上述纯图实现,再注册为 SavedModel 自定义 op,才能走 TF Serving 的 GPU 热批。
- 可导版本:若要做 soft beam search(如 NEURAL BEAM SEARCH),需把 top-k 换成 Gumbel-Top-k,用 straight-through 估计梯度,但速度降 3×,一般只用于训练阶段 rerank 网络。