o
    zi                     @   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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% 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l0m1Z1m2Z2 d dl3m4Z4 d dl5m6Z6 erd dl7m8Z8 edZ9edZ:G dd de'e+Z;dee<ef ded fddZ=dee<ef ddfdd Z>d!eej? ddfd"d#Z@d$e
deAfd%d&ZBd$e6ddfd'd(ZCd)ee<ef d*e<d+eDd,eEd-eEd.eEd/eEddfd0d1ZFdS )2    N)	ExitStack)chain)Path)
TYPE_CHECKINGAnyCallableContextManagerDictListMappingOptionalTupleUnion)RequirementCache)Module)	Optimizer)override)AcceleratorCUDAAccelerator)ClusterEnvironment)	Precision)DDPStrategy)_StrategyRegistry)_Sharded)log)_move_state_into)rank_zero_inforank_zero_warn)
reset_seed)_PATHDeepSpeedEngine	deepspeedzdeepspeed>=0.14.1c                [       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,dee 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	d-e	d.ed/ee	 d0eeeee
ef f  d1e	d2eeej  d3ee d4ed5e	d6e	d7e	d8e	d9ed:ed;ed<ed=ed>ee d?ee
 d@dfZ fdAdBZed@efdCdDZeed@ee
e	f fdEdFZeddHdIZedJedKee d@edGee f fdLdMZedJed@dGfdNdOZedPed@efdQdRZ eddSee d@e!f fdTdUZ"ed@e!fdVdWZ#e		ddXedYee
eeeef f dZee d[eee
e$e
egef f  d@df
d\d]Z%e		ddXedYeeeeee
eeeef f f  d^ed@ee
ef f fd_d`Z&e	a	ddJdGdPedbeee	f dceee	f dded@ej'fdedfZ(edJdGdPedgeee	f d@dfdhdiZ)e*edje+d@dfdkdlZ,	ddmedPee d@edGef fdndoZ-ed fdpdqZ.eddrdsZ/ddtduZ0ddvdwZ1ddxdyZ2ddzd{Z3ded.ed/ee	 d9e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f0d}d~Z4dJede5e
ef d@dfddZ6d0eeeee
ef f  d@eee
ef  fddZ7  Z8S )DeepSpeedStrategyPL_DEEPSPEED_CONFIG_PATHNT   Fcpuz/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-           .         sF  t stdt j||| |+|,d d| _| || _| jdu rz| 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| _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).
                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,   rJ   rK   rV   rW   Nr0   r1   r3   r2   r4   r5   r6   r>   r7   r8   r9   r:   r;   r<   r=   rQ   rR   rS   rT   r.   r@   rA   rB   rC   rD   rE   r?   r   F)_DEEPSPEED_AVAILABLEImportErrorsuper__init___backward_sync_control_load_configrH   _create_default_configr"   _config_initializedutilsloggingloggersetLevelr/   rU   rL   rM   rN   rO   rP   _deepspeed_engine).selfr,   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   rQ   rR   rS   rT   rU   rV   rW   r"   	__class__ Y/home/ubuntu/.local/lib/python3.10/site-packages/lightning_fabric/strategies/deepspeed.pyr\   5   s    1
	
!
zDeepSpeedStrategy.__init__c                 C   s2   t | jtsJ | jd}|d uo|ddkS )Nr-   r.      )
isinstancerH   dictget)rf   r-   ri   ri   rj   zero_stage_3)  s   zDeepSpeedStrategy.zero_stage_3c                 C   s   | j | jdS )N)num_replicasrank)
world_sizeglobal_rankrf   ri   ri   rj   distributed_sampler_kwargs/  s   z,DeepSpeedStrategy.distributed_sampler_kwargsr!   c                 C      | j S N)re   rt   ri   ri   rj   model4  s   zDeepSpeedStrategy.modelmodule
optimizersc                 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_enginere   '_set_deepspeed_activation_checkpointing)rf   ry   rz   	optimizerri   ri   rj   setup_module_and_optimizers8  s   z-DeepSpeedStrategy.setup_module_and_optimizersc                 C   s   |  |\| _}| jS )zxSet up a module for inference (no optimizers).

        For training, see :meth:`setup_module_and_optimizers`.

        )r}   re   )rf   ry   _ri   ri   rj   setup_moduleO  s   zDeepSpeedStrategy.setup_moduler   c                 C   s   t |  )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.

        )NotImplementedError_err_msg_joint_setup_required)rf   r   ri   ri   rj   setup_optimizerY  s   z!DeepSpeedStrategy.setup_optimizer
empty_initc                    sT   | j r|du rtd|d|  }t }| j s#|t j|d || |S )NFz`empty_init=zN` is not a valid choice with `DeepSpeedStrategy` when ZeRO stage 3 is enabled.)r   )ro   r   module_sharded_contextr   enter_contextr[   module_init_context)rf   r   module_sharded_ctxstackrg   ri   rj   r   b  s   

z%DeepSpeedStrategy.module_init_contextc                 C   s*   dd l }| js	J |jj| j| j| jdS )Nr   )enabledr/   config_dict_or_path)r"   r`   zeroInitro   r/   rH   rf   r"   ri   ri   rj   r   o  s   
z(DeepSpeedStrategy.module_sharded_contextpathstatestorage_optionsfilterc                    s   |durt d|durt dt|}t|dkrtdt|dkr(td|d }| |}|jdur;||jfn|f  fdd	| D }t| | j|i d
}|j	||dd dS )a  Save model, optimizer, and other state in a checkpoint directory.

        Args:
            path: A path to where the files should be saved
            state: A dictionary with contents to be saved. If the dict contains modules or optimizers, their
                state-dict will be retrieved and converted automatically.
            storage_options: Unused by this strategy, since it doesn't use a ``CheckpointIO`` plugin.
            filter: Unsupported.

        Raises:
            TypeError:
                If the unused ``storage_options`` gets passed.
            ValueError:
                When no :class:`deepspeed.DeepSpeedEngine` objects were found in the state, or when multiple
                :class:`deepspeed.DeepSpeedEngine` objects were found.

        Nz`DeepSpeedStrategy.save_checkpoint(..., storage_options=...)` is not supported because `DeepSpeedStrategy` does not use the `CheckpointIO`.z`DeepSpeedStrategy.save_checkpoint(..., filter=...)` is not supported because `DeepSpeedStrategy` manages the state serialization internally.r   a  Could not find a DeepSpeed model in the provided checkpoint state. Please provide the model as part of the state like so: `save_checkpoint(..., state={'model': model, ...})`. Make sure you set up the model (and optimizers if any) through the strategy before saving the checkpoint.r*   zFound multiple DeepSpeed engine modules in the given state. Saving checkpoints with DeepSpeed is currently limited to a single model per checkpoint. To save multiple models, call the save method for each model separately with a different path.c                    s   i | ]\}}| vr||qS ri   ri   ).0kvexcluded_objectsri   rj   
