o
    oi!                     @   s   d dl Z d dlmZmZmZmZ d dlZd dlmZm	Z	 d dl
mZ zd dlmZ W n ey5   dZY nw d dlmZmZ d dlmZ dd	lmZmZmZ g d
ZG dd dZdS )    N)AnyCallableDictOptional)	Optimizerlr_scheduler)
DataLoader)Accelerator)ModuleTensor)AverageMeter   )ConfigurationStatsTrackerTrainerState)

preprocessaugmentationsevaluatefit	fit_epochon_epoch_starton_before_modelon_after_modelon_checkpointon_epoch_endc                   @   s  e Zd ZdZ	d4dedee dee dee dede	j
d	ed
eeeed f  ddfddZedejfddZdeddfddZdeddfddZd5ddZe deeef fddZdededdfddZdeeef deeef fd d!Zdeeef deeef fd"d#Zdedeeef fd$d%Zdedefd&d'Z deeef deeef fd(d)Z!ded*eeef defd+d,Z"d-ed*eeef ddfd.d/Z#dedeeef ddfd0d1Z$dedeeef ddfd2d3Z%dS )6Trainera  Base class to train the different models in kornia.

    .. warning::
        The API is experimental and subject to be modified based on the needs of kornia models.

    Args:
        model: the nn.Module to be optimized.
        train_dataloader: the data loader used in the training loop.
        valid_dataloader: the data loader used in the validation loop.
        criterion: the nn.Module with the function that computes the loss.
        optimizer: the torch optimizer object to be used during the optimization.
        scheduler: the torch scheduler object with defiing the scheduling strategy.
        accelerator: the Accelerator object to distribute the training.
        config: a TrainerConfiguration structure containing the experiment hyper parameters.
        callbacks: a dictionary containing the pointers to the functions to overrides. The
          main supported hooks are ``evaluate``, ``preprocess``, ``augmentations`` and ``fit``.

    .. important::
        The API heavily relies on `accelerate <https://github.com/huggingface/accelerate/>`_.
        In order to use it, you must: ``pip install kornia[x]``

    .. seealso::
        Learn how to use the API in our documentation
        `here <https://kornia.readthedocs.io/en/latest/get-started/training.html>`_.

    Nmodeltrain_dataloadervalid_dataloader	criterion	optimizer	schedulerconfig	callbacks).Nreturnc	                 C   s   t d u rtdt  | _| j|| _| j|| _| j|| _|d u r'd n|| j| _	| j|| _
|| _|| _|d u rAi }| D ]\}	}
|	tvrUtd|	 dtt|	|
 qE|j| _tj| _td| _d S )Nz<accelerate library is not installed: pip install "kornia[x]"zNot supported: .train)r	   ModuleNotFoundErroracceleratorpreparer   r   r   todevicer   r    r!   r"   itemscallbacks_whitelist
ValueErrorsetattrr   
num_epochsr   STARTINGstatelogging	getLogger_logger)selfr   r   r   r   r    r!   r"   r#   fn_namefn r9   D/home/ubuntu/.local/lib/python3.10/site-packages/kornia/x/trainer.py__init__Q   s&   zTrainer.__init__c                 C   s   | j jS N)r(   r+   )r6   r9   r9   r:   r+   y   s   zTrainer.devicelossc                 C   s   | j | d S r<   )r(   backward)r6   r=   r9   r9   r:   r>   }   s   zTrainer.backwardepochc                 C   s  | j   t }t| jD ]v\}}|d |d d}| j  | |}| |}| 	|}| 
| j |}| || | ||d }| | | j  || t|d  |d dkr| jd|d  d| j d	|d  dt| j d
|jdd|jd qd S )Nr   r   inputtargetrB   rA   2   zTrain: /z
  Sample: z Loss: z.3f )r   r&   r   	enumerater   r    	zero_gradr   r   r   on_modelr   compute_lossr>   stepupdateitemlenr5   infor0   valavg)r6   r?   losses	sample_idsampleoutputr=   r9   r9   r:   r      s8   






zTrainer.fit_epochc                 C   sj   t | jD ]-}tj| _| | tj| _|  }| | j	|| | 
  | jtjkr- d S | j  qd S r<   )ranger0   r   TRAININGr2   r   VALIDATEr   r   r   r   	TERMINATEr!   rJ   )r6   r?   valid_statsr9   r9   r:   r      s   
zTrainer.fitc              	   C   s   | j   t }t| jD ]d\}}|d |d d}| |}| |}| | j |}| || t	|d }| j
d urM| ||d }|d| | || ||d | |d dkrq| jd| d	t	| j d
|  q| S )Nr   r   r@   rA   rB   rQ   
   zTest: rD   rE   )r   evalr   rF   r   r   r   rH   r   rM   r   rI   rK   rL   update_from_dictcompute_metricsr5   rN   as_dict)r6   statsrR   rS   out
batch_sizeval_lossr9   r9   r:   r      s"   



$zTrainer.evaluateargskwargsc                 O      d S r<   r9   r6   rc   rd   r9   r9   r:   r          zTrainer.on_epoch_startxc                 C      |S r<   r9   r6   rh   r9   r9   r:   r         zTrainer.preprocessc                 C   ri   r<   r9   rj   r9   r9   r:   r      rk   zTrainer.augmentationsc                 G   s   i S )z&Compute metrics during the evaluation.r9   r6   rc   r9   r9   r:   r]      s   zTrainer.compute_metricsc                 G   s   | j d u r	td| j | S )Nz`criterion` should not be None.)r   RuntimeErrorrl   r9   r9   r:   rI      s   

zTrainer.compute_lossc                 C   ri   r<   r9   rj   r9   r9   r:   r      rk   zTrainer.on_before_modelrS   c                 C   s   ||d S )NrA   r9   )r6   r   rS   r9   r9   r:   rH      s   zTrainer.on_modelrT   c                 C   re   r<   r9   )r6   rT   rS   r9   r9   r:   r      rg   zTrainer.on_after_modelc                 O   re   r<   r9   rf   r9   r9   r:   r      rg   zTrainer.on_checkpointc                 O   re   r<   r9   rf   r9   r9   r:   r      rg   zTrainer.on_epoch_endr<   )r$   N)&__name__
__module____qualname____doc__r
   r   r   r   r   r   _LRSchedulerr   r   strr   r;   propertytorchr+   r   r>   intr   r   no_gradr   r   r   r   r   floatr]   rI   r   rH   r   r   r   r9   r9   r9   r:   r   5   sN    $	

(
""""r   )r3   typingr   r   r   r   ru   torch.optimr   r   torch.utils.datar   
accelerater	   ImportErrorkornia.corer
   r   kornia.metricsr   utilsr   r   r   r-   r   r9   r9   r9   r:   <module>   s   