Ë
    S^(h¤T  ã                   ó>  — d Z ddlZddlmZ ddlZddlZddlm	Z	 ddl
mZ ddlmZmZmZ  e«       r
ddlZddlmZ  ej$                  e«      Zd„ Z e«       r e«       rdd	lmZ ndd
lmZ  G d„ de«      Z G d„ de«      Zdad„ Zd„ Zd„ Zd„ Z d„ Z!d„ Z"dd„Z#dd„Z$y)z
Integration with Deepspeed
é    N)Úpartialmethodé   )Údep_version_check)Úis_accelerate_availableÚis_torch_availableÚlogging)Únnc                  óª   — t         j                  j                  d«      d u} | r	 t        j                  d«      }yy # t        j
                  $ r Y yw xY w)NÚ	deepspeedTF)Ú	importlibÚutilÚ	find_specÚimportlib_metadataÚmetadataÚPackageNotFoundError)Úpackage_existsÚ_s     úa/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/integrations/deepspeed.pyÚis_deepspeed_availabler   $   sW   € Ü—^‘^×-Ñ-¨kÓ:À$ÐF€Nñ ð	Ü"×+Ñ+¨KÓ8ˆAØð øô "×6Ñ6ò 	Ùð	ús   ¥< ¼AÁA)ÚHfDeepSpeedConfig)Úobjectc                   ó"   ‡ — e Zd ZdZˆ fd„Zˆ xZS )r   aJ  
    This object contains a DeepSpeed configuration dictionary and can be quickly queried for things like zero stage.

    A `weakref` of this object is stored in the module's globals to be able to access the config from areas where
    things like the Trainer object is not available (e.g. `from_pretrained` and `_get_resized_embeddings`). Therefore
    it's important that this object remains alive while the program is still running.

    [`Trainer`] uses the `HfTrainerDeepSpeedConfig` subclass instead. That subclass has logic to sync the configuration
    with values of [`TrainingArguments`] by replacing special placeholder values: `"auto"`. Without this special logic
    the DeepSpeed configuration is not modified in any way.

    Args:
        config_file_or_dict (`Union[str, Dict]`): path to DeepSpeed config file or dict.

    c                 óf   •— t        | «       t        d«       t        d«       t        ‰| �  |«       y )NÚ
accelerater   )Úset_hf_deepspeed_configr   ÚsuperÚ__init__©ÚselfÚconfig_file_or_dictÚ	__class__s     €r   r   zHfDeepSpeedConfig.__init__J   s)   ø€ ä Ô%Ü˜,Ô'Ü˜+Ô&Ü‰ÑÐ,Õ-ó    )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Ú__classcell__©r!   s   @r   r   r   9   s   ø„ ñ÷ .ð .r"   r   c                   óX   ‡ — e Zd ZdZˆ fd„Zd„ Zd„ Zd
d„Z eed¬«      Z	dd„Z
d	„ Zˆ xZS )ÚHfTrainerDeepSpeedConfigzž
    The `HfTrainerDeepSpeedConfig` object is meant to be created during `TrainingArguments` object creation and has the
    same lifespan as the latter.
    c                 ó@   •— t         ‰| �  |«       d | _        g | _        y ©N)r   r   Ú_dtypeÚ
mismatchesr   s     €r   r   z!HfTrainerDeepSpeedConfig.__init__X   s   ø€ Ü‰ÑÐ,Ô-ØˆŒØˆ�r"   c                 óH   — | j                   €t        d«      ‚| j                   S )Nz8trainer_config_process() wasn't called yet to tell dtype)r-   Ú
ValueError)r   s    r   ÚdtypezHfTrainerDeepSpeedConfig.dtype]   s"   € Ø�;‰;ÐÜÐWÓXÐXØ�{‰{Ðr"   c                 ó4   — | j                  |«      }|€y|dk(  S )NFÚauto)Ú	get_value)r   Úds_key_longÚvals      r   Úis_autoz HfTrainerDeepSpeedConfig.is_autob   s"   € Ø�n‰n˜[Ó)ˆØˆ;Øà˜&‘=Ð r"   c           
      óî   — | j                  |«      \  }}|€y|j                  |«      dk(  r|||<   y|sy|j                  |«      }|�.||k7  r(| j                  j                  d|› d|› d|› d|› �«       yyy)a¶  
        A utility method that massages the config file and can optionally verify that the values match.

        1. Replace "auto" values with `TrainingArguments` value.

        2. If it wasn't "auto" and `must_match` is true, then check that DS config matches Trainer
        config values and if mismatched add the entry to `self.mismatched` - will assert during
        `trainer_config_finalize` for one or more mismatches.

        Nr3   z- ds ú=z vs hf )Úfind_config_nodeÚgetr.   Úappend)r   r5   Úhf_valÚhf_keyÚ
