直接用CosineDecay训练不稳因缺乏warmup阶段,导致初期梯度噪声大、BN统计不稳定;需自定义WarmupCosineDecay类,按step线性warmup后接余弦衰减,并确保total_steps精确计算。

为什么直接用 CosineDecay 会训练不稳?
因为余弦衰减从初始学习率直接开始下降,缺乏 warmup 阶段——前几十个 step 梯度噪声大、batch norm 统计不稳定,模型容易发散。尤其在小 batch 或大模型(如 ViT、ResNet-50)上,loss 会剧烈震荡甚至 NaN。
TensorFlow 2.x 的 tf.keras.optimizers.schedules.CosineDecay 本身不支持 warmup,必须手动组合或改用 CosineDecayRestarts + 自定义 wrapper,但更稳妥的做法是用 LearningRateSchedule 子类封装 warmup + cosine 主体。
- 不要把 warmup 步数设成 0 —— 即使数据集小,也建议至少
warmup_steps=500 -
initial_learning_rate在 warmup 阶段是“目标值”,不是起点;实际从接近 0 线性升到它 - cosine 部分的
alpha(最小学习率比例)别设太低,alpha=0.001比0.0更稳,避免后期梯度更新过弱
怎么手写 WarmupCosineDecay 类?
继承 tf.keras.optimizers.schedules.LearningRateSchedule,重写 __call__ 方法,按 step 判断阶段:warmup 还是 cosine decay。关键点是 step 计数必须全局、不可重置(不能依赖 epoch)。
class WarmupCosineDecay(tf.keras.optimizers.schedules.LearningRateSchedule):
def __init__(self, initial_learning_rate, warmup_steps, total_steps, alpha=0.001):
self.initial_learning_rate = initial_learning_rate
self.warmup_steps = warmup_steps
self.total_steps = total_steps
self.alpha = alpha
<pre class="brush:php;toolbar:false;">def __call__(self, step):
# warmup: linear from 0 to initial_learning_rate
if step < self.warmup_steps:
return self.initial_learning_rate * (step / self.warmup_steps)
# cosine decay: from initial_learning_rate down to alpha * initial_learning_rate
if step >= self.total_steps:
return self.initial_learning_rate * self.alpha
progress = (step - self.warmup_steps) / (self.total_steps - self.warmup_steps)
return self.initial_learning_rate * (0.5 * (1.0 + tf.math.cos(np.pi * progress)) * (1 - self.alpha) + self.alpha)
立即学习“Python免费学习笔记(深入)”;
让 macOS 自动化像说话一样简单 —— 用代码控制你的 Mac,无需学习 AppleScript 系统要求 macOS 14+ (Sonoma) Python 3.9+ 需要开启:辅助功能 + 屏幕录制权限
- 注意
step是 int64 tensor,不能用 Pythonmin()或max(),要用tf.minimum/tf.maximum(示例中省略了,实操需补) -
total_steps必须是训练总 step 数(epochs * steps_per_epoch),不是 epoch 数 - 如果用
tf.data.Dataset+repeat(),确保steps_per_epoch显式设置,否则step可能超界
如何传给 Adam 并验证是否生效?
直接把 schedule 实例传给优化器的 learning_rate 参数即可,TensorFlow 会在每个 step 自动调用 __call__。验证重点不是看日志里有没有 “lr”,而是确认它真在变:
- 加回调:
tf.keras.callbacks.LearningRateScheduler(lambda epoch, lr: print(f"Step {epoch}: lr={lr}"))不适用——这是按 epoch 调用;要用tf.keras.callbacks.Callback重写on_train_batch_begin,读optimizer.learning_rate - 训练前打印
schedule(0)、schedule(warmup_steps//2)、schedule(warmup_steps),确认数值符合预期 - 如果 loss 曲线前 1k step 下降缓慢但平滑,第 1.5k step 后开始加速下降,说明 warmup + cosine 已起效;若前 100 step 就爆炸,大概率
warmup_steps太小或initial_learning_rate太高
用 CosineDecayRestarts 能替代吗?
不能直接替代。虽然名字带 “cosine” 和 “restarts”,但它本质是周期性余弦衰减(如预热后衰减→重启→再衰减),适用于 continual learning 或 multi-stage fine-tuning,**不是 warmup + single cosine decay**。
常见误用:CosineDecayRestarts(initial_learning_rate=1e-3, first_decay_steps=1000) —— 这会让 lr 在 step 0 就是 1e-3,step 1000 降到最低,然后 step 1001 又跳回 1e-3,完全违背 warmup 设计初衷。
- 如果你硬要复用内置类,唯一办法是先用
PolynomialDecay做 warmup,再用CosineDecay接续,但需自定义LearningRateSchedule把两者拼起来 -
CosineDecayRestarts的t_mul和m_mul参数会改变周期长度和振幅,调试成本远高于手写一个 20 行的WarmupCosineDecay - 官方文档没提 warmup,社区常见方案(如 TensorFlow Addons 的
LinearWarmup)已弃用,当前最可控路径仍是自定义 schedule
实际部署时,最容易被忽略的是 total_steps 的计算精度:用 len(dataset)//batch_size 会丢掉最后一个不完整 batch,导致 cosine 阶段提前终止;务必用 tf.data.experimental.cardinality(dataset).numpy() // batch_size 或显式指定 steps_per_epoch。

















