Ë
    Gêñií‚  ã                   óV  — d 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  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„ Z"dd„Z#dd„Z$dd„Z%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                  j                  d«      }yy # t         j                  j                  $ r Y yw xY w)NÚ	deepspeedTF)Ú	importlibÚutilÚ	find_specÚmetadataÚPackageNotFoundError)Úpackage_existsÚ_s     úe/var/www/pod-logistic/pod-ai/venv/lib/python3.12/site-packages/transformers/integrations/deepspeed.pyÚis_deepspeed_availabler   $   sc   € Ü—^‘^×-Ñ-¨kÓ:À$ÐF€Nñ ð	Ü×"Ñ"×+Ñ+¨KÓ8ˆAØð øô ×!Ñ!×6Ñ6ò 	Ùð	ús   ¥A Á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.

        Nr2   z- ds ú=z vs hf )Úfind_config_nodeÚgetr-   Úappend)r   r4   Ú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                 óž  — |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                  rE| j                  j                  di «      | j                  d<   |j                  | j                  d   d<   | j                  d|j                  xs |j                  d«       | j                  d|j                   xs |j"                  d«       | j%                  d«      rt&        j(                  | _        y| j%                  d«      rt&        j,                  | _        yt&        j.                  | _        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Ú
checkpointÚuse_node_local_storagezfp16.enabledzfp16|fp16_full_evalzbf16.enabledzbf16|bf16_full_evalN)Ú
world_sizerE   rF   rB   rI   rJ   Ú
adam_beta1Ú
adam_beta2rK   rL   Ú	fill_onlyÚsave_on_each_noder?   r:   Úfp16Úfp16_full_evalÚbf16Úbf16_full_evalÚis_trueÚtorchÚbfloat16r,   Úfloat16Úfloat32)r   ÚargsÚauto_find_batch_sizerG   s       r   Útrainer_config_processz/HfTrainerDeepSpeedConfig.trainer_config_process…   sç  € ð  Ÿ?™?¨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Ô^ð ×!Ò!à(,¯©¯©¸ÀbÓ(IˆD�K‰K˜Ñ%ØBF×BXÑBXˆD�K‰K˜Ñ%Ð&>Ñ?ð 	�‰˜¨¯©Ò)I°d×6IÑ6IÐLaÔbØ�‰˜¨¯©Ò)I°d×6IÑ6IÐLaÔbð �<‰<˜Ô'ÜŸ.™.ˆD�KØ�\‰\˜.Ô)ÜŸ-™-ˆD�KäŸ-™-ˆD�Kr!   c                 óŒ  — g d¢}|D �cg c]  }| j                  |«      sŒ|‘Œ }}t        |«      dkD  �r”d}t        |d«      �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                  }n_t        |j                  d«      rIt        |j                  j                  d«      r)t        |j                  j                  j                  «      }|€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   Nr?   Ú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.ra   rb   gÍÌÌÌÌÌì?rc   é
   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'.)r6   ÚlenÚhasattrr?   rd   Úmaxre   rf   r/   rR   Úis_zero3ÚintrB   Úget_warmup_stepsr-   Újoin)	r   r]   ÚmodelÚnum_training_stepsÚhidden_size_based_keysÚxÚhidden_size_auto_keysrd   r-   s	            r   Útrainer_config_finalizez0HfTrainerDeepSpeedConfig.trainer_config_finalize¿   s  € ò"
