U
    0-e                     @  sH  d dl mZ 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mZmZ d dlZddlmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ ddlm Z  ed	d
rd dl!m"  m#Z$ ed	d
rd dl%Z%ddddZ&dd Z'G dd dej(Z)ed	d
se*ne)Z+G dd dZ,G dd dZ-G dd dZ.dS )    )annotationsN)contextmanager)partial)AnyCallableOptional   )DistributedTypeDynamoBackendGradientAccumulationPluginget_ccl_versionget_int_from_envis_ccl_availableis_deepspeed_availableis_fp8_availableis_ipex_availableis_mps_availableis_npu_availableis_tpu_availableis_xpu_availableparse_choice_from_envparse_flag_from_env)SageMakerDistributedTypeF)Zcheck_deviceboolreturnc                   C  s
   t ji kS )z
    Checks if the `AcceleratorState` has been initialized from `Accelerator`. Same as `AcceleratorState.initialized`,
    but works as a module method.
    )AcceleratorState_shared_state r   r   Q/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/accelerate/state.pyis_initialized7   s    r    c                  O  s   d S Nr   )argskwargsr   r   r   
do_nothing@   s    r$   c                   @  s2   e Zd ZdZdddddZddd	Zd
d ZdS )ThreadLocalSharedDicta  
    Descriptor that holds a dict shared between instances of a class in the same thread.

    Note: Descriptors have slightly different semantics than just a dict field on its own.
    `PartialState(...)._shared_state` and `PartialState._shared_state` (instance vs class) give the same value: the
    underlying _storage dict. Likewise, `PartialState(...)._shared_state = {...}` overrides the _storage dict inside
    the descriptor as you would expect. However, `PartialState._shared_state = {}` actually replaces the descriptor
    object with a dict instead Thus, you should modify the _storage dict in-place (e.g. `_shared_state.clear()`).

    See Python documentation for an explanation of descriptors: https://docs.python.org/3/howto/descriptor.html

    This is required for using PyTorch/XLA with PJRT in multithreaded mode (required for TPU v2 and v3).

    See https://github.com/pytorch/xla/blob/r2.0/docs/pjrt.md#multithreading-on-tpu-v2v3
    Fr   )thread_localc                 C  s
   i | _ d S r!   Z_storage)selfr&   r   r   r   __init__U   s    zThreadLocalSharedDict.__init__Nc                 C  s   | j S r!   r'   )r(   objobjtyper   r   r   __get__X   s    zThreadLocalSharedDict.__get__c                 C  s
   || _ d S r!   r'   )r(   r*   valuer   r   r   __set__[   s    zThreadLocalSharedDict.__set__)F)N)__name__
__module____qualname____doc__r)   r,   r.   r   r   r   r   r%   D   s   
r%   c                   @  sD  e Zd ZdZe Zd9ddddZddd	d
Zedd Z	e
ddddZe
dd Ze
ddddZe
ddddZe
ddddZdd ZddddZed:dddddZed d! Zed"d# Zd;d%d&d'd(Zd<d%d&d)d*Zd%d&d+d,Zd=d%d-d.d/d0Zd>d%d-d1d2d3Zd4d5 Ze
d6dd7d8Zd$S )?PartialStateah  
    Singleton class that has information about the current training environment and functions to help with process
    control. Designed to be used when only process control and device execution states are needed. Does *not* need to
    be initialized from `Accelerator`.

    **Available attributes:**

        - **device** (`torch.device`) -- The device to use.
        - **distributed_type** ([`~accelerate.state.DistributedType`]) -- The type of distributed environment currently
          in use.
        - **local_process_index** (`int`) -- The index of the current process on the current server.
        - **mixed_precision** (`str`) -- Whether or not the current script will use mixed precision, and if so the type
          of mixed precision being performed. (Choose from 'no','fp16','bf16 or 'fp8').
        - **num_processes** (`int`) -- The number of processes currently launched in parallel.
        - **process_index** (`int`) -- The index of the current process.
        - **is_last_process** (`bool`) -- Whether or not the current process is the last one.
        - **is_main_process** (`bool`) -- Whether or not the current process is the main one.
        - **is_local_main_process** (`bool`) -- Whether or not the current process is the main one on the local node.
        - **debug** (`bool`) -- Whether or not the current script is being run in debug mode.
    Fr   )cpuc                 K  s  | j | _| js|| _d | _tjdd }|d k	r<t	|nd | _	t