<dictcomp>  s    z5DeepSpeedStrategy.save_checkpoint.<locals>.<dictcomp>)r   
checkpoint)client_statetag)
	TypeError!_get_deepspeed_engines_from_stater{   r|   	broadcastr   items_validate_state_keys"_convert_stateful_objects_in_statesave_checkpoint)rf   r   r   r   r   enginesengineri   r   rj   r   }  s0   
z!DeepSpeedStrategy.save_checkpointstrictc           
         s  t |ttfs| jr| jr| |}t j|||dS |s%td|dt	| t
|}t|dkr7tdt|dkrAtd|d }trNddlm  nddlm  t fd	d
| D }tj  |j|d|d|d\}}|du rztdt|t|ddh @ }	t|||	d |S )a  Load the contents from a checkpoint and restore the state of the given objects.

        Args:
            path: A path to where the file is located
            state: A dictionary of objects whose state will be restored in-place from the checkpoint path.
                This should contain exactly one model, and the model must already be set up by DeepSpeed.
            strict: Whether to enforce that the keys in `state` match the keys in the checkpoint.

        Returns:
            Dictionary with the state inside DeepSpeed's engine

        Raises:
            ValueError:
                If no state is provided, when no :class:`deepspeed.DeepSpeedEngine` objects were found in the
                state, or when multiple :class:`deepspeed.DeepSpeedEngine` objects were found.
            RuntimeError:
                If DeepSpeed was unable to load the checkpoint due to missing files or because the checkpoint is
                not in the expected DeepSpeed format.

        )r   r   r   z1Got DeepSpeedStrategy.load_checkpoint(..., state=z) but a state with at least  a model instance to reload is required. Pass it in like so: DeepSpeedStrategy.load_checkpoint(..., state={'model': model, ...})r   a  Could not find a DeepSpeed model in the provided checkpoint state. Please provide the model as part of the state like so: `load_checkpoint(..., state={'model': model, ...})`. Make sure you set up the model (and optimizers if any) through the strategy before loading the checkpoint.r*   zFound multiple DeepSpeed engine modules in the given state. Saving and loading checkpoints with DeepSpeed is currently limited to a single model per checkpoint. To load multiple model states, call the load method for each model checkpoint separately.DeepSpeedOptimizerc                 3   s    | ]
}t |t fV  qd S rw   )rl   r   )r   itemr   ri   rj   	<genexpr>  s    z4DeepSpeedStrategy.load_checkpoint.<locals>.<genexpr>r   F)r   load_optimizer_statesload_lr_scheduler_statesload_module_strictNzDeepSpeed was unable to load the checkpoint. Ensure you passed in a DeepSpeed compatible checkpoint or a single checkpoint file by setting `DeepSpeedStrategy(..., load_full_weights=True)`.r   lr_scheduler)sourcedestinationkeys)rl   r   r   rU   ro   r   r[   load_checkpointr|   _validate_checkpoint_directoryr   r{   _DEEPSPEED_GREATER_EQUAL_0_14_1 deepspeed.runtime.base_optimizerr   deepspeed.runtimeanyvaluestorchcudaempty_cacheRuntimeErrorsetr   )
rf   r   r   r   r   r   optimzer_state_requestedr   r   r   rg   r   rj   r     sJ   



z!DeepSpeedStrategy.load_checkpoint       @max_norm	norm_typeerror_if_nonfinitec                 C      t dNzDeepSpeed handles gradient clipping automatically within the optimizer. Make sure to set the `gradient_clipping` value in your Config.r   )rf   ry   r   r   r   r   ri   ri   rj   clip_gradients_norm  s   	z%DeepSpeedStrategy.clip_gradients_normclip_valc                 C   r   r   r   )rf   ry   r   r   ri   ri   rj   clip_gradients_value   s   z&DeepSpeedStrategy.clip_gradients_valuestrategy_registryc                 C   s   |j 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 |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)descriptiondeepspeed_stage_1z#DeepSpeed with ZeRO Stage 1 enabledr*   )r   r.   deepspeed_stage_1_offloadz5DeepSpeed with ZeRO Stage 1 and optimizer CPU OffloadT)r   r.   r0   deepspeed_stage_2z#DeepSpeed with ZeRO Stage 2 enabledr%   deepspeed_stage_2_offloadz&DeepSpeed ZeRO Stage 2 and CPU Offloaddeepspeed_stage_3zDeepSpeed ZeRO Stage 3rk   deepspeed_stage_3_offloadz&DeepSpeed ZeRO Stage 3 and CPU Offload)r   r.   r0   r1   deepspeed_stage_3_offload_nvmez'DeepSpeed ZeRO Stage 3 and NVMe Offloadnvme)r   r.   r0   r1   r/   r2   r7   )register)clsr   ri   ri   rj   register_strategies)  sJ   
z%DeepSpeedStrategy.register_strategiesrx   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   rv   rw   )requires_grad)pri   ri   rj   <lambda>^  s    z6DeepSpeedStrategy._initialize_engine.<locals>.<lambda>)device_rankF)argsrH   rx   model_parametersr   dist_init_required)	r"   r   
parameters
initializeargparse	Namespaceroot_deviceindexrH   )rf   rx   r   r"   r   deepspeed_enginedeepspeed_optimizerr   ri   ri   rj   r}   R  s   
z$DeepSpeedStrategy._initialize_enginec                    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.)rl   r,   r   r   rh   __name__r[   setup_environmentrt   rg   ri   rj   r   i  s
   z#DeepSpeedStrategy.setup_environmentc                 C   sJ   | j d usJ t| j  t  |   |   | js#|   d| _d S d S NT)rJ    _validate_device_index_selectionr   _set_world_ranks_init_deepspeed_distributedr`   _format_configrt   ri   ri   rj   _setup_distributedr  s   

z$DeepSpeedStrategy._setup_distributedc                 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)r"   rK   platformsystem_set_node_environment_variablesr   infors   rr   _get_process_group_backend_process_group_backendinit_distributed	main_portr   ri   ri   rj   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 )NMASTER_ADDRMASTER_PORTRANK
WORLD_SIZE
LOCAL_RANK)	rK   main_addressosenvironstrr   rs   rr   
local_rankrt   ri   ri   rj   r     s   z1DeepSpeedStrategy._set_node_environment_variablesc                 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_checkpointingrQ   rS   rR   profile)mpu_rQ   contiguous_checkpointingcheckpoint_in_cpur  )r"   rl   rH   rm   rn   checkpointing	configure)rf   r"   checkpoint_configri   ri   rj   r~     s   

