a
    dGS                     @   s.  d dl Z d dlZd dlZd dlZd dlZd dlZd dlmZ d dlm	Z	 d dl
mZmZmZmZmZmZ d dl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mZ d d
lm Z  d dl!m"Z"m#Z#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/m0Z0 d dl1m2Z2 d dl3m4Z4 d dl5m6Z6 d dl7m8Z8 d dl9m:Z: d dl;m<Z< d dl=m>Z> d dl?m@Z@ d dlAmBZB d dlCmDZD d dlEmFZF d dlGmHZH d dlImJZJmKZKmLZL d dlMmNZNmOZOmPZPmQZQ e:rd dlRmSZS neTZSejUV rd d lWmXZX e YeZZ[G d!d" d"e@Z\dS )#    N)	timedelta)Path)AnyCallableDictListOptionalUnion)Tensor)Module)DistributedDataParallel)	Optimizer)CheckpointIOClusterEnvironment)default_pg_timeout)_distributed_available-_get_default_process_group_backend_for_device_init_dist_connection_sync_ddp_if_availablegroup)_IS_WINDOWS_TORCH_GREATER_EQUAL_1_11)_optimizers_to_device)
reset_seed)ReduceOp)LightningOptimizer)LightningDistributedModule)$_LightningPrecisionModuleWrapperBase)prepare_for_backward)_FAIRSCALE_AVAILABLE)PrecisionPlugin)_SubprocessScriptLauncher)ParallelStrategy)
TBroadcast)	TrainerFn)register_ddp_comm_hook)DeadlockDetectedException)rank_zero_inforank_zero_onlyrank_zero_warn)PredictStepSTEP_OUTPUTTestStepValidationStep)OSS)ModelAveragerc                       s@  e Zd ZdZdZddddddddddefed eeej	  ee
 ee ee ee ee ee ee ee ee edd fddZeedd	d
Zeej	dddZeedddZejeddddZeedddZeeeef dddZeedddZeee dddZddddZdd fddZ ddddd Z!e"e#d!d"d#Z$ddd$d%Z%edd&d'Z&ddd(d)Z'ddd*d+Z(ddd,d-Z)ddd.d/Z*d`e+eeg ef ee,d0e"f  eed1 fd2d3Z-ddd4d5Z.eee  dd6d7Z/eedd8d9d:Z0dae1ee1d<d=d>Z2e3dd?d@dAZ4dddBdCZ5dbe3ee ee,e6ef  e3dEdFdGZ7eee8d8dHdIZ9eeee8 d8dJdKZ:eeee8 d8dLdMZ;eee8d8dNdOZ<dddPdQZ=e>eddRdSdTZ?eddUdVZ@dddWdXZAdddYdZZBedd[d\d]ZCdd fd^d_ZD  ZES )cDDPStrategyzKStrategy for multi-process single-device training on one or multiple nodes.ZddpNzpl.accelerators.Accelerator)acceleratorparallel_devicescluster_environmentcheckpoint_ioprecision_pluginddp_comm_stateddp_comm_hookddp_comm_wrappermodel_averaging_periodprocess_group_backendtimeoutkwargsreturnc                    sv   t  j|||||d t| jj d d| _|| _|| _|| _	|| _
|	| _d | _g | _d | _d| _|
| _|| _d S )N)r2   r3   r4   r5   r6   z: initializing DDP plugin   F)super__init__logdetail	__class____name__
_num_nodes_ddp_kwargs_ddp_comm_state_ddp_comm_hook_ddp_comm_wrapper_model_averaging_period_model_averager_pids	_sync_dir"_rank_0_will_call_children_scripts_process_group_backend_timeout)selfr2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   rD    i/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/pytorch_lightning/strategies/ddp.pyrA   K   s(    zDDPStrategy.__init__)r>   c                 C   s   dS NTrT   rR   rT   rT   rU   is_distributedo   s    zDDPStrategy.is_distributedc                 C   s   | j d usJ | j | j S N)r3   
local_rankrW   rT   rT   rU   root_devices   s    zDDPStrategy.root_devicec                 C   s   | j S rY   rF   rW   rT   rT   rU   	num_nodesx   s    zDDPStrategy.num_nodes)r]   r>   c                 C   s
   || _ d S rY   r\   )rR   r]   rT   rT   rU   r]   |   s    c                 C   s   | j d urt| j S dS Nr   )r3   lenrW   rT   rT   rU   num_processes   s    zDDPStrategy.num_processesc                 C   s   t | j| j | jdS )N)Znum_replicasrank)dictr]   r`   global_rankrW   rT   rT   rU   distributed_sampler_kwargs   s    z&DDPStrategy.distributed_sampler_kwargsc                 C   s   dS rV   rT   rW   rT   rT   rU    _is_single_process_single_device   s    z,DDPStrategy._is_single_process_single_devicec                 C   s   | j S rY   )rP   rW   rT   rT   rU   r;      s    z!DDPStrategy.process_group_backendc                 C   s4   | j d usJ | j js0t| j | j| j| _d| _d S rV   )r4   Zcreates_processes_externallyr"   r`   r]   Z	_launcherrO   rW   rT   rT   rU   _configure_launcher   s    zDDPStrategy._configure_launcherc                    s   |    t   d S rY   )setup_distributedr@   setup_environmentrW   rS   rT   rU   rh      s    zDDPStrategy.setup_environmentz
