Seq2Seq 模型的编码器-解码器结构如何工作?

解读

国内面试官问“如何工作”时,通常想听到三层信息:

  1. 数据在张量层面的流动路径(TensorFlow 视角);
  2. 关键组件(Embedding、RNN/Attention、Projection)的数学本质与 API 选型;
  3. 训练与推断阶段在分布式 TF 下的差异(Bucket、采样、BeamSearch、TF Serving 导出)。

回答必须体现“能用 TF 写出来、能上线、能调优”,而不是停留在概念。

知识点

  1. 数据流图:TF1 的 static graph 与 TF2 的 eager/graph 混合模式;tf.function 加速。
  2. 编码器:tf.keras.layers.Embedding → (Bi)LSTM/GRU → 最后一层隐状态或全部时间步输出;state_size、time_major 参数。
  3. 解码器:TrainingHelper/GreedyEmbeddingHelper + BasicDecoder(TF1)或 tf.keras.layers.RNN + 自定义 Cell(TF2);Teacher Forcing 比例调度。
  4. Attention:Bahdanau 与 Luong 的打分函数;AttentionWrapper 的 memory 参数即编码器输出;对齐张量 shape 为 [batch, dec_time, enc_time]。
  5. BeamSearchDecoder:beam_width、length_penalty、coverage_penalty;与 TF Serving 的 SavedModel 签名兼容。
  6. 损失与掩码:sequence_loss 自动 mask 0 长度;label_smoothing 对中文 OOV 友好。
  7. 分布式:tf.distribute.MirroredStrategy 下 stateful RNN 的同步梯度;使用 tf.keras.utils.Sequence 避免 Python GIL。
  8. 端侧:TF Lite 转换时必须将 BeamSearch 拆解为静态循环,或用 TFLite-RNN 算子;模型大小压缩 8bit 量化后 BLEU 下降控制 <0.5。

答案

在 TensorFlow 的实现层面,Seq2Seq 的编码器-解码器结构可以拆成“四条张量管道、两个阶段、一个对齐模块”:

  1. 编码器管道
    输入是形状为 [batch, max_enc_len] 的 token id 矩阵,经 tf.keras.layers.Embedding 得到 [batch, max_enc_len, emb_dim]。接着送入一层或多层双向 LSTM:
    fw_lstm = tf.keras.layers.LSTM(units, return_sequences=True, return_state=True)
    bw_lstm = tf.keras.layers.LSTM(units, return_sequences=True, return_state=True, go_backwards=True)
    enc_out, fw_state_h, fw_state_c, bw_state_h, bw_state_c = tf.keras.layers.Bidirectional(fw_lstm, backward_layer=bw_lstm)(emb)
    enc_state = [tf.concat([fw_state_h, bw_state_h], axis=-1), tf.concat([fw_state_c, bw_state_c], axis=-1)]
    enc_out 的 shape 为 [batch, max_enc_len, 2*units],将作为 memory 供后续 Attention 查询。

  2. 对齐模块(Attention)
    以 BahdanauAttention 为例:
    attention = tf.keras.layers.AdditiveAttention()
    query 是解码器每一步的隐状态 [batch, dec_units],key/value 都是 enc_out。
    计算后得到 context vector [batch, 2*units] 和 alignment vector [batch, max_enc_len]。

  3. 解码器管道(训练阶段)
    目标序列右移一位得到 decoder_input,shape 为 [batch, max_dec_len]。
    通过 Embedding 层(与编码器共享权重可减少 30% 参数量)→ [batch, max_dec_len, emb_dim]。
    使用 tf.keras.layers.RNN 包装自定义 AttentionCell:
    cell = AttentionWrapper(tf.keras.layers.LSTMCell(units), attention)
    initial_state = cell.get_initial_state(inputs=None, batch_size=batch, dtype=tf.float32)
    initial_state = cell.clone_state(enc_state) # 用编码器状态初始化
    decoder_outputs, _ = tf.keras.layers.RNN(cell, return_sequences=True)(decoder_emb, initial_state=initial_state)
    最后经 Dense(vocab_size) 投影得 logits [batch, max_dec_len, vocab_size],用 sparse_categorical_crossentropy 计算损失,mask 掉 padding 位置。

  4. 解码器管道(推断阶段)
    将训练用的 TrainingHelper 换成 BeamSearchDecoder:
    decoder = tf.keras.layers.BeamSearchDecoder(cell, beam_width=5, output_layer=projection)
    final_outputs, _, _ = tf.keras.layers.dynamic_decode(
    decoder, maximum_iterations=max_dec_len,
    decoder_init_input=start_tokens, decoder_init_kwargs={'initial_state': cell.clone_state(enc_state)})
    得到 predicted_ids [batch, beam_width, max_dec_len],取 top beam 即可。
    整个图导出为 SavedModel,TF Serving 通过 assets/ 目录下的 vocab 文件做后处理。

  5. 分布式与性能
    在 8 卡 V100 环境,使用 MirroredStrategy,batch_size 设为 4096 tokens/gpu,梯度累积 2 步,可让 Transformer-base 级别的 Seq2Seq 在 1 天完成 20 epoch 的 1 千万句对训练。TF2 的 mixed_float16 打开后,显存占用下降 25%,速度提升 1.4 倍。

一句话总结:编码器把变长输入压成“记忆张量”,解码器在每一步通过 Attention 动态读取记忆并自回归生成输出;TF 通过静态图或 tf.function 将整条流水线编译成高效 CUDA kernel,最终用 SavedModel 上线。

拓展思考

  1. 中文场景下词表 50000 以上时,如何结合 SentencePiece 与共享 Embedding 减少参数量?
    答:SP 模型设置 character_coverage=0.995,user_defined_symbols 加入常用实体;Embedding 共享后,在 TF2 里用 tf.Variable 的 constraint 对编码器 Embedding 做 L2 正则,防止解码器梯度对编码器表示过度干扰。

  2. 工业界实时翻译 QPS 要求 500,延迟 <200 ms,如何优化 BeamSearch?
    答:TF Serving 开启 batch_scheduling 的 max_batch_size=256,batch_timeout_micros=500;将 BeamSearch 提前展开为静态图,使用 TFLite 的 custom op 或 TF-XLA 的 beam_search_topk 算子;在 GPU 上设置 beam_width=4、length_penalty=0.6,比 CPU 版延迟降低 60%。

  3. 如果标签数据不足,如何利用 TF 生态做半监督?
    答:先用大规模单语语料训练 Language Model(tf.keras.layers.LSTM 或 GPT),再对编码器做 ULMFiT 式逐层解冻;在 Seq2Seq 损失中加入 back-translation 的一致性正则项,通过 tf.stop_gradient 构造 dual learning 闭环,实测 BLEU 可提升 1.8。

  4. TF2 的 GradientTape 与 TF1 的 static decoder 在调试上有何差异?
    答:TF2 eager 下可直接打印 Attention 对齐矩阵,方便可视化中文分词边界;但性能下降 30%,需用 @tf.function 包裹训练步,并在 get_concrete_function 时固定 TensorSpec,否则 retrace 导致 GPU 空转。