d| _|dd }|d krtjdddkotjdtjk}|r0|s0tjdtjks|rtj| _dd l}tj stjjd	d
 d	| _tj | _tj | _ttjdd| _| j	d krt	d| j| _	tj| j	 nt rr|srtj | _t!" | _t!# | _t!$ | _t!% | _	ndtjdddkrttjdddkr|st& st'dtj(| _tj sddl)m*} |dd  t+rt, rd| _nd| _|j-f | jdd| tj | _tj | _ttjdd| _| j	d krt+ rt	d| j| _	| j	d k	rtj.| j	 n*t	d| j| _	| j	d k	rtj| j	 d| _/n"ttjdddkr|stj0 rtj| _tj s*|dd| _| jd krd| _tjjf d| ji| tj | _tj | _ttjdd| _| j	d krrt	d| j| _	tj| j	 nRt1 rB|sBttjdddkrBtj2| _tj s|dd  d| _tjjf d| ji| tj | _tj | _ttjdd| _| j	d kr0t	d| j| _	tj3| j	 nt4ddddgddkr|srt+ rrtj5| _ntj6| _t, rt4dgddks| jtj5krt7 d krdd l8}ndd l9}d}	ntj: rd!}	nd"}	t4d#d$d%d&gd}
t4ddddgd}t4dd'd(d)gd}t4d*d+d,gd}|| _t;|
tjd#< t;|tjd< t;|tjd< tjd-d sld.tjd-< tjd/d s||kr|	d!krt<d0| jtj6kr t4d1d2gddkr dd l=}t|j>dd3| }|dkrd}t?| t@Ad4| d5 tj s:|dd  |	| _tjj| jf|
|d6| tj | _tj | _|rft	d7| _	n0t+ rt	d| j| _	tj.| j	 n| jB| _	n>tj| _d| _d | _| _| j	d kr|rt	d7n| jB| _	t
d8d| _Cd S )9NZACCELERATE_TORCH_DEVICEZACCELERATE_DEBUG_MODEZ_use_sagemaker_dpZACCELERATE_USE_SAGEMAKERfalsetrueZ%ACCELERATE_SAGEMAKER_DISTRIBUTED_TYPEr   Zsmddp)backendZ
LOCAL_RANKcudaACCELERATE_USE_DEEPSPEEDz_DeepSpeed is not available => install it using `pip3 install deepspeed` or build it from source)commr7   ZcclZncclF)Zdist_backendZauto_mpi_discoveryxpunoZhcclnpuZPMI_SIZEZOMPI_COMM_WORLD_SIZEZMV2_COMM_WORLD_SIZEZ
WORLD_SIZEr   ZCCL_WORKER_COUNTz1.12ZmpiZglooZRANKZPMI_RANKZOMPI_COMM_WORLD_RANKZMV2_COMM_WORLD_RANKZMPI_LOCALRANKIDZOMPI_COMM_WORLD_LOCAL_RANKZMV2_COMM_WORLD_LOCAL_RANKZMPI_LOCALNRANKSZOMPI_COMM_WORLD_LOCAL_SIZEZMV2_COMM_WORLD_LOCAL_SIZEZMASTER_PORTZ29500ZMASTER_ADDRzwLooks like distributed multinode run but MASTER_ADDR env not set, please try exporting rank 0's hostname as MASTER_ADDRZOMP_NUM_THREADSZMKL_NUM_THREADS)Zlogicalz4OMP_NUM_THREADS/MKL_NUM_THREADS unset, we set it at z to improve oob performance.)rankZ
world_sizer4   ZFORK_LAUNCHED)Dr   __dict__initializedZ_cpur7   osenvirongettorchdevicer   debugpopr   NOZDATA_PARALLELr	   	MULTI_GPUdistributed_typeZ,smdistributed.dataparallel.torch.torch_smddpdistributedr    Zinit_process_groupZget_world_sizenum_processesZget_rankprocess_indexintlocal_process_indexr9   Z
set_devicer   TPUxmZxrt_world_sizeZget_ordinalZget_local_ordinalZ
xla_devicer   AssertionError	DEEPSPEEDZ	deepspeedr;   r   r   Zinit_distributedr<   _mixed_precisionis_availabler   	MULTI_NPUr>   r   	MULTI_XPU	MULTI_CPUr   oneccl_bindings_for_pytorch	torch_cclZis_mpi_availablestr
ValueErrorpsutil	cpu_countZset_num_threadswarningswarndefault_deviceZfork_launched)r(   r4   r#   Z
env_deviceZuse_sagemaker_dpZsmdistributeddistrZ   r[   r7   r?   sizeZ
local_rankZ
local_sizer^   Znum_cpu_threads_per_processr   r   r   r)   |   s8   





*&



  





zPartialState.__init__r\   r   c                 C  sB   d| j  | jrd| j nd d| j d| j d| j d| j dS )	NzDistributed environment: z  Backend:  z
Num processes: z
Process index: z
Local process index: z	
Device: 
)rK   r7   rM   rN   rP   rF   r(   r   r   r   __repr__+  s    @zPartialState.__repr__c                   C  s   t j  dS zCResets `_shared_state`, is used internally and should not be calledN)r3   r   clearr   r   r   r   _reset_state4  s    zPartialState._reset_statec                 C  s
   | j i kS )z7Returns whether the `PartialState` has been initialized)r   rg   r   r   r   rA   9  s    zPartialState.initializedc                 C  s   | j tjko| jdkS )P
        Whether the Accelerator is configured for distributed training
        r   )rK   r	   rI   rM   rg   r   r   r   use_distributed>  s    zPartialState.use_distributedc                 C  s   | j | jd kS )3Returns whether the current process is the last oner   )rN   rM   rg   r   r   r   is_last_processE  s    zPartialState.is_last_processc                 C  s   | j tjkr| jdkS | jS )7Returns whether the current process is the main processr   )rK   r	   MEGATRON_LMrN   ro   rg   r   r   r   is_main_processJ  s    zPartialState.is_main_processc                 C  s   | j tjkr| jdkS | jS )IReturns whether the current process is the main process on the local noder   )rK   r	   rq   rP   ro   rg   r   r   r   is_local_main_processQ  s    