pl.Trainer)trainerr>   c                 C   s   t | | j| _|  r"|   | jd us0J | j| |   |jj	}|t
jkrz| jrz| jd usjJ | j| j| _|   |t
jkr|   | | t| j| j |t
jkrdd lm  m  m  m} t| j|jr|   d S r^   )bool	broadcastrO   _should_run_deadlock_detection&_share_information_to_prevent_deadlockr2   setupmodel_to_devicestatefnr%   FITTING_layer_syncmodelapplyZsetup_precision_pluginconfigure_ddpZsetup_optimizersr   
optimizersr[   Z>torch.distributed.algorithms.ddp_comm_hooks.post_localSGD_hookdistributed
algorithmsZddp_comm_hooksZpost_localSGD_hook
isinstancerH   ZPostLocalSGDState_enable_model_averaging)rR   ri   Z
trainer_fnZpost_localSGDrT   rT   rU   rn      s(    



zDDPStrategy.setup)rt   r>   c                 C   s6   |   }td| d| j  tf ||d| jS )z^Wraps the model into a :class:`~torch.nn.parallel.distributed.DistributedDataParallel` module.z&setting up DDP model with device ids: z
, kwargs: )module
device_ids)determine_ddp_device_idsrB   rC   rG   r   )rR   rt   r}   rT   rT   rU   _setup_model   s    zDDPStrategy._setup_modelc                 C   sZ   t | jj d t  |   | jt_| 	 | _
| jd usBJ t| j| j
| jd d S )Nz: setting up distributed...)r<   )rB   rC   rD   rE   r   set_world_ranksrc   r)   ra   _get_process_group_backendrP   r4   r   rQ   rW   rT   rT   rU   rg      s    
zDDPStrategy.setup_distributedc                 C   s   | j pt| jS rY   )rP   r   r[   rW   rT   rT   rU   r      s    z&DDPStrategy._get_process_group_backendc                 C   sL   | j d u rd S | j | j| j | j  | j | j| j  | j  t_	d S rY   )
r4   Zset_global_rank	node_rankr`   rZ   Zset_world_sizer]   rc   r)   ra   rW   rT   rT   rU   r      s
    
zDDPStrategy.set_world_ranksc                 C   s   | j dd| j d< d S )Nfind_unused_parametersT)rG   getrW   rT   rT   rU   pre_configure_ddp   s    zDDPStrategy.pre_configure_ddpc                 C   sR   t | jj d | jjdkrN| jrNt| jt	s6J t
| j| j| j| jd d S )Nz: registering ddp hooksZcuda)rt   r7   r8   r9   )rB   rC   rD   rE   r[   typere   rz   rt   r   r&   rH   rI   rJ   rW   rT   rT   rU   _register_ddp_hooks   s    zDDPStrategy._register_ddp_hooksc                 C   s   t | jj d | jd u r&tdddlm}m}m	} | j
D ]`}t|trT|j}tsbt||nd}|st||strt|tst||r@td|jj dq@| jd usJ tjjjjj| j| jjd| _d S )	Nz.: reinitializing optimizers with post localSGDz\Post-localSGD algorithm is used, but model averaging period is not provided to DDP strategy.r   )DistributedOptimizerPostLocalSGDOptimizerZeroRedundancyOptimizerFzKCurrently model averaging cannot work with a distributed optimizer of type .)ZperiodZwarmup_steps)rB   rC   rD   rE   rK   
ValueErrorZtorch.distributed.optimr   r   r   rw   rz   r   Z
_optimizerr   r    r/   rH   torchrx   ry   Zmodel_averagingZ	averagersZPeriodicModelAveragerZstart_localSGD_iterrL   )rR   r   r   r   	optimizerZis_distributed_optimizerrT   rT   rU   r{      s:    



z#DDPStrategy._enable_model_averagingzpl.LightningModule)r   opt_idxclosurert   r=   r>   c                    sL   t  j||||fi |}| jdu r(|S dd |jD }| jt| |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: Any extra arguments to ``optimizer.step``
        Nc                 S   s(   g | ] }|d  D ]}|j dur|qqS )paramsN)Zgrad).0r   paramrT   rT   rU   
