o
    siZ                     @   s>   d dl Z d dlZd dlmZ ddlmZ G dd dejZdS )    N)ReduceLROnPlateau   )flatten_dictc                       s   e Zd ZU dZdZeed< 			d fdd	Zdd Zdd
dZ	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zedd Z  ZS ) Systemau  Base class for deep learning systems.
    Contains a model, an optimizer, a loss function, training and validation
    dataloaders and learning rate scheduler.

    Note that by default, any PyTorch-Lightning hooks are *not* passed to the model.
    If you want to use Lightning hooks, add the hooks to a subclass::

        class MySystem(System):
            def on_train_batch_start(self, batch, batch_idx, dataloader_idx):
                return self.model.on_train_batch_start(batch, batch_idx, dataloader_idx)

    Args:
        model (torch.nn.Module): Instance of model.
        optimizer (torch.optim.Optimizer): Instance or list of optimizers.
        loss_func (callable): Loss function with signature
            (est_targets, targets).
        train_loader (torch.utils.data.DataLoader): Training dataloader.
        val_loader (torch.utils.data.DataLoader): Validation dataloader.
        scheduler (torch.optim.lr_scheduler._LRScheduler): Instance, or list
            of learning rate schedulers. Also supports dict or list of dict as
            ``{"interval": "step", "scheduler": sched}`` where ``interval=="step"``
            for step-wise schedulers and ``interval=="epoch"`` for classical ones.
        config: Anything to be saved with the checkpoints during training.
            The config dictionary to re-instantiate the run for example.

    .. note:: By default, ``training_step`` (used by ``pytorch-lightning`` in the
        training loop) and ``validation_step`` (used for the validation loop)
        share ``common_step``. If you want different behavior for the training
        loop and the validation loop, overwrite both ``training_step`` and
        ``validation_step`` instead.

    For more info on its methods, properties and hooks, have a look at lightning's docs:
    https://pytorch-lightning.readthedocs.io/en/stable/lightning_module.html#lightningmodule-api
    val_lossdefault_monitorNc                    sV   t    || _|| _|| _|| _|| _|| _|d u ri n|| _| 	| 
| j d S N)super__init__model	optimizer	loss_functrain_loader
val_loader	schedulerconfigsave_hyperparametersconfig_to_hparams)selfr   r   r   r   r   r   r   	__class__ J/home/ubuntu/.local/lib/python3.10/site-packages/asteroid/engine/system.pyr
   .   s   

zSystem.__init__c                 O   s   | j |i |S )z_Applies forward pass of the model.

        Returns:
            :class:`torch.Tensor`
        )r   )r   argskwargsr   r   r   forwardC   s   zSystem.forwardTc                 C   s    |\}}| |}|  ||}|S )a  Common forward step between training and validation.

        The function of this method is to unpack the data given by the loader,
        forward the batch through the model and compute the loss.
        Pytorch-lightning handles all the rest.

        Args:
            batch: the object returned by the loader (a list of torch.Tensor
                in most cases) but can be something else.
            batch_nb (int): The number of the batch in the epoch.
            train (bool): Whether in training mode. Needed only if the training
                and validation steps are fundamentally different, otherwise,
                pytorch-lightning handles the usual differences.

        Returns:
            :class:`torch.Tensor` : The loss value on this batch.

        .. note::
            This is typically the method to overwrite when subclassing
            ``System``. If the training and validation steps are somehow
            different (except for ``loss.backward()`` and ``optimzer.step()``),
            the argument ``train`` can be used to switch behavior.
            Otherwise, ``training_step`` and ``validation_step`` can be overwriten.
        )r   )r   batchbatch_nbtraininputstargetsest_targetslossr   r   r   common_stepK   s   zSystem.common_stepc                 C   s$   | j ||dd}| jd|dd |S )a  Pass data through the model and compute the loss.

        Backprop is **not** performed (meaning PL will do it for you).

        Args:
            batch: the object returned by the loader (a list of torch.Tensor
                in most cases) but can be something else.
            batch_nb (int): The number of the batch in the epoch.

        Returns:
            torch.Tensor, the value of the loss.
        Tr   r"   )loggerr#   logr   r   r   r"   r   r   r   training_stepi   s   zSystem.training_stepc                 C   s&   | j ||dd}| jd|ddd dS )a  Need to overwrite PL validation_step to do validation.

        Args:
            batch: the object returned by the loader (a list of torch.Tensor
                in most cases) but can be something else.
            batch_nb (int): The number of the batch in the epoch.
        Fr$   r   T)on_epochprog_barNr&   r(   r   r   r   validation_stepz   s   zSystem.validation_stepc                 C   s:   | j jdd}|dur| j jjd|i| j jd dS dS )z3Log hp_metric to tensorboard for hparams selection.r   N	hp_metricstep)trainercallback_metricsgetr%   log_metricsglobal_step)r   r-   r   r   r   on_validation_epoch_end   s   zSystem.on_validation_epoch_endc                 C   s   | j du r| jS t| j ttfs| j g| _ g }| j D ]>}t|ts2t|tr,|| jd}|| q|	d| j |	dd |d dkrId|d< |d d	v sSJ d
|| q| jg|fS )z<Initialize optimizers, batch-wise and epoch-wise schedulers.N)r   monitorr6   	frequency   intervalr   r/   )epochr/   z1Scheduler interval should be either step or epoch)
r   r   
isinstancelisttupledictr   r   append
setdefault)r   epoch_schedulersschedr   r   r   configure_optimizers   s&   




zSystem.configure_optimizersc                 C   s"   |d u r
|   d S | | d S r   r.   )r   r   metricr   r   r   lr_scheduler_step   s   zSystem.lr_scheduler_stepc                 C      | j S )zTraining dataloader)r   r   r   r   r   train_dataloader      zSystem.train_dataloaderc                 C   rF   )zValidation dataloader)r   rG   r   r   r   val_dataloader   rI   zSystem.val_dataloaderc                 C   s   | j |d< |S )z<Overwrite if you want to save more things in the checkpoint.training_config)r   )r   
checkpointr   r   r   on_save_checkpoint   s   
zSystem.on_save_checkpointc                 C   sP   t | } |  D ]\}}|du rt|| |< qt|ttfr%t|| |< q| S )aJ  Sanitizes the config dict to be handled correctly by torch
        SummaryWriter. It flatten the config dict, converts ``None`` to
        ``"None"`` and any list and tuple into torch.Tensors.

        Args:
            dic (dict): Dictionary to be transformed.

        Returns:
            dict: Transformed dictionary.
        N)r   itemsstrr;   r<   r=   torchtensor)dickvr   r   r   r      s   zSystem.config_to_hparams)NNN)T)__name__
__module____qualname____doc__r   rO   __annotations__r
   r   r#   r)   r,   r5   rC   rE   rH   rJ   rM   staticmethodr   __classcell__r   r   r   r   r      s&   
 #
r   )	rP   pytorch_lightningpltorch.optim.lr_schedulerr   utilsr   LightningModuler   r   r   r   r   <module>   s
    