o
    zig                     @   s  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
 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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&m'Z'm(Z(m)Z) d dl*m+Z+ d dl,m-Z- d dl.m/Z/ d dl0m1Z1 d dl2m3Z3 d dl4m5Z5 d dl6m7Z7 d dl8m9Z9 d dl:m;Z; d dl<m=Z= d dl>m?Z? d dl@mAZAmBZBmCZC d dlDmEZE eFeGZHeA ZIerd dlJZJdejKjddfddZLG dd de7ZMdS )     N)OrderedDict)contextmanager)Path)	TYPE_CHECKINGAnyDict	GeneratorListMappingOptionalTupleUnion)Module)	Optimizer)LRSchedulerReduceLROnPlateau)override)ClusterEnvironment)_StrategyRegistry)_DEEPSPEED_AVAILABLE_format_precision_config_validate_checkpoint_directory _validate_device_index_selection)_optimizers_to_device)
reset_seed)_PATH)CUDAAccelerator)"_init_optimizers_and_lr_schedulers)	Precision)DDPStrategy	TrainerFn)GradClipAlgorithmType)MisconfigurationException)is_overridden)WarningCacherank_zero_inforank_zero_warn)LRSchedulerConfigmodelreturnc                 C   s@   |   D ]}t |_d |_t |_t |_t |_t |_qd S N)modulesr   _backward_hooks_is_full_backward_hook_forward_hooks_forward_pre_hooks_state_dict_hooks_load_state_dict_pre_hooks)r)   module r4   Z/home/ubuntu/.local/lib/python3.10/site-packages/pytorch_lightning/strategies/deepspeed.pyremove_module_hooks<   s   
r6   c                [       s  e Zd 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,ded dede	dee
 dedede
de
de	d e	d!e	d"e
d#e	d$e	d%e	d&ed'ed(e	d)ed*e	d+ed,ed-ed.ed/e	d0e	d1ed2ee
e	f d3eeeee
ef f  d4e	d5eeej  d6ee d7ed8e	d9e	d:e	d;e	d<ed=ed>ed?ed@edAee dBee
 dCdfZ fdDdEZed fdFdGZeddHdIZeddLdMZddNdOZddPdQZeedCefdRdSZedTedUee dCe dVee f fdWdXZ!	ddTedYee dZeee"e#f  dCe dVef fd[d\Z$dd]d^Z%dCe eee& f fd_d`Z'edCefdadbZ(dTedCdfdcddZ)e*eddeee dCe+df f fdgdhZ,e*edCe+df fdidjZ-ddkdlZ.dTedCdfdmdnZ/eedCee
e	f fdodpZ0eddqdrZ1dTedCefdsdtZ2eedCefdudvZ3eddwdxZ4edCefdydzZ5edd{ed|ed}ee dCdfd~dZ6ededCee
ef f fddZ7eedCefddZ8edd{e9e
ef dedCdfddZ:de9e
ef dedCdfddZ;ed{e9e
ef dCdfddZ<e=ede>dCdfddZ?d3eeeee
ef f  dCeee
ef  fddZ@dddZAdddZBded1ed2ee
e	f d<ed=ed>ed?ededede
de
de	d e	d!e	d"e
d#e	d)ed$e	d%e	d&ed'ed(e	dedCef0ddZCdddZDdCe	fddZE  ZFS )DeepSpeedStrategy	deepspeedPL_DEEPSPEED_CONFIG_PATHNT   Fcpuz/local_nvme   i i ʚ;   i         l    J)i autor      i  acceleratorzpl.accelerators.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_pluginprocess_group_backendr*   c-           .         s:  t stdt j||| |+|,d | || _| jdu rw| j|||fi 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l}-d | _|-j	j
j| || _|*| _|!| _|"| _|#| _|$| _|%| _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::  This is an :ref:`experimental <versioning:Experimental API>` feature.

        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-mixed"` or
                `precision="bf16-mixed"`.

            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``). Defaults to GPU.

            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).
                If set to "auto", the strategy tries to infer this from
                the train DataLoader's BatchSampler, else defaults to 1.
                To obtain accurate logs when using datasets that do not support batch samplers,
                set this to the actual per gpu batch size (trainer.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`.)rB   r`   ra   rl   rm   NrF   rG   rI   rH   rJ   rK   rL   rT   rM   rN   rO   rP   rQ   rR   rS   rg   rh   ri   rj   rD   rV   rW   rX   rY   rZ   r[   rU   r   F)r   r#   super__init___load_configr^   _create_default_configr8   _config_initializedutilsloggingloggersetLevelrE   rk   rb   rc   rd   re   rf   ).selfrB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   r8   	__class__r4   r5   ro   K   s    3
	
 
zDeepSpeedStrategy.__init__c                    s0   t | jtstd| jjj dt   d S )Nz;The DeepSpeed strategy is only supported on CUDA GPUs but `z
` is used.)
isinstancerB   r   RuntimeErrorry   __name__rn   setup_environmentrw   rx   r4   r5   r}   =  s
   z#DeepSpeedStrategy.setup_environmentc                 C   s2   | j d usJ t| j  t  |   |   d S r+   )r`   r   r   set_world_ranks_init_deepspeed_distributedr~   r4   r4   r5   setup_distributedF  s
   
