a
    dp                     @   sB  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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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' d dl(m)Z)m*Z* d dl+m,Z, d dl-m.Z. edZ/er,e/r,d dl0Z0G dd de#e%Z1dS )    N)contextmanager)Path)
AnyDict	GeneratorIterableListMappingOptionalTupleTYPE_CHECKINGUnion)RequirementCache)Module)	Optimizer)AcceleratorCUDAAccelerator)ClusterEnvironment)	Precision)DDPStrategy)_Sharded)log)rank_zero_inforank_zero_only)
reset_seed)_PATH	deepspeedc                /       s&  e Zd ZdZdddddddddd	d
ddddddddddddddddddejddddddddddddddf,ee ee	e
eee
e
e	e	e	e
e	e	e	eee	ee	eeeee	e	eee	 eeeee
ef f  e	eeej  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e
e	f dddZeddddZeee edee f dd d!Zedd"d#d$Zeed%d&d'Ze e!d( dd)d*Z"dReeee dd+d,d-Z#eee
ef d.d/d0Z$eee%e f e&e
ef dd1d2d3Z'ee&e
ef dd4d5d6Z(e)edd7d8d9Z*dSeee edef d:d;d<Z+ddd=d>Z,ddd?d@Z-dddAdBZ.dddCdDZ/dddEdFZ0dddGdHZ1eeee	 eeeeeee
e
e	e	e	e
e	ee	e	eee	eedIdJdKZ2ee&e
ef ddLdMdNZ3eeeee
ef f  eee
ef  dOdPdQZ4  Z5S )TDeepSpeedStrategyZPL_DEEPSPEED_CONFIG_PATHNT   cpuFz/local_nvme   i i ʚ;   i         l    J)i r      i  )-acceleratorzero_optimizationstageremote_deviceoffload_optimizeroffload_parametersoffload_params_device	nvme_pathparams_buffer_countparams_buffer_size
max_in_cpuoffload_optimizer_deviceoptimizer_buffer_count
block_sizequeue_depthsingle_submitoverlap_eventsthread_count
pin_memorysub_group_sizecontiguous_gradientsoverlap_commallgather_partitionsreduce_scatterallgather_bucket_sizereduce_bucket_sizezero_allow_untested_optimizerlogging_batch_size_per_gpuconfiglogging_levelparallel_devicescluster_environment
loss_scaleinitial_scale_powerloss_scale_window
hysteresismin_loss_scalepartition_activationscpu_checkpointingcontiguous_memory_optimizationsynchronize_checkpoint_boundaryload_full_weights	precisionprocess_group_backendreturnc-           .          s   t stdt j||| |+|,d d| _| || _| jdu r| j||||||||	|
||||||||||&|'|(|)||||||||d| _ddl}-d| _	|-j
jj| || _|*| _|!| _|"| _|#| _|$| _|%| _d| _dS )a  Provides capabilities to run training using the DeepSpeed library, with training optimizations for large
        billion parameter models. `For more information: https://pytorch-
        lightning.readthedocs.io/en/stable/advanced/model_parallel.html#deepspeed`.

        .. warning:: ``DeepSpeedStrategy`` is in beta and subject to change.

        Defaults have been set to enable ZeRO-Offload and some have been taken from the link below.
        These defaults have been set generally, but may require tuning for optimum performance based on your model size.
        `For more information: https://www.deepspeed.ai/docs/config-json/#zero-optimizations-for-fp16-training`.

        Arguments:

            zero_optimization: Enable ZeRO optimization. This is compatible with either ``precision=16`` or
                ``precision="bf16"``.

            stage: Different stages of the ZeRO Optimizer. 0 is disabled,
                1 is optimizer state partitioning, 2 is optimizer+gradient state partitioning,
                3 is optimizer+gradient_parameter partitioning using the infinity engine.

            remote_device: Device to instantiate the model on initially (``cpu`` or ``nvme``).

            offload_optimizer: Enable offloading optimizer memory and computation to CPU or NVMe
                based on ``offload_optimizer_device``.

            offload_parameters: When using ZeRO Stage 3, Enable offloading parameter memory and computation
                to CPU or NVMe based on ``offload_params_device``.

            offload_params_device: When offloading parameters choose the device to offload to, ``cpu`` or ``nvme``.

            offload_optimizer_device: When offloading optimizer state choose the device to offload to,
                ``cpu`` or ``nvme``.

            params_buffer_count: Number of buffers in buffer pool for
                parameter offloading when ``offload_params_device`` is ``nvme``.

            params_buffer_size: Size of buffers in buffer pool for parameter offloading
                when ``offload_params_device`` is ``nvme``.

            max_in_cpu: Number of parameter elements to maintain in CPU memory when offloading to NVMe is enabled.

            nvme_path: Filesystem path for NVMe device for optimizer/parameter state offloading.

            optimizer_buffer_count: Number of buffers in buffer pool for optimizer state offloading
                when ``offload_optimizer_device`` is set to to ``nvme``.
                This should be at least the number of states maintained per parameter by the optimizer.
                For example, Adam optimizer has 4 states (parameter, gradient, momentum, and variance).

            block_size: When using NVMe Offloading, the I/O block size in bytes.

            queue_depth: When using NVMe Offloading, the I/O queue depth.

            single_submit: When using NVMe Offloading,
                submit requests to storage device as multiple individual requests,
                as opposed to one block of requests.

            overlap_events: When using NVMe Offloading,
                submit requests to storage device in an overlapped fashion
                without waiting for completion of earlier requests.

            thread_count: When using NVMe Offloading,
                Intra-request parallelism for each read/write submitted by a user thread.

            pin_memory: When using ZeRO stage 3, pin optimizer state memory on CPU.
                This could boost throughput at the cost of extra memory overhead.

            sub_group_size: When using ZeRO stage 3, defines the number of parameters
                within a sub group to offload at a time.
                Smaller numbers require more communication, but improve memory efficiency.

            contiguous_gradients: Copies gradients to a continuous buffer as they are produced.
                Avoids memory fragmentation during backwards. Useful when training large models.

            overlap_comm: Overlap the reduction (synchronization) of gradients with the backwards computation.
                This is a speed optimization when training across multiple GPUs/machines.

            allgather_partitions: All gather updated parameters at the end of training step,
                instead of using a series of broadcast collectives.

            reduce_scatter: Use reduce/scatter instead of allreduce to average gradients.

            allgather_bucket_size: Number of elements to allgather at once.
                Used to limit the memory required for larger model sizes, with a tradeoff with speed.

            reduce_bucket_size: Number of elements to reduce at once.
                Used to limit the memory required for larger model sizes, with a tradeoff with speed.

            zero_allow_untested_optimizer: Allow untested optimizers to be used with ZeRO. Currently only Adam is a
                DeepSpeed supported optimizer when using ZeRO.

            logging_batch_size_per_gpu: Config used in DeepSpeed to calculate verbose timing for logging
                on a per sample per second basis (only displayed if logging=logging.INFO).
                To obtain accurate logs when using datasets that do not support batch samplers,
                set this to the actual per gpu batch size.

            config: Pass in a deepspeed formatted config dict,
                or path to a deepspeed config: https://www.deepspeed.ai/docs/config-json.
                All defaults will be ignored if a config is passed in.

            logging_level: Set logging level for deepspeed.

            loss_scale: Loss scaling value for FP16 training.
                0.0 results in dynamic loss scaling, otherwise static.

            initial_scale_power: Power of the initial dynamic loss scale value. Loss scale is computed
                by ``2^initial_scale_power``.

            loss_scale_window: Window in which to raise/lower the dynamic FP16 loss scaling value.

            hysteresis: FP16 Delay shift in Dynamic Loss scaling.

            min_loss_scale: The minimum FP16 dynamic loss scaling value.

            partition_activations: Enables partition activation when used with ZeRO stage 3 and model parallelism.
                Still requires you to wrap your forward functions in deepspeed.checkpointing.checkpoint.
                See `deepspeed tutorial
                <https://www.deepspeed.ai/tutorials/megatron/#deepspeed-activation-checkpoints-optional>`_.

            cpu_checkpointing: Offloads partitioned activations to CPU if ``partition_activations`` is enabled.

            contiguous_memory_optimization: Copies partitioned activations so that they are contiguous in memory.
                Not supported by all models.

            synchronize_checkpoint_boundary: Insert :func:`torch.cuda.synchronize` at each checkpoint boundary.

            load_full_weights: True when loading a single checkpoint file containing the model state dict
                when using ZeRO Stage 3. This differs from the DeepSpeed checkpoint which contains shards
                per worker.
        ztTo use the `DeepSpeedStrategy`, you must have DeepSpeed installed. Install it by running `pip install -U deepspeed`.)r%   rC   rD   rO   rP   N)r)   r*   r,   r+   r-   r.   r/   r7   r0   r1   r2   r3   r4   r5   r6   rJ   rK   rL   rM   r'   r9   r:   r;   r<   r=   r>   r8   r   F)_DEEPSPEED_AVAILABLEImportErrorsuper__init__Z_backward_sync_control_load_configrA   _create_default_configr   _config_initializedutilsloggingloggersetLevelr(   rN   rE   rF   rG   rH   rI   _deepspeed_engine).selfr%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   r   	__class__ n/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/lightning_fabric/strategies/deepspeed.pyrU   /   st     0
