+
    $LjT                     @   ^ RI t ^ RIt^ RIt^ RIt^ RIHt ^ RI Ht ^ RIHt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 ^RIHt ^RIHt ^RIHt ^RI H!t!H"t"H#t#H$t$H%t% ^RI&H't' ^RI(H)t) ^RI*H+t+ ]! ],4      t-]$! 4       '       d
   ^ RI.H/u H0t1 R R lt2R R lt3R R lt4R R lt5R R lt6R R lt7R R lt8R  R! lt9R8R" R# llt:R$ t;R% R& lt<R9R' R( llt=]"! R)4      '       d   ]P|                  M]P^                  t?]?P                  P                  ]P                  ]]P                  .tD]"! R*4      '       d&   ]DP                  ]P                  P                  4       R:R+ ltHR, tIR- tJR:R. R/ lltKR0 R1 ltLR2 tMR3 tNR4 R5 ltOR;R6 R7 lltPR# )<    N)encode)OrderedDict)partialreduce)
MethodType)Optional)Version)	save_file)write_basic_config)
get_logger)PartialState)FSDP_PYTORCH_VERSION)DistributedType)is_deepspeed_availableis_numpy_availableis_torch_distributed_availableis_torch_xla_availableis_weights_only_available)id_tensor_storage)convert_model)is_torch_versionc                X    V ^8  d   QhR\         P                  P                  R\        /#    modulereturntorchnnModulebool)formats   "B/app/.local/lib/python3.14/site-packages/accelerate/utils/other.py__annotate__r$   6   s&     H Huxx H4 H    c                    \        \        R4      '       g   R# \        V \        P                  P                  P
                  4      # )z<
Check whether the module was compiled with torch.compile()
_dynamoF)hasattrr   
isinstancer'   
eval_frameOptimizedModuler   s   &r#   is_compiled_moduler-   6   s1     5)$$femm66FFGGr%   c                X    V ^8  d   QhR\         P                  P                  R\        /# r   r   )r"   s   "r#   r$   r$   @   s"       T r%   c                    \        \        R4      '       g   R# V P                  '       dO   V P                  4        F:  p\	        V\        P
                  P                  P                  4      '       g   K9   R# 	  R# )zT
Check whether the module has submodules that were compiled with `torch.compile()`.
r'   FT)r(   r   _modulesmodulesr)   r'   r*   r+   r   	submodules   & r#   has_compiled_regionsr4   @   sS     5)$$)I)U]]%=%=%M%MNN * r%   c                X    V ^8  d   QhR\         P                  P                  R\        /# r   r   )r"   s   "r#   r$   r$   O   s"     
 
uxx 
4 
r%   c                   a  \        S \        P                  P                  4      ;'       dQ    \	        S 4      ^ 8  ;'       d;    \
        ;QJ d    V 3R lS  4       F  '       d   K   R# 	  R# ! V 3R lS  4       4      # )z
Check whether the module is a repeated block, i.e. `torch.nn.ModuleList` with all children of the same class. This
is useful to determine whether we should apply regional compilation to the module.
c              3   ^   <"   T F"  p\        VS^ ,          P                  4      x  K$  	  R# 5i)r   N)r)   	__class__).0mr   s   & r#   	<genexpr>%is_repeated_blocks.<locals>.<genexpr>X   s%     CFq
1fQi1122Fs   *-FT)r)   r   r   
ModuleListlenallr,   s   fr#   is_repeated_blocksr@   O   sq     	6588../ 	D 	DK!O	D 	DCCFCCC  CFCCr%   c                X    V ^8  d   QhR\         P                  P                  R\        /# r   r   )r"   s   "r#   r$   r$   \   s"       D r%   c                    V P                   '       d,   V P                  4        F  p\        V4      '       g   K   R# 	  R# )z
Check whether the module has repeated blocks, i.e. `torch.nn.ModuleList` with all children of the same class, at
any level of the module hierarchy. This is useful to determine whether we should apply regional compilation to the
module.
TF)r0   r1   r@   r2   s   & r#   has_repeated_blocksrC   \   s1     )I!),, * r%   c                    V ^8  d   QhR\         P                  P                  R\         P                  P                  /# r   r   r   r    )r"   s   "r#   r$   r$   j   s.     E EEHHOO E%((// Er%   c                j   a R V3R lloS! V 3/ VB pRVP                   9  d   WP                   R&   V# )a  
Performs regional compilation where we target repeated blocks of the same class and compile them sequentially to
hit the compiler's cache. For example, in `GPT2LMHeadModel`, the repeated block/class is `GPT2Block`, and can be
accessed as `model.transformer.h[0]`. The rest of the model (e.g. model.lm_head) is compiled separately.