z#DeepSpeedStrategy.setup_distributedtrainer
pl.Trainerc                 C   s   |    | jd usJ | j| | jd usJ | j| j| _| | j| _|jjt	j
kr3| | |   |jjt	j
krEt| j| j |   |   d S r+   )_init_config_if_neededrB   setupr)   rl   convert_module_setup_modelstatefnr!   FITTINGsetup_optimizerssetup_precision_pluginr   
optimizersroot_deviceinit_deepspeedbarrierrw   r   r4   r4   r5   r   N  s   
zDeepSpeedStrategy.setupc                 C   sr   dd l }| jd usJ t dkr(|   td| j d| jd  d| j  | 	 | _
|j| j
| jjd d S )Nr   Windowsz1initializing deepspeed distributed: GLOBAL_RANK: z
, MEMBER: r?   /)distributed_port)r8   ra   platformsystem_set_node_environment_variablesloginfoglobal_rank
world_size_get_process_group_backend_process_group_backendinit_distributed	main_portrw   r8   r4   r4   r5   r   a  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 )NMASTER_ADDRMASTER_PORTRANK
WORLD_SIZE
LOCAL_RANK)	ra   main_addressosenvironstrr   r   r   
local_rankr~   r4   r4   r5   r   p  s   z1DeepSpeedStrategy._set_node_environment_variablesc                 C      dS NTr4   r~   r4   r4   r5   restore_checkpoint_after_setupx     z0DeepSpeedStrategy.restore_checkpoint_after_setupr)   r   deepspeed.DeepSpeedEnginec                 C   sf   t |dkrtdt | d| jdusJ | jdd | ||d \| _}|   | j|gfS )a  Setup 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.Ntrain_micro_batch_size_per_gpur   )len
ValueErrorr^   
setdefault_setup_model_and_optimizerr)   '_set_deepspeed_activation_checkpointing)rw   r)   r   	optimizerr4   r4   r5   _setup_model_and_optimizers}  s   z-DeepSpeedStrategy._setup_model_and_optimizersr   lr_schedulerc           	   	   C   sP   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      | j S r+   )requires_grad)pr4   r4   r5   <lambda>  s    z>DeepSpeedStrategy._setup_model_and_optimizer.<locals>.<lambda>device_rankF)argsr^   r)   model_parametersr   r   dist_init_required)	r8   filter
parameters
initializeargparse	Namespacer   indexr^   )	rw   r)   r   r   r8   r   deepspeed_enginedeepspeed_optimizer_r4   r4   r5   r     s   	z,DeepSpeedStrategy._setup_model_and_optimizerc                 C   s   | j d usJ td| j tjrtd | j jjtjkrt	dt
| jtjs(J | j jr9| j jjr9| | j d S | | j d S )Nconfigure_gradient_clippinga8  Since DeepSpeed handles gradient clipping internally, the default `LightningModule.configure_gradient_clipping` implementation will not actually clip gradients. The hook will still be called. Consider setting `Trainer(gradient_clip_val=..., gradient_clip_algorithm='norm')` which will use the internal mechanism.z7DeepSpeed does not support clipping gradients by value.)lightning_moduler$   plLightningModuler'   r   gradient_clip_algorithmr"   VALUEr#   rz   r)   training_initialize_deepspeed_train_initialize_deepspeed_inferencer~   r4   r4   r5   r     s   z DeepSpeedStrategy.init_deepspeedc                 C   sV   | j d usJ t| j \}}t|dkst|dkrtd|d |r(|d fS d fS )Nr?   zNDeepSpeed currently only supports single optimizer, single optional scheduler.r   )r   r   r   r#   )rw   r   lr_schedulersr4   r4   r5   _init_optimizers  s   z"DeepSpeedStrategy._init_optimizersc                 C   s2   t | jtsJ | jd}|d uo|ddkS )NrC   rD      )rz   r^   dictget)rw   rC   r4   r4   r5   zero_stage_3  s   zDeepSpeedStrategy.zero_stage_3c                 C   s   d\}}t | jtsJ d| jv rtd d }n|  \}}|d ur%|j}| |||\}}|   |g| _|j	}|d urRd |_	|d u rKt
|dd}n||_|g| _|| _d S )N)NNr   zYou have specified an optimizer and/or scheduler within the DeepSpeed config. It is recommended to define it in `LightningModule.configure_optimizers`.step)interval)rz   r^   r   r&   r   	schedulerr   r   r   r   r(   lr_scheduler_configsr)   )rw   r)   r   r   r   r   deepspeed_schedulerr4   r4   r5   r     s0   