!zDeepSpeedStrategy.__init__)rQ   c                 C   s2   t | jtsJ | jd}|d uo0|ddkS )Nr&   r'      )
isinstancerA   dictget)r^   r&   ra   ra   rb   zero_stage_3"  s    zDeepSpeedStrategy.zero_stage_3c                 C   s   t | j| jdS )N)Znum_replicasrank)re   
world_sizeglobal_rankr^   ra   ra   rb   distributed_sampler_kwargs(  s    z,DeepSpeedStrategy.distributed_sampler_kwargszdeepspeed.DeepSpeedEnginec                 C   s   | j S N)r]   rk   ra   ra   rb   model,  s    zDeepSpeedStrategy.model)module
optimizersrQ   c                 C   sJ   t |dkr tdt | d| ||d \| _}|   | j|gfS )a  Set up a model and multiple optimizers together.

        Currently, only a single optimizer is supported.

        Return:
            The model wrapped into a :class:`deepspeed.DeepSpeedEngine` and a list with a single
            deepspeed optimizer.
        r#   z>Currently only one optimizer is supported with DeepSpeed. Got z optimizers instead.r   )len
ValueError_initialize_enginer]   '_set_deepspeed_activation_checkpointing)r^   ro   rp   	optimizerra   ra   rb   setup_module_and_optimizers0  s    z-DeepSpeedStrategy.setup_module_and_optimizers)ro   rQ   c                 C   s   |  |\| _}| jS )zwSet up a module for inference (no optimizers).

        For training, see :meth:`setup_module_and_optimizers`.
        )rs   r]   )r^   ro   _ra   ra   rb   setup_moduleE  s    zDeepSpeedStrategy.setup_module)ru   rQ   c                 C   s   t |  dS )zOptimizers can only be set up jointly with the model in this strategy.

        Please use :meth:`setup_module_and_optimizers` to set up both module and optimizer together.
        N)NotImplementedErrorZ_err_msg_joint_setup_required)r^   ru   ra   ra   rb   setup_optimizerM  s    z!DeepSpeedStrategy.setup_optimizer)NNNc                 c   s   dd l }| jr| jsJ | jjdkr,tj}n| jjdkr@tj}ntj}|jj	| j
