a
    dPT                     @   sj  d dl Z 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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 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! d dl"m#Z#m$Z$ d dl%m&Z& d dl'm(Z(m)Z) d dl*m+Z+ d dl,m-Z- d dl.m/Z/ d dl0m1Z1 d dl2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8 edZ9edZ:e;e<Z=G dd deZ>dS )    N)ABCabstractmethod)
AnyCallableDict	GeneratorListMappingOptionalTupleTypeVarUnion)Tensor)Module)	Optimizer)
DataLoader)CheckpointIO)	_Launcher)move_data_to_device)ReduceOp)_optimizer_to_device_optimizers_to_device)_PATH)"_init_optimizers_and_lr_schedulersLightningOptimizer)TorchCheckpointIO)_WrappingCheckpointIO)PrecisionPlugin)	TrainerFn)LRSchedulerConfigPredictStepSTEP_OUTPUTTestStepTrainingStepValidationStep
TBroadcastTReducec                   @   s  e Zd ZdZded ee ee ddddZeee	 ddd	Z
eed dd
dZejdddddZeedddZejee ddddZeedddZejee ddddZeee dddZejee ddddZdddddZddddZddd d!Zd"dd#d$d%Zd"dd#d&d'Zddd(d)Zeeeef d*d+d,Zeee ee eeed-d.d/Zdeeeg ef ee de!f  eed0d1d2Z"e!ee e#e!ee f d3d4d5Z$e!e!dd6d7Z%eed*d8d9Z&deee'j( eed;d<d=Z)ee*e'j(dd>d?Z+e*ddd@dAZ,ee*e-ddBdCZ.e*de eef ee ee e/ef  e eef dEdFdGZ0e*dee ddHdIdJZ1e*de2ee2dKdLdMZ3e*deee e-edOdPdQZ4de-e-e-dSdTdUZ5eddVdWdXZ6eddVdYdZZ7eee! dd[d\Z8e8jee! dd]d^d\Z8eed dd_d`Z9e:eeef dadbdcZ;e<eef ddddedfZ=e<eef ddddgdhZ>eee?didjdkZ@dddldmZAeeee? didndoZBeeee? didpdqZCeee?didrdsZDe?e?dtdudvZEe?e?dtdwdxZFe?e?dtdydzZGeHeHd{d|d}ZIee-dd~dZJee-dddZKee-dddZLeeef dddZMdeeef e:ee ddddZNe:ddddZOePjQeRdddZSddddZTeUeeef ddddZVddddZWddddZXddddZYddddZZddddZ[ddddZ\ddddZ]ddddZ^eeddddZ_d"dd#ddZ`edddZaeddddZbdS )StrategyzcBase class for all strategies that change the behaviour of the training, validation and test- loop.Nzpl.accelerators.Accelerator)acceleratorcheckpoint_ioprecision_pluginreturnc                 C   s@   || _ || _|| _d | _d | _d | _g | _i | _g | _g | _	d S N)
_accelerator_checkpoint_io_precision_plugin_lightning_module_model	_launcher_optimizers_lightning_optimizerslr_scheduler_configsoptimizer_frequencies)selfr(   r)   r*    r8   n/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/pytorch_lightning/strategies/strategy.py__init__7   s    zStrategy.__init__)r+   c                 C   s   | j S r,   )r2   r7   r8   r8   r9   launcherH   s    zStrategy.launcherc                 C   s   | j S r,   r-   r;   r8   r8   r9   r(   L   s    zStrategy.accelerator)r(   r+   c                 C   s
   || _ d S r,   r=   )r7   r(   r8   r8   r9   r(   P   s    c                 C   s0   | j d u rt | _ nt| j tr*t | j _| j S r,   )r.   r   
isinstancer   r)   r;   r8   r8   r9   r)   T   s
    


zStrategy.checkpoint_io)ior+   c                 C   s
   || _ d S r,   )r.   )r7   r?   r8   r8   r9   r)   ]   s    c                 C   s   | j d ur| j S t S r,   )r/   r   r;   r8   r8   r9   r*   a   s    zStrategy.precision_plugin)r*   r+   c                 C   s
   || _ d S r,   )r/   )r7   r*   r8   r8   r9   r*   e   s    c                 C   s   | j S r,   )r3   r;   r8   r8   r9   
