a
    dM                     @   s   d dl Z d dl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mZ dd	lmZ dd
lmZ e rd dlmZ eddrd dlm  mZ dd Zd!edddZdd Zdd Zedd Zdd Zdd Zd"e eddd Z!dS )#    N)contextmanager   )write_basic_config)PartialState   )DistributedType)is_deepspeed_availableis_tpu_available)convert_model)is_torch_version)DeepSpeedEngineF)Zcheck_devicec                 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   _/var/www/html/stable-diffusion-webui/venv/lib/python3.9/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 r8|tf7 }t	| |rJ| j
} q8|st| d}| jdd}|durt|dr|j}||krnqqn|| _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.
    forwardZ_original_forwardN__wrapped__Z _converted_to_transformer_engineF)Zto_transformer_engine)r   nnparallelZDistributedDataParallelZDataParallelr   Z	_orig_modr   r   r   r   getattr__dict__popr   r   r   r
   )modelr   optionsZis_compiledZcompiled_modelr   Zoriginal_forwardr   r   r   extract_model_from_parallel-   s0    



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!   Z   s    
r!   c                 C   s8   t  jtjkrt| | nt  jdkr4t| | dS )z
    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
    r   N)r   Zdistributed_typer   ZTPUxmsaveZlocal_process_indexr   )objfr   r   r   r#   g   s    r#   c                  k   sR   |   D ]\}}t|tj| < qdV  | D ]}| tjv r.tj| = q.d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strosenvironupper)kwargskeyvaluer   r   r   patch_environmentu   s    r.   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/   r0   r'   )r$   r   r   r   get_pretty_name   s    

r2   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.
    )r&   r   dict
setdefaultmerge_dicts)sourceZdestinationr,   r-   noder   r   r   r5      s    

r5   )portreturnc                 C   sR   | du rd} t  t jt j"}|d| fdkW  d   S 1 sD0    Y  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)r8   sr   r   r   is_port_in_use   s    r@   )T)N)"r(   r;   
contextlibr   r   Zcommands.config.defaultr   stater   Zdataclassesr   Zimportsr   r	   Ztransformer_enginer
   versionsr   Z	deepspeedr   Ztorch_xla.core.xla_modelcoreZ	xla_modelr"   r   boolr    r!   r#   r.   r2   r5   intr@   r   r   r   r   <module>   s,   
	-