d| j|d d V  W d    q1 sz0    Y  nd V  d S )Nr   16bf16T)r(   r7   Zconfig_dict_or_pathdtype)r   rg   rX   rO   torchfloat16Zbfloat16float32zeroZInitr(   rA   )r^   r   r}   ra   ra   rb   module_sharded_contextT  s    
&z(DeepSpeedStrategy.module_sharded_context)
checkpointfilepathstorage_optionsrQ   c                 C   s   t d S rm   ry   )r^   r   r   r   ra   ra   rb   save_checkpointm  s    z!DeepSpeedStrategy.save_checkpoint)checkpoint_pathrQ   c                 C   s   t d S rm   r   )r^   r   ra   ra   rb   load_checkpointp  s    z!DeepSpeedStrategy.load_checkpoint)rp   r   rQ   c                 C   s   d S rm   ra   )r^   rp   r   ra   ra   rb   load_optimizer_state_dicts  s    z+DeepSpeedStrategy.load_optimizer_state_dict)ro   r   rQ   c                 C   s&   | j r"| jr"| | | || d S rm   )rN   rg   Zmodule_to_device_restore_zero_state)r^   ro   r   ra   ra   rb   load_module_state_dicty  s    
z(DeepSpeedStrategy.load_module_state_dict)strategy_registryrQ   c                 C   s   |j d| dd |j d| ddd |j d| d	d
d |j d| dd
dd |j d| ddd |j d| ddddd |j d| dddddddd	 d S )Nr   zDefault DeepSpeed Strategy)descriptionZdeepspeed_stage_1z#DeepSpeed with ZeRO Stage 1 enabledr#   )r   r'   Zdeepspeed_stage_2z#DeepSpeed with ZeRO Stage 2 enabledr   Zdeepspeed_stage_2_offloadz&DeepSpeed ZeRO Stage 2 and CPU OffloadT)r   r'   r)   Zdeepspeed_stage_3zDeepSpeed ZeRO Stage 3rc   Zdeepspeed_stage_3_offloadz&DeepSpeed ZeRO Stage 3 and CPU Offload)r   r'   r)   r*   Zdeepspeed_stage_3_offload_nvmez'DeepSpeed ZeRO Stage 3 and NVMe OffloadZnvme)r   r'   r)   r*   r(   r+   r0   )register)clsr   ra   ra   rb   register_strategies  s<    z%DeepSpeedStrategy.register_strategies)rn   ru   rQ   c                 C   sN   ddl }tdd | }|jtj| jjd| j|||dd\}}}}||fS )zInitialize one model and one optimizer with an optional learning rate scheduler.

        This calls :func:`deepspeed.initialize` internally.
        r   Nc                 S   s   | j S rm   )Zrequires_grad)pra   ra   rb   <lambda>      z6DeepSpeedStrategy._initialize_engine.<locals>.<lambda>)Zdevice_rankF)argsrA   rn   model_parametersru   Zdist_init_required)	r   filter