optimizersi   s    zStrategy.optimizers)r@   r+   c                    s$   | _  fddt jD  _d S )Nc                    s    i | ]\}}|t | |qS r8   )r   Z_to_lightning_optimizer).0idxoptr;   r8   r9   
<dictcomp>p   s   z'Strategy.optimizers.<locals>.<dictcomp>)r3   	enumerater@   r4   )r7   r@   r8   r;   r9   r@   m   s    
zpl.LightningModule)modelr+   c                 C   s   || _ || _dS )zTCalled by the accelerator to connect the accelerator and the model with this plugin.N)r0   rF   r7   rF   r8   r8   r9   connectt   s    zStrategy.connectc                 C   s   dS )z&Attach the launcher based on Strategy.Nr8   r;   r8   r8   r9   _configure_launchery   s    zStrategy._configure_launcherc                 C   s    | j dusJ | j | j dS )zSetup any processes or distributed connections.

        This is called before the LightningModule/DataModule setup hook which allows the user to access the accelerator
        environment before setup is complete.
        N)r(   Zsetup_deviceroot_devicer;   r8   r8   r9   setup_environment|   s    zStrategy.setup_environmentz
pl.Trainer)trainerr+   c                 C   s:   |j jtjkrdS | jdus J t| j\| _| _| _dS )zCreates optimizers and schedulers.

        Args:
            trainer: the Trainer, these optimizers should be connected to
        N)	statefnr   ZFITTINGlightning_moduler   r@   r5   r6   r7   rL   r8   r8   r9   setup_optimizers   s    zStrategy.setup_optimizersc                 C   s>   | j dusJ | j | | | |   t| j| j dS )z{Setup plugins for the trainer fit and creates optimizers.

        Args:
            trainer: the trainer instance
        N)r(   setuprQ   setup_precision_pluginr   r@   rJ   rP   r8   r8   r9   rR      s
    
zStrategy.setupc                 C   s@   | j dusJ | j| j | j| j\}}}|| _ || _|| _dS )z1Attaches the precision plugin to the accelerator.N)rF   r*   rH   r@   r5   )r7   rF   r@   r5   r8   r8   r9   rS      s    
zStrategy.setup_precision_plugin)	optimizerr+   c                 C   s<   t |tr|j}t|dr4|  | jr0| S i S | S )zReturns state of an optimizer.

        Allows for syncing/collating optimizer state from processes in custom plugins.
        consolidate_state_dict)r>   r   Z
_optimizerhasattrrU   is_global_zero
state_dictr7   rT   r8   r8   r9   optimizer_state   s    