Ðð
 -CÖ V qÀdÇlÁlÐSTÅo¢Ð VÐÐ VäÐ$Ó%¨Ó)ØˆKÜ�u˜hÕ'Ü˜5Ÿ<™<¨Ô7Ø"'§,¡,×":Ñ":‘KÜ˜UŸ\™\¨>Ô:ä"% e§l¡l×&?Ñ&?Ó"@‘KÜ˜UŸ\™\¨=Ô9¼gÀeÇlÁl×F^ÑF^Ð`mÔ>nØ"'§,¡,×":Ñ":×"FÑ"F‘KÜ˜UŸ\™\¨=Ô9¼gÀeÇlÁl×F^ÑF^Ð`nÔ>oä"% e§l¡l×&>Ñ&>×&KÑ&KÓ"L�KàÐ"Ü ð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óð ð $ùòa !Ws
   ‰I I)NT©F)r"   r#   r$   r%   r   r0   r6   rB   r   rR   r_   rv   r&   r'   s   @r   r)   r)   R   s7   ø„ ñô
ò
ò
!ó[ñ4 ˜j°UÔ;€Ió8(ötC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{   rm   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                 ó  ‡‡‡‡— ddl Šddl}ddlm} ddlmŠ | j                  «       Šˆˆˆˆfd„Š |j                  «       5   |«       5   ‰| | j                  «       ddd«       ddd«       y# 1 sw Y   ŒxY w# 1 sw Y   yxY w)aA  
    DeepSpeed ZeRO-3 variant of `PreTrainedModel.initialize_weights`. Mirrors the `smart_apply`
    dispatch logic but gathers each module's partitioned parameters before calling
    `_initialize_weights`, so initialization operates on full tensors instead of empty shards.
    Only rank 0 performs the actual init.
    r   Nr   )Úguard_torch_init_functions)ÚPreTrainedModelc                 ó€  •— | j                  «       D ]+  }t        |‰«      r ‰||j                  «       Œ# ‰||«       Œ- t        | j	                  d¬«      «      }|rM‰j
                  j                  |d¬«      5  ‰j                  j                  «       dk(  r	 || ‰«       d d d «       y  || ‰«       y # 1 sw Y   y xY w)NF)Úrecurser   ©Úmodifier_rank)	ÚchildrenÚ
isinstanceÚ_initialize_weightsÚlistÚ
parametersÚzeroÚGatheredParametersÚcommÚget_rank)Úmodel_or_moduleÚfnÚchildÚparamsr†   Ú_apply_zero3r   Úis_remote_codes       €€€€r   r˜   z.initialize_weights_zero3.<locals>._apply_zero34  s¸   ø€ Ø$×-Ñ-Ó/ò 	(ˆEÜ˜% Ô1Ù˜U E×$=Ñ$=Õ>á˜U BÕ'ð		(ô �o×0Ñ0¸Ð0Ó?Ó@ˆÙØ—‘×2Ñ2°6ÈÐ2ÓKñ 8Ø—>‘>×*Ñ*Ó,°Ò1Ù�¨Ô7÷8ð 8ñ ˆ Õ/÷	8ð 8ús   Á:'B4Â4B=)	r   rY   Úinitializationr…   Úmodeling_utilsr†   r™   Úno_gradr�   )rq   rY   r…   r†   r˜   r   r™   s      @@@@r   Úinitialize_weights_zero3r�   %  sv   û€ ó Ûå;Ý0à×)Ñ)Ó+€N÷0ð 
ˆ�‰‹ñ ;Ù'Ó)ñ 	;Ù˜ × 9Ñ 9Ô:÷	;÷;ð ;÷	;ð 	;ú÷;ð ;ús$   ÁA;Á
A/ÁA;Á/A8	Á4A;Á;Bc                 ó  ‡!— t        «       }|�€|j                  di «      j                  dd«      }|j                  di «      }t        |t        «      r,t	        ||j                  di «      j                  dd«      «      }|dkD  rt        d«      ‚dd	lm}m}m	Š!m
} t        |d
d«      }	| j                  }
i }| j                  «       j                  «       D ]4  \  }}t        j                   |j"                  |j$                  d¬«      ||<   Œ6 |D �cg c]  }t        ||«      sŒ|‘Œ }}|D �cg c]  }t        ||«      sŒ|‘Œ }}t'        |«      dk(  r>i }|j                  «       D ]  \  }} |||g |
|«      \  }}||v sŒ|||<   Œ  |	�|	|_        |S |D ��ci c]  }|j*                  D ]  }||“Œ Œ }}}i }i }t-        |j/                  «       ˆ!fd„¬«      }|D ]ƒ  }|j1                  |«      } |||||
|«      \  }}||v sŒ(|�U||   } ||j*                  |j2                  |j4                  ¬«      }|j7                  ||«      }|j9                  ||||«       Œ|||<   Œ… |j                  «       D ]X  \  }}	 |j;                  || | j<                  ¬«      }|j                  «       D ]!  \  }}t        |t>        «      r|d   n|}|||<   Œ# ŒZ |	�|	|_        |S c c}w c c}w c c}}w # t@        $ r} tC        d|› d| › �«      | ‚d} ~ ww xY w)z¼
    Apply weight conversions (renaming and merging/splitting operations) to a state dict.
    This is a simplified version that handles the conversion without loading into the model.
    NÚtensor_parallelÚautotp_sizeé   Ú	inferenceÚtp_sizezóWeight conversions (e.g., MoE expert fusion) with DeepSpeed Tensor Parallelism are not yet implemented but support is coming soon. Please disable tensor_parallel in your DeepSpeed config or convert your checkpoint to the expected format first.r   )ÚWeightConverterÚWeightRenamingÚdot_natural_keyÚrename_source_keyÚ	_metadataÚmeta)r0   Údevicer   c                 ó   •—  ‰| «      S r+   r~   )Úkr¦   s    €r   ú<lambda>z9_apply_weight_conversions_to_state_dict.<locals>.<lambda>‚  s   ø€ ¹/È!Ó:L€ r!   )Úkey)Úsource_patternsÚtarget_patternsÚ
