运行时错误:训练器回调钩子'on_log'失败,属性错误:'NoneType'对象没有属性'step'
RuntimeError: Trainer callback hook 'on_log' failed with AttributeError: 'NoneType' object has no attribute 'step'
ID: huggingface/trainer-callback-hook-failure
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| transformers>=4.35.0 | active | — | — | — |
根因分析
自定义回调的on_log方法在训练器状态完全初始化之前尝试访问trainer.state.global_step,通常发生在第一步记录日志时。
English
A custom callback's on_log method attempts to access trainer.state.global_step before the trainer state is fully initialized, typically when logging occurs during the first step.
官方文档
https://huggingface.co/docs/transformers/main/en/main_classes/callback解决方案
-
Add a guard in the callback to check if trainer.state is initialized: `if trainer.state.global_step is not None:` before accessing step.
-
Override the on_step_begin callback instead of on_log, as state is guaranteed to be initialized at step start.
-
Initialize the callback with a default step value: `self.step = 0` in __init__, then use self.step instead of trainer.state.global_step.
无效尝试
常见但无效的做法:
-
70% 失败
The root cause is accessing state before initialization; moving to another callback may still encounter the same issue if state is not ready.
-
90% 失败
This only postpones the error; it will still occur at the first log event regardless of step count.
-
85% 失败
The error is raised by the Trainer's callback execution wrapper; catching it inside the callback does not prevent the Trainer from propagating it.