Lightning-AI/pytorch-lightning · error · MisconfigurationException

You are trying to `self.log()` but it is not managed by the

Error message

You are trying to `self.log()` but it is not managed by the `Trainer` control flow

What it means

self.log relies on _current_fx_name, an internal marker the Trainer sets before invoking each hook, to decide default on_step/on_epoch behavior. If self.log is called outside that managed control flow (no hook context), the _FxValidator cannot validate the call and MisconfigurationException is raised.

Source

Thrown at src/lightning/pytorch/core/module.py:471

                "You are trying to `self.log()` but the `self.trainer` reference is not registered on the model yet."
                " This is most likely because the model hasn't been passed to the `Trainer`"
            )
            return
        if trainer.barebones:
            rank_zero_warn(
                "You are trying to `self.log()` but `Trainer(barebones=True)` is configured."
                " Logging can impact raw speed so it is disabled under this setting."
            )
            return
        results = trainer._results
        if results is None:
            raise MisconfigurationException(
                "You are trying to `self.log()` but the loop's result collection is not registered"
                " yet. This is most likely because you are trying to log in a `predict` hook,"
                " but it doesn't support logging"
            )
        if self._current_fx_name is None:
            raise MisconfigurationException(
                "You are trying to `self.log()` but it is not managed by the `Trainer` control flow"
            )

        on_step, on_epoch = _FxValidator.check_logging_and_get_default_levels(
            self._current_fx_name, on_step=on_step, on_epoch=on_epoch
        )

        # make sure user doesn't introduce logic for multi-dataloaders
        if add_dataloader_idx and "/dataloader_idx_" in name:
            raise MisconfigurationException(
                f"You called `self.log` with the key `{name}`"
                " but it should not contain information about `dataloader_idx` when `add_dataloader_idx=True`"
            )

        value = apply_to_collection(value, (Tensor, numbers.Number), self.__to_tensor, name)

        if trainer._logger_connector.should_reset_tensors(self._current_fx_name):
            # if we started a new epoch (running its first batch) the hook name has changed

View on GitHub (pinned to 9fed5c27d2)

Solutions

  1. Move the self.log call inside a proper hook (training_step, validation_step, on_train_batch_end, etc.)
  2. For logging outside the loop, use trainer.logger or an external logger directly
  3. Pass explicit on_step/on_epoch only when already inside a supported hook (the fx name must still be set)

Example fix

# before
model = MyModel()
model.log('loss', 0.5)  # outside Trainer control flow

# after
class MyModel(L.LightningModule):
    def training_step(self, batch, batch_idx):
        loss = ...
        self.log('loss', loss)  # inside managed hook
        return loss
Defensive patterns

Strategy: validation

Validate before calling

if self._current_fx_name is None:
    # outside a Trainer-managed hook; use an external logger
    trainer.logger.log_metrics({name: float(value)})
else:
    self.log(name, value)

Type guard

def inside_trainer_hook(module) -> bool:
    return getattr(module, '_current_fx_name', None) is not None

Try / catch

try:
    self.log(name, value)
except MisconfigurationException as e:
    if 'not managed by the `Trainer` control flow' in str(e):
        self.logger and self.logger.log_metrics({name: float(value)})
    else:
        raise

Prevention

When it happens

Trigger: Calling self.log in code not invoked by the Trainer: in __init__, in helper functions called manually, in dataloader methods, or before trainer.fit has started the loop.

Common situations: User calls model.log('loss', loss) while debugging outside training; logs from a DataLoader worker function or from on_before_backward called manually; logs in setup before results registration in some paths.

Related errors


AI-assisted analysis of Lightning-AI/pytorch-lightning@9fed5c27d2 (2026-08-28). Data as JSON: /api/errors/eaeb6cb87457e5b1. Report an issue: GitHub.