z"PartialState.is_local_main_processc                 C  sH   | j tjtjtjtjtjtjfkr.tj	
  n| j tjkrDtd dS )a  
        Will stop the execution of the current process until every other process has reached that point (so this does
        nothing when the script is only run in one process). Useful to do before saving a model.

        Example:

        ```python
        >>> # Assuming two GPU processes
        >>> import time
        >>> from accelerate.state import PartialState

        >>> state = PartialState()
        >>> if state.is_main_process:
        ...     time.sleep(2)
        >>> else:
        ...     print("I'm waiting for the main process to finish its sleep...")
        >>> state.wait_for_everyone()
        >>> # Should print on every process at the same time
        >>> print("Everyone is here")
        ```
        z"accelerate.utils.wait_for_everyoneN)rK   r	   rJ   rW   rX   rY   rT   FSDPrE   rL   ZbarrierrQ   rR   Z
rendezvousrg   r   r   r   wait_for_everyoneZ  s    zPartialState.wait_for_everyone)is_mainc                 c  s"   |s|    d V  |r|    d S r!   )rv   )r(   rw   r   r   r   _goes_first|  s
    zPartialState._goes_first"list | tuple | dict | torch.Tensorinputsapply_paddingc                 #  s   j dkr|V  dS t|t|tr`t|t| d  tfdd| D s`tdt	
