o
    Xεi                     @   s   d dl mZmZ d dlmZmZmZmZmZ d dl	Z	d dl
mZ d dl	mZ d dlmZ e r5d dlmZ G dd	 d	eejZdS )
    )ABCabstractmethod)AnyDictListTupleUnionN)Coqpit)nn)is_apex_available)ampc                   @   s,  e Zd ZdZei ddejdefddZdedefdd	Z	dedefd
dZ
dededeeef fddZdededdfddZe dedefddZdededdfddZedededejjjfddZd$ddZdededeeeef fddZdejddd d!dededeeef fd"d#ZdS )%TrainerModeluB   Abstract 🐸TTS class. Every new 🐸TTS model must inherit this.)	aux_inputinputreturnc                O   s   ddi}	 |S )a
  Forward ... for the model mainly used in training.

        You can be flexible here and use different number of arguments and argument names since it is intended to be
        used by `train_step()` without exposing it out of the model.

        Args:
            input (torch.Tensor): Input tensor.
            aux_input (Dict): Auxiliary model inputs like embeddings, durations or any other sorts of inputs.

        Returns:
            Dict: Model outputs. Main model output must be named as "model_outputs".
        model_outputsN )selfr   r   argskwargsoutputs_dictr   r   A/home/ubuntu/.local/lib/python3.10/site-packages/trainer/model.pyforward   s   zTrainerModel.forwardbatchc                 C      |S )zFormat batch returned by the data loader before sending it to the model.

        If not implemented, model uses the batch as is.
        Can be used for data augmentation, feature ectraction, etc.
        r   r   r   r   r   r   format_batch&      zTrainerModel.format_batchc                 C   r   )zFormat batch on device before sending it to the model.

        If not implemented, model uses the batch as is.
        Can be used for data augmentation, feature ectraction, etc.`
        r   r   r   r   r   format_batch_on_device.   r   z#TrainerModel.format_batch_on_devicer   r   c                 O   
   	 t d)a  Perform a single training step. Run the model forward ... and compute losses.

        Args:
            batch (Dict): Input tensors.
            criterion (nn.Module): Loss layer designed for the model.
            optimizer_idx (int): Index of optimizer to use. 0 for the generator and 1 for the discriminator networks.

        Returns:
            Tuple[Dict, Dict]: Model ouputs and computed losses.
        z' [!] `train_step()` is not implemented.NotImplementedErrorr   r   r   r   r   r   
train_step6   s   zTrainerModel.train_stepNc                 O   r   )a  Create visualizations and waveform examples for training.

        For example, here you can plot spectrograms and generate sample sample waveforms from these spectrograms to
        be projected onto Tensorboard.

        Args:
            batch (Dict): Model inputs used at the previous training step.
            outputs (Dict): Model outputs generated at the previoud training step.
            logger (Logger): Logger instance to log training plots.
            assets (Dict): Assets to be used for logging from the trainer's closure.
            steps (int): Number of training steps taken so far.

        Returns:
            Tuple[Dict, np.ndarray]: training plots and output waveform.
        z& [!] `train_log()` is not implemented.r    r"   r   r   r   	train_logD      zTrainerModel.train_logc                 O   s   t d)a  Perform a single evaluation step. Run the model forward ... and compute losses. In most cases, you can
        call `train_step()` with no changes.

        Args:
            batch (Dict): Input tensors.
            criterion (nn.Module): Loss layer designed for the model.
            optimizer_idx (int): Index of optimizer to use. 0 for the generator and 1 for the discriminator networks.

        Returns:
            Tuple[Dict, Dict]: Model ouputs and computed losses.
        z& [!] `eval_step()` is not implemented.r    r"   r   r   r   	eval_stepW   s   zTrainerModel.eval_stepc                 O   r   )zThe same as `train_log()`z% [!] `eval_log()` is not implemented.r    r"   r   r   r   eval_logf   s   zTrainerModel.eval_logc                  O   r   )ae  Get data loader for the model.

        Args:
            config (Coqpit): Configuration object.
            assets (Dict): Additional assets to be used for data loading.
            is_eval (bool): If True, returns evaluation data loader.
            samples (Union[List[Dict], List[List]]): List of samples to be used for data loading.
            verbose (bool): If True, prints data loading information.
            num_gpus (int): Number of GPUs used for training.
            rank (int): Rank of the current GPU.

        Returns:
            torch.utils.data.DataLoader: Data loader for the model.
        z, [!] `get_data_loader()` is not implemented.r    )r   r   r   r   r   get_data_loaderk   s   zTrainerModel.get_data_loaderc                 C   s   dS )zInitialize model for training.Nr   )r   r   r   r   init_for_training   s   zTrainerModel.init_for_trainingc                 O   r   )a1  Model specific optimization step that must perform the following steps:
            1. Forward pass
            2. Compute loss
            3. Backward pass
            4. Update weights

        Use `self.scaled_backward()` instead of `loss.backward()` to be able to use Mixed Precision Training.

        Args:
            batch (Dict): Input tensors.
            trainer (Trainer): Trainer instance to be able to access the training closure.

        Returns:
            Tuple[Dict, Dict, float]: Model outputs, loss dictionary and grad_norm value.
        z% [!] `optimize()` is not implemented.r    r"   r   r   r   optimize   r%   zTrainerModel.optimizelosstrainerTrainer	optimizer	Optimizerc                 O   sf   |j r-|jr#t||}|  W d   dS 1 sw   Y  dS |j|  dS |  dS )aH  Backward pass with gradient scaling for custom `optimize` calls.

        Args:
            loss (torch.Tensor): Loss to be backpropagated.
            trainer (Trainer): Trainer instance to be able to access the training closure.
            optimizer (Optimizer): Optimizer for APEX AMP based scaled `backward` calls.
        N)use_amp_scaleruse_apexr   
scale_lossbackwardscalerscale)r   r+   r,   r.   r   r   scaled_lossr   r   r   scaled_backward   s   

"zTrainerModel.scaled_backward)r   N)__name__
__module____qualname____doc__r   torchTensorr   r   r   r   r   r   r#   r$   no_gradr&   r'   utilsdata
DataLoaderr(   r)   floatr*   boolr7   r   r   r   r   r      s8    
 
r   )abcr   r   typingr   r   r   r   r   r<   coqpitr	   r
   trainer.trainer_utilsr   apexr   Moduler   r   r   r   r   <module>   s    