a
    d=                     @   s  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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mZmZm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%m&Z& d dl'm(Z(m)Z)m*Z*m+Z+ d dl'm,Z- d dl'm.Z. d dl/m0Z0m1Z1 d dl2m3Z3 d dl4m5Z5 erRd dl6m7Z7m8Z8m9Z9m:Z: dZ;G dd de"e%Z<de	ee  ddddZ=G dd de$Z>e
ee?df  dd d!d"Z@ee?d#d$d%ZAdS )&    N)contextmanager)	timedelta)	AnyDict	GeneratorListOptionalTupleTypeTYPE_CHECKINGUnion)Tensor)Module)	Optimizer)Accelerator)CheckpointIOClusterEnvironment	Precision)default_pg_timeout)FSDPPrecision)_SubprocessScriptLauncher)ParallelStrategy)_BackwardSyncControl_Sharded
TBroadcast)_distributed_available-_get_default_process_group_backend_for_device_init_dist_connection_sync_ddp_if_availablegroup)ReduceOp)_TORCH_GREATER_EQUAL_1_12_TORCH_GREATER_EQUAL_1_13)rank_zero_only)
reset_seed)BackwardPrefetch
CPUOffloadFullyShardedDataParallelMixedPrecision)fsdpfsdp_full_shard_offloadc                       sD  e Zd ZdZddddddeddddfee eeej	  ee
 ee ee ee ee eeddf ed ed eeee eee  f  edd f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e d	ddZeed d	ddZdd	ddZdd	 fddZ eee! e"eee! f dddZ#edd d!d"Z$e!e!d#d$d%Z%edd d&d'Z&e'e(d	d(d)Z)d>e*ee eee+ef  e*d+d,d-Z,eedd.d/d0Z-d?e.ee.d2d3d4Z/e0edd5d6d7Z1dd	d8d9Z2ed	d:d;Z3dd	d<d=Z4  Z5S )@FSDPStrategya
  Strategy for Fully Sharded Data Parallel provided by torch.distributed.

    .. warning:: ``FSDPStrategy`` is in BETA and subject to change. The interface can
        bring breaking changes and new features with the next release of PyTorch.

    Fully Sharded Training shards the entire model across all available GPUs, allowing you to scale model
    size, whilst using efficient communication to reduce overhead. In practice, this means we can remain
    at parity with PyTorch DDP, whilst scaling our model sizes dramatically. The technique is similar
    to ZeRO-Stage 3.

    For more information `check out <https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api>`__.

    Defaults have been set and options have been exposed, but may require configuration
    based on your level of memory/speed efficiency. We suggest having a look at
    `this tutorial <https://pytorch.org/tutorials/intermediate/FSDP_tutorial.html>`__ for more information.

    Arguments:
        cpu_offload: Enable offloading parameters and gradients to CPU to save GPU memory at the cost of speed.
            You can also pass a config: ``cpu_offload=CPUOffload(offload_params=True)``. Note that this currently
            implicitly enables gradient offloading to CPU in order for parameters and gradients to be on same device
            to work with the optimizer. This API is subject to change. Default: no offoading
        backward_prefetch: This is an experimental feature that is subject to change in the near future. It allows
            users to enable two different backward prefetching algorithms to help backward communication and
            computation overlapping. The pros and cons of each algorithm is explained in the class ``BackwardPrefetch``.
        mixed_precision: Mixed Precision config. By default, Lightning will enable FP16 if ``precision=16`` or BF16
            if ``precision=bf16`` unless a config is passed in. This is only available in PyTorch 1.12 and later.
        activation_checkpointing: A single layer or a list of layer classes for which you want to enable activation
            checkpointing. This is typically your transformer block (including attention + feed-forward).
            Enabling this can free up a significant amount of memory at the cost of speed since activations in
            these layers need to be recomputed during backpropagation.
        \**kwargs: Optional keywoard arguments passed to the FSDP context manager which will configure the FSDP class
            when wrapping modules.
    Nr'   r&   r)   )acceleratorparallel_devicescluster_environmentcheckpoint_io	precisionprocess_group_backendtimeoutcpu_offloadbackward_prefetchmixed_precisionactivation_checkpointingkwargsreturnc                    s   t stdt j|||||d d| _|| _|| _t | _|| _	|rRt