j  j }| }t|j  dkrjj d kr} fdd  |||V  dS )	a}  
        Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing
        distributed inference, such as with different prompts.

        Note that when using a `dict`, all keys need to have the same number of elements.

        Args:
            inputs (`list`, `tuple`, `torch.Tensor`, or `dict` of `list`/`tuple`/`torch.Tensor`):
                The input to split between processes.
            apply_padding (`bool`, `optional`, defaults to `False`):
                Whether to apply padding by repeating the last element of the input so that all processes have the same
                number of elements. Useful when trying to perform actions such as `gather()` on the outputs or passing
                in less inputs than there are processes. If so, just remember to drop the padded elements afterwards.


        Example:

        ```python
        # Assume there are two processes
        from accelerate import PartialState

        state = PartialState()
        with state.split_between_processes(["A", "B", "C"]) as inputs:
            print(inputs)
        # Process 0
        ["A", "B"]
        # Process 1
        ["C"]

        with state.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs:
            print(inputs)
        # Process 0
        ["A", "B"]
        # Process 1
        ["C", "C"]
        ```
        r   Nr   c                 3  s   | ]}t | kV  qd S r!   )len).0v)lengthr   r   	<genexpr>  s     z7PartialState.split_between_processes.<locals>.<genexpr>z6All values in the dictionary must have the same lengthc                   s   t | tttjfr|t| kr,| dd  }n| || }rt |tjrvddlm}m} ||j	}||| d d}n||d gt|  7 }|S t | t