must_matchÚconfigÚds_keyÚds_vals           r   Ú
fill_matchz#HfTrainerDeepSpeedConfig.fill_matchi   s“   € ð ×.Ñ.¨{Ó;‰ˆ�Øˆ>Øà�:‰:�fÓ Ò'Ø#ˆF�6‰NØáØà—‘˜FÓ#ˆØÐ &¨FÒ"2Ø�O‰O×"Ñ" U¨;¨-°q¸¸ÀÈÀxÈqÐQWÐPXÐ#YÕZð #3Ðr"   F)r?   c                 ón  — |j                   |j                  z  |j                  z  }| j                  d|j                  d| «       | j                  d|j                  d«       | j                  d|d| «       | j                  d|j                  d«       | j                  d|j
                  d	«       | j                  d
|j                  |j                  gd«       | j                  d|j                  d«       | j                  d|j                  d«       | j                  dd«       | j                  d|j
                  d	«       |j                  s|j                  r|j                  dk(  rdnd}nd}|j                  rE| j                  j!                  di «      | j                  d<   |j                  | j                  d   d<   | j                  d|j                  xs |j                  xr |dk(  d«       | j                  d|dk(  d«       | j                  d|j"                  d«       | j                  d|j$                  xs |j&                  d«       | j)                  d«      rt*        j,                  | _        y| j1                  d«      rt*        j2                  | _        yt*        j4                  | _        y) zŠ
        Adjust the config with `TrainingArguments` values. This stage is run during `TrainingArguments` object
        creation.
        Útrain_micro_batch_size_per_gpuÚper_device_train_batch_sizeÚgradient_accumulation_stepsÚtrain_batch_sizeztrain_batch_size (calculated)Úgradient_clippingÚmax_grad_normzoptimizer.params.lrÚlearning_ratezoptimizer.params.betaszadam_beta1+adam_beta2zoptimizer.params.epsÚadam_epsilonzoptimizer.params.weight_decayÚweight_decayzscheduler.params.warmup_min_lrr   zscheduler.params.warmup_max_lrÚapexÚampNÚ
checkpointÚuse_node_local_storagezfp16.enabledz%fp16|fp16_full_eval+fp16_backend(amp)zamp.enabledzfp16+fp16_backend(apex)zamp.opt_levelÚfp16_opt_levelzbf16.enabledzbf16|bf16_full_eval)Ú
world_sizerF   rG   rC   rJ   rK   Ú
adam_beta1Ú
adam_beta2rL   rM   Ú	fill_onlyÚfp16Úfp16_full_evalÚfp16_backendÚsave_on_each_noder@   r;   rR   Úbf16Úbf16_full_evalÚis_trueÚtorchÚbfloat16r-   Úis_falseÚfloat32Úfloat16)r   ÚargsÚauto_find_batch_sizerH   rY   s        r   Útrainer_config_processz/HfTrainerDeepSpeedConfig.trainer_config_process…   sL  € ð  Ÿ?™?¨T×-MÑ-MÑMÐPT×PpÑPpÑpÐØ�‰Ø,Ø×,Ñ,Ø)Ø$Ð$ô		
ð 	�‰Ø)Ø×,Ñ,Ø)ô	
ð
 	�‰ØØØ+Ø$Ð$ô		
