U
    0-ef                     @   s*  d dl Z d dl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mZmZ ddlmZ ddlmZ eddrd dlm  mZ e rd dlmZ dd Zd'edddZ dd Z!d(ddZ"edd Z#edd Z$dd Z%d d! Z&d)e'ed"d#d$Z(d%d& Z)dS )*    N)contextmanager)
MethodType   )write_basic_config)PartialState   )FSDP_PYTORCH_VERSION)DistributedType)is_deepspeed_availableis_safetensors_availableis_tpu_available)convert_model)is_torch_versionF)Zcheck_device)	save_filec                 C   s(   t ddsttdsdS 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   Z
eval_frameZOptimizedModule)module r   W/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/accelerate/utils/other.pyis_compiled_module&   s    r   T)keep_fp32_wrapperc           	      C   s   t jjjt jjf}t| }|r(| }| j} t rDddlm	} ||f7 }t
dtrdddlm} ||f7 }t| |rv| j} qd|st| d}| jdd}|dk	rt|dr|j}||krqqt|| | _t| d	d
rt| d
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forwardZ_original_forwardN__wrapped__Z _converted_to_transformer_engineF)Zto_transformer_engine)r   nnparallelZDistributedDataParallelZDataParallelr   Z	_orig_modr
   Z	deepspeedr   r   r   Z2torch.distributed.fsdp.fully_sharded_data_parallelr   r   r   getattr__dict__popr   r   r   r   r   )	modelr   optionsZis_compiledZcompiled_modelr   ZFSDPr   Zoriginal_forwardr   r   r   extract_model_from_parallel/   s8    





r%   c                   C   s   t    dS )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_everyoner   r   r   r   r&   c   s    
r&   c                 C   sP   t  jtjkrt| | n0t  jdkrL|r@t| |ddid nt| | dS )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
        safe_serialization (`bool`, *optional*, defaults to `False`): Whether to save `obj` using `safetensors`
    r   formatpt)metadataN)	r   Zdistributed_typer	   ZTPUxmsaveZlocal_process_indexsafe_save_filer   )objfZsafe_serializationr   r   r   r+   p   s    	r+   c                  c   s   t j} t t _dV  | t _dS )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)Z_old_os_environr   r   r   clear_environment   s    r2   c                  k   s   i }|   D ]6\}}| }|tjkr4tj| ||< t|tj|< qdV  | D ]2}| }||krr|| tj|< qNtj|d qNdS )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upperr/   r0   strr"   )kwargsZexisting_varskeyvaluer   r   r   patch_environment   s    
r9   c                 C   sH   t | ds t | ds t| d| } t | dr0| jS t | dr@| jS t| S )z(
    Gets a pretty name from `obj`.
    __qualname____name__	__class__)r   r    r:   r;   r5   )r-   r   r   r   get_pretty_name   s    

r=   c                 C   s@   |   D ]2\}}t|tr2||i }t|| q|||< q|S )z
    Recursively merges two dictionaries.

    Args:
        source (`dict`): The dictionary to merge into `destination`.
        destination (`dict`): The dictionary to merge `source` into.
    )r3   r   r1   
setdefaultmerge_dicts)sourcedestinationr7   r8   noder   r   r   r?      s    

r?   )portreturnc              
   C   sF   | dkrd} t  t jt j }|d| fdkW  5 Q R  S Q R X dS )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)rC   sr   r   r   is_port_in_use   s    rK   c                 C   sB   dD ],}| dk r(t | d d|   S | d } qt | d dS )z7Converts `size` from bytes to the largest possible unit)bytesZKBMBGBTBg      @r    z PB)round)sizexr   r   r   convert_bytes   s
    
rT   )T)F)N)*r/   rF   
contextlibr   typesr   r   Zcommands.config.defaultr   stater   	constantsr   dataclassesr	   Zimportsr
   r   r   Ztransformer_enginer   versionsr   Ztorch_xla.core.xla_modelcoreZ	xla_modelr*   Zsafetensors.torchr   r,   r   boolr%   r&   r+   r2   r9   r=   r?   intrK   rT   r   r   r   r   <module>   s6   
	4

 
#