z9DeepSpeedStrategy._set_deepspeed_activation_checkpointingc              	   C   sJ   | j d u r	td| j d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train_micro_batch_size_per_gpur*   rH   rV   rL   rN   rP   rM   rO   )
rH   r|   
setdefault_format_precision_configrV   rL   rN   rP   rM   rO   rt   ri   ri   rj   r     s   

z DeepSpeedStrategy._format_configzero_kwargsc                 K   sx   ||||d|||||dd}|r4|}|r||
||d|d< |	r,||
||||d|d< | ||d |r:||d	< |S )
N)rQ   rR   rS   rT   )r9   r:   r;   r<   r=   )r  aio)devicer3   buffer_countr>   r0   )r  r3   r  buffer_sizer6   r>   offload_param)rF   r-   r  )update)rf   r-   rF   rG   rQ   rR   rS   rT   r0   r1   r3   r2   r4   r5   r6   r7   r8   r>   r9   r:   r;   r<   r=   r  cfgzero_configri   ri   rj   r_     sF   

z(DeepSpeedStrategy._create_default_configckptc                    s>   ddl d
dtjjdtddf fdd|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 ry   prefixrX   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|||d	 W d    n1 sSw   Y  | j
 D ]\}}	|	d urn|	|| d
  q]d S )N