This allows us to speed up the compilation overhead / cold start of models like LLMs and Transformers in general.
See https://pytorch.org/tutorials/recipes/regional_compilation.html for more details.

Args:
    module (`torch.nn.Module`):
        The model to compile.
    **compile_kwargs:
        Additional keyword arguments to pass to `torch.compile()`.

Returns:
    `torch.nn.Module`: A new instance of the model with some compiled regions.

Example:
```python
>>> from accelerate.utils import compile_regions
>>> from transformers import AutoModelForCausalLM

>>> model = AutoModelForCausalLM.from_pretrained("gpt2")
>>> compiled_model = compile_regions(model, mode="reduce-overhead")
>>> compiled_model.transformer.h[0]
OptimizedModule(
    (_orig_mod): GPT2Block(
            (ln_1): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
            (attn): GPT2Attention(
            (c_attn): Conv1D(nf=2304, nx=768)
            (c_proj): Conv1D(nf=768, nx=768)
            (attn_dropout): Dropout(p=0.1, inplace=False)
            (resid_dropout): Dropout(p=0.1, inplace=False)
        )
        (ln_2): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
        (mlp): GPT2MLP(
            (c_fc): Conv1D(nf=3072, nx=768)
            (c_proj): Conv1D(nf=768, nx=3072)
            (act): NewGELUActivation()
            (dropout): Dropout(p=0.1, inplace=False)
        )
    )
)
```
c                    V ^8  d   QhR\         P                  P                  R\         P                  P                  /# r   rE   )r"   s   "r#   r$   %compile_regions.<locals>.__annotate__   s*       uxx r%   c           	      "  < \        V 4      '       dP   \        P                  P                  4       pV  F)  pVP	                  \        P
                  ! V3/ VB 4       K+  	  V# \        V 4      '       d   V P                  P                  V P                  4      pVP                  P                  V P                  4       / Vn        V P                  4        F  w  rCVP                  VS! V3/ VB 4       K   	  V# \        P
                  ! V 3/ VB pV# N)r@   r   r   r=   appendcompilerC   r8   __new____dict__updater0   named_children
add_module)r   compile_kwargs
new_moduler3   name_compile_regionss   &,   r#   rU   )compile_regions.<locals>._compile_regions   s    f%%,,.J#	!!%--	"L^"LM $  !(())11&2B2BCJ&&v7"$J#)#8#8#:%%d,<Y,Y.,YZ $;
  v@@Jr%   	_orig_mod)rN   )r   rR   rS   rU   s   &, @r#   compile_regionsrX   j   sA    ^   "&;N;J*---+1K(r%   c                L    V ^8  d   QhR\         P                  P                  /# )r   r   rE   )r"   s   "r#   r$   r$      s     ) )ehhoo )r%   c                    \        V 4      '       d   V  F  pVP                  ! R/ VB  K  	  R# \        V 4      '       d&   V P                  4        F  p\	        V3/ VB  K  	  R# V P                  ! R/ VB  R# )a  
Performs regional compilation the same way as `compile_regions`, but specifically for `DeepSpeedEngine.module`.
Since the model is wrapped in a `DeepSpeedEngine` and has many added hooks, offloaded parameters, etc that
`torch.compile(...)` interferes with, version of trgional compilation uses the inplace `module.compile()` method
instead.

Args:
    module (`torch.nn.Module`):
        The model to compile.
    **compile_kwargs:
        Additional keyword arguments to pass to `module.compile()`.
