# 运行时错误：训练器回调钩子'on_log'失败，属性错误：'NoneType'对象没有属性'step'

- **ID:** `huggingface/trainer-callback-hook-failure`
- **领域:** huggingface
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

自定义回调的on_log方法在训练器状态完全初始化之前尝试访问trainer.state.global_step，通常发生在第一步记录日志时。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| transformers>=4.35.0 | active | — | — |

## 解决方案

1. ```
   Add a guard in the callback to check if trainer.state is initialized: `if trainer.state.global_step is not None:` before accessing step.
   ```
2. ```
   Override the on_step_begin callback instead of on_log, as state is guaranteed to be initialized at step start.
   ```
3. ```
   Initialize the callback with a default step value: `self.step = 0` in __init__, then use self.step instead of trainer.state.global_step.
   ```

## 无效尝试

- **** — The root cause is accessing state before initialization; moving to another callback may still encounter the same issue if state is not ready. (70% 失败率)
- **** — This only postpones the error; it will still occur at the first log event regardless of step count. (90% 失败率)
- **** — The error is raised by the Trainer's callback execution wrapper; catching it inside the callback does not prevent the Trainer from propagating it. (85% 失败率)