state_dict	_metadataF)recurser   )modifier_rankT)r  r  local_metadatar   missing_keysunexpected_keys
error_msgs.)getattrcopyr  rn   r   GatheredParameterslistr   is_global_zero_load_from_state_dict_modulesr   )
ry   r  r!  r"  r#  r  metadatar   namechildr  r"   loadrf   ri   rj   r0    s6    z3DeepSpeedStrategy._restore_zero_state.<locals>.load)r  )r  )r"   r   nnr   r  )rf   ry   r  ri   r/  rj   _restore_zero_state  s   	& z%DeepSpeedStrategy._restore_zero_statec                 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   rl   r  r   r   isfileFileNotFoundErroropenjsonr0  rm   )rf   rH   fri   ri   rj   r^   %  s   
zDeepSpeedStrategy._load_config)rX   r!   rw   )NNr   )r   T)rX   N)9r   
__module____qualname__r3  rb   WARNr   r   boolintr  r   r   r	   r   r
   r   r  r   floatr   r\   propertyro   r   ru   rx   r   r   r   r   r   r   r   r   r   r   r   r   Tensorr   r   classmethodr   r   r}   r   r   r   r   r~   r   r_   r   r2  r^   __classcell__ri   ri   rg   rj   r#   2   s6   	
 !"#$%&'()*+,-. u	@"
S


*






	