N )r@   rL   rC   childrencompile_regions_deepspeedr   rR   r3   childs   &,  r#   r]   r]      sd     &!!I//  	V	$	$__&E%e>~> ' 	((r%   c                    V ^8  d   QhR\         P                  P                  R\         P                  P                  /# r   rE   )r"   s   "r#   r$   r$      s*      %((//  r%   c                    \        V 4      '       d   V  F  pVP                  ! R/ VB  K  	  V # \        V 4      '       d&   V P                  4        F  p\	        V3/ VB  K  	  V # V P                  ! R/ VB  V # )a  
Like `compile_regions`, but uses the in-place `module.compile()` instead of `torch.compile(module)`.

Needed for the FSDP2 prepare path: `torch.compile(module)` returns an `OptimizedModule` whose `__call__`
bypasses `nn.Module._call_impl`, so forward/pre hooks added later by `fully_shard` never fire and per-layer
all-gather/reshard is lost. The in-place `module.compile()` keeps `_call_impl` (and its runtime hook check)
on the call path, so FSDP hooks installed afterwards still run.

Args:
    module (`torch.nn.Module`):
        The model to compile.
    **compile_kwargs:
        Additional keyword arguments to pass to `module.compile()`.
r[   )r@   rL   rC   r\   compile_regions_fsdp2r^   s   &,  r#   rb   rb      sy     &!!I//   M 
V	$	$__&E!%:>: ' M 	((Mr%   c                X    V ^8  d   QhR\         P                  P                  R\        /# )r   modelr   r   )r"   s   "r#   r$   r$      s&     C CUXX__ C Cr%   c                   a \        RR4      '       d   ^ RIHo M^ RIHo \        ;QJ d-    V3R lV P                  4        4       F  '       g   K   R# 	  R# ! V3R lV P                  4        4       4      # )z
Check if the model has DTensor parameters.

Args:
    model (`torch.nn.Module`):
        The model to check.

Returns:
    `bool`: Whether the model has DTensor parameters.
>=z2.5.0)DTensorc              3   <   <"   T F  p\        VS4      x  K  	  R # 5irJ   )r)   )r9   prg   s   & r#   r;   $model_has_dtensor.<locals>.<genexpr>   s     B/A!z!W%%/As   TF)r   torch.distributed.tensorrg   torch.distributed._tensorany
parameters)rd   rg   s   &@r#   model_has_dtensorro      sU     g&&4 	63Bu/?/?/AB33B3B3Bu/?/?/ABBBr%   c                <    V ^8  d   QhR\         R\         R\         /# )r   keep_fp32_wrapperkeep_torch_compile	recursiver!   )r"   s   "r#   r$   r$      s)     U U"U?CUW[Ur%   c                  a \         P                  P                  P                  \         P                  P                  3p\        V 4      p\        V 4      pRpV'       d   T pV P                  p M.V'       d'   RV P                  9   d   T pV P                  R,          p \        4       '       d   ^ RI
Hp WH3,          p\        R\        4      '       d    \        4       '       d   ^ RIHp	 WI3,          p\#        W4      '       d   V P$                  p K  V'       d   V3R loS! V 4      p V'       g   V P&                  p
V P                  P)                  RR4      pVe8   \+        V
R4      '       d   V
P,                  p
W8X  g   K&   \/        W4      V n        \1        V R	R
4      '       d   \3        V R
R7       V'       d/   Ve+   V'       d   Wn        Tp V # V'       d   WP                  R&   Tp V # )a_  
Extract a model from its distributed containers.

Args:
    model (`torch.nn.Module`):
        The model to extract.
    keep_fp32_wrapper (`bool`, *optional*):
        Whether to remove mixed precision hooks from the model.
    keep_torch_compile (`bool`, *optional*):
        Whether to unwrap compiled model.
    recursive (`bool`, *optional*, defaults to `False`):
        Whether to recursively extract all cases of `module.module` from `model` as well as unwrap child sublayers
        recursively, not just the top-level distributed containers.