zStrategy.optimizer_state)closure_lossrT   optimizer_idxargskwargsr+   c                 O   sh   |  | | jdusJ | j || j}| jj|| j||g|R i | | j|| j}| | |S )a  Forwards backward-calls to the precision plugin.

        Args:
            closure_loss: a tensor holding the loss value to backpropagate
            optimizer: An optional optimizer that gets passed down to the precision plugin's backward
            optimizer_idx: An optional optimizer index that gets passed down to the precision plugin's backward
            \*args: Positional arguments that get passed down to the precision plugin's backward, intended as arguments
                for the actual function that performs the backward, like :meth:`~torch.Tensor.backward`.
            \**kwargs: Keyword arguments for the same purpose as ``*args``.
        N)pre_backwardrO   r*   backwardpost_backward)r7   r[   rT   r\   r]   r^   r8   r8   r9   r`      s    
"
zStrategy.backward)rT   opt_idxclosurerF   r^   r+   c                 K   s6   |p| j }t|tjsJ | jj|f|||d|S )a~  Performs the actual optimizer step.

        Args:
            optimizer: the optimizer performing the step
            opt_idx: index of the current optimizer
            closure: closure calculating the loss value
            model: reference to the model, optionally defining optimizer step related hooks
            \**kwargs: Keyword arguments to to ``optimizer.step``
        )rF   r\   rc   )rO   r>   plZLightningModuler*   optimizer_step)r7   rT   rb   rc   rF   r^   r8   r8   r9   re      s    
zStrategy.optimizer_step)rF   r@   r+   c                    s$     |} fdd|D }||fS )zSetup a model and multiple optimizers together.

        The returned objects are expected to be in the same order they were passed in. The default implementation will
        call :meth:`_setup_model` and :meth:`_setup_optimizer` on the inputs.
        c                    s   g | ]}  |qS r8   )_setup_optimizer)rA   rT   r;   r8   r9   
<listcomp>       z8Strategy._setup_model_and_optimizers.<locals>.<listcomp>)_setup_model)r7   rF   r@   r8   r;   r9   _setup_model_and_optimizers   s    
z$Strategy._setup_model_and_optimizersc                 C   s   |S )zDPerforms setup for the model, e.g., by wrapping it by another class.r8   rG   r8   r8   r9   ri      s    zStrategy._setup_modelc                 C   s   |S )zHPerforms setup for the optimizer, e.g., by wrapping it by another class.r8   rY   r8   r8   r9   rf      s    zStrategy._setup_optimizerr   )batchdevicedataloader_idxr+   c                 C   s2   | j }|p| j}|dur(|j|||dS t||S )ay  Moves the batch to the correct device.

        The returned batch is of the same type as the input batch, just
        having all tensors on the correct device.

        Args:
            batch: The batch of samples to move to the correct device
            device: The target device
            dataloader_idx: The index of the dataloader to which the batch belongs.
        N)rl   rm   )rO   rJ   Z_apply_batch_transfer_handlerr   )r7   rk   rl   rm   rF   r8   r8   r9   batch_to_device  s
    
zStrategy.batch_to_devicec                 C   s   dS )zReturns the root device.Nr8   r;   r8   r8   r9   rJ     s    zStrategy.root_devicec                 C   s   dS )z&Moves the model to the correct device.Nr8   r;   r8   r8   r9   model_to_device  s    zStrategy.model_to_devicec                 C   s   dS )zcWhether the current process is the rank zero process not only on the local node, but for all nodes.Nr8   r;   r8   r8   r9   rW     s    zStrategy.is_global_zeromean)tensorgroup	reduce_opr+   c                 C   s   dS )a+  Reduces the given tensor (e.g. across GPUs/processes).

        Args:
            tensor: the tensor to sync and reduce
            group: the process group to reduce
            reduce_op: the reduction operation. Defaults to 'mean'.
                Can also be a string 'sum' or ReduceOp.
        Nr8   )r7   rq   rr   rs   r8   r8   r9   reduce"  s    zStrategy.reduce)namer+   c                 C   s   dS )zSynchronizes all processes which blocks processes until the whole group enters this function.

        Args:
            name: an optional name to pass into barrier.
        Nr8   )r7   ru   r8   r8   r9   barrier2  s    zStrategy.barrier)objsrcr+   c                 C   s   dS )zBroadcasts an object to all processes.

        Args:
            obj: the object to broadcast
            src: source rank
        Nr8   )r7   rw   rx   r8   r8   r9   	broadcast:  s    zStrategy.broadcastF)rq   rr   
sync_gradsr+   c                 C   s   dS )a  Perform an all_gather on all processes.

        Args:
            tensor: the tensor to all_gather
            group: the process group to gather results from
            sync_grads: flag that allows users to synchronize gradients for all_gather op
        Nr8   )r7   rq   rr   rz   r8   r8   r9   
all_gatherC  s    zStrategy.all_gatherT)decisionallr+   c                 C   s   |S )z/Reduce a boolean decision across all processes.r8   )r7   r|   r}   r8   r8   r9   reduce_boolean_decisionM  s    z Strategy.reduce_boolean_decision)r[   r+   c                 C   s   dS )z.Run before precision plugin executes backward.Nr8   r7   r[   r8   r8   r9   r_   Q  s    zStrategy.pre_backwardc                 C   s   dS )z-Run after precision plugin executes backward.Nr8   r   r8   r8   r9   ra   T  s    zStrategy.post_backwardc                 C   s   | j dur| j S | jS )z0Returns the potentially wrapped LightningModule.N)r1   r0   r;   r8   r8   r9   rF   W  s    zStrategy.model)	new_modelr+   c                 C   s
   || _ d S r,   )r1   )r7   r   r8   r8   r9   rF   \  s    c                 C   s   | j S )z<Returns the pure LightningModule without potential wrappers.)r0   r;   r8   r8   r9   rO   `  s    zStrategy.lightning_module)checkpoint_pathr+   c                 C   s   t j  | j|S r,   )torchZcudaZempty_cacher)   load_checkpoint)r7   r   r8   r8   r9   r   e  s    