D:-r#   r   rX   r!   c                    s4   ddl m  tdd |  D  } fdd|D S )Nr   r    c                 s   s"    | ]}t |tr| V  qd S rw   )rl   r   modules)r   ry   ri   ri   rj   r   7  s     z4_get_deepspeed_engines_from_state.<locals>.<genexpr>c                    s   g | ]	}t | r|qS ri   )rl   )r   r   r    ri   rj   
<listcomp>8  s    z5_get_deepspeed_engines_from_state.<locals>.<listcomp>)r"   r!   r   r   )r   rC  ri   r    rj   r   4  s   r   c                 C   s4   h d}| |  }|rtdd|  d S d S )N>   ry   	ds_configr   
ds_versionbuffer_namesglobal_stepsr   param_shapesdp_world_sizemp_world_sizeskipped_stepsglobal_samplessparse_tensor_module_nameszYour state has keys that collide with DeepSpeed's internal engine state. This could result in your values being overwritten by DeepSpeed. Consider changing the name of these keys to something else: z, )intersectionr   r   join)r   deepspeed_internal_keyscolliding_keysri   ri   rj   r   ;  s   r   rJ   c                 C   sP   dd | D }t tt| }||kr&td|dddd |D  dd S )	Nc                 S   s   g | ]}|j qS ri   )r   )r   r  ri   ri   rj   rD  W  s    z4_validate_device_index_selection.<locals>.<listcomp>zThe selected device indices z don't match the local rank values of processes. If you need to select GPUs at a specific index, set the `CUDA_VISIBLE_DEVICES` environment variable instead. For example: `CUDA_VISIBLE_DEVICES=,c                 s   s    | ]}t |V  qd S rw   )r  )r   iri   ri   rj   r   ]  s    z3_validate_device_index_selection.<locals>.<genexpr>z`.)r(  ranger{   r   rP  )rJ   selected_device_indicesexpected_device_indicesri   ri   rj   r   V  s   r   r   c                 C   s   |   o	| d   S )zVHeuristic check whether the path points to a top-level DeepSpeed checkpoint directory.r   )is_dir)r   ri   ri   rj   _is_deepspeed_checkpointa  s   rY  c                 C   sz   t | } t| }d|  }|s;t| j}|r t| d| j |  o)t| jj}|r7t| d| jj t|dS )zeValidates that the path points to a DeepSpeed checkpoint directory and suggests fixes for user error.z7The provided path is not a valid DeepSpeed checkpoint: ze. It looks like you passed the path to a subfolder. Try to load using this parent directory instead: z. It looks like you passed the path to a file inside a DeepSpeed checkpoint folder. Try to load using this parent directory instead: N)r   rY  parentr5  is_file)r   path_is_ds_checkpointdefault_messageparent_is_ds_checkpointparent_parent_is_ds_checkpointri   ri   rj   r   f  s(   

r   rH   rV   rL   rN   rP   rM   rO   c                 C   sb   d| vr|dv rt d d|||||d| d< d S d| vr-|dv r/t d d	di| d< d S d S d S )
Nfp16)z16-mixedz16-truezOEnabling DeepSpeed FP16. Model parameters and inputs will be cast to `float16`.T)r   rL   rM   rN   rO   rP   bf16)z
bf16-mixedz	bf16-truezPEnabling DeepSpeed BF16. Model parameters and inputs will be cast to `bfloat16`.r   )r   r  ri   ri   rj   r    s   	r  )Gr   r7  rb   r   r   
contextlibr   	itertoolsr   pathlibr   typingr   r   r   r   r	   r
   r   r   r   r   r    lightning_utilities.core.importsr   torch.nnr   torch.optimr   typing_extensionsr   lightning_fabric.acceleratorsr   r   9lightning_fabric.plugins.environments.cluster_environmentr   "lightning_fabric.plugins.precisionr   lightning_fabric.strategies.ddpr   $lightning_fabric.strategies.registryr   $lightning_fabric.strategies.strategyr   &lightning_fabric.utilities.distributedr   lightning_fabric.utilities.loadr   $lightning_fabric.utilities.rank_zeror   r   lightning_fabric.utilities.seedr    lightning_fabric.utilities.typesr   r"   r!   rY   r   r#   r  r   r   r  r   r<  rY  r   r>  r=  r  ri   ri   ri   rj   <module>   st   0      #
