ó
    Eñiæz  ã                   óö  • S r SSKrSSKrSSKJr  SSKJrJr  SSKJ	r	J
r
  SSKJr  SSKrSSKJrJr  S	S
KJr  S	SKJrJr  S	SKJrJrJr  S	SKJr  \" 5       (       a	  SSKJs  Jr  \" 5       (       a  SSK J!r!  S r"S r#S r$S r%S r&\"SS.S jr'SES jr(S r)S r*S r+S r,S r-S r.S r/S r0 " S  S!\15      r2S" r3S# r4\3S$ 5       r5S%\4S& jr6S%\4S' jr7SFS( jr8SGS) jr9\Rt                  S	\Rv                  S\Rx                  S*\Rz                  S+\R|                  S,\R~                  S-\R€                  S.\R‚                  S/\R„                  S0\R†                  S10
rD\DR‹                  5        V Vs0 s H  u  pX_M	     snn rFS2 rGSHS3\R�                  4S4 jjrI\3SFS5\J4S6 jj5       rKSFS5\J4S7 jjrLSIS8 jrMSFS9 jrN " S: S;\O5      rP\4SJS< j5       rQSFS= jrR\3SKS> j5       rSS? rT " S@ SA5      rUSB rVSC rW\SLSD j5       rXgs  snn f )MzB
A set of basic tensor ops compatible with tpu, gpu, and multigpu
é    N)ÚMapping)ÚcontextmanagerÚnullcontext)Úupdate_wrapperÚwraps)ÚAnyé   )ÚAcceleratorStateÚPartialStateé   )Ú!TORCH_DISTRIBUTED_OPERATION_TYPES)ÚDistributedTypeÚTensorInformation)Úis_npu_availableÚis_torch_distributed_availableÚis_torch_xla_available)Úis_torch_version)ÚReduceOpc                 ó6   • [        U [        R                  5      $ ©N)Ú
isinstanceÚtorchÚTensor©Útensors    ÚX/home/mande/repo/quber/.venv/lib/python3.13/site-packages/accelerate/utils/operations.pyÚis_torch_tensorr   -   s   € Ü�fœeŸl™lÓ+Ð+ó    c           
      óv  • [        U [        R                  R                  [        R                  R                  [        R                  R
                  [        R                  R                  [        R                  R                  [        R                  R                  [        R                  R                  5      $ r   )
r   r   ÚxpuÚFloatTensorÚ
ByteTensorÚ	IntTensorÚ
LongTensorÚ
HalfTensorÚDoubleTensorÚBFloat16Tensorr   s    r   Úis_torch_xpu_tensorr(   1   sm   € ÜØÜ�	‰	×ÑÜ�	‰	×ÑÜ�	‰	×ÑÜ�	‰	×ÑÜ�	‰	×ÑÜ�	‰	×ÑÜ�	‰	× Ñ ó	ð 	r   c                 ó"   • [        U [        5      $ r   )r   r   ©Útensor_infos    r   Úis_tensor_informationr,   >   s   € Ü�kÔ#4Ó5Ð5r   c                 ón   • [        U [        5      =(       a    [        U S5      =(       a    [        U S5      $ )z†
Checks if `data` is a `namedtuple` or not. Can have false positives, but only if a user is trying to mimic a
`namedtuple` perfectly.
Ú_asdictÚ_fields)r   ÚtupleÚhasattr©Údatas    r   Úis_namedtupler4   B   s*   € ô
 �dœEÓ"×\¤w¨t°YÓ'?×\ÄGÈDÐR[ÓD\Ð\r   c                 ór   • [        U 5      (       a  [        U 5      " [        U5      6 $ [        U 5      " U5      $ )zG
Cast a generator to the same type as obj (list, tuple, or namedtuple)
)r4   ÚtypeÚlist)ÚobjÚ	generators     r   Ú
honor_typer:   J   s1   € ô
 �S×ÑÜ�CŒyœ$˜y›/Ð*Ð*ä�CŒy˜Ó#Ð#r   F©Ú	test_typeÚerror_on_other_typec                óà  ^ ^^^^• [        U[        [        45      (       a  [        UUUU UU4S jU 5       5      $ [        U[        5      (       aF  [        U5      " UR                  5        VVs0 s H  u  pgU[        T U/TQ7TTS.TD6_M     snn5      $ T" U5      (       a  T " U/TQ70 TD6$ T(       a2  [        S[        U5       ST R                   STR                   S35      eU$ s  snnf )a  
Recursively apply a function on a data structure that is a nested list/tuple/dictionary of a given base type.

Args:
    func (`callable`):
        The function to recursively apply.
    data (nested list/tuple/dictionary of `main_type`):
        The data on which to apply `func`
    *args:
        Positional arguments that will be passed to `func` when applied on the unpacked data.
    main_type (`type`, *optional*, defaults to `torch.Tensor`):
        The base type of the objects to which apply `func`.
    error_on_other_type (`bool`, *optional*, defaults to `False`):
        Whether to return an error or not if after unpacking `data`, we get on an object that is not of type
        `main_type`. If `False`, the function will leave objects of types different than `main_type` unchanged.
    **kwargs (additional keyword arguments, *optional*):
        Keyword arguments that will be passed to `func` when applied on the unpacked data.

Returns:
    The same data structure as `data` with `func` applied to every object of type `main_type`.
c              3   óJ   >#   • U  H  n[        TU/TQ7TTS .TD6v •  M     g7f)r;   N©Úrecursively_apply)Ú.0ÚoÚargsr=   ÚfuncÚkwargsr<   s     €€€€€r   Ú	<genexpr>Ú$recursively_apply.<locals>.<genexpr>n   sA   øé € ð ò �Aô "Ø˜!ðØ"ñØ.7ÐM`ñØdjöò ùs   ƒ #r;   zUnsupported types (z) passed to `z?`. Only nested list/tuple/dicts of objects that are valid for `z` should be passed.)
r   r0   r7   r:   r   r6   ÚitemsrA   Ú	TypeErrorÚ__name__)rE   r3   r<   r=   rD   rF   ÚkÚvs   ` ````  r   rA   rA   U   s  ü€ ô, �$œ¤˜×&Ñ&ÜØ÷ð ñ ó	ó
ð 	
ô 
�Dœ'×	"Ñ	"Ü�DŒzð
 !ŸJ™JœLô	ò )‘D�Að Ô$Ø˜!ðØ"ñØ.7ÐM`ñØdjñò ñ )ò	ó
ð 	
ñ 
�4�‰Ù�DÐ*˜4Ò* 6Ñ*Ð*Þ	ÜØ!¤$ t£* ¨]¸4¿=¹=¸/ð J+Ø+4×+=Ñ+=Ð*>Ð>QðSó
ð 	
ð €Kùós   Á. C*
c                 ó  ^^^• [        U 5      (       d  [        U S5      (       a  TS:X  a  Sm U R                  TTS9$ [        U [        [        45      (       a  [        U UUU4S jU  5       5      $ [        U [        5      (       ad  [        T[        5      (       a  T/mOTc  / m[        U 5      " U R                  5        VVs0 s H  u  pVXUT;   a  UO[        UTTTS9_M     snn5      $ U $ ! [         a    U R                  T5      s $ [         a5  n[        5       (       a  [        T[        5      (       a  ST 3m SnAO
UeSnAff = f U R                  TTS9$ ! [         a    U R                  T5      s $ f = fs  snnf )	as  
Recursively sends the elements in a nested list/tuple/dictionary of tensors to a given device.

Args:
    tensor (nested list/tuple/dictionary of `torch.Tensor`):
        The data to send to a given device.
    device (`torch.device`):
        The device to send the data to.

Returns:
    The same data structure as `tensor` with all tensors sent to the proper device.
ÚtoÚnpuznpu:0)Únon_blockingznpu:Nc              3   ó<   >#   • U  H  n[        UTTTS 9v •  M     g7f)©rQ   Ú	skip_keysN)Úsend_to_device)rB   ÚtÚdevicerQ   rT   s     €€€r   rG   Ú!send_to_device.<locals>.<genexpr>«   s    øé € ÐoÒhnÐcd”^ A v¸LÐT]Ö^Òhnùs   ƒrS   )r   r1   rO   rJ   ÚAssertionErrorr   r   Úintr0   r7   r:   r   Ústrr6   rI   rU   )r   rW   rQ   rT   ÚerrorrL   rV   s    ```   r   rU   rU   ˆ   s{  ú€ ô �v×Ñ¤'¨&°$×"7Ñ"7à�U‹?ØˆFð	Ø—9‘9˜V°,�9Ð?Ð?ô 
�FœU¤D˜M×	*Ñ	*ÜØÖoÑhnÓoó
ð 	
ô 
�FœG×	$Ñ	$Ü�i¤×%Ñ%Ø"˜‰IØÑØˆIÜ�FŒ|ð #ŸL™LœNôâ*‘D�Að ˜Y›‘1¬N¸1¸fÐS_ÐktÑ,uÒuÙ*òó
ð 	
ð ˆøô= ó 	%Ø—9‘9˜VÓ$Ò$Üó 	ô  ×!Ñ!Ü˜f¤c×*Ñ*Ø# F 8˜_�Füà�ûð	úð	%Ø—9‘9˜V°,�9Ð?Ð?øÜó 	%Ø—9‘9˜VÓ$Ò$ð	%üós;   ®C, Ã E<
Ã,EÄ		EÄ)EÅ EÅEÅE ÅE9Å8E9c                 ó   • S n[        X5      $ )a/  
Recursively gathers the information needed to rebuild a nested list/tuple/dictionary of tensors.

Args:
    data (nested list/tuple/dictionary of `torch.Tensor`):
        The data to send to analyze.

Returns:
    The same data structure as `data` with [`~utils.TensorInformation`] instead of tensors.
c                 ó>   • [        U R                  U R                  S9$ )N)ÚshapeÚdtype)r   r_   r`   r   s    r   Ú_get_data_structureÚ/get_data_structure.<locals>._get_data_structureÈ   s   € Ü  v§|¡|¸6¿<¹<ÑHÐHr   r@   )r3   ra   s     r   Úget_data_structurerc   ¼   s   € òIô Ð0Ó7Ð7r   c                 ó   • S n[        X5      $ )a  
Recursively gathers the shape of a nested list/tuple/dictionary of tensors as a list.

Args:
    data (nested list/tuple/dictionary of `torch.Tensor`):
        The data to send to analyze.

Returns:
    The same data structure as `data` with lists of tensor shapes instead of tensors.
c                 ó,   • [        U R                  5      $ r   )r7   r_   r   s    r   Ú
_get_shapeÚget_shape.<locals>._get_shapeÚ   s   € Ü�F—L‘LÓ!Ð!r   r@   )r3   rf   s     r   Ú	get_shaperh   Î   s   € ò"ô ˜ZÓ.Ð.r   c                 ó$   • S n[        X[        S9$ )zÌ
Recursively initializes tensors from a nested list/tuple/dictionary of [`~utils.TensorInformation`].

Returns:
    The same data structure as `data` with tensors instead of [`~utils.TensorInformation`].
c                 óV   • [         R                  " U R                  SU R                  06$ ©Nr`   )r   Úemptyr_   r`   r*   s    r   Ú_initialize_tensorÚ.initialize_tensors.<locals>._initialize_tensorè   s"   € Ü�{Š{˜K×-Ñ-ÐG°[×5FÑ5FÑGÐGr   ©r<   )rA   r,   )Údata_structurerm   s     r   Úinitialize_tensorsrq   à   s   € òHô Ð/ÔK`ÑaÐar   c                 óâ  • [        U [        [        [        45      (       a'  [	        U 5      S:X  a  [        S[        U 5       S35      e[        U [        [        45      (       a  [        U S   5      $ [        U [        5      (       a%  U R                  5        H  n[        X   5      s  $    O7[        U [        R                  5      (       d  [        S[        U 5       S35      eU R                  S   $ )zì
Recursively finds the batch size in a nested list/tuple/dictionary of lists of tensors.

Args:
    data (nested list/tuple/dictionary of `torch.Tensor`): The data from which to find the batch size.

Returns:
    `int`: The batch size.
r   z&Cannot find the batch size from empty Ú.z0Can only find the batch size of tensors but got )r   r0   r7   r   ÚlenÚ
ValueErrorr6   Úfind_batch_sizeÚkeysr   r   rJ   r_   )r3   rL   s     r   rv   rv   î   s¿   € ô �$œ¤¤gÐ.×/Ñ/´S¸³YÀ!³^ÜÐAÄ$ÀtÃ*ÀÈQÐOÓPÐPä�$œ¤˜×&Ñ&Ü˜t A™wÓ'Ð'Ü	�Dœ'×	"Ñ	"Ø—‘–ˆAÜ" 4¡7Ó+Ò+ò ä˜œeŸl™l×+Ñ+ÜÐJÌ4ÐPTË:È,ÐVWÐXÓYÐYØ�:‰:�a‰=Ðr   c                 óF   •  [        U 5      $ ! [        [        4 a     gf = f)a   
Same as [`utils.operations.find_batch_size`] except will ignore if `ValueError` and `TypeErrors` are raised

Args:
    data (nested list/tuple/dictionary of `torch.Tensor`): The data from which to find the batch size.

Returns:
    `int`: The batch size.
N)rv   ru   rJ   r2   s    r   Úignorant_find_batch_sizery     s,   € ðÜ˜tÓ$Ð$øÜœ	Ð"ó ØØðús   ‚
 � Ÿ c                 ó   • S n[        X5      $ )a;  
Recursively finds tensors in a nested list/tuple/dictionary and converts them to a list of numbers.

Args:
    data (nested list/tuple/dictionary of `torch.Tensor`): The data from which to convert to regular numbers.

Returns:
    The same data structure as `data` with lists of numbers instead of `torch.Tensor`.
c                 óØ   • U R                  5       R                  5       n U R                  [        R                  :X  a  U R                  [        R                  5      n U R                  5       $ r   )ÚdetachÚcpur`   r   Úbfloat16rO   Úfloat32Útolistr   s    r   Ú_convert_to_listÚ!listify.<locals>._convert_to_list!  sF   € Ø—‘“×$Ñ$Ó&ˆØ�<‰<œ5Ÿ>™>Ó)ð —Y‘YœuŸ}™}Ó-ˆFØ�}‰}‹Ðr   r@   )r3   r�   s     r   Úlistifyrƒ     s   € òô Ð-Ó4Ð4r   c                 óJ   • S n[        XSS9n[        R                  " 5         U$ )Nc                 ó¾   • U R                   S:X  a  U R                  5       S    n U R                  5       (       d  U R                  5       n [        R
                  " U 5      $ )Nr   )ÚndimÚcloneÚis_contiguousÚ
contiguousÚxmÚ
all_gatherr   s    r   Ú_tpu_gather_oneÚ$_tpu_gather.<locals>._tpu_gather_one.  sL   € Ø�;‰;˜!ÓØ—\‘\“^ DÑ)ˆFð ×#Ñ#×%Ñ%Ø×&Ñ&Ó(ˆFÜ�}Š}˜VÓ$Ð$r   T©r=   )rA   rŠ   Ú	mark_step)r   rŒ   Úress      r   Ú_tpu_gatherr‘   -  s#   € ò%ô ˜OÈÑ
N€CÜ‡L‚L„NØ€Jr   c                 ó  ^^• [        5       m[        R                  R                  mTR                  R
                  S:X  a/  [        SS5      (       a  [        R                  R                  5         UU4S jn[        XSS9$ )Nr    z<=z2.8c                 ó”  >• U R                   S:X  a  U R                  5       S    n U R                  5       (       d  U R                  5       n TR                  b�  TR                  S:w  aq  [
        R                  " TR                  U R                  5       -  U R                  TR                  S9nT" X5        UR                  " S/U R                  5       SS  Q76 $ [        TR                  5       Vs/ s H  n[
        R                  " U 5      PM     nn[
        R                  R!                  X5        [
        R"                  " USS9$ s  snf )Nr   Úgloo©r`   rW   éÿÿÿÿr   ©Údim)r†   r‡   rˆ   r‰   Úbackendr   rl   Únum_processesÚnumelr`   rW   ÚviewÚsizeÚrangeÚ
empty_likeÚdistributedr‹   Úcat)r   Úoutput_tensorsÚ_Ú	gather_opÚstates      €€r   Ú_gpu_gather_oneÚ$_gpu_gather.<locals>._gpu_gather_oneD  s  ø€ Ø�;‰;˜!ÓØ—\‘\“^ DÑ)ˆFð ×#Ñ#×%Ñ%Ø×&Ñ&Ó(ˆFà�=‰=Ñ$¨¯©¸&Ó)@ô
 #Ÿ[š[Ø×#Ñ# f§l¡l£nÑ4Ø—l‘lØ—|‘|ñˆNñ
 �nÔ-Ø!×&Ò& rÐ>¨F¯K©K«M¸!¸"Ð,=Ò>Ð>ô
 AFÀe×FYÑFYÔ@ZÓ[Ò@Z¸1œe×.Ò.¨vÖ6Ñ@ZˆNÐ[Ü×Ñ×(Ñ(¨Ô@Ü—9’9˜^°Ñ3Ð3ùò \s   Ã/ ETrŽ   )
r   r   r    Úall_gather_into_tensorrW   r6   r   r    ÚsynchronizerA   )r   r¦   r¤   r¥   s     @@r   Ú_gpu_gatherrª   <  s`   ù€ Ü‹N€EÜ×!Ñ!×8Ñ8€Ið ‡|�|×Ñ˜EÓ!Ô&6°t¸U×&CÑ&CÜ�	‰	×ÑÔö4ô8 ˜_È$ÑOÐOr   c                   ó   • \ rS rSrSrSrg)ÚDistributedOperationExceptionic  z}
An exception class for distributed operations. Raised if the operation cannot be performed due to the shape of the
tensors.
© N)rK   Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__Ú__static_attributes__r­   r   r   r¬   r¬   c  s   † ñò
 	r   r¬   c                 ó0   ^ • [        T 5      U 4S j5       nU$ )zn
Verifies that `tensor` is the same shape across all processes. Only ran if `PartialState().debug` is `True`.
c                  óR  >• [        5       R                  [        R                  :X  d  [        5       R                  (       d  T
" U 0 UD6$ T
R
                   ST
R                   3nSU;   a  US   nOU S   n[        5       R                  R                  [        U5      R                  :w  ag  [        SU SUR                  R                   S[        5       R                  R                   S[        5       R                  R                   SU S35      e[        U5      n[        U/5      nUS   bm  UR                  US   5      [        U5      :H  nU(       dF  S	R                  [!        U5       VVs/ s H  u  pxS
U SU 3PM     snn5      n	[        SU SU	 35      eT
" U 0 UD6$ s  snnf )Nrs   r   r   z%One or more of the tensors passed to z were not on the z+ while the `Accelerator` is configured for z. Please move it to the z before calling z
  - zProcess z: znCannot apply desired operation due to shape mismatches. All shapes across devices must be valid.

Operation: `z`
Input shapes:
  - )r   Údistributed_typer   ÚNOÚdebugr®   rK   rW   r6   Úfind_devicer¬   rh   Úgather_objectÚcountrt   ÚjoinÚ	enumerate)rD   rF   Ú	operationr   ÚshapesÚoutputÚare_sameÚir_   Úprocess_shape_strÚfunctions             €r   ÚwrapperÚ!verify_operation.<locals>.wrapperq  sÎ  ø€ ä‹>×*Ñ*¬o×.@Ñ.@Ó@ÌË×H\×H\Ù˜TÐ, VÑ,Ð,Ø×*Ñ*Ð+¨1¨X×->Ñ->Ð,?Ð@ˆ	Ø�vÓØ˜HÑ%‰Fà˜!‘WˆFÜ‹>× Ñ ×%Ñ%¬°VÓ)<×)AÑ)AÓAÜ/Ø7¸	°{ÐBSÐTZ×TaÑTa×TfÑTfÐSgð  hSô  T`ó  Tb÷  Tiñ  Ti÷  Tnñ  Tnð  Soð o)Ü)5«×)>Ñ)>×)CÑ)CÐ(DÐDTÐU^ÐT_Ð_`ðbóð ô ˜6Ó"ˆÜ ˜xÓ(ˆØ�!‰9Ñ Ø—|‘| F¨1¡IÓ.´#°f³+Ñ=ˆHÞØ$,§M¡MÔ[dÐekÔ[lÔ2mÒ[lÉxÈq°X¸a¸SÀÀ5À'Ó3JÑ[lÒ2mÓ$nÐ!Ü3ð'à'0 kÐ1GÐHYÐGZð\óð ñ
 ˜Ð( Ñ(Ð(ùó 3ns   Å.F#
©r   ©rÃ   rÄ   s   ` r   Úverify_operationrÈ   l  s"   ø€ ô
 ˆ8ƒ_ô)ó ð)ð4 €Nr   c                 ó0   ^ • [        T 5      U 4S j5       nU$ )z…
Checks that `verify_operation` failed and if so reports a more helpful error chaining the existing
`DistributedOperationException`.
c                  ó�   >•  T" U 0 UD6$ ! [          a0  nTR                   STR                   3n[        SU S35      UeS nAff = f)Nrs   zError found while calling `z1`. Please see the earlier error for more details.)r¬   r®   rK   )rD   rF   Úer½   rÃ   s       €r   rÄ   Ú"chained_operation.<locals>.wrapper•  sc   ø€ ð	Ù˜TÐ, VÑ,Ð,øÜ,ó 	Ø#×.Ñ.Ð/¨q°×1BÑ1BÐ0CÐDˆIÜ/Ø-¨i¨[Ð8iÐjóàðûð	ús   ƒ ‹
A•+A Á ArÆ   rÇ   s   ` r   Úchained_operationrÍ   �  s"   ø€ ô ˆ8ƒ_ôó ðð €Nr   c                 ó¶   • [        5       R                  [        R                  :X  a  [	        U 5      $ [        5       R                  [
        ;   a  [        U 5      $ U $ )a  
Recursively gather tensor in a nested list/tuple/dictionary of tensors from all devices.

Args:
    tensor (nested list/tuple/dictionary of `torch.Tensor`):
        The data to gather.

Returns:
    The same data structure as `tensor` with all tensors sent to the proper device.
)r   rµ   r   ÚXLAr‘   r   rª   r   s    r   ÚgatherrÐ   ¢  sF   € ô ƒ~×&Ñ&¬/×*=Ñ*=Ó=Ü˜6Ó"Ð"Ü	‹×	(Ñ	(Ô,MÓ	MÜ˜6Ó"Ð"àˆr   Úobjectc                 óê   • [        [        5       R                  5       Vs/ s H  nS PM     nn[        R                  R                  X 5        U VVs/ s H  o3  H  oDPM     M     snn$ s  snf s  snnf r   )rž   r   rš   r   r    Úall_gather_object)rÑ   r£   Úoutput_objectsÚyÚxs        r   Ú_gpu_gather_objectr×   ¶  sa   € Ü$)¬,«.×*FÑ*FÔ$GÓHÒ$G˜q“dÑ$G€NÐHÜ	×Ñ×'Ñ'¨Ô?á%Ô1’~�!«q¨!ŠA©q‰A‘~Ò1Ð1ùò Iùó 2s    A*ÁA/c                 ó¶   • [        5       R                  [        R                  :X  a  [	        S5      e[        5       R                  [
        ;   a  [        U 5      $ U $ )a  
Recursively gather object in a nested list/tuple/dictionary of objects from all devices.

Args:
    object (nested list/tuple/dictionary of picklable object):
        The data to gather.

Returns:
    The same data structure as `object` with all the objects sent to every device.
z&gather objects in TPU is not supported)r   rµ   r   rÏ   ÚNotImplementedErrorr   r×   )rÑ   s    r   r¹   r¹   ½  sG   € ô ƒ~×&Ñ&¬/×*=Ñ*=Ó=Ü!Ð"JÓKÐKÜ	‹×	(Ñ	(Ô,MÓ	MÜ! &Ó)Ð)àˆr   c                 ó"   • SS jn[        X SUS9$ )Nc                 ó@   • [         R                  R                  XS9  U $ )N©Úsrc)r   r    Ú	broadcast)r   rÝ   s     r   Ú_gpu_broadcast_oneÚ*_gpu_broadcast.<locals>._gpu_broadcast_oneÑ  s   € Ü×Ñ×#Ñ# FÐ#Ñ4Øˆr   T)r=   rÝ   ©r   r@   )r3   rÝ   rß   s      r   Ú_gpu_broadcastrâ   Ð  s   € ôô Ð/È4ÐUXÑYÐYr   c                 ól  ^^• [        U [        [        45      (       a  [        U U4S j[	        U 5       5       5      $ [        U [
        5      (       aB  [        U 5      " U R                  5        VVs0 s H  u  p4U[        UT SU 3S9_M     snn5      $ [        R                  " TU U4S j5      $ s  snnf )Nc              3   óF   >#   • U  H  u  p[        UT S U 3S9v •  M     g7f)r£   ©ÚnameN)Ú_tpu_broadcast)rB   rÁ   rV   ræ   s      €r   rG   Ú!_tpu_broadcast.<locals>.<genexpr>Ú  s&   øé € Ð"gÒUfÉTÈQ¤>°!¸T¸FÀ!ÀAÀ3¸-Ö#HÒUfùs   ƒ!r£   rå   c                 ó   >• U T   $ r   r­   )rÖ   rÝ   s    €r   Ú<lambda>Ú _tpu_broadcast.<locals>.<lambda>Ý  s	   ø€ °!°C²&r   )r   r7   r0   r:   r¼   r   r6   rI   rç   rŠ   Úmesh_reduce)r   rÝ   ræ   rL   rM   s    ``  r   rç   rç   Ø  s—   ù€ Ü�&œ4¤˜-×(Ñ(Ü˜&Ô"gÔU^Ð_eÔUfÓ"gÓhÐhÜ	�FœG×	$Ñ	$Ü�FŒ|ÐRX×R^ÑR^ÔR`ÔaÒR`É$È!˜Q¤¨q¸$¸¸qÀÀ°}Ñ EÒEÑR`ÒaÓbÐbÜ�>Š>˜$ Ô(8Ó9Ð9ùó bs   Á0B0
é   é   é   é   é   é   é	   é
   c                 óŽ  • Sn[        5       n[        R                  " U[        R                  UR                  S9nU bT  U R
                  n[        U R                     n[        R                  " [        U5      U/-   [        S9US[        U5      S-   & [        USS9nX3R                  5          n[        USS S	   5      nUSS nX64$ )
z]
Grabs the shape of `tensor` only available on one process and returns a tensor of its shape
i   r•   N©r`   r   Úsum©Ú	reductionr–   r   )r   r   rl   rZ   rW   r_   ÚTENSOR_TYPE_TO_INTr`   r   r7   rt   ÚreduceÚnonzero)r   Úmax_tensor_dimensionr¥   Úbase_tensorr_   Útensor_dtyper`   s          r   Úgather_tensor_shaper   ð  s¿   € ð
 !ÐÜ‹N€EÜ—+’+Ð2¼%¿)¹)ÈEÏLÉLÑY€Kð
 ÑØ—‘ˆÜ)¨&¯,©,Ñ7ˆÜ(-¯ª´T¸%³[ÀLÀ>Ñ5QÔY\Ñ(]ˆÐ$”c˜%“j 1‘nÐ%ä˜°Ñ6€KØ×1Ñ1Ó3Ñ4€Kä�˜B˜CÐ  Ñ#Ó$€EØ˜c˜rÐ"€KØÐÐr   Úreturnc                 ó´   • [        5       n[        U 5      u  p#U c5  [        R                  " U[        U   S9R                  UR                  5      n [        U SS9$ )at  
Copies a tensor that only exists on a single device and broadcasts it to other devices. Differs from `broadcast` as
each worker doesn't need to know its shape when used (and tensor can be `None`)

Args:
    tensor (`torch.tensor`):
        The tensor that should be sent to all devices. Must only have it be defined on a single device, the rest
        should be `None`.
rö   r÷   rø   )r   r   r   ÚzerosÚTENSOR_INT_TO_DTYPErO   rW   rû   )r   r¥   r_   r`   s       r   Úcopy_tensor_to_devicesr  	  sN   € ô ‹N€EÜ& vÓ.�L€EØ�~Ü—’˜UÔ*=¸eÑ*DÑE×HÑHÈÏÉÓVˆÜ�& EÑ*Ð*r   Úfrom_processc                 ó°   • [        5       R                  [        R                  :X  a
  [	        XSS9$ [        5       R                  [
        ;   a	  [        XS9$ U $ )a…  
Recursively broadcast tensor in a nested list/tuple/dictionary of tensors to all devices.

Args:
    tensor (nested list/tuple/dictionary of `torch.Tensor`):
        The data to gather.
    from_process (`int`, *optional*, defaults to 0):
        The process from which to send the data

Returns:
    The same data structure as `tensor` with all tensors broadcasted to the proper device.
zaccelerate.utils.broadcast)rÝ   ræ   rÜ   )r   rµ   r   rÏ   rç   r   râ   )r   r  s     r   rÞ   rÞ     sI   € ô ƒ~×&Ñ&¬/×*=Ñ*=Ó=Ü˜fÐ=YÑZÐZÜ	‹×	(Ñ	(Ô,MÓ	MÜ˜fÑ7Ð7àˆr   c                 ó0  ^• [        5       R                  [        R                  :X  a4  [	        U 5       H#  u  p#[
        R                  " SUU4S j5      X'   M%     U $ [        5       R                  [        ;   a  [        R                  R                  U TS9  U $ )ar  
Broadcast a list of picklable objects from one process to the others.

Args:
    object_list (list of picklable objects):
        The list of objects to broadcast. This list will be modified inplace.
    from_process (`int`, *optional*, defaults to 0):
        The process from which to send the data.

Returns:
    The same list containing the objects from process 0.
z&accelerate.utils.broadcast_object_listc                 ó   >• U T   $ r   r­   )rÖ   r  s    €r   rê   Ú'broadcast_object_list.<locals>.<lambda>?  s   ø€ ÐefÐgsÒetr   rÜ   )r   rµ   r   rÏ   r¼   rŠ   rì   r   r   r    Úbroadcast_object_list)Úobject_listr  rÁ   r8   s    `  r   r  r  0  s}   ø€ ô ƒ~×&Ñ&¬/×*=Ñ*=Ó=Ü Ö,‰FˆAÜŸ^š^Ð,TÐVYÔ[tÓuˆK‹Nñ -ð Ðô 
‹×	(Ñ	(Ô,MÓ	MÜ×Ñ×/Ñ/°ÀÐ/ÑNØÐr   c                 ó    • S n[        X@U5      $ )a*  
Recursively takes a slice in a nested list/tuple/dictionary of tensors.

Args:
    data (nested list/tuple/dictionary of `torch.Tensor`):
        The data to slice.
    tensor_slice (`slice`):
        The slice to take.

Returns:
    The same data structure as `data` with all the tensors slices.
c                 ó
   • X   $ r   r­   )r   Útensor_slices     r   Ú_slice_tensorÚ$slice_tensors.<locals>._slice_tensorS  s   € ØÑ#Ð#r   r@   )r3   r  Úprocess_indexrš   r  s        r   Úslice_tensorsr  E  s   € ò$ô ˜]°,Ó?Ð?r   c                 óŒ  ^ ^• [        T S   [        [        45      (       a/  [        T S   U U4S j[	        [        T S   5      5       5       5      $ [        T S   [        5      (       aS  [        T S   5      " T S   R                  5        VVs0 s H   o"[        T  Vs/ s H  o3U   PM	     snTS9_M"     snn5      $ [        T S   [        R                  5      (       a  [        R                  " T TS9$ [        T [        [        45      (       a  [        T 5      S:X  a  T S   $ [        S[        T S   5       35      es  snf s  snnf )aÑ  
Recursively concatenate the tensors in a nested list/tuple/dictionary of lists of tensors with the same shape.
If there is only a single batch of data, it is returned as-is.

Args:
    data (nested list/tuple/dictionary of lists of tensors `torch.Tensor`):
        The data to concatenate.
    dim (`int`, *optional*, defaults to 0):
        The dimension on which to concatenate.

Returns:
    The same data structure as `data` with all the tensors concatenated.
r   c              3   óh   >#   • U  H"  n[        T Vs/ s H  o"U   PM	     snTS 9v •  M$     gs  snf 7f)r—   N)Úconcatenate)rB   rÁ   Údr3   r˜   s      €€r   rG   Úconcatenate.<locals>.<genexpr>h  s/   øé € Ð#lÒXkÐST¤K¹tÓ0Dºt¸!°1´¹tÑ0DÈ#Ö$NÒXkùÒ0Dùs   ƒ2’-
 2r—   r   z%Can only concatenate tensors but got )r   r0   r7   r:   rž   rt   r   r6   rw   r  r   r   r¡   rJ   )r3   r˜   rL   r  s   ``  r   r  r  Y  s  ù€ ô �$�q‘'œE¤4˜=×)Ñ)Ü˜$˜q™'Õ#lÔX]Ô^aÐbfÐghÑbiÓ^jÔXkÓ#lÓmÐmÜ	�D˜‘GœW×	%Ñ	%Ü�D˜‘GŒ}ÐUYÐZ[ÑU\×UaÑUaÔUcÔdÒUcÐPQ¤¹DÓ-AºD°q°¬d¹DÑ-AÀsÑ!KÒKÑUcÒdÓeÐeÜ	�D˜‘GœUŸ\™\×	*Ñ	*Ü�yŠy˜ 3Ñ'Ð'Ü	�Dœ5¤$˜-×	(Ñ	(¬S°«Y¸!«^Ø�A‰wˆäÐ?ÄÀTÈ!ÁWÃ¸ÐOÓPÐPùò .BùÓds   ÂE 
ÂD;Â)
E 
Ä;E 
c                   ó   • \ rS rSrSrg)ÚCannotPadNestedTensorWarningis  r­   N)rK   r®   r¯   r°   r²   r­   r   r   r  r  s  s   † Úr   r  c           	      ó$   • SS jn[        X@SXUS9$ )a  
Recursively pad the tensors in a nested list/tuple/dictionary of tensors from all devices to the same size so they
can safely be gathered.

Args:
    tensor (nested list/tuple/dictionary of `torch.Tensor`):
        The data to gather.
    dim (`int`, *optional*, defaults to 0):
        The dimension on which to pad.
    pad_index (`int`, *optional*, defaults to 0):
        The value with which to pad.
    pad_first (`bool`, *optional*, defaults to `False`):
        Whether to pad at the beginning or the end.
c                 ó  ^^	^
• [        U SS5      (       a  [        R                  " S[        5        U $ T[	        U R
                  5      :¼  d  T[	        U R
                  5      * :  a  U $ TS:  a  T[	        U R
                  5      -  m[        R                  " U R
                  U R                  S9S    n[        U5      R                  5       n[        U4S jU 5       5      m	T	U R
                  T   :X  a  U $ U R
                  m
[        T
5      nT	UT'   U R                  [        U5      5      U-   nU(       a*  [        UU	U
4S j[        [	        U5      5       5       5      nO([        UU
4S j[        [	        U5      5       5       5      nXU'   U$ )	NÚ	is_nestedFzHCannot pad nested tensors without more information. Leaving unprocessed.r   )rW   c              3   ó,   >#   • U  H	  oT   v •  M     g 7fr   r­   )rB   Úsr˜   s     €r   rG   ÚFpad_across_processes.<locals>._pad_across_processes.<locals>.<genexpr>™  s   øé € Ð-¢u !˜–v¢uùs   ƒc              3   óh   >#   • U  H'  oT:X  a  [        TTT   -
  T5      O
[        S 5      v •  M)     g 7fr   ©Úslice)rB   rÁ   r˜   Úmax_sizeÚold_sizes     €€€r   rG   r   ¢  s4   øé € ð Ú`tÐ[\À#»X”�h ¨#¡Ñ.°Ô9Ì5ÐQUË;ÔVÒ`tùs   ƒ/2c              3   ób   >#   • U  H$  oT:X  a  [        S TT   5      O
[        S5      v •  M&     g7f©r   Nr"  ©rB   rÁ   r˜   r%  s     €€r   rG   r   ¦  s,   øé € ÐoÒZnÐUV¸C³xœE ! X¨c¡]Ô3ÄUÈ4Ã[ÔPÒZnùó   ƒ,/)ÚgetattrÚwarningsÚwarnr  rt   r_   r   r   rW   rÐ   r}   Úmaxr7   Ú	new_zerosr0   rž   )r   r˜   Ú	pad_indexÚ	pad_firstr�   ÚsizesÚnew_sizeÚ
new_tensorÚindicesr$  r%  s    `       @@r   Ú_pad_across_processesÚ3pad_across_processes.<locals>._pad_across_processesˆ  sL  ú€ Ü�6˜;¨×.Ñ.Ü�MŠMØZÜ,ôð ˆMØ”#�f—l‘lÓ#Ó# s¬c°&·,±,Ó.?Ð-?Ó'?ØˆMà�‹7Ø”3�v—|‘|Ó$Ñ$ˆCô �|Š|˜FŸL™L°·±Ñ?ÀÑEˆÜ�t“× Ñ Ó"ˆäÔ-¡uÓ-Ó-ˆØ�v—|‘| CÑ(Ó(ØˆMà—<‘<ˆÜ˜“>ˆØ ˆ�‰Ø×%Ñ%¤e¨H£oÓ6¸ÑBˆ
ÞÜö Ü`eÔfiÐjrÓfsÔ`tóó ‰Gô ÕoÔZ_Ô`cÐdlÓ`mÔZnÓoÓoˆGØ$�7ÑØÐr   T)r=   r˜   r/  r0  ©r   r   Fr@   )r   r˜   r/  r0  r5  s        r   Úpad_across_processesr8  w  s!   € ô" ôD Ø¸4ÀSÐirñð r   c           	      ó(   • SS jn[        UU SUUUS9$ )zê
Takes a `tensor` of arbitrary size and pads it so that it can work given `num_processes` needed dimensions.

New tensors are just the last input repeated.

E.g.:
  Tensor: ([3,4,4]) Num processes: 4 Expected result shape: ([4,4,4])

c                 ó<  ^^
• X-  nXU-  -
  nX-  S:X  a  X!-
  nOX!U-  -
  nXVU-  s=:”  a  S:  a  O  OXV-
  nU R                   m
[        T
5      nX-   US'   U R                  [        U5      5      n[        UU
4S j[	        [        U5      5       5       5      n	XU	'   U$ )Nr   r   c              3   ób   >#   • U  H$  oT:X  a  [        S TT   5      O
[        S5      v •  M&     g7fr'  r"  r(  s     €€r   rG   Ú@pad_input_tensors.<locals>._pad_input_tensors.<locals>.<genexpr>É  s,   øé € ÐkÒVjÐQR¸³8œ˜a ¨#¡Ô/ÄÀtÃÔLÒVjùr)  )r_   r7   r.  r0   rž   rt   )r   Ú
batch_sizerš   r˜   Ú	remainderÚlast_inputsÚto_padr2  r3  r4  r%  s      `      @r   Ú_pad_input_tensorsÚ-pad_input_tensors.<locals>._pad_input_tensorsº  s®   ù€ ØÑ/ˆ	Ø °Ñ$=Ñ>ˆØÑ&¨!Ó+Ø"Ñ/‰Fà"°MÑ&AÑBˆFð  &™Õ,¨1Ö,Ø Ñ)ˆFØ—<‘<ˆÜ˜“>ˆØ Ñ)ˆ�‰Ø×%Ñ%¤e¨H£oÓ6ˆ
ÜÕkÔV[Ô\_Ð`hÓ\iÔVjÓkÓkˆØ$�7ÑØÐr   T)r=   r=  rš   r˜   rá   r@   )r   r=  rš   r˜   rA  s        r   Úpad_input_tensorsrC  ¯  s(   € ôô& ØØØ ØØ#Øñð r   c                 ó"   • SS jn[        X0SXS9$ )a'  
Recursively reduce the tensors in a nested list/tuple/dictionary of lists of tensors across all processes by the
mean of a given operation.

Args:
    tensor (nested list/tuple/dictionary of `torch.Tensor`):
        The data to reduce.
    reduction (`str`, *optional*, defaults to `"mean"`):
        A reduction method. Can be of "mean", "sum", or "none"
    scale (`float`, *optional*):
        A default scaling value to be applied after the reduce, only valid on XLA.

Returns:
    The same data structure as `data` with all the tensors reduced.
c                 ó  • [        5       nU R                  5       nUR                  [        R                  :X  a  U$ UR                  [        R
                  :X  aR  [        R                  " 5         [        R                  " [        R                  U/U5        [        R                  " 5         OLUR                  R                  [        ;   a.  [        R                  R                  U[        R                  5        US:X  a  XCR                   -  nU$ )NÚmean)r   r‡   rµ   r   r¶   rÏ   rŠ   r�   Ú
all_reduceÚ
REDUCE_SUMÚvaluer   r   r    r   ÚSUMrš   )r   rù   Úscaler¥   Úcloned_tensors        r   Ú_reduce_across_processesÚ(reduce.<locals>._reduce_across_processesé  s·   € Ü“ˆØŸ™›ˆØ×!Ñ!¤_×%7Ñ%7Ó7Ø Ð Ø×!Ñ!¤_×%8Ñ%8Ó8ô
 �LŠLŒNÜ�MŠMœ"Ÿ-™-¨-¨¸%Ô@Ü�LŠL�NØ×#Ñ#×)Ñ)Ô-NÓNÜ×Ñ×(Ñ(¨¼¿¹ÔEØ˜ÓØ×0Ñ0Ñ0ˆMØÐr   T)r=   rù   rK  ©rF  g      ð?r@   )r   rù   rK  rM  s       r   rû   rû   ×  s   € ô$ô& Ø ¸dÈiñð r   c                 ó"   • S nS n[        XUS9$ )aZ  
Recursively converts the elements nested list/tuple/dictionary of tensors in FP16/BF16 precision to FP32.

Args:
    tensor (nested list/tuple/dictionary of `torch.Tensor`):
        The data to convert from FP16/BF16 to FP32.

Returns:
    The same data structure as `tensor` with all tensors that were in FP16/BF16 precision converted to FP32.
c                 ó"   • U R                  5       $ r   )Úfloatr   s    r   Ú_convert_to_fp32Ú)convert_to_fp32.<locals>._convert_to_fp32  s   € Ø�|‰|‹~Ðr   c                 ó¦   • [        U 5      =(       d    [        U S5      =(       a-    U R                  [        R                  [        R
                  4;   $ rk   )r   r1   r`   r   Úfloat16r~   r   s    r   Ú_is_fp16_bf16_tensorÚ-convert_to_fp32.<locals>._is_fp16_bf16_tensor  s@   € Ü Ó'×C¬7°6¸7Ó+C÷ 
ÈÏÉÜ�M‰MÜ�N‰NðZ
ñ J
ð 	
r   ro   r@   )r   rS  rW  s      r   Úconvert_to_fp32rY    s   € òò
ô Ð-ÐAUÑVÐVr   c                   ó*   • \ rS rSrSrS rS rS rSrg)ÚConvertOutputsToFp32i  aE  
Decorator to apply to a function outputting tensors (like a model forward pass) that ensures the outputs in FP16
precision will be convert back to FP32.

Args:
    model_forward (`Callable`):
        The function which outputs we want to treat.

Returns:
    The same function as `model_forward` but with converted outputs.
c                 ó&   • Xl         [        X5        g r   )Úmodel_forwardr   )Úselfr]  s     r   Ú__init__ÚConvertOutputsToFp32.__init__&  s   € Ø*ÔÜ�tÕ+r   c                 ó8   • [        U R                  " U0 UD65      $ r   )rY  r]  )r^  rD   rF   s      r   Ú__call__ÚConvertOutputsToFp32.__call__*  s   € Ü˜t×1Ò1°4ÐB¸6ÑBÓCÐCr   c                 ó.   • [         R                  " S5      e)Nz‘Cannot pickle a prepared model with automatic mixed precision, please unwrap the model with `Accelerator.unwrap_model(model)` before pickling it.)ÚpickleÚPicklingError)r^  s    r   Ú__getstate__Ú!ConvertOutputsToFp32.__getstate__-  s   € Ü×"Ò"ð `ó
ð 	
r   )r]  N)	rK   r®   r¯   r°   r±   r_  rb  rg  r²   r­   r   r   r[  r[    s   † ñ
ò,òDõ
r   r[  c                 ó8   ^ • [        T 5      m U 4S jnT Ul        U$ )Nc                  ó   >• T" U 0 UD6$ r   r­   )rD   rF   r]  s     €r   ÚforwardÚ(convert_outputs_to_fp32.<locals>.forward6  s   ø€ Ù˜dÐ- fÑ-Ð-r   )r[  Ú__wrapped__)r]  rk  s   ` r   Úconvert_outputs_to_fp32rn  3  s!   ø€ Ü(¨Ó7€Mõ.ð (€GÔà€Nr   c                 óF  • [        U [        5      (       a*  U R                  5        H  n[        U5      nUc  M  Us  $    g[        U [        [
        45      (       a  U  H  n[        U5      nUc  M  Us  $    g[        U [        R                  5      (       a  U R                  $ g)zÕ
Finds the device on which a nested dict/list/tuple of tensors lies (assuming they are all on the same device).

Args:
    (nested list/tuple/dictionary of `torch.Tensor`): The data we want to know the device of.
N)	r   r   Úvaluesr¸   r0   r7   r   r   rW   )r3   r8   rW   s      r   r¸   r¸   ?  sŠ   € ô �$œ× Ñ Ø—;‘;–=ˆCÜ  Ó%ˆFØÓ!Ø’ò !ô 
�Dœ5¤$˜-×	(Ñ	(ÛˆCÜ  Ó%ˆFØÓ!Ø’ò ô 
�Dœ%Ÿ,™,×	'Ñ	'Ø�{‰{Ðð 
(r   c              #   ób  #   • [        5       R                  [        R                  :w  d<  [        5       R                  b2  [        5       R                  R                  5       (       d  [        5       nOSSKnUR                  R                  XX#S9nU   Sv •  SSS5        g! , (       d  f       g= f7f)z|
Wrapper around `deepspeed.runtime.zero.GatheredParameters`, but if Zero-3 is not enabled, will be a no-op context
manager.
Nr   )Úmodifier_rankÚ
fwd_moduleÚenabled)
r
   rµ   r   Ú	DEEPSPEEDÚdeepspeed_pluginÚis_zero3_init_enabledr   Ú	deepspeedÚzeroÚGatheredParameters)Úparamsrr  rs  rt  Úgather_param_contextrx  s         r   rz  rz  T  sƒ   é € ô Ó×*Ñ*¬o×.GÑ.GÓGÜÓ×+Ñ+Ñ7Ü Ó"×3Ñ3×IÑI×KÑKä*›}Ñãà(Ÿ~™~×@Ñ@Ø¸Jð  Að  
Ðò 
Û÷ 
×	Ö	üs   ‚BB/ÂBÂ	B/Â
B,Â(B/)FNrá   )r   zbroadcast tensorr   )NNr7  rO  )NNT)Yr±   re  r+  Úcollections.abcr   Ú
contextlibr   r   Ú	functoolsr   r   Útypingr   r   r¥   r
   r   Ú	constantsr   Údataclassesr   r   Úimportsr   r   r   Úversionsr   Útorch_xla.core.xla_modelÚcoreÚ	xla_modelrŠ   Útorch.distributedr   r   r(   r,   r4   r:   rA   rU   rc   rh   rq   rv   ry   rƒ   r‘   rª   Ú	Exceptionr¬   rÈ   rÍ   rÐ   r×   r¹   râ   rç   rR  ÚdoubleÚhalfr~   Úuint8Úint8Úint16Úint32Úint64Úboolrú   rI   r  r   r   r  rZ   rÞ   r  r  r  ÚUserWarningr  r8  rC  rû   rY  r[  rn  r¸   rz  )rL   rM   s   00r   Ú<module>r“     sA  ðñó Û Ý #ß 2ß +Ý ã ç 2Ý 8ß ;÷ñ õ
 'ñ ×Ñß)Ð)á!×#Ñ#Ý*ò,ò
ò6ò]ò$ð 4CÐX]õ 0ôf1òh8ò$/ò$bòò.ò"5ò.ò$PôN	 Iô 	ò òFð& ñó ðð&2˜sô 2ð˜#ô ô&Zô:ð 
‡K�K�Ø	‡L�L�!Ø	‡J�J�Ø	‡N�N�AØ	‡K�K�Ø	‡J�J�Ø	‡K�K�Ø	‡K�K�Ø	‡K�K�Ø	‡J�J�ðÐ ð );×(@Ñ(@Ô(BÔCÒ(B¡ �q’tÑ(BÒCÐ òñ2+¨5¯<©<õ +ð" ñ Cô ó ðñ*°Sõ ô*@ô(Qô4	 ;ô 	ð ó4ó ð4ôn%ðP ó&ó ð&òRW÷0
ñ 
ò4	òð* óó ñùóQ Ds   Å*G5