如何用 tf.data 的 rebatch 函数在训练中途动态增大 batch size?

解读

面试官真正想考察的是两点:

  1. 你是否知道 tf.data.Dataset 的“不可变性”——它一旦生成,batch size 就写死在计算图里,不能像 Keras 的 model.fit(batch_size=...) 那样在 epoch 之间随手改。
  2. 你是否掌握“用 rebatch/unbatch → batch”组合在 Python 端重新构造数据流,并把它无缝嫁接到 Keras 的 train_step 或 model.fit 里,实现“epoch 越大,batch 越大”这一常见 trick(加速收敛、稳定后期梯度)。

国内大厂(阿里、头条、商汤)线上训练普遍用 tf.data + ParameterServer 架构,如果答“我直接改 fit 的 batch_size”会被直接判负,因为那样会触发图重建、PS 重启,任务可能直接被 YARN/K8s 杀掉。所以必须给出“图外 rebatch”方案,并说明对性能、shuffle、分布式的影响。

知识点

  1. tf.data.Dataset 的 batch()/unbatch()/rebatch() 区别:
    • batch(N) 把 N 条样本拼成一条;unbatch() 把一条拆回多条;rebatch(N) 只在已 batched 的数据集上生效,等价于 unbatch().batch(N)。
  2. 训练脚本里 epoch → batch_size 的映射策略:线性增长、指数增长、阶梯增长。
  3. tf.py_function / tf.numpy_function 的陷阱:会打断计算图,导致 XLA 失效、GPU 延迟增大,因此 rebatch 逻辑应放在 Python 端,而不是写进 tf.data 的 map。
  4. Keras 的 Model.train_step 可重写,但 batch size 由数据决定,因此“动态”只能依靠“换 Dataset”。
  5. 分布式训练下, rebatch 后的 global batch size 必须能被 worker 数整除,否则 NCCL AllReduce 会挂。

答案

核心思路:每个 epoch 开始前,在 Python 端根据当前 epoch 指数算出新的 batch_size,然后用 rebatch(new_size) 生成新的 Dataset,再喂给 model.fit。代码骨架如下(单卡为例,多卡只要保证 new_global_batch % strategy.num_replicas_in_sync == 0 即可):

import tensorflow as tf

def make_dataset(base_bs):
    # 基础 pipeline:并发解析、打乱、预取
    ds = tf.data.TFRecordDataset("train.tfrec")
    ds = ds.map(_parse_fn, num_parallel_calls=tf.data.AUTOTUNE)
    ds = ds.shuffle(10_000)
    ds = ds.batch(base_bs, drop_remainder=True)
    ds = ds.prefetch(tf.data.AUTOTUNE)
    return ds

def rebatch_dataset(batched_ds, new_bs):
    # 关键一行:先拆再合
    return batched_ds.unbatch().batch(new_bs, drop_remainder=True)

# 训练逻辑
start_bs = 64
factor     = 1.5
max_bs     = 1024
epochs     = 50

for epoch in range(epochs):
    # 1. 计算新 batch_size
    new_bs = min(int(start_bs * (factor ** epoch)), max_bs)
    # 2. 第一次 epoch 直接建图,后续 epoch 复用基础 pipeline
    if epoch == 0:
        train_ds = make_dataset(start_bs)
    if new_bs != start_bs:          # 需要 rebatch
        train_ds = rebatch_dataset(train_ds, new_bs)
    # 3. 训练一个 epoch
    model.fit(train_ds, epochs=1, verbose=1)

要点解释

  • rebatch 只在已 batched 的 Dataset 上调用,避免重复 shuffle。
  • drop_remainder=True 保证静态 shape,XLA 不会报错。
  • 分布式场景下,把 new_bs 替换成 new_bs * strategy.num_replicas_in_sync,再 rebatch,最后 strategy.experimental_distribute_dataset(rebatched_ds)。
  • 如果数据量很大,可把基础 pipeline 做成 ds = ds.cache(),rebatch 之前 cache,避免重复解析。

拓展思考

  1. 能否在 Graph 内部做“真·动态 batch”?
    TensorFlow 2.x 的 tf.data 仍要求输出签名静态一致,所以 batch dimension 必须固定;真正动态 batch 需要 tf.raw_ops.BatchFunction 或 TensorFlow Serving 的 batching scheduler,训练阶段基本不用。

  2. 与 learning rate 联动:
    通常 batch size 放大 k 倍,lr 也放大 k 倍(线性缩放规则)。可在 rebatch 后同步调整 optimizer.learning_rate,保证收敛曲线平稳。

  3. 与混合精度、XLA 的冲突:
    rebatch 会改变张量 shape,若已开启 XLA,请保证 new_bs 始终为 8 的倍数,否则可能出现 cudnn 卷积算法选择失败。

  4. 生产环境建议:
    把“epoch → batch_size”策略写进 YAML,训练任务启动时一次性生成所有 epoch 的 Dataset 句柄列表,避免 epoch 切换时 Python GIL 阻塞数据预取线程;同时用 TensorBoard 的 tf.summary.scalar("batch_size", new_bs, step=epoch) 记录,方便复现实验。