<listcomp>      z.DDPStrategy.optimizer_step.<locals>.<listcomp>)r@   optimizer_steprL   Zparam_groupsZaverage_parametersiter)rR   r   r   r   rt   r=   Zoptimizer_outputr   rS   rT   rU   r     s    
zDDPStrategy.optimizer_stepc                 C   sP   t | jj d |   t| jtjt	fs2J | 
t| j| _|   d S )Nz%: configuring DistributedDataParallel)rB   rC   rD   rE   r   rz   rt   plZLightningModuler   r   r   r   rW   rT   rT   rU   rv   "  s
    zDDPStrategy.configure_ddpc                 C   s   | j jdkrd S | j jgS )Ncpu)r[   r   indexrW   rT   rT   rU   r~   )  s    z$DDPStrategy.determine_ddp_device_ids)argsr=   r>   c                 O   s:   t  s
d S tj dkr,tjj|  d n
tj  d S )NZnccl)r}   )r   r   rx   get_backendbarrierr~   rR   r   r=   rT   rT   rU   r   .  s
    zDDPStrategy.barrierr   )objsrcr>   c                 C   s2   |g}| j |krd g}tjj||tjd |d S )Nr   r   )rc   r   rx   Zbroadcast_object_list_groupZWORLD)rR   r   r   rT   rT   rU   rk   6  s
    
zDDPStrategy.broadcast)closure_lossr>   c                 C   s6   t | jtsdS | jdusJ | jjs2t| j| dS )z.Run before precision plugin executes backward.N)rz   rt   r   lightning_moduleautomatic_optimizationr   )rR   r   rT   rT   rU   pre_backward=  s
    zDDPStrategy.pre_backwardc                 C   s<   t | jj d| j d | jd us*J | j| j d S )Nz: moving model to device [z]...)rB   rC   rD   rE   r[   rt   torW   rT   rT   rU   ro   E  s    zDDPStrategy.model_to_devicemean)tensorr   	reduce_opr>   c                 C   s   t |trt|||d}|S )a  Reduces a tensor from several distributed processes to one aggregated tensor.

        Args:
            tensor: the tensor to sync and reduce
            group: the process group to gather results from. Defaults to all processes (world)
            reduce_op: the reduction operation. Defaults to 'mean'/'avg'.
                Can also be a string 'sum' to calculate the sum during reduction.

        Return:
            reduced value, except when the input was not a tensor the output remains is unchanged
        )r   )rz   r
   r   )rR   r   r   r   rT   rT   rU   reduceJ  s    
zDDPStrategy.reducec                 O   sL   | j d usJ | j   | j |i |W  d    S 1 s>0    Y  d S rY   )rt   r6   Ztrain_step_contextr   rT   rT   rU   training_step\  s    zDDPStrategy.training_stepc                 O   s   | j   | jd usJ | jd us(J | jjjjtjkrX| j|i |W  d    S t	| jt
shJ | jj|i |W  d    S W d    n1 s0    Y  d S rY   )r6   Zval_step_contextr   rt   ri   rp   rq   r%   rr   rz   r.   validation_stepr   rT   rT   rU   r   a  s    zDDPStrategy.validation_stepc                 O   sP   | j  2 t| jtsJ | jj|i |W  d    S 1 sB0    Y  d S rY   )r6   Ztest_step_contextrz   rt   r-   	test_stepr   rT   rT   rU   r   m  s    zDDPStrategy.test_stepc                 O   sP   | j  2 t| jtsJ | jj|i |W  d    S 1 sB0    Y  d S rY   )r6   Zpredict_step_contextrz   rt   r+   predict_stepr   rT   rT   rU   r   r  s    zDDPStrategy.predict_stepc                 C   s0   | j d usJ | j js,| jd us$J d| j_d S rV   )r   r   rt   Zrequire_backward_grad_syncrW   rT   rT   rU   post_training_stepw  s    zDDPStrategy.post_training_step)strategy_registryr>   c                 C   s.   |j d| ddd |j | j| | jj d d S )NZ ddp_find_unused_parameters_falsez3DDP Strategy with `find_unused_parameters` as FalseF)descriptionr   )r   )registerstrategy_namerD   rE   )clsr   rT   rT   rU   register_strategies}  s    zDDPStrategy.register_strategiesc                 C   s   t dddkp| jS )a  Determines whether the plugin will perform process reconciliation in case of errors.

        If the environment variable `PL_RECONCILE_PROCESS` is set, run detection regardless of the cluster environment.
        By default this is disabled. Otherwise, if the cluster environment creates the processes, allow the scheduler /
        parent process to perform the process termination, external to Lightning.
        ZPL_RECONCILE_PROCESS01)osgetenvrO   rW   rT   rT   rU   rl     s    z*DDPStrategy._should_run_deadlock_detectionc                 C   sh   |    | jdkrt | _g }d}t| jD ](}|| | j| || j	| j 7 }q.|| j
 | _d S r^   )_share_pidsrZ   tempfilemkdtemprN   ranger]   appendrk   