ð 	�‰Ð+¨T×-?Ñ-?ÀÔQà�‰Ð-¨t×/AÑ/AÀ?ÔSØ�‰Ø$Ø�_‰_˜dŸo™oÐ.Ø#ô	
ð
 	�‰Ð.°×0AÑ0AÀ>ÔRØ�‰Ð7¸×9JÑ9JÈNÔ[à�‰Ð7¸Ô;Ø�‰Ð8¸$×:LÑ:LÈoÔ^ð �9Š9˜×+Ò+Ø%)×%6Ñ%6¸&Ò%@™6Àe‰LàˆLà×!Ò!à(,¯©¯©¸ÀbÓ(IˆD�K‰K˜Ñ%ØBF×BXÑBXˆD�K‰K˜Ñ%Ð&>Ñ?ð 	�‰ØØ�i‰iÒ.˜4×.Ñ.ÒI°LÀEÑ4IØ3ô	
ð 	�‰˜ |°vÑ'=Ð?XÔYØ�‰˜¨×)<Ñ)<Ð>NÔOà�‰˜¨¯©Ò)I°d×6IÑ6IÐLaÔbð �<‰<˜Ô'ÜŸ.™.ˆD�KØ�]‰]˜>Ô*ÜŸ-™-ˆD�KäŸ-™-ˆD�Kr"   c                 ól  — g d¢}|D �cg c]  }| j                  |«      sŒ|‘Œ }}t        |«      dkD  �r„t        |j                  d«      r|j                  j                  }nüt        |j                  d«      r t        |j                  j                  «      }nÆt        |j                  d«      rAt        |j                  j                  d«      r!|j                  j                  j                  }not        |j                  d«      rJt        |j                  j                  d«      r*t        |j                  j                  j                  «      }nt        d|› d�«      ‚| j                  d||z  «       | j                  «       r6| j                  d	t        d
|z  |z  «      «       | j                  dd|z  «       | j                  d|d«       | j                  d|j                  |«      d«       t        | j                  «      dkD  r*dj                  | j                  «      }t        d|› d�«      ‚yc c}w )z�
        This stage is run after we have the model and know num_training_steps.

        Now we can complete the configuration process.
        )ú$zero_optimization.reduce_bucket_sizeú-zero_optimization.stage3_prefetch_bucket_sizeú4zero_optimization.stage3_param_persistence_thresholdr   Úhidden_sizeÚhidden_sizesÚtext_configz½The model's config file has neither `hidden_size` nor `hidden_sizes` entry, therefore it's not possible to automatically fill out the following `auto` entries in the DeepSpeed config file: zb. You can fix that by replacing `auto` values for these keys with an integer value of your choice.rg   rh   gÍÌÌÌÌÌì?ri   é
   z scheduler.params.total_num_stepsznum_training_steps (calculated)z!scheduler.params.warmup_num_stepsÚwarmup_stepsú
z]Please correct the following DeepSpeed config values that mismatch TrainingArguments values:
zF
The easiest method is to set these DeepSpeed config values to 'auto'.N)r7   ÚlenÚhasattrr@   rj   Úmaxrk   rl   r0   rV   Úis_zero3ÚintrC   Úget_warmup_stepsr.   Újoin)	r   rc   ÚmodelÚnum_training_stepsÚhidden_size_based_keysÚxÚhidden_size_auto_keysrj   r.   s	            r   Útrainer_config_finalizez0HfTrainerDeepSpeedConfig.trainer_config_finalizeÏ   sö  € ò"
Ðð
 -CÖ V qÀdÇlÁlÐSTÅo¢Ð VÐÐ VäÐ$Ó%¨Ó)Ü�u—|‘| ]Ô3Ø#Ÿl™l×6Ñ6‘Ü˜Ÿ™ ~Ô6ä! %§,¡,×";Ñ";Ó<‘Ü˜Ÿ™ }Ô5¼'À%Ç,Á,×BZÑBZÐ\iÔ:jØ#Ÿl™l×6Ñ6×BÑB‘Ü˜Ÿ™ }Ô5¼'À%Ç,Á,×BZÑBZÐ\jÔ:kä! %§,¡,×":Ñ":×"GÑ"GÓH‘ä ð5à5JÐ4Kð LYðYóð ð �N‰NÐAÀ;ÐQ\ÑC\Ô]Ø�}‰}Œà—‘ØCÜ˜˜kÑ)¨KÑ7Ó8ôð —‘ØJØ˜Ñ$ôð 	�‰Ø.ØØ-ô	
ð
 	�‰Ø/Ø×!Ñ!Ð"4Ó5Øô	