zStrategy.load_checkpoint)
checkpointr+   c                 C   s"   | j d usJ | j |d  d S )NrX   )rO   load_state_dict)r7   r   r8   r8   r9   load_model_state_dicti  s    zStrategy.load_model_state_dictc                 C   s8   |d }t | j|D ]\}}|| t|| j qd S )Noptimizer_states)zipr@   r   r   rJ   )r7   r   r   rT   Z	opt_stater8   r8   r9   load_optimizer_state_dictm  s    
z"Strategy.load_optimizer_state_dict)r]   r^   r+   c                 O   sP   | j  2 t| jtsJ | jj|i |W  d   S 1 sB0    Y  dS )zThe actual training step.

        See :meth:`~pytorch_lightning.core.module.LightningModule.training_step` for more details
        N)r*   Ztrain_step_contextr>   rF   r#   training_stepr7   r]   r^   r8   r8   r9   r   s  s    zStrategy.training_stepc                 C   s   d S r,   r8   r;   r8   r8   r9   post_training_step|  s    zStrategy.post_training_stepc                 O   sP   | j  2 t| jtsJ | jj|i |W  d   S 1 sB0    Y  dS )zThe actual validation step.

        See :meth:`~pytorch_lightning.core.module.LightningModule.validation_step` for more details
        N)r*   Zval_step_contextr>   rF   r$   validation_stepr   r8   r8   r9   r     s    zStrategy.validation_stepc                 O   sP   | j  2 t| jtsJ | jj|i |W  d   S 1 sB0    Y  dS )z}The actual test step.

        See :meth:`~pytorch_lightning.core.module.LightningModule.test_step` for more details
        N)r*   Ztest_step_contextr>   rF   r"   	test_stepr   r8   r8   r9   r     s    zStrategy.test_stepc                 O   sP   | j  2 t| jtsJ | jj|i |W  d   S 1 sB0    Y  dS )zThe actual predict step.

        See :meth:`~pytorch_lightning.core.module.LightningModule.predict_step` for more details
        N)r*   Zpredict_step_contextr>   rF   r    predict_stepr   r8   r8   r9   r     s    zStrategy.predict_step)outputr+   c                 C   s   |S r,   r8   r7   r   r8   r8   r9   training_step_end  s    zStrategy.training_step_endc                 C   s   |S r,   r8   r   r8   r8   r9   validation_step_end  s    zStrategy.validation_step_endc                 C   s   |S r,   r8   r   r8   r8   r9   test_step_end  s    zStrategy.test_step_end)
dataloaderr+   c                 C   s   |S )zWraps the dataloader if necessary.

        Args:
            dataloader: iterable. Ideally of type: :class:`torch.utils.data.DataLoader`
        r8   )r7   r   r8   r8   r9   process_dataloader  s    zStrategy.process_dataloaderc                 C   s   dS )a  Override to delay restoring from checkpoint till after pre-dispatch. This is useful when the plugin
        requires all the setup hooks to run before loading checkpoint.

        Returns:
            If true, restore checkpoint after pre_dispatch.
        Fr8   r;   r8   r8   r9   restore_checkpoint_after_setup  s    z'Strategy.restore_checkpoint_after_setupc                 C   s   dS )zOverride to disable Lightning restoring optimizers/schedulers.

        This is useful for plugins which manage restoring optimizers/schedulers.
        Tr8   r;   r8   r8   r9   lightning_restore_optimizer  s    z$Strategy.lightning_restore_optimizerc                 C   s   dS )z<Whether the plugin handles gradient accumulation internally.Fr8   r;   r8   r8   r9   handles_gradient_accumulation  s    z&Strategy.handles_gradient_accumulationc                 C   s   | j dusJ | j  S )zReturns model state.N)rO   rX   r;   r8   r8   r9   lightning_module_state_dict  s    z$Strategy.lightning_module_state_dict)r   filepathstorage_optionsr+   c                 C   s   | j r| jj|||d dS )a>  Save model/training states as a checkpoint file through state-dump and file-write.

        Args:
            checkpoint: dict containing model and trainer state
            filepath: write-target file's path
            storage_options: parameter for how to save to storage, passed to ``CheckpointIO`` plugin
        )r   N)rW   r)   save_checkpoint)r7   r   r   r   r8   r8   r9   r     s    
