a
    d0                     @   s   d dl Z d dlmZmZ d dlmZmZmZmZm	Z	m
Z
mZ d dlmZ d dlZd dlmZ d dlmZ d dlmZ d dlmZ e
d	ZG d
d deee ZdS )    N)ABCabstractmethod)AnyDictGenericOptionalTypeTypeVarUnion)Metric)_ResultCollection)BaseProgress)MisconfigurationException)_fault_tolerant_trainingTc                   @   s  e Zd ZdZddddZeddddZejddd	d
dZeedddZ	e	jeddddZ	ee
edddZeedddZd ddddZed ed  f ddddZedddZeeedddZe
ddddZeeddd d!Zeeddd"d#Ze
eeddd$d%Zddd&d'Zedd(d)Zddd*d+Zedd,d-Zedd.d/d0Zd:ee e ed2d3d4Z!d;ee eee e"f  dd5d6d7Z#d<ee eee e"f  dd5d8d9Z$dS )=LoopaB  Basic Loops interface. All classes derived from this must implement the following properties and methods:

        * :attr:`done` (property): Condition to break the loop
        * :attr:`reset` (method): Resets the internal state between multiple calls of :attr:`run`
        * :attr:`advance` (method): Implements one step of the loop

    This class implements the following loop structure:

    .. code-block:: python

        on_run_start()

        while not done:
            on_advance_start()
            advance()
            on_advance_end()

        on_run_end()
    N)returnc                 C   s   d| _ d | _d S )NF)_restarting_trainerself r   e/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/pytorch_lightning/loops/loop.py__init__2   s    zLoop.__init__z
pl.Trainerc                 C   s   | j d u rtd| j S )Nz&The loop is not attached to a Trainer.)r   RuntimeErrorr   r   r   r   trainer6   s    
zLoop.trainer)r   r   c                 C   s*   || _ | j D ]}t|tr||_qdS )z.Connects this loop's trainer and its children.N)r   __dict__values
isinstancer   r   )r   r   vr   r   r   r   <   s    
c                 C   s   | j S )zDWhether the state of this loop was reloaded and it needs to restart.)r   r   r   r   r   
restartingD   s    zLoop.restarting)r    r   c                 C   s,   || _ t|  D ]}t|tr||_qdS )z7Connects this loop's restarting value and its children.N)r   varsr   r   r   r    )r   r    loopr   r   r   r    I   s    
c                 C   s   dS )zProperty indicating when the loop is finished.

        Example::

            @property
            def done(self):
                return self.trainer.global_step >= self.trainer.max_steps
        Nr   r   r   r   r   doneQ   s    z	Loop.donec                 C   s   dS )zDetermine whether to return immediately from the call to :meth:`run`.

        Example::

            @property
            def skip(self):
                return len(self.trainer.train_dataloader) == 0
        Fr   r   r   r   r   skip]   s    
z	Loop.skip)kwargsr   c                 K   s   dS )zhOptionally connect one or multiple loops to this one.

        Linked loops should form a tree.
        Nr   )r   r%   r   r   r   connecti   s    zLoop.connect)loopsr   c           	   	      s   i }|  D ]\}}t| | t|trt jjj}t|jj}||krtt	d| jj
 d|j
 d jj
 d fdd|D }|f i |}n|}dd  j  D }|jf i | | j|_|||< q| jf i | dS )	a  Optionally replace one or multiple of this loop's sub-loops.

        This method takes care of instantiating the class (if necessary) with all existing arguments, connecting all
        sub-loops of the old loop to the new instance, setting the ``Trainer`` reference, and connecting the new loop to
        the parent.

        Args:
            **loops: ``Loop`` subclasses or instances. The name used should match the loop attribute name you want to
                replace.

        Raises:
            MisconfigurationException: When passing a ``Loop`` class, if the ``__init__`` arguments do not match those
                of the Loop class it replaces.
        `z	.replace(z<)` can only be used if the `__init__` signatures match but `z` does not.c                    s    i | ]}|d kr|t  |qS r   )getattr).0pZold_loopr   r   
<dictcomp>       z Loop.replace.<locals>.<dictcomp>c                 S   s    i | ]\}}t |tr||qS r   )r   r   )r*   nlpr   r   r   r-      r.   N)itemsr)   r   typeinspect	signature	__class__r   
parametersr   __name__r   r&   r   )	r   r'   Z	new_loopsnameZtype_or_objectZold_parametersZcurrent_parametersr%   r"   r   r,   r   replaceo   s(    


zLoop.replacec                 C   s   dS )zThe function to run when :meth:`run` should be skipped, determined by the condition in :attr:`skip`.

        Returns:
            the default output value of :meth:`on_run_end`
        Nr   r   r   r   r   on_skip   s    zLoop.on_skip)argsr%   r   c                 O   s   | j r|  S |   | j|i | | jsxz2| j|i | | j|i | |   d| _W q& t	yt   Y qxY q&0 q&d| _| 
 }|S )a  The main entry point to the loop.

        Will frequently check the :attr:`done` condition and calls :attr:`advance`
        until :attr:`done` evaluates to ``True``.

        Override this if you wish to change the default behavior. The default implementation is:

        Example::

            def run(self, *args, **kwargs):
                if self.skip:
                    return self.on_skip()

                self.reset()
                self.on_run_start(*args, **kwargs)

                while not self.done:
                    self.advance(*args, **kwargs)

                output = self.on_run_end()
                return output

        Returns:
            The output of :attr:`on_run_end` (often outputs collected from each step of the loop)
        F)r$   r:   reseton_run_startr#   on_advance_startadvanceon_advance_endr   StopIteration