r|  D ]} | | ||| |< q| S | S d S )Nr8   r   )pad_across_processessend_to_device)Z	pad_index)
isinstancelisttuplerE   ZTensorr}   Zaccelerate.utilsr   r   rF   dictkeys)r{   start_index	end_indexresultr   r   Ztensorized_resultkey)_split_valuesr|   num_samples_per_processr(   r   r   r     s     
z;PartialState.split_between_processes.<locals>._split_values)rM   r}   r   r   r   r   allvaluesr]   mathceilrN   )r(   r{   r|   r   r   r   )r   r|   r   r   r(   r   split_between_processes  s    '


"z$PartialState.split_between_processesc                 c  s   |  | jE dH  dS )a1  
        Lets the main process go first inside a with block.

        The other processes will enter the with block after the main process exits.

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> with accelerator.main_process_first():
        ...     # This will be printed first by process 0 then in a seemingly
        ...     # random order by the other processes.
        ...     print(f"This will be printed by process {accelerator.process_index}")
        ```
        N)rx   rr   rg   r   r   r   main_process_first  s    zPartialState.main_process_firstc                 c  s   |  | jE dH  dS )a9  
        Lets the local main process go inside a with block.

        The other processes will enter the with block after the main process exits.

        Example:

        ```python
        >>> from accelerate.state import PartialState

        >>> state = PartialState()
        >>> with state.local_main_process_first():
        ...     # This will be printed first by local process 0 then in a seemingly
        ...     # random order by the other processes.
        ...     print(f"This will be printed by process {state.local_process_index}")
        ```
        N)rx   rt   rg   r   r   r   local_main_process_first  s    z%PartialState.local_main_process_firstNzCallable[..., Any])functionc                 C  s"   | j std| js| js|S tS )a  
        Decorator that only runs the decorated function on the main process.

        Args:
            function (`Callable`): The function to decorate.

        Example:

        ```python
        >>> from accelerate.state import PartialState

        >>> state = PartialState()


        >>> @state.on_main_process
        ... def print_something():
        ...     print("This will be printed by process 0 only.")


        >>> print_something()
        "This will be printed by process 0 only"
        ```
        zUThe `PartialState` or `Accelerator` must be initialized before calling this function.)rA   r]   rr   rm   r$   r(   r   r   r   r   on_main_process  s
    zPartialState.on_main_processc                 C  s   | j s| js|S tS )a  
        Decorator that only runs the decorated function on the local main process.

        Args:
            function (`Callable`): The function to decorate.

        Example:
        ```python
        # Assume we have 2 servers with 4 processes each.
        from accelerate.state import PartialState

        state = PartialState()


        @state.on_local_main_process
        def print_something():
            print("This will be printed by process 0 only on each server.")


        print_something()
        # On server 1:
        "This will be printed by process 0 only"
        # On server 2:
        "This will be printed by process 0 only"
        ```
        )rt   rm   r$   r   r   r   r   on_local_main_process  s    z"PartialState.on_local_main_processc                 C  s   | j s| js|S tS )a  
        Decorator that only runs the decorated function on the last process.

        Args:
            function (`Callable`): The function to decorate.

        Example:
        ```python
        # Assume we have 4 processes.
        from accelerate.state import PartialState

        state = PartialState()


        @state.on_last_process
        def print_something():
            print(f"Printed on process {state.process_index}")


        print_something()
        "Printed on process 3"
        ```
        )ro   rm   r$   r   r   r   r   on_last_process;  s    zPartialState.on_last_processrO   )r   rN   c                 C  s.   |dkrt | j|dS | j|ks&| js*|S tS )a  
        Decorator that only runs the decorated function on the process with the given index.

        Args:
            function (`Callable`, `optional`):
                The function to decorate.
            process_index (`int`, `optional`):
                The index of the process on which to run the function.

        Example:
        ```python
        # Assume we have 4 processes.
        from accelerate.state import PartialState

        state = PartialState()


        @state.on_process(process_index=2)
        def print_something():
            print(f"Printed on process {state.process_index}")


        print_something()
        "Printed on process 2"
        ```
        N)rN   )r   
on_processrN   rm   r$   )r(   r   rN   r   r   r   r   W  s
    zPartialState.on_process)r   rP   c                 C  s.   |dkrt | j|dS | j|ks&| js*|S tS )aO  
        Decorator that only runs the decorated function on the process with the given index on the current node.

        Args:
            function (`Callable`, *optional*):
                The function to decorate.
            local_process_index (`int`, *optional*):
                The index of the local process on which to run the function.

        Example:
        ```python
        # Assume we have 2 servers with 4 processes each.
        from accelerate import Accelerator

        accelerator = Accelerator()


        @accelerator.on_local_process(local_process_index=2)
        def print_something():
            print(f"Printed on process {accelerator.local_process_index}")


        print_something()
        # On server 1:
        "Printed on process 2"
        # On server 2:
        "Printed on process 2"
        ```
        N)rP   )r   on_local_processrP   rm   r$   )r(   r   rP   r   r   r   r   x  s
    zPartialState.on_local_processc                 O  s   | j rt|| d S r!   )rt   printr(   r"   r#   r   r   r   r     s    zPartialState.printztorch.devicec                 C  s\   t  rdtjd< tdS tj r.tdS t r>tdS t rNtdS tdS dS )	a  
        Returns the default device which is:
        - MPS if `torch.backends.mps.is_available()` and `torch.backends.mps.is_built()` both return True.
        - CUDA if `torch.cuda.is_available()`
        - NPU if `is_npu_available()`
        - CPU otherwise
        1ZPYTORCH_ENABLE_MPS_FALLBACKZmpsr9   zxpu:0r>   r4   N)	r   rB   rC   rE   rF   r9   rV   r   r   rg   r   r   r   rb     s    	





zPartialState.default_device)F)F)N)N)NN)NN)r/   r0   r1   r2   
SharedDictr   r)   rh   staticmethodrk   propertyrA   rm   ro   rr   rt   rv   rx   r   r   r   r   r   r   r   r   r   r   rb   r   r   r   r   r3   d   sB    0	

"	N

!$r3   c                   @  s   e Zd ZdZe Zd+ddddddZedd	d
dZdd Z	d,ddZ
edd Zedd Zed-ddddZedd Zedd	ddZedd	ddZedd	ddZdd  Zed.d!dd"d#d$Zed%d& Zed'd( Zd)d* ZdS )/r   a  
    Singleton class that has information about the current training environment.

    **Available attributes:**

        - **device** (`torch.device`) -- The device to use.
        - **distributed_type** ([`~accelerate.state.DistributedType`]) -- The type of distributed environment currently
          in use.
        - **initialized** (`bool`) -- Whether or not the `AcceleratorState` has been initialized from `Accelerator`.
        - **local_process_index** (`int`) -- The index of the current process on the current server.
        - **mixed_precision** (`str`) -- Whether or not the current script will use mixed precision, and if so the type
          of mixed precision being performed. (Choose from 'no','fp16','bf16 or 'fp8').
        - **num_processes** (`int`) -- The number of processes currently launched in parallel.
        - **process_index** (`int`) -- The index of the current process.
        - **is_last_process** (`bool`) -- Whether or not the current process is the last one.
        - **is_main_process** (`bool`) -- Whether or not the current process is the main one.
        - **is_local_main_process** (`bool`) -- Whether or not the current process is the main one on the local node.
        - **debug** (`bool`) -- Whether or not the current script is being run in debug mode.
    NFr\   r   )mixed_precisionr4   _from_acceleratorc           	      K  s  | j | _tdrd}tj i kr*t|f| | jtj  | || | jsd | _d | _|d krjt	ddn|
 }|dkrt std|| _|std| jtjkrdn|| _| jtjkr|dkrtjd	rtd
tjd< tdtjd< d| _n"tdtjd< td
tjd< d| _ndtjdddkrB|sB|| _n@| jtjkrtjdddkrtj| _| jdkr|| j || _tjdddkrtj| _|| j || _n| jtjkrtjdddkrtj| _| jdkr|| j || _n~| jtjtj tj!fkrt" r4tddd| _nd| _| jtj krtjdddkrtj| _| jdkr||| j || _| jj#t$j!kr| jdkr| j%j&dkrdt'j(j)j*_+| jtj d< d S )NZACCELERATE_USE_CPUTZACCELERATE_MIXED_PRECISIONr=   Zfp8zDUsing `fp8` precision requires `transformer_engine` to be installed.zPlease make sure to properly initialize your accelerator via `accelerator = Accelerator()` before using any functionality from the `accelerate` library.bf16ZACCELERATE_DOWNCAST_BF16r   ZXLA_USE_BF16r   ZXLA_DOWNCAST_BF16Fr:   r5   r6   ZACCELERATE_USE_FSDPZACCELERATE_USE_MEGATRON_LMZACCELERATE_USE_IPEX)defaultr9   rK   ),r   r@   r   r3   update_check_initializedrA   deepspeed_pluginZuse_ipexr   lowerr   r]   dynamo_pluginrK   r	   rT   rU   rQ   rB   rC   rD   r\   Zdowncast_bfloatrJ   ru   Zset_mixed_precisionfsdp_pluginrq   megatron_lm_pluginrW   rY   rX   rI   r   r7   r
   rF   typerE   backendsr9   matmulZ
allow_tf32)	r(   r   r4   r   r   r   r   r   r#   r   r   r   r)     s    




zAcceleratorState.__init__r   c                 C  s   | j tj kS r!   )r   r3   rg   r   r   r   rA   "  s    zAcceleratorState.initializedc                 C  s<   t   d| j d }| jtjkr8|d| jj d7 }|S )Nz
Mixed precision type: rf   zds_config: )r3   rh   r   rK   r	   rT   r   deepspeed_config)r(   reprr   r   r   rh   &  s    zAcceleratorState.__repr__c                 C  sd   | j r`d}|r*| jjdkr*t|jdd|dk	r`|| jkr`| jtjkr`t|jd| dddS )zeChecks if a modification is trying to be made and the `AcceleratorState` has already been initializedzAcceleratorState has already been initialized and cannot be changed, restart your runtime completely and pass `{flag}` to `Accelerator()`.r4   zcpu=True)flagNzmixed_precision='')	rA   rF   r   r]   formatrU   rK   r	   rT   )r(   r   r4   errr   r   r   r   ,  s    
z#AcceleratorState._check_initializedc                 C  s   t dt | jdkS )NzThe `use_fp16` property is deprecated and will be removed in version 1.0 of Accelerate use `AcceleratorState.mixed_precision == 'fp16'` instead.r=   )r`   ra   FutureWarningrU   rg   r   r   r   use_fp16:  s
    zAcceleratorState.use_fp16c                 C  sX   | j tjkrN| jj}|di ddr.d}qT|di ddrHd}qTd}n| j}|S )NZfp16enabledFr   r=   )rK   r	   rT   r   r   rD   rU   )r(   configr   r   r   r   r   C  s    z AcceleratorState.mixed_precisionZreset_partial_statec                 C  s   t j  | rt  dS ri   )r   r   rj   r3   rk   r   r   r   r   rk   Q  s    