parametersZ
initializeargparse	NamespaceZroot_deviceindexrA   )r^   rn   ru   r   r   Zdeepspeed_engineZdeepspeed_optimizerrw   ra   ra   rb   rs     s    	z$DeepSpeedStrategy._initialize_enginec                 C   sX   t | jts"td| jjj dt  |   | jt	_
|   | jsT|   d| _d S )Nz;The DeepSpeed strategy is only supported on CUDA GPUs but `z
` is used.T)rd   r%   r   RuntimeErrorr`   __name__r   Z_set_world_ranksrj   r   rh   _init_deepspeed_distributedrX   _format_configrk   ra   ra   rb   _setup_distributed  s    z$DeepSpeedStrategy._setup_distributedc                 C   sr   dd l }| jd usJ t dkrP|   td| j d| jd  d| j  | 	 | _
|j| j
| jjd d S )Nr   Windowsz1initializing deepspeed distributed: GLOBAL_RANK: z
, MEMBER: r#   /)Zdistributed_port)r   rD   platformsystem_set_node_environment_variablesr   inforj   ri   Z_get_process_group_backendZ_process_group_backendZinit_distributed	main_port)r^   r   ra   ra   rb   r     s    
z-DeepSpeedStrategy._init_deepspeed_distributedc                 C   sb   | j d usJ | j jtjd< t| j jtjd< t| jtjd< t| jtjd< t| jtjd< d S )NZMASTER_ADDRZMASTER_PORTZRANKZ
WORLD_SIZEZ
LOCAL_RANK)	rD   Zmain_addressosenvironstrr   rj   ri   Z
local_rankrk   ra   ra   rb   r     s    z1DeepSpeedStrategy._set_node_environment_variablesc                 C   s`   dd l }t| jtsJ | jdr\| jd }|jjd |d|d|d|dd d S )Nr   activation_checkpointingrJ   rL   rK   profile)Zmpu_rJ   Zcontiguous_checkpointingZcheckpoint_in_cpur   )r   rd   rA   re   rf   Zcheckpointing	configure)r^   r   Zcheckpoint_configra   ra   rb   rt     s    
z9DeepSpeedStrategy._set_deepspeed_activation_checkpointingc                 C   s,   | j d u rtd| j dd |   d S )NzTo use DeepSpeed you must pass in a DeepSpeed config dict, or a path to a JSON config. See: https://pytorch-lightning.readthedocs.io/en/stable/advanced/model_parallel.html#deepspeedtrain_micro_batch_size_per_gpur#   )rA   rr   
setdefault_format_precision_configrk   ra   ra   rb   r     s    
z DeepSpeedStrategy._format_configc                 C   s   t | jtsJ | jjdkrRd| jvr~td d| j| j| j| j| j	d| jd< n,d| jvr~| jjdkr~td ddi| jd< d S )	Nr{   Zfp16zEnabling DeepSpeed FP16.T)enabledrE   rF   rG   rH   rI   r|   zEnabling DeepSpeed BF16.r   )
rd   rA   re   rO   r   rE   rF   rG   rH   rI   rk   ra   ra   rb   r     s    
z*DeepSpeedStrategy._format_precision_config)r&   r?   r@   rJ   rK   rL   rM   r)   r*   r,   r+   r-   r.   r/   r0   r1   r7   r2   r3   r4   r5   r6   zero_kwargsrQ   c                 K   sx   ||||d|||||dd}|rh|}|r>||
||d|d< |	rX||
||||d|d< | ||d |rt||d	< |S )
N)rJ   rK   rL   rM   )r2   r3   r4   r5   r6   )r   Zaio)devicer,   buffer_countr7   r)   )r   r,   r   buffer_sizer/   r7   Zoffload_param)r?   r&   r   )update)r^   r&   r?   r@   rJ   rK   rL   rM   r)   r*   r,   r+   r-   r.   r/   r0   r1   r7   r2   r3   r4   r5   r6   r   cfgZzero_configra   ra   rb   rW     sH    

