
    9i                         d dl Z d dlZd dlZd dlZd dlmZ d dlmZ d dlm	Z	 d dl
Z
d dlmZ ddlmZ ddlmZ dd	lmZ d
dlmZ d
dlmZ d
dlmZmZmZ d
dlmZ d
dlmZ  ee      Z  ed      r	d dl!m"c m#Z$  e       rd dl%m&Z' d Z(d#de)fdZ*d Z+d$de)de)fdZ,ed        Z-ed        Z.d Z/d Z0d%de1de)fd Z2d! Z3d" Z4y)&    N)contextmanager)partial)
MethodType)Version   )write_basic_config)
get_logger)PartialState   )FSDP_PYTORCH_VERSION)DistributedType)is_deepspeed_availableis_safetensors_availableis_tpu_available)convert_model)is_torch_versionF)check_device)	save_filec                     t        dd      st        t        d      syt        | t        j                  j
                  j                        S )zD
    Check whether the module was compiled with torch.compile()
    <z2.0.0_dynamoF)r   hasattrtorch
isinstancer   
eval_frameOptimizedModule)modules    `/var/www/html/backtest/airagagent/rag_env/lib/python3.12/site-packages/accelerate/utils/other.pyis_compiled_moduler   .   s7     W%WUI-Ffemm66FFGG    keep_fp32_wrapperc                    t         j                  j                  j                  t         j                  j                  f}t        |       }|r| }| j                  } t               rddlm	} ||fz  }t        dt              rddlm} ||fz  }t        | |      r| j                  } t        | |      r|st!        | d      }| j"                  j%                  dd      }|<t'        |d      r|j(                  }||k(  rnt'        |d      rt+        ||       | _        t!        | d	d
      rt/        | d
       |r	| _        |} | S )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.

    Returns:
        `torch.nn.Module`: The extracted model.
    r   )DeepSpeedEnginez>=)FullyShardedDataParallelforward_original_forwardN__wrapped__ _converted_to_transformer_engineF)to_transformer_engine)r   nnparallelDistributedDataParallelDataParallelr   	_orig_modr   	deepspeedr#   r   r   2torch.distributed.fsdp.fully_sharded_data_parallelr$   r   r   getattr__dict__popr   r'   r   r%   r   )	modelr!   optionsis_compiledcompiled_modelr#   FSDPr%   original_forwards	            r   extract_model_from_parallelr:   7   s*    xx  88%((:O:OPG$U+K-O%%23gD7
UG
$ UG
$ %+ >>--.A4H''=1!--.. '=1 'w6EM5<eD%u=#( Lr    c                  4    t               j                          y)a  
    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_everyone r    r   r<   r<   k   s     N$$&r    save_on_each_nodesafe_serializationc                 H   |st         j                  nt        t        ddi      }t	               j
                  t        j                  k(  rt        j                  | |       yt	               j                  r|s
 || |       yt	               j                  r|r
 || |       yyy)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`
    formatpt)metadataN)r   saver   safe_save_filer
   distributed_typer   TPUxmis_main_processis_local_main_process)objfr>   r?   	save_funcs        r   rD   rD   x   s{     #5

'.\dfj[k:lI~&&/*=*==
Q		'	'0A#q		-	-2C#q 3D	-r    c               #   p   K   t         j                  } t               t         _        d | t         _        yw)a  
    A context manager that will cache origin `os.environ` and replace it with a empty dictionary in this context.

    When this context exits, the cached `os.environ` will be back.

    Example:

    ```python
    >>> import os
    >>> from accelerate.utils import clear_environment

    >>> os.environ["FOO"] = "bar"
    >>> with clear_environment():
    ...     print(os.environ)
    ...     os.environ["FOO"] = "new_bar"
    ...     print(os.environ["FOO"])
    {}
    new_bar

    >>> print(os.environ["FOO"])
    bar
    ```
    N)osenvirondict)_old_os_environs    r   clear_environmentrS      s$     2 jjOBJ	 BJs   46c               +     K   i }| j                         D ]Y  \  }}|j                         }|t        j                  v rt        j                  |   ||<   t	        |      t        j                  |<   [ d | D ]M  }|j                         }||v r||   t        j                  |<   .t        j                  j                  |d       O yw)a  
    A context manager that will add each keyword argument passed to `os.environ` and remove them when exiting.

    Will convert the values in `kwargs` to strings and upper-case all the keys.

    Example:

    ```python
    >>> import os
    >>> from accelerate.utils import patch_environment

    >>> with patch_environment(FOO="bar"):
    ...     print(os.environ["FOO"])  # prints "bar"
    >>> print(os.environ["FOO"])  # raises KeyError
    ```
    N)itemsupperrO   rP   strr3   )kwargsexisting_varskeyvalues       r   patch_environmentr\      s     $ Mlln %
Uiik"**!#CM#e*

3	% 
 &iik-+C0BJJsOJJNN3%&s   CCc                     t        | d      st        | d      st        | d|       } t        | d      r| j                  S t        | d      r| j                  S t	        |       S )z(
    Gets a pretty name from `obj`.
    __qualname____name__	__class__)r   r1   r^   r_   rW   )rK   s    r   get_pretty_namera      sX     3'Z0Hc;,sN#sJ||s8Or    c                     | j                         D ]9  \  }}t        |t              r|j                  |i       }t	        ||       5|||<   ; |S )z
    Recursively merges two dictionaries.

    Args:
        source (`dict`): The dictionary to merge into `destination`.
        destination (`dict`): The dictionary to merge `source` into.
    )rU   r   rQ   
setdefaultmerge_dicts)sourcedestinationrZ   r[   nodes        r   rd   rd      sU     lln %
UeT"))#r2Dt$$K% r    portreturnc                     | d} t        j                   t         j                  t         j                        5 }|j                  d| f      dk(  cddd       S # 1 sw Y   yxY w)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  	localhostr   )socketAF_INETSOCK_STREAM
connect_ex)rh   ss     r   is_port_in_userq      sS    
 |	v~~v'9'9	: 6a||[$/0A56 6 6s   AA c                 h    dD ]  }| dk  rt        | d       d| c S | dz  } ! t        | d       dS )z7Converts `size` from bytes to the largest possible unit)bytesKBMBGBTBg      @r    z PB)round)sizexs     r   convert_bytesr|      sO    . &=D!n%Qqc**
 D!nS!!r    c                  
   t        j                         } | j                  }|dk7  ryt        j                  d| j
                        ^}}}d}t        |      t        |      k  r!d| d| d}t        j                  |d	       yy)
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   loggerwarning)infor   _versionmin_versionmsgs         r   check_os_kernelr     s     >>D[[FXX0$,,?NAwKw'+..&wi/[\g[h is s 	 	sd3 /r    )T)FF)N)5rO   r   r   rl   
contextlibr   	functoolsr   typesr   r   packaging.versionr   commands.config.defaultr   loggingr	   stater
   	constantsr   dataclassesr   importsr   r   r   transformer_enginer   versionsr   r_   r   torch_xla.core.xla_modelcore	xla_modelrH   safetensors.torchr   rE   r   boolr:   r<   rD   rS   r\   ra   rd   intrq   r|   r   r=   r    r   <module>r      s    
  	  %    % 8     + ( W W - & 
H	 '))=H1$ 1h
'D d . ! !@  &  &F
$6 6 6"4r    