ô ˆt�‰Ó !Ò#ØŸ™ 4§?¡?Ó3ˆJÜðØ'˜LÐ(oðqóð ð $ùò[ !Ws
   ‰H1 H1)NT©F)r#   r$   r%   r&   r   r1   r7   rC   r   rV   re   r|   r'   r(   s   @r   r*   r*   R   s8   ø„ ñô
ò
ò
!ó[ñ4 ˜j°UÔ;€IóH(öT@r"   r*   c                 ó.   — t        j                  | «      ay r,   )ÚweakrefÚrefÚ_hf_deepspeed_config_weak_ref)Úhf_deepspeed_config_objs    r   r   r     s   € ô
 %,§K¡KÐ0GÓ$HÑ!r"   c                  ó   — d a y r,   )r�   © r"   r   Úunset_hf_deepspeed_configr…     s
   € ð %)Ñ!r"   c                  óT   — t         �"t        «       �t        «       j                  «       S y)NF)r�   rs   r„   r"   r   Úis_deepspeed_zero3_enabledr‡   $  s&   € Ü$Ð0Ô5RÓ5TÐ5`Ü,Ó.×7Ñ7Ó9Ð9àr"   c                  óL   — t         �t        «       �t        «       j                  S y r,   )r�   r@   r„   r"   r   Údeepspeed_configr‰   +  s#   € Ü$Ð0Ô5RÓ5TÐ5`Ü,Ó.×5Ñ5Ð5àr"   c                 ó¤   ‡‡‡— t        |dd«      Š|j                  «       }‰�‰|_        g Šddt        j                  fˆˆˆfd„Š ‰| |d¬«       ‰S )zÏ
    Loads state dict into a model specifically for Zero3, since DeepSpeed does not support the `transformers`
    tensor parallelism API.

    Nearly identical code to PyTorch's `_load_from_state_dict`
    Ú	_metadataNFÚmodulec                 ó´  •— ‰€i n‰j                  |d d i «      }||d<   |||dg g ‰f}t        «       rÚt        |D �cg c]  }|j                  |«      sŒ|‘Œ c}«      dkD  r¬dd l}t        | j                  |d d d¬«      «      }|j                  «       D �	cg c]  }	|	|v sŒ||	   ‘Œ }
}	t        |
«      dkD  rV|j                  j                  |
d¬«      5  t        j                  j                  «       dk(  r | j                  |Ž  d d d «       | j                  j                  «       D ]  \  }}|€Œ	 ‰||||z   dz   |«       Œ y c c}w c c}	w # 1 sw Y   ŒJxY w)	NéÿÿÿÿÚassign_to_params_buffersTr   F)ÚprefixÚrecurse)Úmodifier_rankú.)r;   r‡   rp   Ú
startswithr   ÚdictÚnamed_parametersÚkeysÚzeroÚGatheredParametersr^   ÚdistributedÚget_rankÚ_load_from_state_dictÚ_modulesÚitems)rŒ   Ú
state_dictr�   r�   Úlocal_metadatarc   Úkeyr   r–   ÚkÚparams_to_gatherÚnameÚchildÚ
error_msgsÚloadr   s                €€€r   r§   z/_load_state_dict_into_zero3_model.<locals>.loadC  so  ø€ Ø'Ð/™°X·\±\À&ÈÈ"À+ÈrÓ5RˆØ5MˆÐ1Ñ2à˜F N°D¸"¸bÀ*ÐMˆô &Ô'¬CÀ
Ö0e¸ÈcÏnÉnÐ]cÕNd²Ò0eÓ,fÐijÒ,jÛô  $ F×$;Ñ$;À6È#È2À;ÐX]Ð$;Ó$^Ó_ÐØ=G¿_¹_Ó=NÖh¸ÐRSÐWgÒRgÐ 0°Ó 3ÐhÐÐhÜÐ#Ó$ qÒ(ð —^‘^×6Ñ6Ð7GÐWXÐ6ÓYñ <Ü×(Ñ(×1Ñ1Ó3°qÒ8Ø4˜×4Ñ4°dÑ;÷<ð "Ÿ?™?×0Ñ0Ó2ò 	W‰KˆD�%ØÑ Ù�U˜J¨°©¸Ñ(;Ð=UÕVñ	Wùò 1fùò  i÷
<ð <ús#   ¼EÁEÂ	E	Â E	Ã1EÅE)r�   )Ú F)ÚgetattrÚcopyr‹   r	   ÚModule)Úmodel_to_loadrŸ   r¦   r§   r   s     @@@r   Ú!_load_state_dict_into_zero3_modelr­   2  sX   ú€ ô �z ;°Ó5€HØ—‘Ó"€JØÐØ'ˆ
Ôà€JñW”R—Y‘Y÷ Wñ4 	ˆ˜
¸UÕCàÐr"   c                 ó‚  ‡ ‡— ddl m}m} |j                  }d}d|v r!|j                  rt        d«      ‚ ||¬«      }n:|j                  «       rt        j                  d«       ‰ j                  «       }d|d	<   d}	d
|v r ||«      }	||	fS t        ||«      rˆˆ fd„}
 |||