Returns:
    `torch.nn.Module`: The extracted model.
NrW   )DeepSpeedEnginerf   )FullyShardedDataParallelc                    < \        V R 4      '       d   S! V P                  4      pMT pVP                  4        F  w  r#\        WS! V4      4       K  	  V# r,   )r(   r   rP   setattr)r   unwrapped_modulerT   r_   _recursive_unwraps   &   r#   r{   6extract_model_from_parallel.<locals>._recursive_unwrap*  sT     vx((#4V]]#C #) />>@(0A%0HI  A##r%   _original_forward__wrapped__ _converted_to_transformer_engineF)to_transformer_engine)r   r   parallelDistributedDataParallelDataParallelr-   r4   rW   rN   r   	deepspeedrv   r   r   r   2torch.distributed.fsdp.fully_sharded_data_parallelrw   r)   r   forwardpopr(   r~   r   getattrr   )rd   rq   rr   rs   optionsis_compiledhas_compiledcompiled_modelrv   FSDPr   original_forwardr{   s   &&&&        @r#   extract_model_from_parallelr      s   ( xx  88%((:O:OPG$U+K'.LN	%..("NNN;/E-%%2338V8X8Xg7
U
$
$
	$ "%(-- >>--.A4H''=11!--.&w6EM5<eDD%u=n8',$"E
 L	 38##K0"ELr%   c                 6    \        4       P                  4        R# )z
Introduces a blocking point in the script, making sure all processes have reached this point before continuing.

<Tip warning={true}>

Make sure all processes will reach this instruction otherwise one of your processes will hang forever.

</Tip>
N)r   wait_for_everyoner[   r%   r#   r   r   P  s     N$$&r%   c                $    V ^8  d   QhR\         /# )r   
state_dict)dict)r"   s   "r#   r$   r$   ]  s          r%   c           	     ,   \         P                  ! \        4      pV P                  4        F>  w  r#\	        V\
        4      '       d   K  V\        V4      ,          P                  V4       K@  	  VP                  4        UUu/ uF  w  rE\        V4      ^8  g   K  WEbK  	  ppp\        4       pVP                  4        FF  pV Uu. uF  q"V 9   g   K  VNK  	  ppVP                  VR,          4       VR,           F  pW K  	  KH  	  \        V4      ^ 8  d   \        P                  RV R24       V P                  4        U	U
u/ uF8  w  rT	\	        V
\        P                  4      '       d   V
P!                  4       MT
bK:  	  p p	p
V # u uppi u upi u up
p	i )z
Cleans the state dictionary from a model and removes tensor aliasing if present.

Args:
    state_dict (`dict`):
        The state dictionary from a model
:   NNzRemoved shared tensor zk while saving. This should be OK, but check by verifying that you don't receive any warning while reloading)collectionsdefaultdictlistitemsr)   strr   rK   r>   setvaluesrO   loggerwarningr   Tensor
contiguous)r   ptrsrT   tensorptrnamesshared_ptrs
warn_namesfound_nameskvs   &          r#    clean_state_dict_for_safetensorsr   ]  sa    ""4(D"((*&#&&"6*+2248 +
 15

O*#E
Q:3:KOJ##% ).D1CttD+b/*OOD  $ & :$ZL  1\  ]	
 WaVfVfVhiVhda!z!U\\'B'BQ\\^IVhJi# P E js    FFFF>Fc                0    V ^8  d   QhR\         R\         /# )r   save_on_each_nodesafe_serializationrt   )r"   s   "r#   r$   r$     s      D d r%   c                   \        4       P                  \        P                  8X  d   \        P
                  ! V 4      p V'       d6   \        \        RR/R7      p\        V \        4      '       d   \        V 4      p M\        P                  p\        4       P                  '       d   V'       g   V! W4       R# \        4       P                  '       d   V'       d   V! W4       R# R# R# )a  
Save the data to disk. Use in place of `torch.save()`.