z-DeepSpeedStrategy._initialize_deepspeed_train
empty_init)NNNc                 #   sd    | j r|du rtd|dd V  d S t j|d d V  W d    d S 1 s+w   Y  d S )NFz`empty_init=zN` is not a valid choice with `DeepSpeedStrategy` when ZeRO stage 3 is enabled.)r   )r   NotImplementedErrorrn   tensor_init_context)rw   r   rx   r4   r5   r     s   
"z%DeepSpeedStrategy.tensor_init_contextc                 c   sV    dd l }|   |jj| j| j| jd d V  W d    d S 1 s$w   Y  d S )Nr   )enabledrE   config_dict_or_path)r8   r   zeroInitr   rE   r^   r   r4   r4   r5   model_sharded_context  s   "z'DeepSpeedStrategy.model_sharded_contextc                 C   sd   dd l }t| jtsJ | jdr0| jd }|jjd |d|d|d|dd d S d S )Nr   activation_checkpointingrg   ri   rh   profile)mpu_rg   contiguous_checkpointingcheckpoint_in_cpur   )r8   rz   r^   r   r   checkpointing	configure)rw   r8   checkpoint_configr4   r4   r5   r     s   

z9DeepSpeedStrategy._set_deepspeed_activation_checkpointingc              	   C   s   dd l }t| jtsJ ddi}d| jv r|d| jd i d| jv r.|d| jd i | jr?|| jd | jd d t| |jtj	| j
jd	||d d g d
d\}}}}|| _d S )Nr   r   r?   fp16bf16r\   rC   r\   rC   r   F)r   r^   r)   r   r   r   r   )r8   rz   r^   r   updater   r6   r   r   r   r   r   r)   )rw   r)   r8   inference_configr   r4   r4   r5   r      s.   


	z1DeepSpeedStrategy._initialize_deepspeed_inferencec                 C   s   | j | jdS )N)num_replicasrank)r   r   r~   r4   r4   r5   distributed_sampler_kwargs=  s   z,DeepSpeedStrategy.distributed_sampler_kwargsc                 C   s   g | _ g | _dS )zCreates optimizers and schedulers.

        Args:
            trainer: the Trainer, these optimizers should be connected to

        N)r   r   r   r4   r4   r5   r   B  s   
z"DeepSpeedStrategy.setup_optimizersc                 C   s   |S r+   r4   )rw   r)   r4   r4   r5   r   Q  s   zDeepSpeedStrategy._setup_modelc                 C   r   )z>Whether the strategy handles gradient accumulation internally.Tr4   r~   r4   r4   r5   handles_gradient_accumulationT  s   z/DeepSpeedStrategy.handles_gradient_accumulationc                 C   r   r+   )r)   r~   r4   r4   r5   r   Z  s   z"DeepSpeedStrategy.deepspeed_enginec                 C   s   | j dkp	| jdkS )Nr?   )num_processes	num_nodesr~   r4   r4   r5   _multi_device^  s   zDeepSpeedStrategy._multi_device
checkpointfilepathstorage_optionsc                    sv   |  |}|durtd| jj d| jr!| jr!| jr!td ddg  fdd|	 D }| j
j||d	d
 dS )a  Save model/training states as a checkpoint file through state-dump and file-write.

        Args:
            checkpoint: The checkpoint state dictionary
            filepath: write-target file's path
            storage_options: not used for ``DeepSpeedStrategy`` as ``CheckpointIO`` is not used

        Raises:
            TypeError:
                If ``storage_options`` arg is passed in

        Nze`Trainer.save_checkpoint(..., storage_options=...)` with `storage_options` arg is not supported for `z ` as `CheckpointIO` is not used.a  When saving the DeepSpeed Stage 3 checkpoint, each worker will save a shard of the checkpoint within a directory. If a single file is required after training, see https://lightning.ai/docs/pytorch/stable/advanced/model_parallel.html#deepspeed-zero-stage-3-single-file for instructions.