on_run_end)r   r;   r%   outputr   r   r   run   s    
zLoop.runc                 C   s   dS )a\  Resets the internal state of the loop at the beginning of each call to :attr:`run`.

        Example::

            def reset(self):
                # reset your internal state or add custom logic
                # if you expect run() to be called multiple times
                self.current_iteration = 0
                self.outputs = []
        Nr   r   r   r   r   r<      s    z
Loop.resetc                 O   s   dS )zHook to be called as the first thing after entering :attr:`run` (except the state reset).

        Accepts all arguments passed to :attr:`run`.
        Nr   r   r;   r%   r   r   r   r=      s    zLoop.on_run_startc                 O   s   dS )z{Hook to be called each time before :attr:`advance` is called.

        Accepts all arguments passed to :attr`run`.
        Nr   rE   r   r   r   r>      s    zLoop.on_advance_startc                 O   s   dS )a#  Performs a single step.

        Accepts all arguments passed to :attr:`run`.

        Example::

            def advance(self, iterator):
                batch = next(iterator)
                loss = self.trainer.lightning_module.training_step(batch, batch_idx)
                ...
        Nr   rE   r   r   r   r?      s    zLoop.advancec                 C   s   dS )z<Hook to be called each time after :attr:`advance` is called.Nr   r   r   r   r   r@      s    zLoop.on_advance_endc                 C   s   dS )zlHook to be called at the end of the run.

        Its return argument is returned from :attr:`run`.
        Nr   r   r   r   r   rB      s    zLoop.on_run_endc                 C   s   dS )zUse to release memory etc.Nr   r   r   r   r   teardown  s    zLoop.teardownc                 C   s   i S )zCalled when saving a model checkpoint, use to persist loop state.

        Returns:
            The current loop state.
        r   r   r   r   r   on_save_checkpoint  s    zLoop.on_save_checkpoint)
state_dictr   c                 C   s   dS )zACalled when loading a model checkpoint, use to reload loop state.Nr   )r   rH   r   r   r   on_load_checkpoint  s    zLoop.on_load_checkpoint )destinationprefixr   c                 C   s   |du ri }|   ||d < t }| j D ]n\}}|| }t|trT| ||< q,t|trp|||d  q,|r,t|tr,|	  | ||< |
  q,|S )a>  The state dict is determined by the state and progress of this loop and all its children.

        Args:
            destination: An existing dictionary to update with this loop's state. By default a new dictionary
                is returned.
            prefix: A prefix for each key in the state dictionary
        NrH   .)rG   r   r   r1   r   r   rH   r   r   syncZunsync)r   rK   rL   Z
ft_enabledkr   keyr   r   r   rH     s    


zLoop.state_dict)rH   rL   metricsr   c                 C   sR   |  | || | j D ]*\}}t|tr|| || d  qd| _dS )z2Loads the state of this loop and all its children.rM   TN)_load_from_state_dictcopyr   r1   r   r   load_state_dictr    )r   rH   rL   rQ   rO   r   r   r   r   rT   ,  s
    
zLoop.load_state_dictc           	      C   s   | j }| j D ]\}}|| }||vr*qt|trD|||  qt|tr|d ur|jd urdd | jj	 D }|r|
| |j|| || jjjd | jjs|jdd q|d |v r| ||d   d S )Nc                 S   s    i | ]\}}t |tr||qS r   )r   r   )r*   r8   moduler   r   r   r-   D  s   
z.Loop._load_from_state_dict.<locals>.<dictcomp>)rQ   Zsync_fnF)rQ   rH   )r   r   r1   r   r   rT   r   Zlightning_moduler   Znamed_modulesupdateZstrategyreduceZis_global_zeror<   rI   )	r   rH   rL   rQ   r   rO   r   rP   Zmetric_attributesr   r   r   rR   9  s$    


zLoop._load_from_state_dict)NrJ   )rJ   N)N)%r7   
__module____qualname____doc__r   propertyr   setterboolr    r   r#   r$   r&   r
   r   r9   r   r:   r   rD   r<   r=   r>   r?   r@   rB   rF   r   rG   rI   r   strrH   r   rT   rR   r   r   r   r   r      sP   
-.   r   )r3   abcr   r   typingr   r   r   r   r   r	   r
   Ztorchmetricsr   Zpytorch_lightningplZ<pytorch_lightning.trainer.connectors.logger_connector.resultr   Z"pytorch_lightning.trainer.progressr   Z&pytorch_lightning.utilities.exceptionsr   Z#pytorch_lightning.utilities.importsr   r   r   r   r   r   r   <module>   s   $