operations)rq   r?   z'Failed to apply weight conversion for 'zb'. This likely means the checkpoint format is incompatible with the current model version. Error: )"rƒ   r:   rŒ   Údictrl   ÚNotImplementedErrorÚcore_model_loadingr¤   r¥   r¦   r§   ÚgetattrÚbase_model_prefixÚ
state_dictÚitemsrY   ÚemptyÚshaper0   rj   r¨   r¯   ÚsortedÚkeysÚpopr°   r±   Ú
setdefaultÚ
add_tensorÚconvertr?   rŽ   Ú	ExceptionÚRuntimeError)"rq   r·   Úweight_mappingÚ	ds_configr£   Úinference_configr¤   r¥   r§   r   ÚprefixÚmodel_state_dictr®   ÚparamÚentryÚ	renamingsÚ
convertersÚnew_state_dictÚoriginal_keyÚtensorÚrenamed_keyr   Ú	converterr¬   Úpattern_to_converterÚconversion_mappingÚsorted_keysÚsource_patternÚnew_converterÚmappingÚrealized_valueÚtarget_nameÚer¦   s"                                    @r   Ú'_apply_weight_conversions_to_state_dictrÚ   H  s�  ø€ ô !Ó"€IØÐà—-‘-Ð 1°2Ó6×:Ñ:¸=È!ÓLˆà$Ÿ=™=¨°bÓ9ÐÜÐ&¬Ô-Ü˜'Ð#3×#7Ñ#7Ð8IÈ2Ó#N×#RÑ#RÐS\Ð^_Ó#`ÓaˆGØ�QŠ;Ü%ðdóð ÷ iÓhô �z ;°Ó5€Hà×$Ñ$€Fð ÐØ×&Ñ&Ó(×.Ñ.Ó0ò [‰
ˆˆUÜ %§¡¨E¯K©K¸u¿{¹{ÐSYÔ ZÐ˜Òð[ð %3ÖX˜5´jÀÈÕ6W’ÐX€IÐXØ%3ÖZ˜E´zÀ%ÈÕ7Y’%ÐZ€JÐZô ˆ:ƒ˜!ÒØˆØ$.×$4Ñ$4Ó$6ò 	5Ñ ˆL˜&Ù.¨|¸YÈÈFÐTdÓe‰NˆK˜ØÐ.Ò.Ø.4�˜{Ò+ð	5ð
 ÐØ'/ˆNÔ$ØÐð ;E×h¨YÈi×NgÑNgÒhÈ˜A˜y™LÐh˜AÐhÐÑhð
 ÐØ€NÜ˜Ÿ™Ó*Ó0LÔM€KØ#ò 5ˆØ—‘ Ó-ˆÙ&7¸ÀiÐQ[Ð]cÐeuÓ&vÑ#ˆ�^ð Ð*Ò*àÐ)ð 1°Ñ@�	Ù /Ø$-×$=Ñ$=Ø$-×$=Ñ$=Ø(×3Ñ3ô!�ð
 -×7Ñ7¸À]ÓS�Ø×"Ñ" ;°¸nÈfÕUð /5�˜{Ò+ð+5ð0 !3× 8Ñ 8Ó :ò Ñˆ�Wð	Ø$Ÿ_™_ØØØ—|‘|ð -ó ˆNð
 '5×&:Ñ&:Ó&<ò 4Ñ"�˜UÜ$.¨u´dÔ$;˜˜ašÀ�Ø.3�˜{Ò+ñ4ðð$ ÐØ#+ˆÔ àÐùòK YùÚZùó iøôT ò 	ÜØ9¸+¸ð Gà˜ðóð ð	ûð	ús7   ÄKÄ KÄ*KÄ<KÆKÉ2AK!Ë!	LË*K<Ë<Lc           	      ó  ‡‡	‡
‡— t        |dd«      Š
|j                  «       }‰
�‰
|_        d}|�t        |dd«      }|�"t        |«      dkD  rt	        | ||«      }|| _        g Š| j                  «       }t        |j                  «       «      Št        | dd«      }|j                  «       D ��ci c]%  \  }}|j                  |› d|› �«      �|› d|› �n||“Œ' }}}ddt        j                  fˆˆ	ˆ
ˆfd	„Š	 ‰	| |d¬
«       ‰‰fS c c}}w )a°  
    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`

    Args:
        model_to_load: The model to load weights into
        state_dict: The state dict containing the weights
        load_config: Optional LoadStateDictConfig containing weight_mapping and other loading options
    r¨   NrÃ   r   r¶   ú.FÚmodulec                 óœ  •— ‰€i n‰j                  |d d i «      }||d<   |||dg g ‰f}t        «       �rKdd l}t        | j	                  |d d d¬«      «      }g }|D ]5  }	|	|v sŒ||	   }
d|
_        |j                  |
«       ‰j                  |	«       Œ7 t        |«      dkD  rV|j                  j                  |d¬«      5  t        j                  j                  «       dk(  r | j                  |Ž  d d d «       t        | j                  |d d d¬«      «      }|j!                  «       D ]V  \  }	}|	|v sŒ|€Œ‰j                  |	«       t        j"                  «       5  |j%                  ||	   «       d d d «       d|_        ŒX | j&                  j!                  «       D ]  \  }}|€Œ	 ‰||||z   dz   |«       Œ y # 1 sw Y   ŒÈxY w# 1 sw Y   ŒUxY w)	NéÿÿÿÿÚassign_to_params_buffersTr   F)rÆ   rˆ   r‰   rÜ   )r:   r�   r   r²   Únamed_parametersÚ_is_hf_initializedr;   Údiscardrj   r�   r‘   rY   Údistributedr“   Ú_load_from_state_dictÚnamed_buffersr¸   rœ   Úcopy_Ú_modules)rÝ   r·   rÆ   rà   Úlocal_metadatar]   r   rá   Úparams_to_gatherr¬   rÈ   ræ   ÚbufÚnamer–   Ú
error_msgsÚloadr   Úmissing_keyss                  €€€€r   rî   z/_load_state_dict_into_zero3_model.<locals>.loadÝ  sï  ø€ Ø'Ð/™°X·\±\À&ÈÈ"À+ÈrÓ5RˆØ5MˆÐ1Ñ2à˜F N°D¸"¸bÀ*ÐMˆô &Õ'Ûô  $ F×$;Ñ$;À6È#È2À;ÐX]Ð$;Ó$^Ó_ÐØ!ÐØ%ò ,�Ø˜
’?Ø,¨QÑ/�Eà/3�EÔ,Ø$×+Ñ+¨EÔ2Ø ×(Ñ(¨Õ+ð,ô Ð#Ó$ qÒ(ð —^‘^×6Ñ6Ð7GÐWXÐ6ÓYñ <Ü×(Ñ(×1Ñ1Ó3°qÒ8Ø4˜×4Ñ4°dÑ;÷<ô
 ! ×!5Ñ!5¸VÀCÀR¸[ÐRWÐ!5Ó!XÓYˆMØ'×-Ñ-Ó/ò 2‘��3Ø˜
’? s¡Ø ×(Ñ(¨Ô+ÜŸ™›ñ 1ØŸ	™	 *¨Q¡-Ô0÷1à-1�CÕ*ð2ð "Ÿ?™?×0Ñ0Ó2ò 	W‰KˆD�%ØÑ Ù�U˜J¨°©¸Ñ(;Ð=UÕVñ	W÷<ð <ú÷1ð 1ús   Â>1F6ÅGÆ6F?ÇG	)rà   )Ú F)rµ   Úcopyr¨   rj   rÚ   Ú_weight_conversionsr·   Úsetr¼   r¸   r:   r	   ÚModule)Úmodel_to_loadr·   Úload_configrÃ   Úmeta_model_state_dictÚprefix_modelr¬   Úvrí   rî   r   rï   s           @@@@r   Ú!_load_state_dict_into_zero3_modelrú   ³  s>  û€ ô �z ;°Ó5€HØ—‘Ó"€JØÐØ'ˆ
Ôð €NØÐÜ  Ð.>ÀÓEˆð Ð!¤c¨.Ó&9¸AÒ&=Ü<¸]ÈJÐXfÓgˆ
à,:ˆÔ)à€JØ)×4Ñ4Ó6ÐÜÐ,×1Ñ1Ó3Ó4€Lä˜=Ð*=¸tÓD€Lð ×$Ñ$Ó&÷áˆAˆqð #8×";Ñ";¸|¸nÈAÈaÈSÐ<QÓ"RÐ"^ˆLˆ>˜˜1˜#Ñ	ÐdeÐhiÑ	ið€Jñ ñ)W”R—Y‘Y÷ )Wð )WñV 	ˆ˜
¸UÕCà�|Ð#Ð#ùóis   Â+*Dc                 ó&  ‡ ‡— ddl m}m} |j                  }d}d|v r
 ||¬«      }n:|j	                  «       rt
        j                  d«       ‰ j                  «       }d|d<   d}	d	|v r ||«      }	||	fS t        ||«      rˆˆ fd
„}
 |||
¬«      }	||	fS )zY
    A convenience wrapper that deals with optimizer and lr scheduler configuration.
    r   )Ú
DummyOptimÚDummySchedulerNÚ	optimizer)r—   z¢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)rr   rþ   )rñ   Úlr_schedulerÚcreate_scheduler)rþ   Útrainer_copyr  rr   Útrainers      €€r   Ú_lr_scheduler_callablez5deepspeed_optim_sched.<locals>._lr_scheduler_callable3  s=   ø€ ä#Ÿy™y¨Ó1�ð -1�Ô)Ø+×<Ñ<Ø'9ÀYð  =ó  �ð $Ð#r!   )Úlr_scheduler_callable)	Úaccelerate.utilsrü   rý   r?   Ú
is_offloadÚloggerÚinfoÚcreate_optimizerrŒ   )r  Úhf_deepspeed_configr]   rr   Úmodel_parametersrü   rý   r?   rþ   r  r  s   `  `       r   Údeepspeed_optim_schedr    sµ   ù€ ÷ <à ×'Ñ'€Fð €IØ�fÑÙÐ&6Ô7‰	à×)Ñ)Ô+Ü�K‰KðVôð ×,Ñ,Ó.ˆ	à26ˆÐ.Ñ/à€LØ�fÑÙ% iÓ0ˆð" �lÐ"Ð"ô �i Ô,õ	$ñ *¨)ÐKaÔbˆ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  r1ddl}|j%                  ||
|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  )NNNrŸ   r    r¡   )rq   r£   r0   r?   c                 ó   — | j                   S r+   )Úrequires_grad)Úps    r   r­   z deepspeed_init.<locals>.<lambda>{  s
   € °·±€ r!   )Údeepspeed.utilsr
  rq   r]   ÚacceleratorÚstateÚdeepspeed_pluginÚhf_ds_configrv   ÚsetLevelÚget_process_log_levelrm   r/   Údel_config_sub_treerþ   r?   r:   r   Útp_model_initr0   rŽ   Úfilterr�   r  )r  rr   r¢   Ú	ds_loggerrq   r]   r  rþ   r  r  Údeepspeed_tp_sizer   s               r   Údeepspeed_initr   C  sq  € õ* 4à�M‰M€EØ�<‰<€Dà!×-Ñ-×3Ñ3×DÑD×QÑQÐð ×/Ñ/°°eÐ=OÔPð ×Ñ�t×1Ñ1Ó3Ô4áà"×+Ñ+Ô-ÜÐlÓmÐmð 	×/Ñ/°Ô<Ø×/Ñ/°Ô?Ø",Ñˆ	�<ØÐð* �lÐ"Ð"ð' !ˆÔØ/×6Ñ6×:Ñ:Ð;LÈbÓQ×UÑUÐVcÐefÓgÐØ˜qÒ Ûà×+Ñ+ØØ)Ø)×/Ñ/Ó1Ø*×1Ñ1ð	 ,ó ˆ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 )Úglobr»   rj   r
  r  Úload_checkpointr/   )Ú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!   c                 óæ   — | j                   j                  }t        |j                  j                  «      |_        |j                  j                  |_        |j                  j                  ||«       y)a“  
    Sets values in the deepspeed plugin based on the TrainingArguments.

    Args:
        accelerator (`Accelerator`): The Accelerator object.
        args (`TrainingArguments`): The training arguments to propagate to DeepSpeed config.
        auto_find_batch_size (`bool`, *optional*, defaults to `False`):
            Whether batch size was auto-discovered by trying increasingly smaller sizes.
    N)r  r  r)   r  r?   rƒ   r_   )r  r]   r^   Ú	ds_plugins       r   Úpropagate_args_to_deepspeedr.  ž  sY   € ð ×!Ñ!×2Ñ2€Iä5°i×6LÑ6L×6SÑ6SÓT€IÔØ!*×!7Ñ!7×!>Ñ!>€IÔØ×Ñ×1Ñ1°$Ð8LÕMr!   c                 óØ  ‡‡— d|vrd|v r|d   |d<    |di |¤Ž}|j                   }|j                  dk(  r&|j                  dkD  rddlm} |j                  «       }n5| j                  �| j                  d   j                  «       }nt        d«      ‚|j                  }	t        j                  j                  j                  j                  ||¬	«      Š|d   d
k7  j                  d«      j                  «       }
t        j                  j                  j                  j                  |
|¬	«      Št        ˆˆfd„t!        |	«      D «       «      }t        ‰«      }|t#        |d«      z  }|r||fS |S )aq  
    Computes the loss under sequence parallelism with `sp_backend="deepspeed"` and `sp_size > 1`.

    Performs weighted loss aggregation across SP ranks, accounting for varying numbers of valid tokens per rank
    (e.g., when some ranks receive only padding or prompt tokens that are masked with -100).

    Args:
        accelerator (`Accelerator`): The accelerator instance with `torch_device_mesh` support.
        model (`torch.nn.Module`): The model to compute the loss for.
        inputs (`dict[str, torch.Tensor | Any]`): The input data for the model. Must include `"shift_labels"` key.
        return_outputs (`bool`): Whether to return the model outputs along with the loss.
        pc (`accelerate.parallelism_config.ParallelismConfig`): The parallelism configuration.

    Returns:
        The loss, or a tuple of `(loss, outputs)` if `return_outputs` is `True`.
    ÚlabelsÚshift_labelsr   r¡   r   )ÚgroupsÚspz™Sequence parallelism is enabled but no SP process group is available. Ensure torch_device_mesh is initialized or sp_backend='deepspeed' with sp_size > 1.)Úgroupiœÿÿÿrß   c              3   óD   •K  — | ]  }‰|   d kD  r‰|   ‰|   z  –— Œ y­w)r   Nr~   )Ú.0ÚrankÚgood_tokens_per_rankÚlosses_per_ranks     €€r   ú	<genexpr>z,deepspeed_sp_compute_loss.<locals>.<genexpr>Þ  s6   øè ø€ ò àØ Ñ%¨Ò)ð 	˜ÑÐ 4°TÑ :Õ:ñùs   ƒ r~   )ÚlossÚ
sp_backendÚsp_sizer  r2  Ú_get_sequence_parallel_groupÚtorch_device_meshÚ	get_groupr/   rY   rä   r	   Ú
functionalÚ
all_gatherÚviewÚsumÚrangerl   )r  rq   ÚinputsÚreturn_outputsÚpcÚoutputsr;  r2  Úsp_groupÚsp_world_sizeÚgood_tokensÚ
total_lossÚtotal_good_tokensr8  r9  s                @@r   Údeepspeed_sp_compute_lossrO  ¯  sc  ù€ ð, �vÑ .°FÑ":à! .Ñ1ˆˆxÑÙ‰o�f‰o€GØ�<‰<€Dð 
‡}�}˜Ò#¨¯
©
°QªÝ*à×6Ñ6Ó8‰Ø	×	&Ñ	&Ð	2Ø×0Ñ0°Ñ6×@Ñ@ÓB‰äðbó
ð 	
ð —J‘J€Mä×'Ñ'×*Ñ*×5Ñ5×@Ñ@ÀÈXÐ@ÓV€Oà˜.Ñ)¨TÑ1×7Ñ7¸Ó;×?Ñ?ÓA€KÜ ×,Ñ,×/Ñ/×:Ñ:×EÑEÀkÐYaÐEÓbÐäô ä˜-Ó(ôó €Jô
 Ð0Ó1ÐØœÐ-¨qÓ1Ñ1€Dá,ˆD�'ˆ?Ð6°$Ð6r!   r+   rw   )T)'r%   rñ   Úimportlib.metadatar   Úimportlib.utilry   Ú	functoolsr   Údependency_versions_checkr   Úutilsr   r   r   rY   r	   Ú
get_loggerr"   r
  r   Úaccelerate.utils.deepspeedr   ÚDeepSpeedConfigÚbuiltinsr   r)   r{   r   r   r�   rƒ   r�   rÚ   rú   r  r   r+  r.  rO  r~   r!   r   ú<module>rY     sÌ   ðñó Û Û Û Ý #å 9ß HÑ Hñ ÔÛÝð 
ˆ×	Ñ	˜HÓ	%€ò
ñ ÔÑ!7Ô!9ÞOõ 3ô.˜ô .ô2pÐ0ô pðh !%Ð òIò)òòò ;òFhóVW$òt3#ól@#óFPó0Nó"77r!   