+
    QV-j°ß  ã                   ó  € R t ^ RIt^ RIt^ RIt^ RIt^ RIt^ RIt^ RIt^ RIt^ RI	t	^ RI
t
^ RIHtHt ^ RIHt ^ RIHtHt ^ RIHt ^ RIHt ^ RIHt ^ RIt^ RIt^ RIHt ^ RIHt ^ R	IH t  ^ R
I!H"t"H#t#H$t$H%t% ^ RI&H't' ^RI(H)t) ^RI*H+t+ ^RI,H-t-H.t.H/t/H0t0Ht ]0! 4       '       d#   ]Pb                  ! ]! ]	Pd                  4      4       ]/! 4       '       d   ^ RI3H4t5 ].! 4       '       d   ^ RI6H7t7 ]Pp                  ! ]94      t:R t;R R lt<RTR lt=RTR lt>RTR lt?R t@R tAR tBR tCRUR R lltDRUR ltER tFR]PŽ                  ! R4      3R R  lltHR! tI]R" R# l4       tJ ! R$ R%]'4      tK ! R& R'4      tLR( R) ltMRTR* ltNRTR+ ltOR, tP] ! R- R.4      4       tQRVR/ ltR ! R0 R1]%4      tS ! R2 R3]'4      tT ! R4 R5]%4      tU ! R6 R7]#4      tVR8 tWR9 R: ltXR; tYRWR< ltZR= t[R> R? lt\R@ RA lt]RURB RC llt^RXRD lt_RURE lt`RF taRG tb]-! 4       '       d@   ^ RIcHdu Hte ]ePÌ                  ! 4       RYRH l4       tg]ePÌ                  ! 4       RI 4       thRJ tiRK tj] ! RL RM4      4       tk ! RN RO]PØ                  PÚ                  4      tn ! RP RQ]74      toRR tpRS tqR# )Zz(
Torch utilities for the Trainer class.
N)ÚIteratorÚMapping)Úcontextmanager)Ú	dataclassÚfield)Úchain)ÚStreamHandler)ÚAny)Úversion)Únn)ÚDatasetÚIterableDatasetÚRandomSamplerÚSampler)ÚDistributedSampler)Úis_deepspeed_zero3_enabled)ÚBatchEncoding)Úis_sagemaker_mp_enabledÚis_torch_availableÚis_torch_xla_availableÚis_training_run_on_sagemakerÚlogging)ÚLRSchedulerc                 ó¬   € \        V R 4      '       d$   V P                  e   \        V P                  4      # \        V R4      '       d   V P                  # R# )Úbatch_samplerNÚsampler)Úhasattrr   Úget_dataloader_samplerr   )Ú
dataloaders   &Ún/Volumes/fast/ai/experiments/ui-tars-smoke/.venv/lib/python3.14/site-packages/transformers/trainer_pt_utils.pyr   r   C   sI   € Üˆz˜?×+Ò+°
×0HÑ0HÒ0TÜ% j×&>Ñ&>Ó?Ð?Ü	�˜Y×	'Ò	'Ø×!Ñ!Ð!ñ 
(ó    c                ób   € V ^8„  d   QhR\         P                  \        P                  ,          /# )é   Útensor_or_array)ÚtorchÚTensorÚnpÚndarray)Úformats   "r   Ú__annotate__r)   J   s    € ÷ ñ ¤§¡¬r¯z©zÕ 9ñ r    c                 ó¢   € \        V \        P                  4      '       d   \        P                  ! V 4      p V # \        P                  ! V 4      p V # ©N)Ú
isinstancer$   r%   Ú
atleast_1dr&   )r#   s   &r   r-   r-   J   sA   € Ü�/¤5§<¡<×0Ò0Ü×*Ò*¨?Ó;ˆð Ðô Ÿ-š-¨Ó8ˆØÐr    c                óž  € \        V 4      p \        V4      p\        V P                  4      ^8X  g*   V P                  ^,          VP                  ^,          8X  d   \        P                  ! W3^ R7      # V P                  ^ ,          VP                  ^ ,          ,           \        V P                  ^,          VP                  ^,          4      3V P                  R,          ,           pV P                  W24      pWRV P                  ^ ,          1RV P                  ^,          13&   WV P                  ^ ,          R1RVP                  ^,          13&   V# )z`Concatenates `tensor1` and `tensor2` on first axis, applying padding on the second if necessary.©Údimºr"   NNN)r-   ÚlenÚshaper$   ÚcatÚmaxÚnew_full)Útensor1Útensor2Úpadding_indexÚ	new_shapeÚresults   &&&  r   Útorch_pad_and_concatenater<   R   s  € ä˜Ó!€GÜ˜Ó!€Gä
ˆ7�=‰=Ó˜QÔ '§-¡-°Õ"2°g·m±mÀAÕ6FÔ"FÜ�yŠy˜'Ð+°Ô3Ð3ð —‘˜qÕ! G§M¡M°!Õ$4Õ4´c¸'¿-¹-ÈÕ:JÈGÏMÉMÐZ[ÕL\Ó6]Ð^Ðah×anÑanÐoqÕarÕr€Ið ×Ñ˜iÓ7€FØ5<ÐˆW�]‰]˜1ÕÐÐ1 §¡¨qÕ!1Ð1Ð1Ñ2Ø5<ˆ7�=‰=˜ÕÑÐ1 §¡¨qÕ!1Ð1Ð1Ñ2Ø€Mr    c                ó¬  € \        V 4      p \        V4      p\        V P                  4      ^8X  g*   V P                  ^,          VP                  ^,          8X  d   \        P                  ! W3^ R7      # V P                  ^ ,          VP                  ^ ,          ,           \        V P                  ^,          VP                  ^,          4      3V P                  R,          ,           p\        P                  ! WVR7      pWRV P                  ^ ,          1RV P                  ^,          13&   WV P                  ^ ,          R1RVP                  ^,          13&   V# )z^Concatenates `array1` and `array2` on first axis, applying padding on the second if necessary.)Úaxisr1   ©r3   N)r-   r2   r3   r&   Úconcatenater5   Ú	full_like)Úarray1Úarray2r9   r:   r;   s   &&&  r   Únumpy_pad_and_concatenaterD   d   s  € ä˜Ó€FÜ˜Ó€Fä
ˆ6�<‰<Ó˜AÔ §¡¨a¥°F·L±LÀµOÔ!CÜ�~Š~˜vÐ.°QÔ7Ð7ð —‘˜a• 6§<¡<°¥?Õ2´C¸¿¹ÀQ½ÈÏÉÐVWÍÓ4YÐZÐ]c×]iÑ]iÐjlÕ]mÕm€Iô �\Š\˜&°yÔA€FØ39ÐˆV�\‰\˜!�_ÐÐ/ §¡¨Q¥Ð/Ð/Ñ0Ø39ˆ6�<‰<˜�?ÑÐ/ §¡¨Q¥Ð/Ð/Ñ0Ø€Mr    c                ó  a€ \        V \        P                  4      '       d!   \        V\        P                  4      '       g9   \        V 4      \        V4      J g!   Q R\        V 4       R\        V4       R24       h\        V \        \
        34      '       d%   \        V 4      ! V3R l\        W4       4       4      # \        V \        P                  4      '       d   \        WSR7      # \        V \        4      '       dG   \        V 4      ! V P                  4        UUu/ uF  w  r4V\        WAV,          SR7      bK  	  upp4      # \        V \        P                  4      '       d   \        WSR7      # \        R\        V 4       24      hu uppi )z—