zStrategy.save_checkpoint)r   r+   c                 C   s   | j r| j| dS )zpRemove checkpoint filepath from the filesystem.

        Args:
            filepath: Path to checkpoint
        N)rW   r)   remove_checkpoint)r7   r   r8   r8   r9   r     s    zStrategy.remove_checkpointc                 c   s
   dV  dS )a  Provide hook to create modules in a distributed aware context. This is useful for when we'd like to
        shard the model instantly, which is useful for extremely large models which can save memory and
        initialization time.

        Returns: Model parallel context.
        Nr8   r;   r8   r8   r9   model_sharded_context  s    zStrategy.model_sharded_contextc                 C   sj   t | jtd | jdur:t| jj d | j	  | j
  | jdusRJ | j  | j  dS )zThis method is called to teardown the training process.

        It is the right place to release memory and free other resources.
        cpuNz: moving model to CPU)r   r@   r   rl   rO   logZdetail	__class____name__r   r*   teardownr(   r)   r;   r8   r8   r9   r     s    



zStrategy.teardown)strategy_registryr+   c                 C   s   d S r,   r8   )clsr   r8   r8   r9   register_strategies  s    zStrategy.register_strategiesc                 C   s   dS )zCalled when train begins.Nr8   r;   r8   r8   r9   on_train_start  s    zStrategy.on_train_startc                 C   s   dS )zCalled when validation begins.Nr8   r;   r8   r8   r9   on_validation_start  s    zStrategy.on_validation_startc                 C   s   dS )zCalled when test begins.Nr8   r;   r8   r8   r9   on_test_start  s    zStrategy.on_test_startc                 C   s   dS )zCalled when predict begins.Nr8   r;   r8   r8   r9   on_predict_start  s    zStrategy.on_predict_startc                 C   s   dS )zCalled when train ends.Nr8   r;   r8   r8   r9   on_train_end
  s    zStrategy.on_train_endc                 C   s   dS )zCalled when validation ends.Nr8   r;   r8   r8   r9   on_validation_end  s    zStrategy.on_validation_endc                 C   s   dS )zCalled when test end.Nr8   r;   r8   r8   r9   on_test_end  s    zStrategy.on_test_endc                 C   s   dS )zCalled when predict ends.Nr8   r;   r8   r8   r9   on_predict_end  s    zStrategy.on_predict_end)rk   	batch_idxr+   c                 C   s   dS )zCCalled in the training loop before anything happens for that batch.Nr8   )r7   rk   r   r8   r8   r9   on_train_batch_start  s    zStrategy.on_train_batch_startc                 C   s   | j | dS )zFHook to do something before the training/evaluation/prediction starts.N)r*   dispatchrP   r8   r8   r9   r     s    zStrategy.dispatchc                 C   s   t t| }i |d< |S )Nr4   )dictvarsr7   rM   r8   r8   r9   __getstate__"  s    zStrategy.__getstate__)rM   r+   c                 C   s   || _ | j| _d S r,   )__dict__r@   r   r8   r8   r9   __setstate__(  s    zStrategy.__setstate__)NNN)N)Nr   )Nrp   )N)r   )NF)T)N)cr   
__module____qualname____doc__r
   r   r   r:   propertyr   r<   r(   setterr)   r*   r   r   r@   rH   rI   rK   rQ   rR   rS   r   strr   rZ   intr   r`   r   r   r   re   r   rj   ri   rf   r   rl   rn   r   rJ   ro   boolrW   r   rt   rv   r%   ry   r{   r~   r_   ra   rF   rO   r   r   r	   r   r   r!   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   
contextlibcontextmanagerr   r   r   classmethodr   r   r   r   r   r   r   r   r   r   r   r   r   r8   r8   r8   r9   r'   4   s     	
" 
"  

						 		r'   )?r   loggingabcr   r   typingr   r   r   r   r   r	   r
   r   r   r   r   r   Ztorch.nnr   Ztorch.optimr   Ztorch.utils.datar   Zpytorch_lightningrd   Zlightning_fabric.pluginsr   Z*lightning_fabric.strategies.launchers.baser   Zlightning_fabric.utilitiesr   Z&lightning_fabric.utilities.distributedr   Z$lightning_fabric.utilities.optimizerr   r   Z lightning_fabric.utilities.typesr   Z pytorch_lightning.core.optimizerr   r   Zpytorch_lightning.pluginsr   Z$pytorch_lightning.plugins.io.wrapperr   Z#pytorch_lightning.plugins.precisionr   Z pytorch_lightning.trainer.statesr   Z!pytorch_lightning.utilities.typesr   r    r!   r"   r#   r$   r%   r&   	getLoggerr   r   r'   r8   r8   r8   r9   <module>   s2   0 	
