# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0

"""Monitor betas during training."""


from composer.core import Callback, State
from composer.loggers import Logger
from llmfoundry.callbacks import callbacks

__all__ = ["BetasMonitor"]


@callbacks.register(name="betas_monitor")
class BetasMonitor(Callback):
    """Logs the betas.

    This callback iterates over all optimizers and their parameter groups to log
    betas under
    ``beta_{i}-{OPTIMIZER_NAME}/group{GROUP_NUMBER}`` keys.

    Example:
        .. doctest::

            >>> from composer import Trainer
            >>> from composer.callbacks import LRMonitor
            >>> # constructing trainer object with this callback
            >>> trainer = Trainer(
            ...     model=model,
            ...     train_dataloader=train_dataloader,
            ...     eval_dataloader=eval_dataloader,
            ...     optimizers=optimizer,
            ...     max_duration="1ep",
            ...     callbacks=[LRMonitor()],
            ... )

    The betas are logged by the :class:`.Logger` to the following key as described
    below.

    +---------------------------------------------+---------------------------------------+
    | Key                                         | Logged data                       |
    +=============================================+=======================================+
    |                                             | betas for each optimizer and  |
    | ``beta_{i}-{OPTIMIZER_NAME}/group{GROUP_NUMBER}`` | parameter group is |
    |                                             | logged to a separate key.         |
    +---------------------------------------------+---------------------------------------+

    """

    def batch_end(self, state: State, logger: Logger) -> None:  # noqa: PLR6301
        """Log the betas at the end of the batch.

        In case we are using schedulers over the betas.

        Parameters
        ----------
        state : State
            The current state of training.
        logger : Logger
            The logger to log the betas.

        """
        assert state.optimizers is not None, "optimizers must be defined"
        step = state.timestamp.batch.value
        for optimizer in state.optimizers:
            betas = [group["betas"] for group in optimizer.param_groups]
            for idx, beta_tuple in enumerate(betas):
                for i in range(len(beta_tuple)):
                    logger.log_metrics(
                        {f"beta{i + 1}-group{idx}": beta_tuple[i]},
                        step,
                    )