Args:
    obj:
        The data to save
    f:
        The file (or file-like object) to use to save the data
    save_on_each_node (`bool`, *optional*, defaults to `False`):
        Whether to only save on the global main process
    safe_serialization (`bool`, *optional*, defaults to `False`):
        Whether to save `obj` using `safetensors` or the traditional PyTorch way (that uses `pickle`).
r"   pt)metadataN)r   distributed_typer   XLAxm_maybe_convert_to_cpur   safe_save_filer)   r   r   r   saveis_main_processis_local_main_process)objfr   r   	save_funcs   &&&& r#   r   r     s    $ ~&&/*=*==&&s+Nh5EF	c;''237CJJ	~%%%.?#		-	-	-2C# 3D	-r%   z2.0.0z1.25.0c                |    \        4       '       dO   \        P                  P                  4       pRV9  d   RVR&   \        P                  P	                  \
        4       MVP                  RR4       \        P                  ! V 3RV/VB p\        4       '       dF   \        P                  P                  4        X'       d    \        P                  P	                  V4       V#   \        4       '       dH   \        P                  P                  4        X'       d!   \        P                  P	                  T4       i i i ; i)a  
Compatible drop-in replacement of `torch.load()` which allows for `weights_only` to be used if `torch` version is
2.4.0 or higher. Otherwise will ignore the kwarg.

Will also add (and then remove) an exception for numpy arrays

Args:
    f:
        The file (or file-like object) to use to load the data
    map_location:
        a function, `torch.device`, string or a dict specifying how to remap storage locations
    **kwargs:
        Additional keyword arguments to pass to `torch.load()`.
weights_onlyTNmap_location)	r   r   serializationget_safe_globalsadd_safe_globalsTORCH_SAFE_GLOBALSr   loadclear_safe_globals)r   r   kwargsold_safe_globals
loaded_objs   &&,  r#   r   r     s    G$&&$22CCEV+)-~&001CDJJ~t,ZZGGG
$&&224##445EF	 %&&224##445EF   's   B	C" "6D;"D;c                    \        V R4      '       g    \        V R4      '       g   \        V RV 4      p \        V R4      '       d   V P                  # \        V R4      '       d   V P                  # \	        V 4      # )z 
Gets a pretty name from `obj`.
__qualname____name__r8   )r(   r   r   r   r   )r   s   &r#   get_pretty_namer     sd     3''Z0H0Hc;,sN##sJ||s8Or%   c                    V P                  4        F>  w  r#\        V\        4      '       d    VP                  V/ 4      p\	        W44       K:  W1V&   K@  	  V# )z
Recursively merges two dictionaries.

Args:
    source (`dict`): The dictionary to merge into `destination`.
    destination (`dict`): The dictionary to merge `source` into.
)r   r)   r   
setdefaultmerge_dicts)sourcedestinationkeyvaluenodes   &&   r#   r   r     sM     lln
eT""))#r2D$$ % r%   c                F    V ^8  d   QhR\         \        ,          R\        /# )r   portr   )r   intr!   )r"   s   "r#   r$   r$     s     6 6# 6$ 6r%   c                    V f   Rp \         P                   ! \         P                  \         P                  4      ;_uu_ 4       pVP                  RV 34      ^ 8H  uuRRR4       #   + '       g   i     R# ; i)z
Checks if a port is in use on `localhost`. Useful for checking if multiple `accelerate launch` commands have been
run and need to see if the port is already in use.
Ni<s  	localhost)socketAF_INETSOCK_STREAM
connect_ex)r   ss   & r#   is_port_in_user     sP    
 |	v~~v'9'9	:	:a||[$/0A5 
;	:	:	:s   A##A4	c                $    V ^8  d   QhR\         /# )r   r   )r   )r"   s   "r#   r$   r$     s     
" 
"s 
"r%   c                    \         P                   ! \         P                  \         P                  4      ;_uu_ 4       p V P                  R4       V P	                  4       ^,          uuRRR4       #   + '       g   i     R# ; i)z
Gets a free port on `localhost`. Useful for automatic port selection when port 0 is specified in distributed
training scenarios.

Returns:
    int: An available port number
N) r   )r   r   r   bindgetsockname)r   s    r#   get_free_portr     sI     
v~~v'9'9	:	:a	w}}q! 
;	:	:	:s   (A//B 	c                x    R F&  pV R8  d   \        V ^4       RV 2u # V R,          p K(  	  \        V ^4       R2# )z7Converts `size` from bytes to the largest possible unitg      @ z PB)bytesKBMBGBTB)round)sizexs   & r#   convert_bytesr   	  sJ    .&=D!n%Qqc** /
 D!nS!!r%   c                    \         P                  ! 4       p V P                  pVR8w  d   R# \        P                  ! RV P
                  4      vr#pRp\        V4      \        V4      8  d#   RV RV R2p\        P                  VRR	7       R# R# )
zFWarns if the kernel version is below the recommended minimum on Linux.LinuxNz(\d+\.\d+\.\d+)z5.5.0zDetected kernel version z,, which is below the recommended minimum of zo; this can cause the process to hang. It is recommended to upgrade the kernel to the minimum version or higher.T)main_process_only)	platformunamesystemresplitreleaser	   r   r   )infor   _versionmin_versionmsgs         r#   check_os_kernelr     s     >>D[[FXX0$,,?NAKw'+..&wi/[\g[h is s 	 	sd3 /r%   c                $    V ^8  d   QhR\         /# )r   attr)r   )r"   s   "r#   r$   r$   %  s     5 5 5r%   c                L    R p\        W .VP                  R4      ,           4      # )z
Recursive `getattr`.