Concat the `new_tensors` to `tensors` on the first dim and pad them on the second if needed. Works for tensors or
nested list/tuples/dict of tensors.
zEExpected `tensors` and `new_tensors` to have the same type but found z and Ú.c              3   óB   <"  € T F  w  r\        WSR 7      x € K  	  R# 5i)©r9   N)Únested_concat)Ú.0ÚtÚnr9   s   &  €r   Ú	<genexpr>Ú nested_concat.<locals>.<genexpr>€   s!   øé € ÐtÑZsÑRVÐRSœ]¨1¸}×MÑMÓZsùs   ƒrH   z(Unsupported type for concatenation: got )r,   r$   r%   ÚtypeÚlistÚtupleÚzipr<   r   ÚitemsrI   r&   r'   rD   Ú	TypeError)ÚtensorsÚnew_tensorsr9   ÚkrK   s   &&f  r   rI   rI   v   sA  ø€ ô
 �w¤§¡×-Ò-´*¸[Ì%Ï,É,×2WÒ2WÜ�G‹}¤ [Ó 1Ó1ð 	
ØSÔTXÐY`ÓTaÐSbÐbgÔhlÐmxÓhyÐgzÐz{Ð|ó	
Ð1ô �'œD¤%˜=×)Ò)Ü�GŒ}ÔtÔZ]Ð^eÔZsÓtÓtÐtÜ	�GœUŸ\™\×	*Ò	*Ü(¨È]Ô[Ð[Ü	�GœW×	%Ò	%Ü�GŒ}ØZa×ZgÑZgÔZiÔjÑZiÑRVÐRSˆQ”˜a¨Q¥¸}ÔMÒMÑZiÒjó
ð 	
ô 
�GœRŸZ™Z×	(Ò	(Ü(¨È]Ô[Ð[äÐBÄ4ÈÃ=À/ÐRÓSÐSùó ks   Ä F
c                ó¼  € \        V \        \        34      '       d   V  F  p\        V4      pVf   K  Vu # 	  R# \        V \        4      '       d-   V P                  4        F  p\        V4      pVf   K  Vu # 	  R# \        V \        P                  \        P                  34      '       d0   \        V P                  4      ^8¼  d   V P                  ^ ,          # R# R# )zN
Find the first dimension of a tensor in a nested list/tuple/dict of tensors.
N)r,   rP   rQ   Úfind_batch_sizer   Úvaluesr$   r%   r&   r'   r2   r3   )rU   rK   r;   Úvalues   &   r   rY   rY   �   s®   € ô �'œD¤%˜=×)Ò)ÛˆAÜ$ QÓ'ˆFØÔ!Ø’ó ô 
�GœW×	%Ò	%Ø—^‘^Ö%ˆEÜ$ UÓ+ˆFØÔ!Ø’ó &ô 
�GœeŸl™l¬B¯J©JÐ7×	8Ò	8Ü#& w§}¡}Ó#5¸Ô#:ˆw�}‰}˜QÕÐDÀÐDñ 
9r    c           
     óØ  € \        V \        \        34      '       d   \        V 4      ! R V  4       4      # \        V \        4      '       d>   \        V 4      ! V P                  4        UUu/ uF  w  rV\        V4      bK  	  upp4      # V P                  4       pVP                  \        P                  8X  d    VP                  \        P                  4      pVP                  4       # u uppi )zENumpify `tensors` (even if it's a nested list/tuple/dict of tensors).c              3   ó8   "  € T F  p\        V4      x € K  	  R # 5ir+   )Únested_numpify©rJ   rK   s   & r   rM   Ú!nested_numpify.<locals>.<genexpr>¢   s   é € Ð@¹°1œ^¨A×.Ð.»ùó   ‚)r,   rP   rQ   rO   r   rS   r^   ÚcpuÚdtyper$   Úbfloat16ÚtoÚfloat32Únumpy©rU   rW   rK   s   &  r   r^   r^   Ÿ   s¦   € ä�'œD¤%˜=×)Ò)Ü�GŒ}Ñ@¹Ó@Ó@Ð@Ü�'œ7×#Ò#Ü�GŒ}¸w¿}¹}¼ÔO¹±t°q˜a¤°Ó!2Ò2¹ÒOÓPÐPà�‰‹€AØ‡w�w”%—.‘.Ô ð �D‰D”—‘ÓˆØ�7‰7‹9Ðùó Ps   Á)C&
c           
     ó€  € \        V \        \        34      '       d   \        V 4      ! R V  4       4      # \        V \        4      '       d>   \        V 4      ! V P                  4        UUu/ uF  w  rV\        V4      bK  	  upp4      # \        V \        P                  4      '       d   V P                  4       # T # u uppi )zDDetach `tensors` (even if it's a nested list/tuple/dict of tensors).c              3   ó8   "  € T F  p\        V4      x € K  	  R # 5ir+   )Únested_detachr_   s   & r   rM   Ú nested_detach.<locals>.<genexpr>²   s   é € Ð?±w°!œ]¨1×-Ð-³wùra   )
r,   rP   rQ   rO   r   rS   rk   r$   r%   Údetachrh   s   &  r   rk   rk   ¯   s�   € ä�'œD¤%˜=×)Ò)Ü�GŒ}Ñ?±wÓ?Ó?Ð?Ü	�GœW×	%Ò	%Ü�GŒ}¸g¿m¹m¼oÔN¹o±d°a˜a¤¨qÓ!1Ò1¹oÒNÓOÐOÜ)¨'´5·<±<×@Ò@ˆ7�>‰>ÓÐMÀgÐMùó Os   Á)B:
c                 ó   a€ \        4       '       dÝ   ^ RIHu Hp \	        V \
        \        34      '       d%   \        V 4      ! V3R l\        V 4       4       4      # \	        V \        4      '       dR   \        V 4      ! \        V P                  4       4       UUUu/ uF  w  pw  rEV\        VS RV 24      bK  	  uppp4      # \        V 4      p VP                  SV \        P                  4      # \!        R4      hu upppi )é    Nc              3   óJ   <"  € T F  w  r\        VS R V 24      x € K  	  R# 5i)Ú_N)Únested_xla_mesh_reduce)rJ   ÚirK   Únames   &  €r   rM   Ú)nested_xla_mesh_reduce.<locals>.<genexpr>½   s*   øé € Ð iÑVhÉdÈaÔ!7¸¸d¸VÀ1ÀQÀC¸=×!IÐ!IÓVhùs   ƒ #rq   z;Torch xla must be installed to use `nested_xla_mesh_reduce`)r   Útorch_xla.core.xla_modelÚcoreÚ	xla_modelr,   rP   rQ   rO   Ú	enumerater   rS   rr   r-   Úmesh_reducer$   r4   ÚImportError)rU   rt   Úxmrs   rW   rK   s   &f    r   rr   rr   ¸   sÒ   ø€ Ü×Òß-Ð-ä�g¤¤e˜}×-Ò-Ü˜”=Ô iÔV_Ð`gÔVhÓ iÓiÐiÜ�gœw×'Ò'Ü˜”=ÜNWÐX_×XeÑXeÓXgÔNhÕiÑNhÁÀÁFÀQ�Ô*¨1°°°a¸°s¨mÓ<Ò<ÑNhÓióð ô ˜WÓ%ˆØ�~‰~˜d G¬U¯Y©YÓ7Ð7äÐWÓXÐXùô js   Â C9c                óJ   € V ^8„  d   QhR\         R\        R,          R\         /# )r"   ÚtensorÚnum_total_examplesNÚreturn)r	   Úint)r(   s   "r   r)   r)   É   s*   € ÷ Iñ Iœsð I¼¸d½
ð IÌcñ Ir    c                 ó~  a€  \        V \        \        34      '       d   \        V 4      ! V3R  lV  4       4      # \        V \        4      '       d?   \        V 4      ! V P                  4        UUu/ uF  w  r#V\        VS4      bK  	  upp4      # \        V 4      P                  4       p \        \        P                  ! 4       4       Uu. uF  q@P                  4       NK  	  pp\        P                  ! WP4       \        P                  ! V^ R7      pSe   VRS pV# u uppi u upi   \          d    \!        R4      hi ; i)c              3   ó<   <"  € T F  p\        VS4      x € K  	  R # 5ir+   )Údistributed_concat)rJ   rK   r   s   & €r   rM   Ú%distributed_concat.<locals>.<genexpr>Ì   s   øé € ÐZÑSYÈaÔ 2°1Ð6H× IÐ IÓSYùó   ƒr/   Nú(Not currently using distributed training)r,   rQ   rP   rO   r   rS   r„   r-   Ú
contiguousÚrangeÚdistÚget_world_sizeÚcloneÚ
all_gatherr$   r4   ÚAssertionError)r~   r   rW   rK   rq   Úoutput_tensorsÚconcats   &f     r   r„   r„   É   s  ø€ ðIÜ�fœu¤d˜m×,Ò,Ü˜”<ÔZÑSYÓZÓZÐZÜ�fœg×&Ò&Ü˜”<ÐZ`×ZfÑZfÔZhÔ iÑZhÑRVÐRS Ô$6°qÐ:LÓ$MÒ!MÑZhÒ iÓjÐjÜ˜FÓ#×.Ñ.Ó0ˆÜ27¼×8KÒ8KÓ8MÔ2NÓOÑ2N¨QŸ,™,ž.Ñ2NˆÐOÜ�Š˜Ô/Ü—’˜>¨qÔ1ˆð Ò)ØÐ/Ð/Ð0ˆFØˆùó !jùâOøô ô IÜÐGÓHÐHðIús9   ƒD% ŸD% º4D% Á.D
ÂD% Â9D% ÃD Ã:D% ÄD% Ä%D<c                óÔ   € ^RI Hp V f   R# \        4       '       d   Vf   Rp\        W4      p V # \	        4       '       d   \        V 4      p V # WP                  8X  d   \        V 4      p V # )zV
Gather value of `tensors` (tensor or list/tuple of nested tensors) across processes.
)ÚParallelModeNÚnested_gather)Útraining_argsr’   r   rr   r   Ú
smp_gatherÚDISTRIBUTEDr„   )rU   Úparallel_modert   r’   s   &&& r   r“   r“   Ü   sl   € õ ,à‚ÙÜ×ÒØŠ<Ø"ˆDÜ(¨Ó7ˆð
 €Nô	 
!×	"Ò	"Ü˜WÓ%ˆð €Nð 
×2Ñ2Ô	2Ü$ WÓ-ˆØ€Nr    c                óú  € V f   R# V P                  4       ^8X  d   R# V P                  4       R9   dÉ   V P                  R,          pV^8:  d   R# V P                  4       ^8X  d   V R,          pM	V ^ ,          p\        P                  ! V^R7      p\        P                  ! VR8*  4      ;'       g    \        P                  ! VR8  4      p\        V\        P                  4      '       d   VP                  4       # T# R# )	aj  
Check if an attention mask is causal (compatible with causal attention).

Context parallelism only supports causal attention patterns. This function
checks if the provided attention mask is compatible.

Args:
    attention_mask (`torch.Tensor`): The attention mask to check.

Returns:
    `bool`: True if the mask is causal or compatible with causal attention.
T)Údiagonalg�íµ ÷Æ°>F)é   é   éÿÿÿÿ)ro   ro   g     ˆÃÀ)r0   r3   r$   ÚtriuÚallr,   r%   Úitem)Úattention_maskÚseq_lenÚmaskÚupper_triangularÚ	is_causals   &    r   Úis_attention_mask_causalr¥   ï   sß   € ð ÒÙð ×ÑÓ˜qÔ áØ	×	Ñ	Ó	 Ô	'ð !×&Ñ& rÕ*ˆØ�aŒ<Ùð ×ÑÓ 1Ô$Ø! $Õ'‰Dà! !Õ$ˆDô !Ÿ:š: d°QÔ7Ðô —I’IÐ.°$Ñ6Ó7×]Ð]¼5¿9º9ÐEUÐX\ÑE\Ó;]ˆ	Ü#-¨i¼¿¹×#FÒ#Fˆy�~‰~ÓÐUÈIÐUñ r    Úcudac                ó¸   € V ^8„  d   QhR\         \        \        ,          ,          R\        R,          R\        P                  R,          R\        P
                  /# )r"   Úscalarsr   NÚdevicer€   )rP   r�   Úfloatr$   r©   r%   )r(   s   "r   r)   r)     sP   € ÷ Iñ IÜ”#œ•+ÕðIä˜d�
ðIô �L‰L˜4ÕðIô ‡\�\ñ	Ir    c                 óV  €  \         P                  ! WR 7      p\        \        P                  ! 4       4       Uu. uF  qCP                  4       NK  	  pp\        P                  ! WS4       \         P                  ! V^ R7      pVe   VRV pV# u upi   \         d    \        R4      hi ; i))r©   r/   Nr‡   )	r$   r~   r‰   rŠ   r‹   rŒ   r�   r4   rŽ   )r¨   r   r©   Útensorized_scalarrq   r�   r�   s   &&&    r   Údistributed_broadcast_scalarsr­     sž   € ð
IÜ!ŸLšL¨Ô@ÐÜ=BÄ4×CVÒCVÓCXÔ=YÓZÑ=Y¸×1Ñ1Ö3Ñ=YˆÐZÜ�Š˜Ô:Ü—’˜>¨qÔ1ˆð Ò)ØÐ/Ð/Ð0ˆFØˆùò [øô ô IÜÐGÓHÐHðIús   ‚7B ¹BÁ:B ÂB ÂB(c                 ó¾   € \        V 4      ^8”  dM   V  FD  pVP                  \        Jg   K  \        P                  ! VP
                  VP                  4       KF  	  R# R# )é   N)r2   ÚcategoryÚUserWarningÚwarningsÚwarnÚmessage)Úcaught_warningsÚws   & r   Úreissue_pt_warningsr·   /  s@   € ä
ˆ?Ó˜aÔÛ ˆAØ�z‰z¤Õ,Ü—’˜aŸi™i¨¯©Ö4ó !ñ  r    c                ó$   € V ^8„  d   QhR\         /# )r"   Ú
local_rank©r�   )r(   s   "r   r)   r)   8  s   € ÷ ñ ¬Sñ r    c              #  óŠ   "  € V R9  d   \         P                  ! 4        Rx € V ^ 8X  d   \         P                  ! 4        R# R# 5i)z£
Decorator to make all processes in distributed training wait for each local_master to do something.

Args:
    local_rank (`int`): The rank of the local process.
N)rœ   ro   )rŠ   Úbarrier)r¹   s   &r   Útorch_distributed_zero_firstr½   7  s0   é € ð ˜Ô Ü�ŠŒÛ	Ø�Q„Ü�ŠŽñ ùs   ‚AAc                   óB   a a€ ] tR tRt oRtV 3R ltV 3R ltRtVtV ;t	# )ÚDistributedSamplerWithLoopiF  aÇ  
Like a torch.utils.data.distributed.DistributedSampler` but loops at the end back to the beginning of the shuffled
samples to make each process have a round multiple of batch_size samples.

Args:
    dataset (`torch.utils.data.Dataset`):
        Dataset used for sampling.
    batch_size (`int`):
        The batch size used with this sampler
    kwargs (`dict[str, Any]`, *optional*):
        All other keyword arguments passed to `DistributedSampler`.
c                ó6   <€ \         SV `  ! V3/ VB  W n        R # r+   )ÚsuperÚ__init__Ú
batch_size)ÚselfÚdatasetrÃ   ÚkwargsÚ	__class__s   &&&,€r   rÂ   Ú#DistributedSamplerWithLoop.__init__T  s   ø€ Ü‰Ò˜Ñ+ FÒ+Ø$Žr    c                ó|  <€ \        \        SV `	  4       4      p\        V4      V P                  ,          ^ 8X  d   ^ M,V P                  \        V4      V P                  ,          ,
          pV P
                  \        V P                  4      V P                  ,          8  d   ^M^ pWW3V,            ,          p\        V4      # )ro   )	rP   rÁ   Ú__iter__r2   rÃ   ÚrankrÅ   Únum_replicasÚiter)rÄ   ÚindicesÚ	remainderÚstart_remainderrÇ   s   &   €r   rÊ   Ú#DistributedSamplerWithLoop.__iter__X  s‘   ø€ Ü”u‘wÑ'Ó)Ó*ˆÜ˜W›¨¯©Õ7¸1Ô<‘AÀ$Ç/Á/ÔTWÐX_ÓT`Ðcg×crÑcrÕTrÕBrˆ	ð  $Ÿy™y¬3¨t¯|©|Ó+<¸t×?PÑ?PÕ+PÔP™!ÐVWˆØ˜?¸yÕ-HÐIÕIˆÜ�G‹}Ðr    )rÃ   )
Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__rÂ   rÊ   Ú__static_attributes__Ú__classdictcell__Ú__classcell__©rÇ   Ú__classdict__s   @@r   r¿   r¿   F  s   ù‡ € ñõ%÷õ r    r¿   c                   ód   a € ] tR tRt o RtRV 3R lR lltV 3R lR ltV 3R lR ltR	 tR
t	V t
R# )ÚEvalLoopContainerib  a=  
Container to store intermediate results of evaluation loop.