¬«      }	||	fS ‰ j                  ‰|¬«      }	||	fS )zY
    A convenience wrapper that deals with optimizer and lr scheduler configuration.
    r   )Ú
DummyOptimÚDummySchedulerNÚ	optimizerz|--adafactor was passed, but also found `optimizer` configured in the DeepSpeed config. Only one optimizer can be configured.)Úparamsz¢Detected ZeRO Offload and non-DeepSpeed optimizers: This combination should work as long as the custom optimizer has both CPU and GPU implementation (except LAMB)TÚzero_allow_untested_optimizerÚ	schedulerc                 óf   •— t        j                   ‰«      }d |_        |j                  ‰| ¬«      }|S )N©rx   r±   )rª   Úlr_schedulerÚcreate_scheduler)r±   Útrainer_copyr·   rx   Útrainers      €€r   Ú_lr_scheduler_callablez5deepspeed_optim_sched.<locals>._lr_scheduler_callable�  s=   ø€ ä#Ÿy™y¨Ó1�ð -1�Ô)Ø+×<Ñ<Ø'9ÀYð  =ó  �ð $Ð#r"   )Úlr_scheduler_callabler¶   )Úaccelerate.utilsr¯   r°   r@   Ú	adafactorr0   Ú
is_offloadÚloggerÚinfoÚcreate_optimizerÚ
isinstancer¸   )rº   Úhf_deepspeed_configrc   rx   Úmodel_parametersr¯   r°   r@   r±   r·   r»   s   `  `       r   Údeepspeed_optim_schedrÆ   b  sö   ù€ ÷ <à ×'Ñ'€Fð €IØ�fÑØ�>Š>Üð8óð ñ Ð&6Ô7‰	à×)Ñ)Ô+Ü�K‰KðVôð ×,Ñ,Ó.ˆ	à26ˆÐ.Ñ/à€LØ�fÑÙ% iÓ0ˆð& �lÐ"Ð"ô# �i Ô,õ	$ñ *¨)ÐKaÔbˆLð �lÐ"Ð"ð #×3Ñ3ÐGYÐenÐ3ÓoˆLà�lÐ"Ð"r"   c                 óº  — ddl m} | j                  }| j                  }| j                  j
                  j                  j                  }|j                  |||«       |j                  |j                  «       «       |rH|j                  «       st        d«      ‚|j                  d«       |j                  d«       d\  }}d}	||fS d| _        |j                  j!                  di «      j!                  d	d«      }