Args:
    obj:
        A class instance holding the attribute.
    attr (`str`):
        The attribute that is to be retrieved, e.g. 'attribute1.attribute2'.
c                     \        W4      # rJ   )r   )r   r  s   &&r#   _getattr#recursive_getattr.<locals>._getattr0  s    s!!r%   .)r   r   )r   r  r  s   && r#   recursive_getattrr  %  s#    " (EDJJsO344r%   c                    V ^8  d   QhR\         P                  P                  R\        R\        \         P                  P                  ,          /# )r   rd   return_fqnsr   )r   r   r    r!   r   )r"   s   "r#   r$   r$   6  s<     ! ! !t !X\]b]e]e]l]lXm !r%   c                    V'       g   T MRV 3pV.p. pV'       d   VP                  4       pV'       d   Vw  reVP                  4        Fx  w  rx\        V\        P                  P
                  4      '       g   K1  V'       d/   X'       d   VR,           V,           MTp	VP                  W34       Kg  VP                  V4       Kz  	  V'       d   VP                  XV34       K  VP                  V4       K  VRRR1,          # )a)  Traverse the model in bottom-up order and return the children modules in that order.

Args:
    model (`torch.nn.Module`): the model to get the children of

Returns:
    `list[torch.nn.Module]`: a list of children modules of `model` in bottom-up order. The last element is the
    `model` itself.
r   r  N)r   rP   r)   r   r   r    rK   )
rd   r	  topstackordered_modulescurrent_modulecurrent_module_namerT   r  
child_names
   &&        r#   get_module_children_bottom_upr  6  s     #%UCEEO
2@/(779JD$00EX!4s!:T!A^bJLL*!34LL& : ""$7#HI"">24R4  r%   )TTF)FFrJ   )F)Qr   r   r   r   codecsr   r   	functoolsr   r   typesr   typingr   numpynpr   packaging.versionr	   safetensors.torchr
   r   commands.config.defaultr   loggingr   stater   	constantsr   dataclassesr   importsr   r   r   r   r   modelingr   transformer_enginer   versionsr   r   r   torch_xla.core.xla_modelcore	xla_modelr   r-   r4   r@   rC   rX   r]   rb   ro   r   r   r   r   _corenp_core
multiarray_reconstructndarraydtyper   rK   dtypesUInt32DTyper   r   r   r   r   r   r   r  r  r[   r%   r#   <module>r/     sP     	   # %     % 9 8     + (  ( - & 
H	 ))H
EP)04C(Up
' FH )11"((rww ##JJ
HH  hbii334@
$6
""4$5"! !r%   