zAcceleratorState._reset_statec                 C  s   t  jS )rl   )r3   rm   rg   r   r   r   rm   X  s    z AcceleratorState.use_distributedc                 C  s   t  jS )rn   )r3   ro   rg   r   r   r   ro   _  s    z AcceleratorState.is_last_processc                 C  s   t  jS )rp   )r3   rr   rg   r   r   r   rr   d  s    z AcceleratorState.is_main_processc                 C  s   t  jS )rs   )r3   rt   rg   r   r   r   rt   i  s    z&AcceleratorState.is_local_main_processc                 C  s   t    d S r!   )r3   rv   rg   r   r   r   rv   n  s    z"AcceleratorState.wait_for_everyonery   rz   c              	   c  s&   t  j||d}|V  W 5 Q R X dS )a  
        Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing
        distributed inference, such as with different prompts.

        Note that when using a `dict`, all keys need to have the same number of elements.

        Args:
            inputs (`list`, `tuple`, `torch.Tensor`, or `dict` of `list`/`tuple`/`torch.Tensor`):
                The input to split between processes.
            apply_padding (`bool`, `optional`, defaults to `False`):
                Whether to apply padding by repeating the last element of the input so that all processes have the same
                number of elements. Useful when trying to perform actions such as `gather()` on the outputs or passing
                in less inputs than there are processes. If so, just remember to drop the padded elements afterwards.


        Example:

        ```python
        # Assume there are two processes
        from accelerate.state import AcceleratorState

        state = AcceleratorState()
        with state.split_between_processes(["A", "B", "C"]) as inputs:
            print(inputs)
        # Process 0
        ["A", "B"]
        # Process 1
        ["C"]

        with state.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs:
            print(inputs)
        # Process 0
        ["A", "B"]
        # Process 1
        ["C", "C"]
        ```
        )r|   N)r3   r   )r(   r{   r|   r   r   r   r   q  s    'z(AcceleratorState.split_between_processesc              	   c  s    t    dV  W 5 Q R X dS )z
        Lets the main process go first inside a with block.

        The other processes will enter the with block after the main process exits.
        N)r3   r   rg   r   r   r   r     s    z#AcceleratorState.main_process_firstc              	   c  s    t    dV  W 5 Q R X dS )z
        Lets the local main process go inside a with block.

        The other processes will enter the with block after the main process exits.
        N)r3   r   rg   r   r   r   r     s    z)AcceleratorState.local_main_process_firstc                 O  s   t  j|| d S r!   )r3   r   r   r   r   r   r     s    zAcceleratorState.print)NFNNNNF)NN)F)F)r/   r0   r1   r2   r   r   r)   r   rA   rh   r   r   r   r   rk   rm   ro   rr   rt   rv   r   r   r   r   r   r   r   r   r   r     sH          U



)
	
	r   c                   @  s   e Zd ZdZe Zd"ddddZeddd	d