state_dictoptimizer_statesc                    s   i | ]\}}| vr||qS r4   r4   ).0kv_exclude_keysr4   r5   
<dictcomp>  s    z5DeepSpeedStrategy.save_checkpoint.<locals>.<dictcomp>r   )client_statetag)	broadcast	TypeErrorry   r|   r   r   is_global_zerowarning_cachewarnitemsr   save_checkpoint)rw   r   r   r   r4   r  r5   r  b  s   
	z!DeepSpeedStrategy.save_checkpointcheckpoint_pathc                    s   | j r| jr| |}t |S t| | jd usJ ddlm} | jj	j
j|jk}| jj||d| jjd\}}|d u rAtd|S )Nr   r    F)load_optimizer_statesload_lr_scheduler_statesload_module_strictzDeepSpeed was unable to load the checkpoint. Ensure you passed in a DeepSpeed compatible checkpoint or a single checkpoint file with `Trainer(strategy=DeepSpeedStrategy(load_full_weights=True))`.)rk   r   r  rn   load_checkpointr   r    pytorch_lightning.trainer.statesr!   r   r   r   r   r   strict_loadingr#   )rw   r  r!   
is_fittingr   r  rx   r4   r5   r    s$   

z!DeepSpeedStrategy.load_checkpointc                 C   s8   | j d usJ | jr| jr| j jjjtjkrtd dS )Na  A single checkpoint file has been given. This means optimizer states cannot be restored. If you'd like to restore these states, you must provide a path to the originally saved DeepSpeed checkpoint. When using ZeRO 3, the original path should be a directory.F)	r   rk   r   r   r   r   r!   r   r'   r~   r4   r4   r5   lightning_restore_optimizer  s   z-DeepSpeedStrategy.lightning_restore_optimizerstrictc                 C   s.   | j r| jr|   | j||d d S d S d S )N)r  )rk   r   model_to_device_restore_zero_state)rw   r   r  r4   r4   r5   load_model_state_dict  s   z'DeepSpeedStrategy.load_model_state_dictckptc                    sP   ddl jdusJ d
dtjjdtddf fddjdd	 dS )a8  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 r3   prefixr*   c           
   
      s   g }g }g } d }t |dd }| }|d ur||_|d u r!i n	||d d i }jjt| jdddd jrI| j	||||||d W d    n1 sSw   Y  | j
 D ]\}}	|	d urn|	|| d	  q]d S )
Nr   	_metadataF)recurser   )modifier_rank)r   r  local_metadatar  missing_keysunexpected_keys
error_msgs.)getattrcopyr  r   r   GatheredParameterslistr   r
  _load_from_state_dict_modulesr  )
r3   r  r$  r%  r&  r   metadatar#  namechildr  r8   loadrw   r  r4   r5   r2    s6    z3DeepSpeedStrategy._restore_zero_state.<locals>.load)r  )r  )r8   r   torchnnr   r   )rw   r  r  r4   r1  r5   r    s   	( z%DeepSpeedStrategy._restore_zero_statec                 C   s   d S r+   r4   )rw   r   r4   r4   r5   load_optimizer_state_dict  r   z+DeepSpeedStrategy.load_optimizer_state_dictstrategy_registryc                 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 )Nr8   zDefault DeepSpeed Strategy)descriptiondeepspeed_stage_1z#DeepSpeed with ZeRO Stage 1 enabledr?   )r7  rD   deepspeed_stage_2z#DeepSpeed with ZeRO Stage 2 enabledr:   deepspeed_stage_2_offloadz&DeepSpeed ZeRO Stage 2 and CPU OffloadT)r7  rD   rF   deepspeed_stage_3zDeepSpeed ZeRO Stage 3r   deepspeed_stage_3_offloadz&DeepSpeed ZeRO Stage 3 and CPU Offload)r7  rD   rF   rG   deepspeed_stage_3_offload_nvmez'DeepSpeed ZeRO Stage 3 and NVMe Offloadnvme)r7  rD   rF   rG   rE   rH   rM   )register)clsr6  r4   r4   r5   register_strategies  s<   
z%DeepSpeedStrategy.register_strategiesc                 C   s   |d u r| j tjv rtd| j  d tj| j  }t|ttfrFtj|s-t	d| t
|}t|}W d    n1 sAw   Y  t|tsQ|d u sQJ |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&   rz   r   r   pathisfiler#   openjsonr2  r   )rw   r^   fr4   r4   r5   rp     s   
zDeepSpeedStrategy._load_configc                 C   s   | j s|   d| _ d S d S r   )rr   _format_configr~   r4   r4   r5   r     s   
z(DeepSpeedStrategy._init_config_if_neededc              	   C   sD   | j d u r	td|   t| j | jj| j| j| j| j	| j
d d S )NzTo use DeepSpeed you must pass in a DeepSpeed config dict, or a path to a JSON config. See: https://lightning.ai/docs/pytorch/stable/advanced/model_parallel.html#deepspeed)r^   	precisionrb   rd   rf   rc   re   )r^   r#   (_format_batch_size_and_grad_accum_configr   rl   rI  rb   rd   rf   rc   re   r~   r4   r4   r5   rH  "  s   

