a
    d                     @   s   d dl Z d dlmZmZmZ d dlZd dlmZ d dlm	Z	 zd dl
mZ W n eyb   dZY n0 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)CallableDictOptional)
DataLoader)Accelerator)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i fejeeeej ej	j
ej	jjeeeef dd	ddZeejdddZejdd	d
dZeddddZddddZe edddZdd ZeedddZeedddZejeeef dddZ ejejdddZ!eeddd Z"ed!d"d#Z#ejed$d%d&Z$d'd( Z%d)d* Z&dS )+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returnc	                 C   s   t d u rtdt  | _| j|| _| j|| _| j|| _|d u rNd n
|| j| _	| j|| _
|| _|| _| D ],\}	}
|	tvrtd|	 dtt|	|
 q~|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   ZSTARTINGstatelogging	getLogger_logger)selfr   r   r   r   r   r   r   r   fn_namefn r3   Y/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/kornia/x/trainer.py__init__>   s"    zTrainer.__init__)r   c                 C   s   | j jS N)r#   r&   )r0   r3   r3   r4   r&   d   s    zTrainer.device)lossr   c                 C   s   | j | d S r6   )r#   backward)r0   r7   r3   r3   r4   r8   h   s    zTrainer.backward)epochr   c                 C   s  | j   t }t| jD ]\}}|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targetr<   r;   2   zTrain: /z
  Sample: z Loss: z.3f )r   r!   r   	enumerater   r   Z	zero_gradr   r   r   on_modelr   compute_lossr8   stepupdateitemlenr/   infor+   valavg)r0   r9   losses	sample_idsampleoutputr7   r3   r3   r4   r   k   s4    






zTrainer.fit_epochc                 C   sh   t | jD ]X}tj| _| | tj| _|  }| | j	|| | 
  | jtjkrX qd| j  q
d S r6   )ranger+   r   ZTRAININGr,   r   ZVALIDATEr   r   r   r   Z	TERMINATEr   rC   )r0   r9   Zvalid_statsr3   r3   r4   r      s    
zTrainer.fitc              	   C   s   | j   t }t| jD ]\}}|d |d d}| |}| |}| | j |}| || t	|d }| j
d ur| ||d }|d| | || ||d | |d dkr| jd| d	t	| j d
|  q| S )Nr   r   r:   r;   r<   rJ   
   zTest: r>   r?   )r   evalr
   r@   r   r   r   rA   r   rF   r   rB   rD   rE   Zupdate_from_dictcompute_metricsr/   rG   Zas_dict)r0   statsrK   rL   outZ
batch_sizeZval_lossr3   r3   r4   r      s     



&zTrainer.evaluatec                 O   s   d S r6   r3   r0   argskwargsr3   r3   r4   r      s    zTrainer.on_epoch_start)xr   c                 C   s   |S r6   r3   r0   rW   r3   r3   r4   r      s    zTrainer.preprocessc                 C   s   |S r6   r3   rX   r3   r3   r4   r      s    zTrainer.augmentations)rU   r   c                 G   s   i S )z&Compute metrics during the evaluation.r3   r0   rU   r3   r3   r4   rQ      s    zTrainer.compute_metricsc                 G   s   | j d u rtd| j | S )Nz`criterion` should not be None.)r   RuntimeErrorrY   r3   r3   r4   rB      s    
zTrainer.compute_lossc                 C   s   |S r6   r3   rX   r3   r3   r4   r      s    zTrainer.on_before_model)rL   c                 C   s   ||d S )Nr;   r3   )r0   r   rL   r3   r3   r4   rA      s    zTrainer.on_model)rM   rL   c                 C   s   d S r6   r3   )r0   rM   rL   r3   r3   r4   r      s    zTrainer.on_after_modelc                 O   s   d S r6   r3   rT   r3   r3   r4   r      s    zTrainer.on_checkpointc                 O   s   d S r6   r3   rT   r3   r3   r4   r      s    zTrainer.on_epoch_end)'__name__
__module____qualname____doc__nnModuler   r   torchZoptimZ	OptimizerZlr_schedulerZCosineAnnealingLRr	   r   strr   r5   propertyr&   ZTensorr8   intr   r   Zno_graddictr   r   r   r   floatrQ   rB   r   rA   r   r   r   r3   r3   r3   r4   r   #   s<   #
&r   )r-   typingr   r   r   ra   Ztorch.nnr_   Ztorch.utils.datar   Z
accelerater   ImportErrorZkornia.metricsr   utilsr	   r
   r   r(   r   r3   r3   r3   r4   <module>   s   