ZeddddZ	eddddZ
eddddZeddddZeddddZdd Zdd Zdd Zdd ZeddddZed d! ZdS )#GradientStateaE  
    Singleton class that has information related to gradient synchronization for gradient accumulation

    **Available attributes:**

        - **end_of_dataloader** (`bool`) -- Whether we have reached the end the current dataloader
        - **remainder** (`int`) -- The number of extra samples that were added from padding the dataloader
        - **sync_gradients** (`bool`) -- Whether the gradients should be synced across all devices
        - **active_dataloader** (`Optional[DataLoader]`) -- The dataloader that is currently being iterated over
        - **dataloader_references** (`List[Optional[DataLoader]]`) -- A list of references to the dataloaders that are
            being iterated over
        - **num_steps** (`int`) -- The number of steps to accumulate over
        - **adjust_scheduler** (`bool`) -- Whether the scheduler should be adjusted to account for the gradient
            accumulation
        - **sync_with_dataloader** (`bool`) -- Whether the gradients should be synced at the end of the dataloader
            iteration and the number of total steps reset
    Nz$Optional[GradientAccumulationPlugin])gradient_accumulation_pluginc                 C  s\   | j | _| js8d| _d | _d g| _|d k	r2| ni | _|d k	rX| j| krX| | _d S )NT)r   r@   rA   sync_gradientsactive_dataloaderdataloader_referencesZ	to_kwargsplugin_kwargs)r(   r   r   r   r   r)     s    zGradientState.__init__rO   r   c                 C  s   | j ddS )z.Returns the number of steps to accumulate over	num_stepsr   r   rD   rg   r   r   r   r     s    zGradientState.num_stepsr   c                 C  s   | j ddS )z0Returns whether the scheduler should be adjustedadjust_schedulerFr   rg   r   r   r   r     s    zGradientState.adjust_schedulerc                 C  s   | j ddS )zyReturns whether the gradients should be synced at the end of the dataloader iteration and the number of total steps resetsync_with_dataloaderTr   rg   r   r   r   r     s    z"GradientState.sync_with_dataloaderc                 C  s
   t ji kS )z8Returns whether the `GradientState` has been initialized)r   r   rg   r   r   r   rA     s    zGradientState.initializedc                 C  s   | j s