sRtd|pXg }t|tsj|gn|| _t|| _|	| _|
| _d S )Nz9`FSDPStrategy` is supported from PyTorch v1.12.0 onwards.)r-   r.   r/   r0   r1      zOActivation checkpointing requires torch >= 1.13.0. HINT: `pip install -U torch`)r"   NotImplementedErrorsuper__init__
_num_nodes_process_group_backend_timeout_FSDPBackwardSyncControlZ_backward_sync_control_ddp_kwargsr#   
ValueError
isinstancelist_activation_checkpointing_init_cpu_offloadr4   r5   r6   )selfr-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   	__class__ i/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/lightning_fabric/strategies/fsdp.pyr=   Y   s,    
zFSDPStrategy.__init__)r9   c                 C   s   | j d usJ | j | j S N)r.   
local_rankrH   rK   rK   rL   root_device   s    zFSDPStrategy.root_devicec                 C   s   | j S rM   r>   rO   rK   rK   rL   	num_nodes   s    zFSDPStrategy.num_nodes)rR   r9   c                 C   s
   || _ d S rM   rQ   )rH   rR   rK   rK   rL   rR      s    c                 C   s   | j d urt| j S dS )Nr   )r.   lenrO   rK   rK   rL   num_processes   s    zFSDPStrategy.num_processesc                 C   s   t | j| j | jdS )N)Znum_replicasrank)dictrR   rT   global_rankrO   rK   rK   rL   distributed_sampler_kwargs   s    z'FSDPStrategy.distributed_sampler_kwargsc                 C   s   | j S rM   )r?   rO   rK   rK   rL   r2      s    z"FSDPStrategy.process_group_backendc                 C   s$   | j r| j S t| jtr | jjS d S rM   )r6   rD   r1   r   mixed_precision_configrO   rK   rK   rL   rY      s    z#FSDPStrategy.mixed_precision_configc                 C   s.   | j d usJ | j js*t| j | j| j| _d S rM   )r/   Zcreates_processes_externallyr   rT   rR   Z	_launcherrO   rK   rK   rL   _configure_launcher   s    z FSDPStrategy._configure_launcherc                    s   |    t   d S rM   )_setup_distributedr<   setup_environmentrO   rI   rK   rL   r\      s    zFSDPStrategy.setup_environment)module
optimizersr9   c                 C   s   t dt| j dd S )NzThe `z` does not support the joint setup of module and optimizer(s). Please do it in this order: Create the model, call `setup_module`, create the optimizer, call `setup_optimizer`.)r;   type__name__)rH   r]   r^   rK   rK   rL   setup_module_and_optimizers   s    z(FSDPStrategy.setup_module_and_optimizersr(   r]   r9   c                    sz   ddl m  d| jv r8t fdd| D r8| jd=  f || j| j| j| jj	d| j}t
rv| jrvt|| jd |S )z|Wraps the model into a
        :class:`~torch.distributed.fsdp.fully_sharded_data_parallel.FullyShardedDataParallel` module.r   r(   Zauto_wrap_policyc                 3   s   | ]}t | V  qd S rM   rD   ).0modrc   rK   rL   	<genexpr>   s   z,FSDPStrategy.setup_module.<locals>.<genexpr>)r]   r4   r5   r6   	device_id)r]   layers)2torch.distributed.fsdp.fully_sharded_data_parallelr(   rB   anymodulesr4   r5   rY   rP   indexr#   rF   _setup_activation_checkpointing)rH   r]   Zwrapped_modulerK   rc   rL   setup_module   s"    

zFSDPStrategy.setup_module	optimizerr9   c                    s^   ddl m  t|j}|dkr.td| dt fdd|jd d D rR|S td	d
S )aH  Set up an optimizer for a model wrapped with FSDP.

        This setup method doesn't modify the optimizer or wrap the optimizer. The only thing it currently does is verify
        that the optimizer was created after the model was wrapped with :meth:`setup_module` with a reference to the
        flattened parameters.
        r   FlatParameterr:   zSAn optimizer used with an FSDP model does not support multiple param groups. Found z parameter groups.c                 3   s   | ]}t | V  qd S rM   rd   re   paramrr   rK   rL   rg          z/FSDPStrategy.setup_optimizer.<locals>.<genexpr>paramszThe optimizer does not seem to reference any FSDP parameters. HINT: Make sure to create the optimizer after setting up the model.N)torch.distributed.fsdprs   rS   param_groupsrC   rk   )rH   rq   Z
num_groupsrK   rr   rL   setup_optimizer   s    
 zFSDPStrategy.setup_optimizerc                 C   s   d S rM   rK   )rH   r]   rK   rK   rL   module_to_device   s    zFSDPStrategy.module_to_devicec                 c   sh   ddl m} ddlm} |f || j| j| j| jjd| j	 d V  W d    n1 sZ0    Y  d S )Nr   rc   )enable_wrap)Zwrapper_clsr4   r5   r6   rh   )
rj   r(   Ztorch.distributed.fsdp.wrapr|   r4   r5   rY   rP   rm   rB   )rH   r(   r|   rK   rK   rL   module_sharded_context   s    z#FSDPStrategy.module_sharded_contextmean)tensorr    	reduce_opr9   c                 C   s   t |trt|||d}|S )N)r   )rD   r   r   )rH   r   r    r   rK   rK   rL   
all_reduce   s    
zFSDPStrategy.all_reduce)argsr8   r9   c                 O   s<   t  s
d S tj dkr.tjj| jjgd n
tj  d S )NZnccl)Z
device_ids)r   torchdistributedget_backendbarrierrP   rm   )rH   r   r8   rK   rK   rL   r      s
    zFSDPStrategy.barrierr   )objsrcr9   c                 C   s2   |g}| j |krd g}tjj||tjd |d S )Nr   r   )rW   r   r   Zbroadcast_object_list_groupZWORLD)rH   r   r   rK   rK   rL   	broadcast  s
    