z(DeepSpeedStrategy._create_default_config)ro   ckptrQ   c                    s:   ddl dtjjtdd fdd|dd dS )	a7  Overrides the normal load_state_dict behaviour in PyTorch to ensure we gather parameters that may be
        sharded across processes before loading the state dictionary when using ZeRO stage 3. This is then
        automatically synced across processes.

        Args:
            ckpt: The ckpt file.
        r   N )ro   prefixrQ   c           
   
      s   g }g }g } d }t |dd }| }|d ur6||_|d u rBi n||d d i }jjt| jdddd. jr| j	|||d|||d	 W d    n1 s0    Y  | j
 D ]"\}}	|	d ur|	|| d
  qd S )N
state_dict	_metadataF)Zrecurser   )Zmodifier_rankT)r   r   local_metadatastrictmissing_keysunexpected_keys
error_msgs.)getattrcopyr   rf   r   ZGatheredParameterslistr   Zis_global_zeroZ_load_from_state_dictZ_modulesitems)
ro   r   r   r   r   r   metadatar   namechildr   r   loadr^   ra   rb   r   U  s.     $
z3DeepSpeedStrategy._restore_zero_state.<locals>.load)r   )r   )r   r~   nnr   r   )r^   ro   r   ra   r   rb   r   K  s    " z%DeepSpeedStrategy._restore_zero_state)rA   rQ   c                 C   s   |d u r2| j tjv r2td| j  d tj| j  }t|ttfrtj|sZt	d| t
|}t|}W d    n1 s0    Y  t|ts|d u sJ |S )Nz"Loading DeepSpeed config from set z environment variablezHYou passed in a path to a DeepSpeed config but the path does not exist: )DEEPSPEED_ENV_VARr   r   r   rd   r   r   pathisfileFileNotFoundErroropenjsonr   re   )r^   rA   fra   ra   rb   rV   w  s    
(zDeepSpeedStrategy._load_config)N)N)6r   
__module____qualname__r   rZ   WARNr
   r   boolintr   r   r   r   r   r   r~   r   r   floatr   rU   propertyrg   rl   rn   r   r   r   rv   rx   rz   r   r   r   r   r   r   r	   r   r   classmethodr   rs   r   r   r   rt   r   r   rW   r   rV   __classcell__ra   ra   r_   rb   r   ,   s2   t# 

F,r   )2r   r   rZ   r   r   
contextlibr   pathlibr   typingr   r   r   r   r   r	   r
   r   r   r   r~   Z lightning_utilities.core.importsr   Ztorch.nnr   Ztorch.optimr   Zlightning_fabric.acceleratorsr   r   Z9lightning_fabric.plugins.environments.cluster_environmentr   Z"lightning_fabric.plugins.precisionr   Zlightning_fabric.strategies.ddpr   Z$lightning_fabric.strategies.strategyr   Z&lightning_fabric.utilities.distributedr   Z$lightning_fabric.utilities.rank_zeror   r   Zlightning_fabric.utilities.seedr   Z lightning_fabric.utilities.typesr   rR   r   r   ra   ra   ra   rb   <module>   s0   0