z DeepSpeedStrategy._format_configzero_kwargsc                 K   s~   ||||d|||||dd}|r3|}|r||
||d|d< |	r,||
||||d|d< ||d|}|d	kr=d
|i|}|S )N)rg   rh   ri   rj   )rO   rP   rQ   rR   rS   )r   aio)devicerI   buffer_countrT   rF   )rM  rI   rN  buffer_sizerL   rT   offload_paramr   r@   r   r4   )rw   rC   r\   r]   rg   rh   ri   rj   rF   rG   rI   rH   rJ   rK   rL   rM   rN   rT   rO   rP   rQ   rR   rS   rK  cfgzero_configr4   r4   r5   rq   3  sH   

	z(DeepSpeedStrategy._create_default_configc                 C   s   t | jtsJ | jd u rd S d| jv rtd| jjj| jd< d| jvr.|  }|| jd< d| jvr?| jjjp9d| jd< d S d S )Ngradient_accumulation_stepszDo not set `gradient_accumulation_steps` in the DeepSpeed config as this will be set with the `accumulate_grad_batches` argument passed via the Lightning Trainer.r   gradient_clippingg        )	rz   r^   r   r   r#   r   accumulate_grad_batches_auto_select_batch_sizegradient_clip_val)rw   
batch_sizer4   r4   r5   rJ  x  s   




z:DeepSpeedStrategy._format_batch_size_and_grad_accum_configc                 C   sD   | j d usJ d}| j jjj}| r | }t|dr |jj}|S )Nr?   batch_sampler)	r   r   fit_loop_data_source
is_defined
dataloaderhasattrrY  rX  )rw   rX  data_sourcetrain_dataloaderr4   r4   r5   rV    s   
z)DeepSpeedStrategy._auto_select_batch_size)r*   N)r   r   r*   Nr+   )r*   r   )T)Gr|   
__module____qualname__strategy_namerB  rt   WARNr   boolintr   r   r   r   r   r	   r3  rM  r   floatr   ro   r   r}   r   r   r   r   propertyr   r   r   r   r   r   r   r   r   r(   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r
   r  r  r5  classmethodr   rA  rp   r   rH  rq   rJ  rV  __classcell__r4   r4   rx   r5   r7   G   s   	

 !"#$%&'()*+,-. s




	"$
"$ "/2 


	


Er7   )Nr   rF  rt   r   r   collectionsr   
contextlibr   pathlibr   typingr   r   r   r   r	   r
   r   r   r   r3  torch.nnr   torch.optimr   torch.optim.lr_schedulerr   r   typing_extensionsr   pytorch_lightningr   lightning_fabric.pluginsr   lightning_fabric.strategiesr   %lightning_fabric.strategies.deepspeedr   r   r   r   $lightning_fabric.utilities.optimizerr   lightning_fabric.utilities.seedr    lightning_fabric.utilities.typesr   #pytorch_lightning.accelerators.cudar    pytorch_lightning.core.optimizerr   #pytorch_lightning.plugins.precisionr    pytorch_lightning.strategies.ddpr   r  r!   pytorch_lightning.utilitiesr"   &pytorch_lightning.utilities.exceptionsr#   )pytorch_lightning.utilities.model_helpersr$   %pytorch_lightning.utilities.rank_zeror%   r&   r'   !pytorch_lightning.utilities.typesr(   	getLoggerr|   r   r  r8   r4  r6   r7   r4   r4   r4   r5   <module>   sJ   ,