|
d
kD  r&ddl}|j%                  ||
|j'                  «       ¬«      }t)        t+        d„ |j-                  «       «      «      }	t/        | ||||	«      \  }}||fS )a  
    Init DeepSpeed, after updating the DeepSpeed configuration with any relevant Trainer's args.

    If `resume_from_checkpoint` was passed then an attempt to resume from a previously saved checkpoint will be made.

    Args:
        trainer: Trainer object
        num_training_steps: per single gpu
        resume_from_checkpoint: path to a checkpoint if to resume from after normal DeepSpeedEngine load
        inference: launch in inference mode (no optimizer and no lr scheduler)
        auto_find_batch_size: whether to ignore the `train_micro_batch_size_per_gpu` argument as it's being
            set automatically by the auto batch size finder

    Returns: optimizer, lr_scheduler

    We may use `deepspeed_init` more than once during the life of Trainer, when we do - it's a temp hack based on:
    https://github.com/deepspeedai/DeepSpeed/issues/1394#issuecomment-937405374 until Deepspeed fixes a bug where it
    can't resume from a checkpoint after it did some stepping https://github.com/deepspeedai/DeepSpeed/issues/1612

    r   )rÀ   zMZeRO inference only makes sense with ZeRO Stage 3 - please adjust your configr±   r·   )NNNÚtensor_parallelÚautotp_sizeé   )rw   Útp_sizer1   c                 ó   — | j                   S r,   )Úrequires_grad)Úps    r   ú<lambda>z deepspeed_init.<locals>.<lambda>Ò  s
   € °·±€ r"   )Údeepspeed.utilsrÀ   rw   rc   ÚacceleratorÚstateÚdeepspeed_pluginÚhf_ds_configr|   ÚsetLevelÚget_process_log_levelrs   r0   Údel_config_sub_treer±   r@   r;   r   Útp_model_initr1   ÚlistÚfilterÚ
parametersrÆ   )rº   rx   Ú	inferenceÚ	ds_loggerrw   rc   rÄ   r±   r·   rÅ   rË   r   s               r   Údeepspeed_initrÞ   Ÿ  s]  € õ* 4à�M‰M€EØ�<‰<€Dà!×-Ñ-×3Ñ3×DÑD×QÑQÐð ×/Ñ/°°eÐ=OÔPð ×Ñ�t×1Ñ1Ó3Ô4áà"×+Ñ+Ô-ÜÐlÓmÐmð 	×/Ñ/°Ô<Ø×/Ñ/°Ô?Ø",Ñˆ	�<ØÐð  �lÐ"Ð"ð !ˆÔØ%×,Ñ,×0Ñ0Ð1BÀBÓG×KÑKÈMÐ[\Ó]ˆØ�QŠ;Ûà×+Ñ+°%ÀÐPc×PiÑPiÓPkÐ+ÓlˆEÜ¤Ñ'@À%×BRÑBRÓBTÓ UÓVÐÜ"7ØÐ(¨$Ð0BÐDTó#
Ñˆ	�<ð �lÐ"Ð"r"   c                 óþ   — dd l }t        |j                  |› d�«      «      }t        |«      dkD  rAt        j	                  d|› �«       | j                  ||dd¬«      \  }}|€t        d|› �«      ‚y t        d|› �«      ‚)Nr   z/global_step*zAttempting to resume from T)Úload_module_strictÚload_optimizer_statesÚload_lr_scheduler_statesz-[deepspeed] failed to resume from checkpoint z!Can't find a valid checkpoint at )ÚglobÚsortedrp   rÀ   rÁ   Úload_checkpointr0   )Údeepspeed_engineÚcheckpoint_pathrà   rã   Údeepspeed_checkpoint_dirsÚ	load_pathr   s          r   Údeepspeed_load_checkpointrê   Ý  s¢   € ó
 ä & t§y¡y°OÐ3DÀMÐ1RÓ'SÓ TÐä
Ð$Ó%¨Ò)Ü�‰Ð0°Ð0AÐBÔCà'×7Ñ7ØØ1Ø"&Ø%)ð	 8ó 
‰ˆ	�1ð ÐÜÐLÈ_ÐL]Ð^Ó_Ð_ð ô Ð<¸_Ð<MÐNÓOÐOr"   r}   )T)%r&   rª   Úimportlib.metadatar   r   Úimportlib.utilr   r   Ú	functoolsr   Údependency_versions_checkr   Úutilsr   r   r   r^   r	   Ú
get_loggerr#   rÀ   r   Úaccelerate.utils.deepspeedr   ÚDeepSpeedConfigÚbuiltinsr   r*   r�   r   r…   r‡   r‰   r­   rÆ   rÞ   rê   r„   r"   r   ú<module>rô      s²   ðñó Ý /Û Û Ý #å 9ß HÑ Hñ ÔÛÝð 
ˆ×	Ñ	˜HÓ	%€ò
ñ ÔÑ!7Ô!9ÞOõ 3ô.˜ô .ô2}Ð0ô }ðB !%Ð òIò)òòò-ò`:#óz;#ô|Pr"   