Args:
    do_nested_concat (`bool`, *optional*, defaults to `True`):
        If set to `True`, each iteration will recursively concatenate a new object containing tensors to
        the existing stored tensors, provided that the structure of the existing object and the new one
        are identical. If set to `False`, all newly added tensors will be stored in a list.
    padding_index (`int`, *optional*, defaults to -100):
        Value used to pad tensors of different shapes when `do_nested_concat=True`.
c                ó&   <€ V ^8„  d   QhRS[ RS[/# )r"   Údo_nested_concatr9   )Úboolr�   )r(   rÛ   s   "€r   r)   ÚEvalLoopContainer.__annotate__o  s   ø€ ÷ ñ ©ð ÁSñ r    c                ó:   € Wn         W n        R V n        R V n        R # r+   )rß   r9   rU   Úarrays)rÄ   rß   r9   s   &&&r   rÂ   ÚEvalLoopContainer.__init__o  s   € Ø 0ÔØ*ÔØˆŒØˆŽr    c                ó   <€ V ^8„  d   QhRR/# ©r"   r€   N© )r(   rÛ   s   "€r   r)   rá   u  s   ø€ ÷ )ñ )˜dñ )r    c                ó  € V P                   f   V P                  '       d   TMV.V n         R# V P                  '       d)   \        V P                   WP                  R7      V n         R# V P                   P	                  V4       R# )zlAdd tensors to the stored objects. If `do_nested_concat=True`, the tensors will be concatenated recursively.NrH   )rU   rß   rI   r9   Úappend)rÄ   rU   s   &&r   ÚaddÚEvalLoopContainer.addu  sX   € à�<‰<ÒØ&*×&;×&;Ð&;™7À'ÀˆDŽLØ×"×"Ð"Ü(¨¯©°w×N`ÑN`ÔaˆDŽLà�L‰L×Ñ Ö(r    c                ó   <€ V ^8„  d   QhRR/# ræ   rç   )r(   rÛ   s   "€r   r)   rá   ~  s   ø€ ÷ ñ  $ñ r    c                ó0  € V P                   f   R# \        V P                   4      pV P                  f   Wn        MTV P                  '       d(   \	        V P                  WP
                  R7      V n        MV P                  P                  V4       RV n         R# )zGMove tensors in stored objects to CPU and convert them to numpy arrays.NrH   )rU   r^   rã   rß   rI   r9   Úextend)rÄ   Ú
new_arrayss   & r   Úto_cpu_and_numpyÚ"EvalLoopContainer.to_cpu_and_numpy~  sm   € ð �<‰<ÒÙä# D§L¡LÓ1ˆ
Ø�;‰;ÒØ$�KØ×"×"Ð"Ü'¨¯©°Z×OaÑOaÔbˆD�Kà�K‰K×Ñ˜zÔ*ð ˆŽr    c                ó:   € V P                  4        V P                  # )z6Returns the numpified and moved to CPU stored objects.)rð   rã   ©rÄ   s   &r   Ú
get_arraysÚEvalLoopContainer.get_arrays�  s   € à×ÑÔØ�{‰{Ðr    )rã   rß   r9   rU   N)Téœÿÿÿ)rÒ   rÓ   rÔ   rÕ   rÖ   rÂ   rê   rð   rô   r×   rØ   ©rÛ   s   @r   rÝ   rÝ   b  s2   ø‡ € ñ
÷ò ÷)ð )÷ð ÷$ð r    rÝ   c                ól   € V ^8„  d   QhR\         P                  P                  P                  R\        /# )r"   rÅ   rÃ   )r$   ÚutilsÚdatar   r�   )r(   s   "r   r)   r)   –  s.   € ÷ _ñ _œUŸ[™[×-Ñ-×5Ñ5ð _Ä3ñ _r    c                 ó´   € \         P                  ! 4       ^8:  d   \        V 4      # \        V \         P                  ! 4       \         P                  ! 4       R7      # )r¯   )rÌ   rË   )ÚxrÚ
world_sizer   r   Úglobal_ordinal)rÅ   rÃ   s   &&r   Úget_tpu_samplerrÿ   –  s9   € Ü	‡}‚}ƒ˜!ÔÜ˜WÓ%Ð%Ü˜g´B·M²M³OÌ"×J[ÒJ[ÓJ]Ô^Ð^r    c                óÌ   a€ \        V \        \        34      '       d   \        V 4      ! V3R lV  4       4      # \        P
                  ! WS.V P                  R,          O5R7      # )z\Create the same nested structure as `arrays` with a first dimension always at `num_samples`.c              3   ó<   <"  € T F  p\        VS4      x € K  	  R # 5ir+   )Únested_new_like)rJ   ÚxÚnum_sampless   & €r   rM   Ú"nested_new_like.<locals>.<genexpr>Ÿ  s   øé € ÐLÁVÀœO¨A¨{×;Ð;ÃVùr†   ºr¯   NNr?   )r,   rP   rQ   rO   r&   rA   r3   )rã   r  r9   s   &f&r   r  r  œ  sL   ø€ ä�&œ4¤˜-×(Ò(Ü�FŒ|ÔLÁVÓLÓLÐLÜ�<Š<˜°kÐ5UÀFÇLÁLÐQSÕDTÑ5UÔVÐVr    c                ó¾   € \         P                  ! WV P                  ^ ,          V3V P                  R,          ,           R7      pWRRV P                  ^,          13&   V# )zmExpand the `arrays` so that the second dimension grows to `new_seq_length`. Uses `padding_index` for padding.r1   r?   ºNNNN)r&   rA   r3   )rã   Únew_seq_lengthr9   r;   s   &&& r   Úexpand_liker
  £  sQ   € ä�\Š\˜&¸¿¹ÀQ½ÈÐ7XÐ[a×[gÑ[gÐhjÕ[kÕ7kÔl€FØ#)ˆ1Ð�—‘˜Q•ÐÐÑ Ø€Mr    c                ó0  a€ \        V \        \        34      '       d   \        V 4      ! V3R lV  4       4      # \        V \        4      '       d?   \        V 4      ! V P                  4        UUu/ uF  w  r#V\        VS4      bK  	  upp4      # V RS # u uppi )zQTruncate `tensors` at `limit` (even if it's a nested list/tuple/dict of tensors).c              3   ó<   <"  € T F  p\        VS4      x € K  	  R # 5ir+   )Únested_truncate)rJ   rK   Úlimits   & €r   rM   Ú"nested_truncate.<locals>.<genexpr>­  s   øé € ÐHÁ¸1œ_¨Q°×6Ð6Ãùr†   N)r,   rP   rQ   rO   r   rS   r  )rU   r  rW   rK   s   &f  r   r  r  ª  sz   ø€ ä�'œD¤%˜=×)Ò)Ü�GŒ}ÔHÁÓHÓHÐHÜ�'œ7×#Ò#Ü�GŒ}ÀwÇ}Á}ÄÔWÁ¹t¸q˜a¤°°EÓ!:Ò:ÁÒWÓXÐXà�6�Eˆ?Ðùó Xs   Á-B
c                   óB   a € ] tR tRt o RtRtRtR	R ltV 3R ltRt	V t
R# )
ÚLabelSmootheri´  a$  
Adds label-smoothing on a pre-computed output from a Transformers model.

Args:
    epsilon (`float`, *optional*, defaults to 0.1):
        The label smoothing factor.
    ignore_index (`int`, *optional*, defaults to -100):
        The index in the labels to ignore when computing the loss.
gš™™™™™¹?c                óî  € \        V\        4      '       d
   VR ,          MV^ ,          pV'       d4   VRRR
1R3,          P                  4       pVR,          P                  4       p\        P                  P                  VR
R7      ) pVP                  4       VP                  4       ^,
          8X  d   VP                  R
4      pVP                  V P                  4      p\        P                  ! V^ R7      pVP                  R
VR7      pVP                  R
R\        P                  R7      pVP                  VR	4       VP                  VR	4       VP!                  4       VP#                  4       P                  4       ,
          p	VP                  4       V	,          pVP                  4       W•P$                  R
,          ,          ,          p^V P&                  ,
          V,          V P&                  V,          ,           # )Úlogits.Nr  r/   )Úmin)r0   ÚindexT)r0   Úkeepdimrc   g        rœ   ).r  )r,   Údictrˆ   r   Ú
functionalÚlog_softmaxr0   Ú	unsqueezeÚeqÚignore_indexr$   ÚclampÚgatherÚsumrf   Úmasked_fill_ÚnumelÚlongr3   Úepsilon)
rÄ   Úmodel_outputÚlabelsÚshift_labelsr  Ú	log_probsÚpadding_maskÚnll_lossÚsmoothed_lossÚnum_active_elementss
   &&&&      r   Ú__call__ÚLabelSmoother.__call__Ã  s…  € Ü+5°lÄD×+IÒ+I�˜hÖ'È|Ð\]ÍˆßØ˜C  "  a˜KÕ(×3Ñ3Ó5ˆFØ˜G•_×/Ñ/Ó1ˆFä—]‘]×.Ñ.¨v¸2Ð.Ó>Ð>ˆ	Ø�:‰:‹<˜9Ÿ=™=›?¨QÕ.Ô.Ø×%Ñ% bÓ)ˆFà—y‘y ×!2Ñ!2Ó3ˆô —’˜V¨Ô+ˆØ×#Ñ#¨°&Ð#Ó9ˆà!Ÿ™¨"°dÄ%Ç-Á-˜ÓPˆà×Ñ˜l¨CÔ0Ø×"Ñ" <°Ô5ð +×0Ñ0Ó2°\×5FÑ5FÓ5H×5LÑ5LÓ5NÕNÐØ—<‘<“>Ð$7Õ7ˆØ%×)Ñ)Ó+Ð/BÇ_Á_ÐUWÕEXÕ/XÕYˆØ�D—L‘LÕ  HÕ,¨t¯|©|¸mÕ/KÕKÐKr    c                ó2   <€ V ^8„  d   Qh/ S[ ;R&   S[;R&   # )r"   r#  r  )rª   r�   )r(   rÛ   s   "€r   r)   ÚLabelSmoother.__annotate__´  s   ø‡ ‚ ñ Ññ ñ Ñò r    rç   Nrö   ©F)rÒ   rÓ   rÔ   rÕ   rÖ   r#  r  r,  Ú__annotate_func__r×   rØ   r÷   s   @r   r  r  ´  s#   ø‡ € ñð €GØ€LôL÷ ƒ r    r  c           	     óâ  a € Vf-   \        \        S 4      V^,          ,          ^24      pV^ 8X  d   ^p\        P                  ! \        S 4      VR7      pW!,          p\	        ^ \        S 4      V4       Uu. uF  qdWfV,            P                  4       NK  	  ppV Uu. uF  p\        VV 3R lRR7      NK  	  ppV Uu. uF  pS V^ ,          ,          NK  	  p	p\        P                  ! \        P                  ! V	4      4      P                  4       p
Wz,          ^ ,          V^ ,          ^ ,          uV^ ,          ^ &   Wz,          ^ &   V UUu. uF  qˆ F  qfNK  	  K  	  upp# u upi u upi u upi u uppi )aÒ  
Return a list of indices so that each slice of `batch_size` consecutive indices correspond to elements of similar
lengths. To do this, the indices are:

- randomly permuted
- grouped in mega-batches of size `mega_batch_mult * batch_size`
- sorted by length in each mega-batch

The result is the concatenation of all mega-batches, with the batch of `batch_size` containing the element of
maximum length placed first, so that an OOM happens sooner rather than later.
©Ú	generatorc                 ó   <€ SV ,          # r+   rç   )rs   Úlengthss   &€r   Ú<lambda>Ú,get_length_grouped_indices.<locals>.<lambda>ö  s	   ø€ °7¸1¶:r    T)ÚkeyÚreverse)
r  r2   r$   Úrandpermr‰   ÚtolistÚsortedÚargmaxr~   rŸ   )r6  rÃ   Úmega_batch_multr4  rÎ   Úmegabatch_sizers   ÚmegabatchesÚ	megabatchÚmegabatch_maximumsÚmax_idxs   f&&&       r   Úget_length_grouped_indicesrE  ß  sM  ø€ ð ÒÜœc '›l¨z¸A­~Õ>ÀÓCˆà˜aÔØˆOô �nŠnœS ›\°YÔ?€GØ$Õ1€NÜEJÈ1ÌcÐRYËlÐ\jÔEkÓlÑEkÀ˜1 >Õ1Ð2×9Ñ9Ö;ÑEk€KÐlÙ^iÓjÑ^iÐQZ”6˜)Ô)=Àt×LÑ^i€KÐjñ BMÓMÁ°I˜' )¨A¥,×/Ð/ÁÐÐMÜ�lŠlœ5Ÿ<š<Ð(:Ó;Ó<×AÑAÓC€Gà1<Õ1EÀaÕ1HÈ+ÐVWÍ.ÐYZÕJ[Ð.€K�…N�1Ñ�{Õ+¨AÑ.á*Ô>™{�)²I¨qŠA±I‰A™{Ò>Ð>ùò mùÚjùò Nùó
 ?s   Á3!EÂE!Â;E&ÅE+c                   óF   a € ] tR tRt o RtR	V 3R lR lltR tR tRtV t	R# )
ÚLengthGroupedSampleri  z’
Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while
keeping a bit of randomness.
Nc          	      ól   <€ V ^8„  d   QhRS[ RS[R,          RS[S[ ,          R,          RS[R,          /# )r"   rÃ   rÅ   Nr6  Úmodel_input_name)r�   r   rP   Ústr)r(   rÛ   s   "€r   r)   Ú!LengthGroupedSampler.__annotate__  sD   ø€ ÷ #ñ #áð#ñ ˜4•ð#ñ ‘c•˜TÕ!ð	#ñ
  �*ñ#r    c                ó¼  € Vf   Vf   \        R4      hWn        Vfi   Ve   TMRp\        V^ ,          \        \        34      '       d   WB^ ,          9  d   \        RV R24      hV Uu. uF  p\        Wd,          4      NK  	  ppME\        V\        P                  4      '       d&   \        P                  R4       VP                  4       pW0n        WPn        R # u upi )Nú,One of dataset and lengths must be provided.Ú	input_idsúXCan only automatically infer lengths for datasets whose items are dictionaries with an 'ú' key.zcIf lengths is a torch.Tensor, LengthGroupedSampler will be slow. Converting lengths to list[int]...)Ú
ValueErrorrÃ   r,   r  r   r2   r$   r%   ÚloggerÚinfor<  r6  r4  )rÄ   rÃ   rÅ   r6  rI  r4  Úfeatures   &&&&&& r   rÂ   ÚLengthGroupedSampler.__init__  sÓ   € ð Š?˜wšÜÐKÓLÐLà$ŒØŠ?Ø3CÒ3OÑ/ÐU`ÐÜ˜g a�j¬4´Ð*?×@Ò@ÐDTÐdeÕ\fÔDfÜ ðØ(Ð)¨ð1óð ñ FMÓMÁW¸'”s˜7Õ4Ö5ÁWˆGÐMˆGÜ˜¤§¡×.Ò.Ü�K‰KØuôð —n‘nÓ&ˆGàŒØ"Žùò Ns   Á)Cc                ó,   € \        V P                  4      # r+   )r2   r6  ró   s   &r   Ú__len__ÚLengthGroupedSampler.__len__%  s   € Ü�4—<‘<Ó Ð r    c                óp   € \        V P                  V P                  V P                  R 7      p\	        V4      # )r3  )rE  r6  rÃ   r4  rÍ   )rÄ   rÎ   s   & r   rÊ   ÚLengthGroupedSampler.__iter__(  s)   € Ü,¨T¯\©\¸4¿?¹?ÐVZ×VdÑVdÔeˆÜ�G‹}Ðr    )rÃ   r4  r6  )NNNN)
rÒ   rÓ   rÔ   rÕ   rÖ   rÂ   rW  rÊ   r×   rØ   r÷   s   @r   rG  rG    s#   ø‡ € ñ÷
#ò #ò:!÷ð r    rG  c                   óL   a € ] tR tRt o RtR	V 3R lR lltV 3R lR ltRtV tR# )
ÚDistributedLengthGroupedSampleri-  zž
Distributed Sampler that samples indices in a way that groups together features of the dataset of roughly the same
length while keeping a bit of randomness.
Nc                ó    <€ V ^8„  d   QhRS[ RS[R,          RS[ R,          RS[ R,          RS[ RS[RS[S[ ,          R,          R	S[R,          /# )
r"   rÃ   rÅ   NrÌ   rË   ÚseedÚ	drop_lastr6  rI  )r�   r   rà   rP   rJ  )r(   rÛ   s   "€r   r)   Ú,DistributedLengthGroupedSampler.__annotate__4  st   ø€ ÷ 7ñ 7áð7ñ ˜4•ð7ñ ˜D•jð	7ñ
 �D�jð7ñ ð7ñ ð7ñ ‘c•˜TÕ!ð7ñ  �*ñ7r    c	                óÈ  € Vf   Vf   \        R4      hVf<   \        P                  ! 4       '       g   \        R4      h\        P                  ! 4       pVf<   \        P                  ! 4       '       g   \        R4      h\        P
                  ! 4       pWn        W0n        W@n        ^ V n	        W`n
        Vfi   Ve   TMRp\        V^ ,          \        \        34      '       d   W‚^ ,          9  d   \        RV R24      hV U	u. uF  p	\        W˜,          4      NK  	  pp	ME\        V\        P                   4      '       d&   \"        P%                  R4       VP'                  4       pWpn        V P                  '       d}   \        V P(                  4      V P                  ,          ^ 8w  dR   \*        P,                  ! \        V P(                  4      V P                  ,
          V P                  ,          4      V n        M?\*        P,                  ! \        V P(                  4      V P                  ,          4      V n        V P.                  V P                  ,          V n        WPn        R # u up	i )NrM  z,Requires distributed package to be availablerN  rO  rP  znIf lengths is a torch.Tensor, DistributedLengthGroupedSampler will be slow. Converting lengths to list[int]...)rQ  rŠ   Úis_availableÚRuntimeErrorr‹   Úget_rankrÃ   rÌ   rË   Úepochr_  r,   r  r   r2   r$   r%   rR  rS  r<  r6  ÚmathÚceilr  Ú
total_sizer^  )
rÄ   rÃ   rÅ   rÌ   rË   r^  r_  r6  rI  rT  s
   &&&&&&&&& r   rÂ   Ú(DistributedLengthGroupedSampler.__init__4  sÜ  € ð Š?˜wšÜÐKÓLÐLØÒÜ×$Ò$×&Ò&Ü"Ð#QÓRÐRÜ×.Ò.Ó0ˆLØŠ<Ü×$Ò$×&Ò&Ü"Ð#QÓRÐRÜ—=’=“?ˆDà$ŒØ(ÔØŒ	ØˆŒ
Ø"ŒàŠ?Ø3CÒ3OÑ/ÐU`ÐÜ˜g a�j¬4´Ð*?×@Ò@ÐDTÐdeÕ\fÔDfÜ ðØ(Ð)¨ð1óð ñ FMÓMÁW¸'”s˜7Õ4Ö5ÁWˆGÐMˆGÜ˜¤§¡×.Ò.Ü�K‰Kð ôð —n‘nÓ&ˆGàŒð �>�>ˆ>œc $§,¡,Ó/°$×2CÑ2CÕCÀqÔHô  $Ÿyšy¬#¨d¯l©lÓ*;¸d×>OÑ>OÕ*OÐSW×SdÑSdÕ)dÓeˆDÕä#Ÿyšy¬¨T¯\©\Ó):¸T×=NÑ=NÕ)NÓOˆDÔØ×*Ñ*¨T×->Ñ->Õ>ˆŒØŽ	ùò) Ns   Ä Ic                ó    <€ V ^8„  d   QhRS[ /# ©r"   r€   )r   )r(   rÛ   s   "€r   r)   r`  m  s   ø€ ÷ ñ ™(ñ r    c                ó.  € \         P                  ! 4       pVP                  V P                  V P                  ,           4       \        V P                  V P                  VR 7      pV P                  '       g'   W"RV P                  \        V4      ,
           ,          pMVRV P                   p\        V4      V P                  8X  g   Q hW P                  V P                  V P                  1,          p\        V4      V P                  8X  g   Q h\        V4      # )r3  N)r$   Ú	GeneratorÚmanual_seedr^  re  rE  r6  rÃ   r_  rh  r2   rË   rÌ   r  rÍ   )rÄ   ÚgrÎ   s   &  r   rÊ   Ú(DistributedLengthGroupedSampler.__iter__m  sÎ   € ä�OŠOÓˆØ	�‰�d—i‘i $§*¡*Õ,Ô-Ü,¨T¯\©\¸4¿?¹?ÐVWÔXˆà�~�~ˆ~àÐA $§/¡/´C¸³LÕ"@ÐBÕB‰Gð Ð/ §¡Ð0ˆGÜ�7‹|˜tŸ™Ô.Ð.Ð.ð Ÿ)™) d§o¡o¸×8IÑ8IÐIÕJˆÜ�7‹|˜t×/Ñ/Ô/Ð/Ð/ä�G‹}Ðr    )	rÃ   r_  re  r6  rÌ   r  rË   r^  rh  )NNNro   FNN)	rÒ   rÓ   rÔ   rÕ   rÖ   rÂ   rÊ   r×   rØ   r÷   s   @r   r\  r\  -  s   ø‡ € ñ÷7ò 7÷rö r    r\  c                   óF   a € ] tR tRt o RtR	V 3R lR lltR tR tRtV t	R# )
ÚShardSampleri‚  a¸  
Sampler that shards batches between several processes. Dispatches indices batch by batch: on 2 processes with batch
size 4, the first two batches are `[0, 1, 2, 3, 4, 5, 6, 7]` and `[8, 9, 10, 11, 12, 13, 14, 15]`, which shard into
`[0, 1, 2, 3]` and `[8, 9, 10, 11]` for GPU-0 and `[4, 5, 6, 7]` and `[12, 13, 14, 15]` for GPU-1.

The sampler thus yields `[0, 1, 2, 3, 8, 9, 10, 11]` on GPU-0 and `[4, 5, 6, 7, 12, 13, 14, 15]` on GPU-1.
c          
      ó8   <€ V ^8„  d   QhRS[ RS[RS[RS[RS[/# )r"   rÅ   rÃ   r_  Únum_processesÚprocess_index)r   r�   rà   )r(   rÛ   s   "€r   r)   ÚShardSampler.__annotate__‹  sD   ø€ ÷ @ñ @áð@ñ ð@ñ ð	@ñ
 ð@ñ ñ@r    c                óú   € Wn         W n        W0n        W@n        WPn        W$,          ;V n        pV'       d   \        V4      V,          M%\        P                  ! \        V4      V,          4      pWv,          V n	        R # r+   )
rÅ   rÃ   r_  rt  ru  Útotal_batch_sizer2   rf  rg  Útotal_num_samples)rÄ   rÅ   rÃ   r_  rt  ru  rx  Únum_batchess   &&&&&&  r   rÂ   ÚShardSampler.__init__‹  sd   € ð ŒØ$ŒØ"ŒØ*ÔØ*Ôà3=Õ3MÐMˆÔÐ 0ç:C”c˜'“lÐ&6Ö6ÌÏÊÔSVÐW^ÓS_ÐbrÕSrÓIsˆØ!,Õ!?ˆÖr    c                ó¨  € \        \        \        V P                  4      4      4      p\        V4      V P                  8  d(   WR V P                  \        V4      ,
           ,          pKA  . p\        V P
                  V P                  ,          V P                  V P                  4       F  pW!W3V P
                  ,            ,          pK   	  \        V4      # r+   )	rP   r‰   r2   rÅ   ry  rÃ   ru  rx  rÍ   )rÄ   rÎ   r;   Úbatch_starts   &   r   rÊ   ÚShardSampler.__iter__ž  s¤   € Ü”uœS §¡Ó.Ó/Ó0ˆô �'‹l˜T×3Ñ3Ô3ØÐH $×"8Ñ"8¼3¸w»<Õ"GÐIÕIŠGàˆÜ  §¡°4×3EÑ3EÕ!EÀt×G]ÑG]Ð_c×_tÑ_tÖuˆKØ˜k¸$¿/¹/Õ,IÐJÕJŠFñ vô �F‹|Ðr    c                ó<   € V P                   V P                  ,          # r+   )ry  rt  ró   s   &r   rW  ÚShardSampler.__len__¬  s   € à×%Ñ%¨×);Ñ);Õ;Ð;r    )rÃ   rÅ   r_  rt  ru  rx  ry  N)r¯   Fr¯   ro   )
rÒ   rÓ   rÔ   rÕ   rÖ   rÂ   rÊ   rW  r×   rØ   r÷   s   @r   rr  rr  ‚  s%   ø‡ € ñ÷@ò @ò&÷<ð <r    rr  c                   óL   a € ] tR tRt o RtR
V 3R lR lltR tR tR tRt	V t
R	# )ÚIterableDatasetShardi±  aX  
Wraps a PyTorch `IterableDataset` to generate samples for one of the processes only. Instances of this class will
always yield a number of samples that is a round multiple of the actual batch size (which is `batch_size x
num_processes`). Depending on the value of the `drop_last` attribute, it will either stop the iteration at the
first batch that would be too small or loop with indices from the beginning.

On two processes with an iterable dataset yielding of `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]` with a batch size of
2:

- the shard on process 0 will yield `[0, 1, 4, 5, 8, 9]` so will see batches `[0, 1]`, `[4, 5]`, `[8, 9]`
- the shard on process 1 will yield `[2, 3, 6, 7, 10, 11]` so will see batches `[2, 3]`, `[6, 7]`, `[10, 11]`

<Tip warning={true}>

    If your IterableDataset implements some randomization that needs to be applied the same way on all processes
    (for instance, a shuffling), you should use a `torch.Generator` in a `generator` attribute of the `dataset` to
    generate your random numbers and call the [`~trainer_pt_utils.IterableDatasetShard.set_epoch`] method of this
    object. It will set the seed of this `generator` to `seed + epoch` on all processes before starting the
    iteration. Alternatively, you can also implement a `set_epoch()` method in your iterable dataset to deal with
    this.

</Tip>

Args:
    dataset (`torch.utils.data.IterableDataset`):
        The batch sampler to split in several shards.
    batch_size (`int`, *optional*, defaults to 1):
        The size of the batches per shard.
    drop_last (`bool`, *optional*, defaults to `False`):
        Whether or not to drop the last incomplete batch or complete the last batches by using the samples from the
        beginning.
    num_processes (`int`, *optional*, defaults to 1):
        The number of processes running concurrently.
    process_index (`int`, *optional*, defaults to 0):
        The index of the current process.
    seed (`int`, *optional*, defaults to 0):
        A random seed that will be used for the random number generation in
        [`~trainer_pt_utils.IterableDatasetShard.set_epoch`].
c                ó>   <€ V ^8„  d   QhRS[ RS[RS[RS[RS[RS[/# )r"   rÅ   rÃ   r_  rt  ru  r^  )r   r�   rà   )r(   rÛ   s   "€r   r)   Ú!IterableDatasetShard.__annotate__Ú  sG   ø€ ÷ ñ á ðñ ðñ ð	ñ
 ðñ ðñ ñr    c                ój   € Wn         W n        W0n        W@n        WPn        W`n        ^ V n        ^ V n        R# )ro   N)rÅ   rÃ   r_  rt  ru  r^  re  Únum_examples)rÄ   rÅ   rÃ   r_  rt  ru  r^  s   &&&&&&&r   rÂ   ÚIterableDatasetShard.__init__Ú  s3   € ð ŒØ$ŒØ"ŒØ*ÔØ*ÔØŒ	ØˆŒ
ØˆÖr    c                ó„   € Wn         \        V P                  R 4      '       d   V P                  P                  V4       R# R# )Ú	set_epochN)re  r   rÅ   r‰  )rÄ   re  s   &&r   r‰  ÚIterableDatasetShard.set_epochì  s/   € ØŒ
Ü�4—<‘< ×-Ò-Ø�L‰L×"Ñ" 5Ö)ñ .r    c              #  ó  "  € ^ V n         \        V P                  R4      '       g‘   \        V P                  R4      '       du   \        V P                  P                  \
        P                  4      '       dA   V P                  P                  P                  V P                  V P                  ,           4       V P                  V P                  ,          p\        V P                  V P                  ,          V P                  ^,           V P                  ,          4      pRp. pV P                   Fh  pV ;P                   ^,          un         VP                  V4       \        V4      V8X  g   K?  V F  pWF,          x € K  	  Vf   VP!                  4       p. pKj  	  V P"                  '       gV   \        V4      ^ 8”  dD   Vf   VP!                  4       p\        V4      V8  d   WC,          pK  V F  pWF,          x € K  	  R# R# R# 5i)ro   r‰  r4  N)r†  r   rÅ   r,   r4  r$   rm  rn  r^  re  rÃ   rt  r‰   ru  ré   r2   Úcopyr_  )rÄ   Úreal_batch_sizeÚprocess_sliceÚfirst_batchÚcurrent_batchÚelementrs   s   &      r   rÊ   ÚIterableDatasetShard.__iter__ñ  s€  é € ØˆÔä˜Ÿ™ k×2Ò2Ü˜Ÿ™ k×2Ò2Ü˜4Ÿ<™<×1Ñ1´5·?±?×CÒCà�L‰L×"Ñ"×.Ñ.¨t¯y©y¸4¿:¹:Õ/EÔFØŸ/™/¨D×,>Ñ,>Õ>ˆÜ˜d×0Ñ0°4·?±?ÕBÀT×EWÑEWÐZ[ÕE[Ð_c×_nÑ_nÕDnÓoˆàˆØˆØ—|”|ˆGØ×Ò Õ"ÕØ× Ñ  Ô)ä�=Ó! _Ö4Û&�AØ'Õ*Ô*ñ 'àÒ&Ø"/×"4Ñ"4Ó"6�KØ "’ñ $ð �~�~ˆ~¤# mÓ"4°qÔ"8ØÒ"Ø+×0Ñ0Ó2�Ü�mÓ$ Ô6ØÕ,’Û"�Ø#Õ&Ô&ó #ñ #9‰~ùs   ‚E$HÅ+>HÆ*AHc                ón  € V P                   '       dI   \        V P                  4      V P                  V P                  ,          ,          V P                  ,          # \
        P                  ! \        V P                  4      V P                  V P                  ,          ,          4      V P                  ,          # r+   )r_  r2   rÅ   rÃ   rt  rf  rg  ró   s   &r   rW  ÚIterableDatasetShard.__len__  sr   € à�>�>ˆ>Ü˜Ÿ™Ó%¨$¯/©/¸D×<NÑ<NÕ*NÕOÐSW×SbÑSbÕbÐbä—9’9œS §¡Ó.°$·/±/ÀD×DVÑDVÕ2VÕWÓXÐ[_×[jÑ[jÕjÐjr    )rÃ   rÅ   r_  re  r†  rt  ru  r^  N)r¯   Fr¯   ro   ro   )rÒ   rÓ   rÔ   rÕ   rÖ   rÂ   r‰  rÊ   rW  r×   rØ   r÷   s   @r   r‚  r‚  ±  s,   ø‡ € ñ&÷Pò ò$*ò
'÷Bkð kr    r‚  c                ó¤   € \        \        V \        V 4      ,
          4      ^d,          4      p\        P                  ! \        V 4      R7       RVR 2# )zF
Convert seconds to hh:mm:ss.msec, msecs rounded to 2 decimal places.
)ÚsecondsrF   Ú02d)r�   ÚabsÚdatetimeÚ	timedelta)ÚsecsÚmsecs   & r   Ú_secs2timedeltar�    sD   € ô
 Œs�4œ#˜d›)Õ#Ó$ sÕ*Ó+€DÜ× Ò ¬¨T«Ô3Ð4°A°d¸3°ZÐ@Ð@r    c                ót   € V ^8„  d   QhR\         \        \        3,          R\         \        \        3,          /# )r"   Úmetricsr€   )r  rJ  rª   )r(   s   "r   r)   r)   #  s,   € ÷ ñ œD¤¤e Õ,ð ´´c¼5°jÕ1Añ r    c                óJ  € V P                  4       pVP                  4        F~  w  r#RV9   d   V^,	           R2W&   K  RV9   d   \        V4      W&   K2  VR8X  d   \        V4      ^,	           R2W&   KR  \	        W,          \
        4      '       g   Kp  \        V^4      W&   K€  	  V# )zã
Reformat Trainer metrics values to a human-readable format.

Args:
    metrics (`dict[str, float]`):
        The metrics returned from train/evaluate/predict

Returns:
    metrics (`dict[str, float]`): The reformatted metrics
Ú_mem_ÚMBÚ_runtimeÚ
total_flosÚGF)rŒ  rS   r�  r�   r,   rª   Úround)rŸ  Úmetrics_copyrW   Úvs   &   r   Úmetrics_formatr©  #  s‘   € ð —<‘<“>€LØ×"Ñ"Ö$‰ˆØ�aŒ<Ø!" b¥ 	¨˜nˆL‹OØ˜1Œ_Ü-¨aÓ0ˆL‹OØ�,ÔÜ!$ Q£¨2¥ ¨bÐ1ˆL‹OÜ˜�¬×/Ô/Ü# A q›kˆL‹Oñ %ð Ðr    c           	     óL  € V P                  4       '       g   R# \        RV R24       \        V4      p\        R V 4       4      p\        R VP	                  4        4       4      p\        VP                  4       4       F"  p\        RVRV 2 RW6,          R	V 2 24       K$  	  R# )
aK  
Log metrics in a specially formatted way.

Under distributed environment this is done only for a process with rank 0.

Args:
    split (`str`):
        Mode/split name: one of `train`, `eval`, `test`
    metrics (`dict[str, float]`):
        The metrics returned from train/evaluate/predictmetrics: metrics dict

Notes on memory reports:

In order to get memory usage report you need to install `psutil`. You can do that with `pip install psutil`.

Now when this method is run, you will see a report that will include:

```
init_mem_cpu_alloc_delta   =     1301MB
init_mem_cpu_peaked_delta  =      154MB
init_mem_gpu_alloc_delta   =      230MB
init_mem_gpu_peaked_delta  =        0MB
train_mem_cpu_alloc_delta  =     1345MB
train_mem_cpu_peaked_delta =        0MB
train_mem_gpu_alloc_delta  =      693MB
train_mem_gpu_peaked_delta =        7MB
```

**Understanding the reports:**

- the first segment, e.g., `train__`, tells you which stage the metrics are for. Reports starting with `init_`
    will be added to the first stage that gets run. So that if only evaluation is run, the memory usage for the
    `__init__` will be reported along with the `eval_` metrics.
- the third segment, is either `cpu` or `gpu`, tells you whether it's the general RAM or the gpu0 memory
    metric.
- `*_alloc_delta` - is the difference in the used/allocated memory counter between the end and the start of the
    stage - it can be negative if a function released more memory than it allocated.
- `*_peaked_delta` - is any extra memory that was consumed and then freed - relative to the current allocated
    memory counter - it is never negative. When you look at the metrics of any stage you add up `alloc_delta` +
    `peaked_delta` and you know how much memory was needed to complete that stage.

The reporting happens only for process of rank 0 and gpu 0 (if there is a gpu). Typically this is enough since the
main process does the bulk of work, but it could be not quite so if model parallel is used and then other GPUs may
use a different amount of gpu memory. This is also not the same under DataParallel where gpu0 may require much more
memory than the rest since it stores the gradient and optimizer states for all participating GPUs. Perhaps in the
future these reports will evolve to measure those too.

The CPU RAM metric measures RSS (Resident Set Size) includes both the memory which is unique to the process and the
memory shared with other processes. It is important to note that it does not include swapped out memory, so the
reports could be imprecise.

The CPU peak memory is measured using a sampling thread. Due to python's GIL it may miss some of the peak memory if
that thread didn't get a chance to run when the highest memory was used. Therefore this report can be less than
reality. Using `tracemalloc` would have reported the exact peak memory, but it doesn't report memory allocations
outside of python. So if some C++ CUDA extension allocated its own memory it won't be reported. And therefore it
was dropped in favor of the memory sampling approach, which reads the current process memory usage.

The GPU allocated and peak memory reporting is done with `torch.cuda.memory_allocated()` and
`torch.cuda.max_memory_allocated()`. This metric reports only "deltas" for pytorch-specific allocations, as
`torch.cuda` memory management system doesn't track any memory allocated outside of pytorch. For example, the very
first cuda call typically loads CUDA kernels, which may take from 0.5 to 2GB of GPU memory.

Note that this tracker doesn't account for memory allocations outside of [`Trainer`]'s `__init__`, `train`,
`evaluate` and `predict` calls.

Because `evaluation` calls may happen during `train`, we can't handle nested invocations because
`torch.cuda.max_memory_allocated` is a single counter, so if it gets reset by a nested eval call, `train`'s tracker
will report incorrect info. If this [pytorch issue](https://github.com/pytorch/pytorch/issues/16266) gets resolved
it will be possible to change this class to be re-entrant. Until then we will only track the outer level of
`train`, `evaluate` and `predict` methods. Which means that if `eval` is called during `train`, it's the latter
that will account for its memory usage and that of the former.

This also means that if any other tool that is used along the [`Trainer`] calls
`torch.cuda.reset_peak_memory_stats`, the gpu peak memory stats could be invalid. And the [`Trainer`] will disrupt
the normal behavior of any such tools that rely on calling `torch.cuda.reset_peak_memory_stats` themselves.

For best performance you may want to consider turning the memory profiling off for production runs.
Nz***** z metrics *****c              3   óJ   "  € T F  p\        \        V4      4      x € K  	  R # 5ir+   ©r2   rJ  ©rJ   r  s   & r   rM   Úlog_metrics.<locals>.<genexpr>’  s   é € Ð9Ñ'8 !”#”c˜!“f—+�+Ó'8ùó   ‚!#c              3   óJ   "  € T F  p\        \        V4      4      x € K  	  R # 5ir+   r¬  r­  s   & r   rM   r®  “  s   é € ÐBÑ'A !”#”c˜!“f—+�+Ó'Aùr¯  z  z <z = Ú>)Úis_world_process_zeroÚprintr©  r5   rZ   r=  Úkeys)rÄ   ÚsplitrŸ  Úmetrics_formattedÚk_widthÚv_widthr9  s   &&&    r   Úlog_metricsr¹  >  s¢   € ð^ ×%Ñ%×'Ò'Ùä	ˆF�5�'˜Ð
(Ô)Ü& wÓ/ÐÜÑ9Ñ'8Ó9Ó9€GÜÑBÐ'8×'?Ñ'?Ô'AÓBÓB€GÜÐ'×,Ñ,Ó.Ö/ˆÜ��3�r˜'˜�lÐ# 3Ð'8Õ'=¸aÀ¸y¸[Ð&IÐJÖKó 0r    c           	     óB  € V P                  4       '       g   R# \        P                  P                  V P                  P
                  V R24      p\        VR4      ;_uu_ 4       p\        P                  ! W%^RR7       RRR4       V'       dØ   \        P                  P                  V P                  P
                  R4      p\        P                  P                  V4      '       d4   \        V4      ;_uu_ 4       p\        P                  ! V4      pRRR4       M/ pXP                  V4       \        VR4      ;_uu_ 4       p\        P                  ! We^RR7       RRR4       R# R#   + '       g   i     Lñ; i  + '       g   i     Ln; i  + '       g   i     R# ; i)aƒ  
Save metrics into a json file for that split, e.g. `train_results.json`.

Under distributed environment this is done only for a process with rank 0.

Args:
    split (`str`):
        Mode/split name: one of `train`, `eval`, `test`, `all`
    metrics (`dict[str, float]`):
        The metrics returned from train/evaluate/predict
    combined (`bool`, *optional*, defaults to `True`):
        Creates combined metrics by updating `all_results.json` with metrics of this call

To understand the metrics please read the docstring of [`~Trainer.log_metrics`]. The only difference is that raw
unformatted numbers are saved in the current method.

Nz_results.jsonr¶   T)ÚindentÚ	sort_keyszall_results.json)r²  ÚosÚpathÚjoinÚargsÚ
output_dirÚopenÚjsonÚdumpÚexistsÚloadÚupdate)rÄ   rµ  rŸ  Úcombinedr¾  ÚfÚall_metricss   &&&&   r   Úsave_metricsrË  ™  s  € ð$ ×%Ñ%×'Ò'Ùä�7‰7�<‰<˜Ÿ	™	×,Ñ,°°°}Ð.EÓF€DÜ	ˆd�C�Œ˜AÜ�	Š	�' Q°$Õ7÷ 
÷ Ü�w‰w�|‰|˜DŸI™I×0Ñ0Ð2DÓEˆÜ�7‰7�>‰>˜$×ÒÜ�d—”˜qÜ"Ÿiši¨›l�÷ �ð ˆKà×Ñ˜7Ô#Ü�$˜�_Œ_ Ü�IŠI�k¨Q¸$Õ?÷ ‰_ñ ÷ 
�ú÷ —ú÷ �_ˆ_ús$   Á$E'Ã:E:ÅFÅ'E7	Å:F
	ÆF	c                óÔ   € V P                  4       '       g   R# \        P                  P                  V P                  P
                  R4      pV P                  P                  V4       R# )z¨
Saves the Trainer state, since Trainer.save_model saves only the tokenizer with the model.

Under distributed environment this is done only for a process with rank 0.
Nztrainer_state.json)r²  r½  r¾  r¿  rÀ  rÁ  ÚstateÚsave_to_json)rÄ   r¾  s   & r   Ú
save_staterÏ  À  sG   € ð ×%Ñ%×'Ò'Ùä�7‰7�<‰<˜Ÿ	™	×,Ñ,Ð.BÓC€DØ‡J�J×Ñ˜DÖ!r    c                ó$   € V ^8„  d   QhR\         /# rk  rº   )r(   s   "r   r)   r)   Î  s   € ÷ Nñ N¬#ñ Nr    c                óV   € \        R V P                  P                  4        4       4      # )z)
Get the number of trainable parameters.
c              3   óh   "  € T F(  qP                   '       g   K  VP                  4       x € K*  	  R # 5ir+   )Úrequires_gradr!  )rJ   Úps   & r   rM   Ú/get_num_trainable_parameters.<locals>.<genexpr>Ò  s    é € ÐMÑ"9˜Q¿_½_Œyˆq�w‰w�yˆyÓ"9ùs   ‚2š2)r  ÚmodelÚ
parametersró   s   &r   Úget_num_trainable_parametersrØ  Î  s"   € ô ÑM $§*¡*×"7Ñ"7Ô"9ÓMÓMÐMr    c                ó:   € V ^8„  d   QhR\         \        ,          /# rk  )rP   rª   )r(   s   "r   r)   r)   Ö  s   € ÷ Bñ B¤¤U¥ñ Br    c                ó–   € V P                   f   \        R4      hV P                   P                   Uu. uF  qR,          NK  	  up# u upi )zB
Returns the learning rate of each parameter from self.optimizer.
úPTrainer optimizer is None, please make sure you have setup the optimizer before.Úlr©Ú	optimizerrQ  Úparam_groups)rÄ   Úgroups   & r   Úget_learning_ratesrá  Ö  sB   € ð ‡~�~ÒÜÐkÓlÐlØ%)§^¡^×%@Ò%@ÓAÑ%@˜E�$�KˆKÑ%@ÑAÐAùÒAs   ²Ac                ó„   € V ^8„  d   QhR\         \        P                  P                  P                  ,          R,          /# )r"   ÚparamN)rJ  r$   r   Ú	parameterÚ	Parameter)r(   s   "r   r)   r)   à  s0   € ÷ Fñ F¤S¬5¯8©8×+=Ñ+=×+GÑ+GÕ%GÈ$Õ%Nñ Fr    c                óú   € V P                   f   \        R4      hVe/   V P                   P                   F  pWR,          9   g   K  Vu # 	  V P                   P                   Uu. uF  q"R,          NK  	  up# u upi )zï
Returns optimizer group for a parameter if given, else returns all optimizer groups for params.

Args:
    param (`str` or `torch.nn.parameter.Parameter`, *optional*):
        The parameter for which optimizer group needs to be returned.
rÛ  ÚparamsrÝ  )rÄ   rã  rà  s   && r   Úget_optimizer_grouprè  à  sm   € ð ‡~�~ÒÜÐkÓlÐlØÒØ—^‘^×0Ô0ˆEØ˜h�Ö'Ø’ñ 1ð *.¯©×)DÒ)DÓEÑ)D �(�OˆOÑ)DÑEÐEùÒEs   Á$A8c                ó|   aa€ \        4       '       d   R oMR o\        VV3R lV P                  4        4       4      # )zg
Calculate model's total param count. If trainable_only is True then count only those requiring grads.
c                 ó^   € \        V R 4      '       d   V P                  # V P                  4       # )Úds_numel)r   rë  r!  ©rÔ  s   &r   r!  Ú$get_model_param_count.<locals>.numel÷  s#   € Ü!(¨¨J×!7Ò!7�1—:‘:ÐF¸Q¿W¹W»YÐFr    c                 ó"   € V P                  4       # r+   )r!  rì  s   &r   r!  rí  ü  s   € Ø—7‘7“9Ðr    c              3   ól   <"  € T F)  pS'       d   VP                   '       g   K  S! V4      x € K+  	  R # 5ir+   )rÓ  )rJ   rÔ  r!  Útrainable_onlys   & €€r   rM   Ú(get_model_param_count.<locals>.<genexpr>ÿ  s#   øé € Ð]Ñ!3˜A¿>ÈQÏ_Í_Œx‰u�Q�xˆxÓ!3ùs   ƒ4�4¤4)r   r  r×  )rÖ  rð  r!  s   &f@r   Úget_model_param_countrò  ñ  s5   ù€ ô "×#Ò#ó	Gò
	ô Õ] ×!1Ñ!1Ô!3Ó]Ó]Ð]r    c                óž  aa	a
€ Ve'   V Uu. uF  p\         P                  ! V4      NK  	  upM. p. pV P                  4        F’  w  o
p\        WaV4      pTV Uau. uFk  o\	        V\        V4      4      '       d   K   \        ;QJ d     VV
3R lV 4       F  '       g   K   RM	  RM! VV
3R lV 4       4      '       d   Kd  S
 RS 2NKm  	  up,          pK”  	  TV P                   U	a	u. uFG  o	\        ;QJ d    V	3R lV 4       F  '       g   K   RM	  RM! V	3R lV 4       4      '       d   KE  S	NKI  	  up	,          pV# u upi u upi u up	i )zR
Returns the names of the model parameters that are not inside a forbidden layer.
c              3   ój   <"  € T F(  qP                  S R S 2P                  4       4      x € K*  	  R# 5i)rF   N©ÚsearchÚlower)rJ   ÚpatternrL   rt   s   & €€r   rM   Ú&get_parameter_names.<locals>.<genexpr>  s0   øé € ÐfÑMeÀ'Ÿ™¨$¨¨q°° }×':Ñ':Ó'<×=Ð=ÓMeùs   ƒ03TFrF   c              3   ó`   <"  € T F#  qP                  SP                  4       4      x € K%  	  R # 5ir+   rõ  )rJ   rø  rW   s   & €r   rM   rù    s#   øé € Ð/rÑYqÈg·±¸q¿w¹w»y×0IÐ0IÓYqùs   ƒ+.)ÚreÚcompileÚnamed_childrenÚget_parameter_namesr,   rQ   ÚanyÚ_parameters)rÖ  Úforbidden_layer_typesÚforbidden_layer_namesrø  Úforbidden_layer_patternsr;   ÚchildÚchild_paramsrL   rW   rt   s   &&&     ``@r   rþ  rþ    s'  ú€ ð
 G\ÒFgÑ,AÓBÑ,A Œ�Š�GÖ	Ñ,AÒBÐmoð ð €FØ×+Ñ+Ö-‰ˆˆeÜ*¨5ÐI^Ó_ˆØá!ô
á!�Ü˜e¤UÐ+@Ó%A×Bô ÷ “CÕfÑMeÓf—C—C’CÕfÑMeÓf×fô ˆtˆf�A�a�S‹MÙ!ñ
õ 	
Šñ .ð Ø×$Ò$ôÙ$ˆa¯C«CÔ/rÑYqÓ/r¯C¯CªCÔ/rÑYqÓ/r×,r�ˆÑ$ñõ €Fð €Mùò! 	Cùò

ùòs;   ŒE ÁEÁ<
EÂEÂEÃ EÃ(E
Ã8E
ÄE
Ä/E
c                óâ   € \        V P                  4       4      pV P                  P                  V8X  d   V P                  # \	        V4      ^ 8X  d   R# V F  p\        W14      pVf   K  Vu # 	  R# )z›
Gets a class from a module by its name.

Args:
    module (`torch.nn.Module`): The module to get the class from.
    name (`str`): The name of the class.
N)rP   ÚchildrenrÇ   rÒ   r2   Úget_module_class_from_name)Úmodulert   Úmodules_childrenÚchild_moduleÚmodule_classs   &&   r   r  r    sg   € ô ˜FŸO™OÓ-Ó.ÐØ×Ñ× Ñ  DÔ(Ø×ÑÐÜ	ÐÓ	 !Ô	#Ùã,ˆLÜ5°lÓIˆLØÔ'Ø#Ò#ó -r    c                 óä   € V '       dh   V F_  p\         P                  P                  W4      p\         P                  P                  V4      '       g   KI  \         P                  ! V4       Ka  	  R # R # r+   )r½  r¾  r¿  ÚisfileÚremove)Úis_main_processrÁ  Ú	filenamesÚfilenameÚfiles   &&&  r   Úremove_dummy_checkpointr  .  sD   € ßÛ!ˆHÜ—7‘7—<‘< 
Ó5ˆDÜ�w‰w�~‰~˜d×#Ô#Ü—	’	˜$–ó "ñ r    c                 ó˜   € V ! R/ VB p\        V\        4      '       d
   VR ,          MV^ ,          pWB,          pV P                  V4       V# )Úlossrç   )r,   r  Úbackward)rÖ  ÚinputsÚgradient_accumulation_stepsÚoutputsr  s   &&&  r   Úsmp_forward_backwardr  9  sA   € á‘/˜&‘/ˆÜ",¨W´d×";Ò";ˆw�vŽÀÈÅˆØÕ+ˆØ�‰�tÔØˆr    c                 ó   € V ! R/ VB # )Nrç   rç   )rÖ  r  s   &&r   Úsmp_forward_onlyr  A  s   € á‰�v‰Ðr    c           
      óœ  € \        V \        \        34      '       d   \        V 4      ! R  V  4       4      # \        V \        4      '       d>   \        V 4      ! V P                  4        UUu/ uF  w  rV\        V4      bK  	  upp4      # \        V \        P                  4      '       g   \        R\        V 4       R24      h\        P                  ! V \        P                  P                  4      pV Uu. uF  p\        V4      NK  	  pp\        P                  ! V Uu. uF  qDP!                  4       NK  	  up^ R7      # u uppi u upi u upi )c              3   ó8   "  € T F  p\        V4      x € K  	  R # 5ir+   )r•   r_   s   & r   rM   Úsmp_gather.<locals>.<genexpr>G  s   é € Ð>±v°!¤
¨1§ ³vùra   z Can't gather the values of type z-, only of nested list/tuple/dicts of tensors.r/   )r,   rP   rQ   rO   r  rS   r•   r$   r%   rT   ÚsmpÚ	allgatherÚ	CommGroupÚDP_GROUPr-   r4   rb   )r~   rW   r¨  Úall_tensorsrK   s   &    r   r•   r•   E  sù   € Ü�fœt¤U˜m×,Ò,Ü˜”<Ñ>±vÓ>Ó>Ð>Ü˜¤×%Ò%Ü˜”<¸f¿l¹l¼nÔ M¹n±d°a ¤J¨q£MÒ!1¹nÒ MÓNÐNÜ˜F¤E§L¡L×1Ò1ÜØ2´4¸³<°.Ð@mÐnóð ô —m’m F¬C¯M©M×,BÑ,BÓCˆÙ.9Ó:©k¨”z !–}©kˆÐ:Ü�yŠy©;Ó7©; aŸ%™%ž'©;Ñ7¸QÔ?Ð?ùó !Nùò ;ùÚ7s   Á)D>
Ã3EÄE	c           
      ót  € \        V \        \        34      '       d   \        V 4      ! R  V  4       4      # \        V \        4      '       d>   \        V 4      ! V P                  4        UUu/ uF  w  rV\        V4      bK  	  upp4      # V P                  4       P                  4       P                  4       # u uppi )c              3   ó8   "  € T F  p\        V4      x € K  	  R # 5ir+   )Úsmp_nested_concatr_   s   & r   rM   Ú$smp_nested_concat.<locals>.<genexpr>T  s   é € ÐE¹f¸Ô 1°!× 4Ð 4»fùra   )
r,   rP   rQ   rO   r  rS   r(  rm   r�   rb   )r~   rW   r¨  s   &  r   r(  r(  R  sŒ   € Ü�fœt¤U˜m×,Ò,Ü˜”<ÑE¹fÓEÓEÐEÜ˜¤×%Ò%Ü˜”<ÀVÇ\Á\Ä^Ô TÁ^¹T¸Q Ô$5°aÓ$8Ò!8Á^Ò TÓUÐUð �}‰}‹×%Ñ%Ó'×+Ñ+Ó-Ð-ùó !Us   Á)B4
c                   óø   a € ] tR tRt o Rt]! RRR/R7      t]! RRR/R7      t]! R	RR
/R7      t]! R	RR/R7      t	]! RRR/R7      t
]! RRR/R7      t]! RRR/R7      t]R 4       tR tRR ltV 3R ltRtV tR# )ÚAcceleratorConfigi\  aÇ  
A subset of arguments relating to the underlying [`accelerate.Accelerator`]
implementation utilized in the `Trainer` that can be customized.
Mostly relating to data.

Parameters:
    split_batches (`bool`, *optional*, defaults to `False`):
        Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. If
        `True` the actual batch size used will be the same on any kind of distributed processes, but it must be a
        round multiple of the `num_processes` you are using. If `False`, actual batch size used will be the one set
        in your script multiplied by the number of processes.
    dispatch_batches (`bool`, *optional*):
        If set to `True`, the dataloader prepared by the Accelerator is only iterated through on the main process
        and then the batches are split and broadcast to each process. Will default to `True` for `DataLoader` whose
        underlying dataset is an `IterableDataset`, `False` otherwise.
    even_batches (`bool`, *optional*, defaults to `True`):
        If set to `True`, in cases where the total batch size across all processes does not exactly divide the
        dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among
        all workers.
    use_seedable_sampler (`bool`, *optional*, defaults to `True`):
        Whether or not use a fully seedable random sampler ([`accelerate.data_loader.SeedableRandomSampler`]). Ensures
        training results are fully reproducible using a different sampling technique. While seed-to-seed results
        may differ, on average the differences are negligible when using multiple different seeds to compare. Should
        also be ran with [`~utils.set_seed`] for the best results.
    gradient_accumulation_kwargs (`dict`, *optional*):
        Additional kwargs to configure gradient accumulation, see [`accelerate.utils.GradientAccumulationPlugin`].
        Any of the following (optional) keys are acceptable:
          num_steps (`int`): Will take precedence over [`~.TrainingArguments.gradient_accumulation_steps`] if
            the latter is set to 1, otherwise an exception will be raised.
          sync_each_batch (`bool`): Whether to synchronize the gradients at each data batch.
            The [`accelerate.utils.GradientAccumulationPlugin`] default is `False`.
    non_blocking (`bool`, *optional*, defaults to `False`):
        Whether to use non-blocking CUDA calls to help minimize synchronization during
        distributed training with prepared `DataLoader` inputs being moved to device.
        Best if used with `pin_memory=True` in the `TrainingArguments`.
    use_configured_state (`bool*, *optional*, defaults to `False`):
        Whether or not to use a pre-configured `AcceleratorState` or `PartialState` defined
        before calling `TrainingArguments`. If `True`, an `Accelerator` or `PartialState`
        must be initialized. May lead to issues using sweeps or hyperparameter tuning.

FÚhelpau  Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. If `True` the actual batch size used will be the same on any kind of distributed processes, but it must be a round multiple of the `num_processes` you are using. If `False`, actual batch size used will be the one set in your script multiplied by the number of processes.)ÚdefaultÚmetadataNa  If set to `True`, the dataloader prepared by the Accelerator is only iterated through on the main process and then the batches are split and broadcast to each process. Will default to `True` for `DataLoader` whose underlying dataset is an `IterableDataslet`, `False` otherwise.TzÝIf set to `True`, in cases where the total batch size across all processes does not exactly divide the dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among all workers.a}  Whether or not use a fully seedable random sampler ([`accelerate.data_loader.SeedableRandomSampler`]).Ensures training results are fully reproducible using a different sampling technique. While seed-to-seed results may differ, on average the differences are negligible when usingmultiple different seeds to compare. Should also be ran with [`~utils.set_seed`] for the best results.zùWhether to use non-blocking CUDA calls to help minimize synchronization during distributed training with prepared `DataLoader` inputs being moved to device. Best if used with `pin_memory=True` in the `TrainingArguments`. Requires accelerate v0.30.0.aé  Additional kwargs to configure gradient accumulation, see [`accelerate.utils.GradientAccumulationPlugin`]. Any of the following (optional) keys are acceptable:   num_steps (`int`): Will take precedence over [`~.TrainingArguments.gradient_accumulation_steps`] if     the latter is set to 1, otherwise an exception will be raised.   sync_each_batch (`bool`): Whether to synchronize the gradients at each data batch.     The [`accelerate.utils.GradientAccumulationPlugin`] default is `False`.zóWhether or not to use a pre-configured `AcceleratorState` or `PartialState` defined before calling `TrainingArguments`.If `True`, an `Accelerator` or `PartialState` must be initialized. May lead to issues using sweeps or hyperparameter tuning.c                ó‚  a € \         P                  P                  V4      '       d   \        P                  M\        pV! VR RR7      ;_uu_ 4       p\
        P                  ! V4      pRRR4       \        V 3R lX 4       4      p\        V4      ^ 8”  d   \        RV RV R24      hS ! R/ VB #   + '       g   i     LO; i)	Úrzutf-8)ÚencodingNc              3   óL   <"  € T F  qSP                   9  g   K  Vx € K  	  R # 5ir+   )Ú__dataclass_fields__)rJ   r9  Úclss   & €r   rM   Ú3AcceleratorConfig.from_json_file.<locals>.<genexpr>Ð  s   øé € Ð^©; CÀS×E]ÑE]Ñ:]ŸCšC«;ùs   ƒ$š
$zThe config file at z had unknown keys (zu), please try upgrading your `transformers` version or fix (and potentially remove these keys) from your config file.rç   )
r½  r¾  rÅ  ÚiorÂ  rÃ  rÆ  r=  r2   rQ  )r4  Ú	json_fileÚ	open_filerÉ  Úconfig_dictÚ
extra_keyss   f&    r   Úfrom_json_fileÚ AcceleratorConfig.from_json_fileÉ  s¤   ø€ ô  "Ÿw™wŸ~™~¨i×8Ò8”B—G’G¼dˆ	Ù�y #°×8Õ8¸AÜŸ)š) A›,ˆK÷ 9ô Ô^©;Ó^Ó^ˆ
Üˆz‹?˜QÔÜØ% i [Ð0CÀJÀ<ð P]ð ]óð ñ Ñ!�[Ñ!Ð!÷ 9×8ús   ÁB.Â.B>	c                óB   € \         P                  ! V P                  4      # r+   )rŒ  ÚdeepcopyÚ__dict__ró   s   &r   Úto_dictÚAcceleratorConfig.to_dictØ  s   € Ü�}Š}˜TŸ]™]Ó+Ð+r    c                ó8   € V P                   P                  W4      # r+   )r?  Úpop)rÄ   r9  r-  s   &&&r   rC  ÚAcceleratorConfig.popÛ  s   € Ø�}‰}× Ñ  Ó.Ð.r    c                óŠ   <€ V ^8„  d   Qh/ S[ ;R&   S[ R,          ;R&   S[ ;R&   S[ ;R&   S[ ;R&   S[R,          ;R&   S[ ;R&   # )	r"   Úsplit_batchesNÚdispatch_batchesÚeven_batchesÚuse_seedable_samplerÚnon_blockingÚgradient_accumulation_kwargsÚuse_configured_state)rà   r  )r(   rÛ   s   "€r   r)   ÚAcceleratorConfig.__annotate__\  s„   ø‡ ‚ ñZ ñ ñ[ ñl ˜T•kñ ñm ñ| ñ ñ} ñL ñ ñM ñ` ñ ña ñt #'¨¥+ñ 
ñu ñJ ñ òK r    rç   r+   )rÒ   rÓ   rÔ   rÕ   rÖ   r   rF  rG  rH  rI  rJ  rK  rL  Úclassmethodr;  r@  rC  r1  r×   rØ   r÷   s   @r   r+  r+  \  sþ   ø‡ € ñ(ñV  Øàð Eð
ô€Mñ %*Øàð Oð
ô%Ðñ Øàð ð
ô€Lñ "'Øàð uð
ô"Ðñ Øàð ð
ô€Lñ 16Øàð Zð
ô
1Ð ñ "'Øàð Kð
ô"Ðð ñ"ó ð"ò,ô/÷ ƒ r    r+  c                   óf   a a€ ] tR tRt oRtR	V 3R lltR
V3R lR lltR	V3R lR lltRtVt	V ;t
# )ÚLayerWiseDummyOptimizeriß  aÈ  
For Layer-wise optimizers such as GaLoRE optimizer, the optimization
step is already done through the post gradient hooks. Therefore
the trick is to create a dummy optimizer that can take arbitrary
args and kwargs and return a no-op during training.

Initial idea from @hiyouga in LLaMA-Factory:
https://github.com/hiyouga/LLaMA-Factory/commit/8664262cde3919e10eaecbd66e8c5d356856362e#diff-ebe08ab14496dfb9e06075f0fdd36799ef6d1535cc4dd4715b74c4e3e06fe3ba
c                óˆ   <€ \         P                  ! ^^4      pWn        \        SV `  V.RVP                  RR4      /4       R# )r¯   rÜ  gü©ñÒMbP?N)r$   ÚrandnÚoptimizer_dictrÁ   rÂ   Úget)rÄ   rS  rÆ   Údummy_tensorrÇ   s   &&, €r   rÂ   Ú LayerWiseDummyOptimizer.__init__ê  s:   ø€ Ü—{’{ 1 aÓ(ˆØ,ÔÜ‰Ñ˜,˜¨$°·
±
¸4ÀÓ0GÐ)HÖIr    c                ó$   <€ V ^8„  d   QhRS[ RR/# )r"   Úset_to_noner€   N)rà   )r(   rÛ   s   "€r   r)   Ú$LayerWiseDummyOptimizer.__annotate__ï  s   ø€ ÷ ñ ¡Tð °Tñ r    c                ó   € R # r+   rç   )rÄ   rX  s   &&r   Ú	zero_gradÚ!LayerWiseDummyOptimizer.zero_gradï  ó   € Ùr    c                ó.   <€ V ^8„  d   QhRS[ R,          /# ræ   )rª   )r(   rÛ   s   "€r   r)   rY  ò  s   ø€ ÷ ñ ¡E¨D¥Lñ r    c                ó   € R # r+   rç   )rÄ   Úclosures   &&r   ÚstepÚLayerWiseDummyOptimizer.stepò  r]  r    )rS  r+   ©T)rÒ   rÓ   rÔ   rÕ   rÖ   rÂ   r[  ra  r×   rØ   rÙ   rÚ   s   @@r   rP  rP  ß  s)   ù‡ € ñ÷J÷
ò ÷÷ ò r    rP  c                   óB   a a€ ] tR tRt oRtV 3R ltR tR tRtVt	V ;t
# )ÚLayerWiseDummyScheduleriö  a  
For Layer-wise optimizers such as GaLoRE optimizer, the optimization and scheduling step
are already done through the post gradient hooks. Therefore
the trick is to create a dummy scheduler that can take arbitrary
args and kwargs and return a no-op during training.
c                ó\   <€ VR ,          V n         \        R/ VB pRp\        SV `  W44       R# )rÜ  Nrç   rœ   )Ú
default_lrrP  rÁ   rÂ   )rÄ   rÀ  rÆ   rÞ  Ú
last_epochrÇ   s   &*,  €r   rÂ   Ú LayerWiseDummyScheduler.__init__þ  s-   ø€ Ø  �,ˆŒÜ+Ñ5¨fÑ5ˆ	Øˆ
Ü‰Ñ˜Ö/r    c           	     ó  € V P                   .pV P                  eg   V P                  P                  P                  4        UUu. uF$  q"P                   Uu. uF  q3R,          NK  	  upNK&  	  ppp\        \        V!  4      pV# u upi u uppi )NrÜ  )rg  rÞ  rS  rZ   rß  rP   r   )rÄ   ÚlrsÚoptimrà  Úparam_wise_lrss   &    r   Úget_lrÚLayerWiseDummyScheduler.get_lr  sƒ   € à�‰Ðˆð �>‰>Ò%àKOÏ>É>×KhÑKh×KoÑKoÔKqôÙKqÀ%×*<Ò*<Ó=Ñ*< �t—�Ñ*<Ô=ÑKqð ñ ô ”u˜nÑ-Ó.ˆCàˆ
ùò	 >ùós   ÁB	ÁBÁ&B	ÂB	c                ó   € V P                   # r+   )Úbase_lrsró   s   &r   Ú_get_closed_form_lrÚ+LayerWiseDummyScheduler._get_closed_form_lr  s   € Ø�}‰}Ðr    )rg  )rÒ   rÓ   rÔ   rÕ   rÖ   rÂ   rn  rr  r×   rØ   rÙ   rÚ   s   @@r   re  re  ö  s   ù‡ € ñõ0ò÷ò r    re  c                ó@  € V P                  4       pRp V'       d$   VP                  P                  W$,          4       R# VP                  P                  W$,          4       R#   \         d1   p\
        P                  TP                  YR7      4        Rp?R# Rp?ii ; i)zIHelper to set RNG state for a specific device type (CUDA, NPU, MLU, MUSA)zµDidn't manage to set back the RNG states of the {backend} because of the following error:
 {exception}
This won't yield the same results as if the training had not been interrupted.)ÚbackendÚ	exceptionN)r÷  ÚrandomÚset_rng_state_allÚset_rng_stateÚ	ExceptionrR  Úerrorr(   )Údevice_nameÚdevice_moduleÚcheckpoint_rng_stateÚis_distributedÚdevice_state_keyÚerr_templateÚes   &&&&   r   Úset_rng_state_for_devicerƒ    s�   € à"×(Ñ(Ó*Ðð M€LðLßØ× Ñ ×2Ñ2Ð3GÕ3YÖZà× Ñ ×.Ñ.Ð/CÕ/UÖVøÜô Lä�‰�\×(Ñ(°Ð(ÓJ×KÒKûðLús!   ”A" œ!A" ¿!A" Á"BÁ-%BÂBc                 óš  € \         P                  ! \        P                  4      P                  \         P                  ! R4      P                  8  d   \
        P                  ! 4       # \         P                  ! \        P                  4      \         P                  ! R4      8¼  d   \        P                  M\        P                  p V P                  P                  \        P                  \        P                  .pV\        \        P                  ! \        P                  4      4      .,          p\        P                   P#                  V4      # )aþ  
Context manager to allowlist numpy objects for torch.load with weights_only=True.

Starting from version 2.4 PyTorch introduces a check for the objects loaded
with torch.load(weights_only=True). Starting from 2.6 weights_only=True becomes
a default and requires allowlisting of objects being loaded.

See: https://github.com/pytorch/pytorch/pull/137602
See: https://pytorch.org/docs/stable/notes/serialization.html#torch.serialization.add_safe_globals
See: https://github.com/huggingface/accelerate/pull/3036
z2.6z2.0.0)r
   Úparser$   Ú__version__ÚreleaseÚ
contextlibÚnullcontextr&   Ú_corerw   Ú
multiarrayÚ_reconstructr'   rc   rO   Úuint32ÚserializationÚsafe_globals)Únp_coreÚ	allowlists     r   r�  r�  #  sÆ   € ô ‡}‚}”U×&Ñ&Ó'×/Ñ/´'·-²-ÀÓ2F×2NÑ2NÔNÜ×%Ò%Ó'Ð'ä!Ÿ-š-¬¯©Ó7¼7¿=º=ÈÓ;QÔQŒb�hŠhÔWY×W^ÑW^€GØ×#Ñ#×0Ñ0´"·*±*¼b¿h¹hÐG€Ið ”$”r—x’x¤§	¡	Ó*Ó+Ð,Õ,€Iä×Ñ×+Ñ+¨IÓ6Ð6r    )rö   r+   )NNrc  r0  )r¯   )rrÖ   rˆ  rŒ  r™  r6  rÃ  rf  r½  rû  Úsysr²   Úcollections.abcr   r   r   Údataclassesr   r   Ú	itertoolsr   r   r   Útypingr	   rg   r&   r$   Útorch.distributedÚdistributedrŠ   Ú	packagingr
   r   Útorch.utils.datar   r   r   r   Útorch.utils.data.distributedr   Úintegrations.deepspeedr   Útokenization_utils_baser   rù   r   r   r   r   Úadd_handlerÚstdoutÚtorch_xla.runtimeÚruntimerü   Útorch.optim.lr_schedulerr   Ú
get_loggerrÒ   rR  r   r-   r<   rD   rI   rY   r^   rk   rr   r„   r“   r¥   r©   r­   r·   r½   r¿   rÝ   rÿ   r  r
  r  r  rE  rG  r\  rr  r‚  r�  r©  r¹  rË  rÏ  rØ  rá  rè  rò  rþ  r  r  Ú!smdistributed.modelparallel.torchÚmodelparallelr!  ra  r  r  r•   r(  r+  rl  Ú	OptimizerrP  re  rƒ  r�  rç   r    r   Ú<module>r§     sŒ  ðñó Û Û Û 	Û Û Û 	Û 	Û 
Û ß -Ý %ß (Ý Ý !Ý ã Û Ý  Ý Ý ß MÓ MÝ ;å >Ý 2÷õ ñ  ×!Ò!Ø×Ò™ c§j¡jÓ1Ô2á×ÒÝ"á×ÒÝ4ð 
×	Ò	˜HÓ	%€ò"õôô$ô$Tò.Eò$ò NòY÷"Iô&ò&*ð^ &*Ø"'§,¢,¨vÓ"6÷Iò&5ð ôó ðôÐ!3ô ÷81ñ 1õh_ôWôòð ÷'Lð 'Ló ð'LôT ?ôF(˜7ô (ôVRÐ&8ô Rôj,<�7ô ,<ô^fk˜?ô fkòRAõò6WLôv#@òN
"õNõB÷Fô"^ô"ò0$ò( ñ ×Òß3Ð3à‡X‚XƒZóó ðð 	‡X‚XƒZñó ðò@ò.ð ÷/ð /ó ð/ôD˜eŸk™k×3Ñ3ô ô.˜kô ò>Lô7r    