dS | jjS )zAReturns whether we have reached the end of the current dataloaderF)in_dataloaderr   end_of_dataloaderrg   r   r   r   r     s    zGradientState.end_of_dataloaderc                 C  s   | j s
dS | jjS )zOReturns the number of extra samples that were added from padding the dataloaderr8   )r   r   	remainderrg   r   r   r   r     s    zGradientState.remainderc              	   C  s&   d| j  d| j d| j d| j d	S )NzSync Gradients: z
At end of current dataloader: z
Extra samples added: z
Gradient accumulation plugin: rf   )r   r   r   r   rg   r   r   r   rh     s    $zGradientState.__repr__c                 C  s
   || _ dS )zhPrivate function that sets whether gradients should be synchronized. Users should not have to call this.N)r   )r(   r   r   r   r   _set_sync_gradients   s    z!GradientState._set_sync_gradientsc                 C  s   || _ | j| j  dS )zPrivate function that adds a dataloader to `self.dataloader_references` and sets `in_dataloader` to `True`. Users should not have to call this.N)r   r   appendr(   Z
dataloaderr   r   r   _add_dataloader  s    zGradientState._add_dataloaderc                 C  s   | j | | j d | _dS )zPrivate function that removes a dataloader from `self.dataloader_references` and sets `in_dataloader` to `False` if there are no more dataloaders. Users should not have to call this.r8   N)r   remover   r   r   r   r   _remove_dataloader	  s    z GradientState._remove_dataloaderc                 C  s
   | j dk	S )z6Returns whether the current process is in a dataloaderN)r   rg   r   r   r   r     s    zGradientState.in_dataloaderc                   C  s   t j  dS ri   )r   r   rj   r   r   r   r   rk     s    zGradientState._reset_state)N)r/   r0   r1   r2   r   r   r)   r   r   r   r   rA   r   r   rh   r   r   r   r   r   rk   r   r   r   r   r     s.   r   )/
__future__r   r   rB   	threadingr`   
contextlibr   	functoolsr   typingr   r   r   rE   utilsr	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   Zutils.dataclassesr   Ztorch_xla.core.xla_modelcoreZ	xla_modelrR   Z	torch_npur    r$   localr%   r   r   r3   r   r   r   r   r   r   <module>   s4   D

	    V ~