zFSDPStrategy.broadcast)strategy_registryr9   c                 C   s8   t rtj sd S |jd| dd |jd| ddd d S )Nr*   zFully Sharded Data Parallel)descriptionr+   z.Fully Sharded Data Parallel and CPU OffloadingT)r   r4   )r"   r   r   Zis_availableregister)clsr   rK   rK   rL   register_strategies  s    z FSDPStrategy.register_strategiesc                 C   sF   t   |   | jt_|  | _| jd us.J t| j| j| j	d d S )N)r3   )
r%   _set_world_ranksrW   r$   rU   _get_process_group_backendr?   r/   r   r@   rO   rK   rK   rL   r[     s    
zFSDPStrategy._setup_distributedc                 C   s   | j pt| jS rM   )r?   r   rP   rO   rK   rK   rL   r   '  s    z'FSDPStrategy._get_process_group_backendc                 C   sL   | j d u rd S | j | j| j | j  | j | j| j  | j  t_	d S rM   )
r/   Zset_global_rankZ	node_rankrT   rN   Zset_world_sizerR   rW   r$   rU   rO   rK   rK   rL   r   *  s
    
zFSDPStrategy._set_world_ranks)Nr~   )r   )6r`   
__module____qualname____doc__r   r   r   r   r   Zdevicer   r   r   strr   r   boolr
   r   r   r=   propertyrP   intrR   setterrT   r   rX   r2   rY   rZ   r\   r   r	   ra   ro   rz   r{   r   r   r}   r   r!   r   r   r   r   classmethodr   r[   r   r   __classcell__rK   rK   rI   rL   r,   6   s~   $*	 r,   r(   )r]   ri   r9   c                    sB   ddl m}m}m}  fdd}tj||jd}|| ||d d S )Nr   )apply_activation_checkpointingcheckpoint_wrapperCheckpointImplc                    s   t | t S rM   )rD   tuple)	submoduleri   rK   rL   <lambda>9  rv   z1_setup_activation_checkpointing.<locals>.<lambda>)Zcheckpoint_impl)Zcheckpoint_wrapper_fncheck_fn)Z;torch.distributed.algorithms._checkpoint.checkpoint_wrapperr   r   r   	functoolspartialZNO_REENTRANT)r]   ri   r   r   r   r   wrapperrK   r   rL   rn   2  s    rn   c                   @   s    e Zd ZeeedddZdS )rA   rb   c                 c   sf   ddl m} t||s4td| jj d|jj d|  dV  W d   n1 sX0    Y  dS )zuBlocks gradient synchronization inside the
        :class:`~torch.distributed.fsdp.FullyShardedDataParallel` wrapper.r   rc   zABlocking backward sync is only possible if the module passed to `zB.no_backward_sync` is wrapped in `FullyShardedDataParallel`. Got: .N)rj   r(   rD   	TypeErrorrJ   r`   Zno_sync)rH   r]   r(   rK   rK   rL   no_backward_syncB  s    

z)_FSDPBackwardSyncControl.no_backward_syncN)r`   r   r   r   r   r   r   rK   rK   rK   rL   rA   A  s   rA   r'   )r4   r9   c                 C   s(   ddl m} t| |r| S |t| dS )Nr   )r'   )Zoffload_params)rx   r'   rD   r   )r4   r'   rK   rK   rL   rG   R  s    rG   rp   c                    s,   ddl m  t fdd| jd d D S )Nr   rr   c                 3   s   | ]}t | V  qd S rM   rd   rt   rr   rK   rL   rg   [  rv   z-_optimizer_has_flat_params.<locals>.<genexpr>rw   )rx   rs   rk   ry   )rq   rK   rr   rL   _optimizer_has_flat_paramsX  s    r   )Br   
contextlibr   datetimer   typingr   r   r   r   r   r	   r
   r   r   r   r   Ztorch.nnr   Ztorch.optimr   Zlightning_fabric.acceleratorsr   Zlightning_fabric.pluginsr   r   r   Z5lightning_fabric.plugins.collectives.torch_collectiver   Z'lightning_fabric.plugins.precision.fsdpr   Z7lightning_fabric.strategies.launchers.subprocess_scriptr   Z$lightning_fabric.strategies.parallelr   Z$lightning_fabric.strategies.strategyr   r   r   Z&lightning_fabric.utilities.distributedr   r   r   r   r    r   r!   Z"lightning_fabric.utilities.importsr"   r#   Z$lightning_fabric.utilities.rank_zeror$   Zlightning_fabric.utilities.seedr%   rj   r&   r'   r(   r)   Z_FSDP_ALIASESr,   rn   rA   r   rG   r   rK   rK   rK   rL   <module>   s:   , }