def on_step_begin(
self, state: TrainerState, micro_batches: list[dict[str, Any]] | None = None, **kwargs: Any,
) -> None:
"""Reset per-step metric state, including steps that do not emit a log."""
del state, micro_batches, kwargs
self._router_aux_sum = None
self._router_aux_count = 0
self._micro_step_outputs_seen = False
def on_micro_step_end(self, state: TrainerState, loss_dict: dict[str, Any], **kwargs: Any) -> None:
"""Accumulate detached router outputs without synchronizing device scalars."""
del state, kwargs
if self.logging_steps <= 0 or getattr(self.trainer, "global_rank", 0) != 0:
return
self._micro_step_outputs_seen = True
aux_loss = loss_dict.get("router_aux_loss") if loss_dict is not None else None
if aux_loss is not None:
value = aux_loss.detach()
if self._router_aux_sum is None:
# Graph executors may reuse output storage on the next microbatch.
self._router_aux_sum = value.clone()
else:
self._router_aux_sum += value
self._router_aux_count += 1
@staticmethod
def _format_value(value: Any) -> str:
"""Format a scalar metric compactly for one terminal line."""