world_sizer   )rR   Z	sync_dirsZglobal_node_rank_zero_rT   rT   rU   rm     s    

z2DDPStrategy._share_information_to_prevent_deadlockc                 C   sL   |    | tjt | jd}|  	 }t
|tr@|n|g| _dS )z3Make all DDP processes aware of all processes pids.)deviceN)r   Z
all_gatherr   r   r   getpidr[   r   numpytolistrz   listrM   )rR   ZpidsrT   rT   rU   r     s    zDDPStrategy._share_pids)tracer>   c                 C   s   | j dk rd S |  sd S | j}|s0td d S t|jddd tdtj	
|| j d td tt|| j | j krd S | jD ]}|t krt|tj qt| td| j d| d S )	N   zQError handling mechanism for deadlock detection is uninitialized. Skipping check.T)parentsexist_okz.pl   zDeadLock detected from rank: z 
 )r   rl   rN   r*   r   mkdirr   saver   pathjoinrc   timesleepr_   listdirr]   rM   r   killsignalSIGKILLshutilrmtreer'   )rR   r   Zsync_dirpidrT   rT   rU   reconciliate_processes  s$    



z"DDPStrategy.reconciliate_processesc                    s   t | jj d | j}t| jtr\trV| jj	sV| j
 drVtd| jj d || _|d ur|jd ur|jjjtjkr| jr| jd usJ | j| j| _t   d S )Nz: tearing down strategyZcan_set_static_graphzyYour model can run with static graph optimizations. For future training runs, we suggest you pass `Trainer(..., strategy=z%(static_graph=True))` to enable them.)rB   rC   rD   rE   r   rz   rt   r   r   Zstatic_graphZ_get_ddp_logging_datar   r(   Z_trainerrp   rq   r%   rr   rs   revertr@   teardown)rR   Z	pl_modulerS   rT   rU   r     s4    zDDPStrategy.teardown)N)r   )Nr   )FrE   
__module____qualname____doc__r   r   r   r   r   r   r   r   r!   objectr   intstrr   r   rA   propertyrj   rX   r[   r]   setterr`   r   rd   re   r;   rf   rh   rn   r   r   r   rg   r   r   r   r   r{   r   r	   r   rv   r~   r   r$   rk   r
   r   ro   r   r   r,   r   r   r   r   r   classmethodr   rl   rm   r   r   r   __classcell__rT   rT   rS   rU   r1   F   s   $#	# 
 	#r1   )]loggingr   r   r   r   r   datetimer   pathlibr   typingr   r   r   r   r   r	   r   Ztorch.distributedr
   Ztorch.nnr   Ztorch.nn.parallel.distributedr   Ztorch.optim.optimizerr   Zpytorch_lightningr   Zlightning_fabric.pluginsr   r   Z5lightning_fabric.plugins.collectives.torch_collectiver   Z&lightning_fabric.utilities.distributedr   r   r   r   r   r   Z"lightning_fabric.utilities.importsr   r   Z$lightning_fabric.utilities.optimizerr   Zlightning_fabric.utilities.seedr   Z lightning_fabric.utilities.typesr   Z pytorch_lightning.core.optimizerr   Zpytorch_lightning.overridesr   Z pytorch_lightning.overrides.baser   Z'pytorch_lightning.overrides.distributedr   Z%pytorch_lightning.overrides.fairscaler    Z#pytorch_lightning.plugins.precisionr!   Z8pytorch_lightning.strategies.launchers.subprocess_scriptr"   Z%pytorch_lightning.strategies.parallelr#   Z%pytorch_lightning.strategies.strategyr$   Z pytorch_lightning.trainer.statesr%   Z'pytorch_lightning.utilities.distributedr&   Z&pytorch_lightning.utilities.exceptionsr'   Z%pytorch_lightning.utilities.rank_zeror(   r)   r*   Z!pytorch_lightning.utilities.typesr+   r,   r-   r.   Zfairscale.optimr/   r   rx   Zis_availableZ6torch.distributed.algorithms.model_averaging.averagersr0   	getLoggerrE   rB   r1   rT   rT   rT   rU   <module>   sX    
