
    g                       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mZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z(  e"            r	d dl)m*c m+Z,  ed	
          rd dl-Z- e d	
          rd dl.Z. e!d	
          rd dl/Z/ ej0        e1          Z2ddZ3d Z4 G d dej5                  Z6 e"            se7ne6Z8 G d d          Z9 G d d          Z: G d d          Z;dS )    )annotationsN)contextmanager)partial)AnyCallableOptional   )DistributedTypeDynamoBackendGradientAccumulationPlugincheck_cuda_p2p_ib_supportcheck_fp8_capabilitydeepspeed_requiredget_ccl_versionget_cpu_distributed_informationget_int_from_envis_ccl_availableis_datasets_availableis_deepspeed_availableis_fp8_availableis_ipex_availableis_mlu_availableis_mps_availableis_musa_availableis_npu_availableis_torch_xla_availableis_xpu_availableparse_choice_from_envparse_flag_from_envset_numa_affinity)SageMakerDistributedTypeF)check_devicereturnboolc                 "    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     L/var/www/html/ai-engine/env/lib/python3.11/site-packages/accelerate/state.pyis_initializedr+   F   s    
 )R//r)   c                     d S Nr(   )argskwargss     r*   
do_nothingr0   O   s    4r)   c                  *    e Zd ZdZd	d
dZddZ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
    Fthread_localr$   c                    i | _         d S r-   _storage)selfr3   s     r*   __init__zThreadLocalSharedDict.__init__d   s    r)   Nc                    | j         S r-   r5   )r7   objobjtypes      r*   __get__zThreadLocalSharedDict.__get__g   s
    }r)   c                    || _         d S r-   r5   )r7   r:   values      r*   __set__zThreadLocalSharedDict.__set__j   s    r)   F)r3   r$   r-   )__name__
__module____qualname____doc__r8   r<   r?   r(   r)   r*   r2   r2   S   sZ                     r)   r2   c                     e Zd ZdZ e            Zg dZd.d/dZd0d	Ze	d
             Z
ed1d            Zed             Zed1d            Zed1d            Zed1d            Zd Zd2dZed.d3d            Zed             Zed             Zd4d5dZd4d5dZd5dZd6d7d!Zd6d8d#Zd$ Zed9d&            Z	 d:d;d)Zd* Zd4d+Z d<d-Z!dS )=PartialStateaQ  
    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`.

    Args:
        cpu (`bool`, *optional*):
            Whether or not to force the script to execute on CPU. Will ignore any accelerators available if set to
            `True` and force the execution on the CPU.
        kwargs (additional keyword arguments, *optional*):
            Additional keyword arguments to pass to the relevent `init_process_group` function. Valid `kwargs` can be
            found in [`utils.InitProcessGroupKwargs`]. See the example section for detailed usage.

    **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.

    Example:
    ```python
    from accelerate.utils import InitProcessGroupKwargs

    # To include `InitProcessGroupKwargs`, init then call `.to_kwargs()`
    kwargs = InitProcessGroupKwargs(...).to_kwargs()
    state = PartialState(**kwargs)
    ```
    )_cpu_mixed_precisionr'   backenddebugdevicedistributed_typefork_launchedlocal_process_indexnum_processesprocess_indexFcpur$   c                    | j         | _        | j        sT|| _        d | _        t
          j                            dd           }|t          j	        |          nd | _	        t          d          | _        |                    dd           }d }|Qt
          j                            dd          dk    o,t
          j                            d          t          j        k    }|                    dd           }|                     |||          \  }}|||k    rt!          d	| d
|           || _        || _        d}	|s	| j        dk    rt%          t
          j                            dd                    dk    rt
          j                            dd          dk    rOt'                      st)          d          ddlm}
 |
                                s |
j        d+| j        dd| d}	nZ| j        t2          j        t2          j        fvr;t          j                                        st          j        j        d+d| j        i| | j        t2          j        t2          j        fv rt=                      }t?          |j                   t
          j        d<   t?          |j!                  t
          j        d<   t?          |j"                  t
          j        d<   t?          |j#                  t
          j        d<   t
          j                            dd           sdt
          j        d<   t
          j                            dd           s*|j#        |j!        k    r| j        dk    rt!          d          |j         |d<   |j!        |d<   | j        t2          j        k    rxtI          dgd          dk    rcdd l%}t%          |&                    d           |j#        z            }|dk    rd!}t          j'        |           tQ          j)        d"| d#           t          j                                        st          j        j        d+d| j        i| | j        (t2          j        | _        d!| _*        d| _+        d| _,        nW| j        dk    r| -                                 t]          j/        | j	        t]          j0                               t]          j1                    | _*        t]          j2                    | _+        tg          d$          rt]          j4                    | _,        nt%          t
          j                            dd                    | _,        nt          j        5                                | _*        t          j        6                                | _+        |-t%          t
          j                            dd                    n|j"        | _,        | -                                 |	rt2          j7        | _        t          d%d          rtq          | j,                   | j	        j9        d&k    r9tu                      s+d't
          j        vsd(t
          j        vrtw          d)          t          d*d          | _<        d S ),NACCELERATE_TORCH_DEVICEACCELERATE_DEBUG_MODE_use_sagemaker_dpACCELERATE_USE_SAGEMAKERfalsetrue%ACCELERATE_SAGEMAKER_DISTRIBUTED_TYPErI   zYour assigned backend z is not avaliable, please use Fxla
LOCAL_RANKACCELERATE_USE_DEEPSPEEDz_DeepSpeed is not available => install it using `pip3 install deepspeed` or build it from sourcer   )comm)dist_backendauto_mpi_discoveryTRANK
WORLD_SIZELOCAL_WORLD_SIZEMASTER_PORT29500MASTER_ADDRmpizTried to launch on distributed with multinode, but `MASTER_ADDR` env was not set, please try exporting rank 0's hostname as `MASTER_ADDR`rank
world_sizeOMP_NUM_THREADS)logicalr	   z4OMP_NUM_THREADS/MKL_NUM_THREADS unset, we set it at z to improve oob performance.check_is_tpuACCELERATE_CPU_AFFINITYcudaNCCL_P2P_DISABLENCCL_IB_DISABLEzUsing RTX 4000 series doesn't support faster communication broadband via P2P or IB. Please set `NCCL_P2P_DISABLE="1"` and `NCCL_IB_DISABLE="1" or use `accelerate launch` which will do this automatically.FORK_LAUNCHEDr(   )=r'   __dict__initializedrG   rI   osenvirongettorchrK   r   rJ   popr!   NO_prepare_backend
ValueErrorrL   intr   ImportError	deepspeedr^   r+   init_distributedr
   	MULTI_XPU	MULTI_CPUdistributedinit_process_groupr   strrh   ri   
local_ranklocal_world_sizer   psutil	cpu_countset_num_threadswarningswarnrO   rP   rN   
set_devicexmset_replicationget_xla_supported_devicesxrt_world_sizeget_ordinalr   get_local_ordinalget_world_sizeget_rank	DEEPSPEEDr    typer   NotImplementedErrorrM   )r7   rQ   r/   
env_deviceuse_sagemaker_dpdist_informationoriginal_backendrI   rL   use_deepspeeddistr   num_cpu_threads_per_processs                r*   r8   zPartialState.__init__   sY   * y	DIDL(A4HHJ6@6L%,z222RVDK,-DEEDJ%zz*=tDD#'JNN#=wGG6Q o
'NOOSkSnn !  &zz)T::(,(=(=cCSUe(f(f%G%+;K0K0K !s:J!s!sjq!s!sttt"DL$4D!!M ]4<500rz~~lB7788B>>z~~&@'JJfTT577 "- !B# #  ;:::::#2244 q1D1pt|`eppioppp(, -o6OQ`Qj5kkk % 1 @ @ B B l )<\\T\\U[\\\$)BOD](^^^#B#D#D %()9)>%?%?
6"+./?/J+K+K
<(+./?/J+K+K
<(145E5V1W1W
-.z~~mT:: 807BJ}-
}d;;(9=M=XXX--$R   "2!6v'7'B|$ )_-FFF(*;)<a@@AEE!MMM25(((77:J:[[3 3/ 3a77673)*EFFFM(Oj ( ( (  
 (7799 Y%8XXXQWXXX |#(7(:%%&"%&"+,((&&!!!"4;0L0N0NOOO%'%6%8%8"%'^%5%5")t<<< U/1/C/E/ED,,/22:>>,PR3S3S/T/TD,,%*%6%E%E%G%G"%*%6%?%?%A%A"=M=UC
|R88999[k[v ( OO B(7(A% ##<eDD <!$":;;; {6))2K2M2M)%RZ77;LTVT^;^;^-6   1!DDr)   r#   r   c                ~    d| j          | j        r
d| j        z   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: 
)rL   rI   rO   rP   rN   rK   r7   s    r*   __repr__zPartialState.__repr__(  s    '(= 'aeam?uPTP\@\@\su ' '"0' '"0' ' %)$<' ' {	' ' '	
r)   c                 B    t           j                                         dS zCResets `_shared_state`, is used internally and should not be calledN)rF   r'   clearr(   r)   r*   _reset_statezPartialState._reset_state1  s     	"((*****r)   c                    | j         i k    S )z7Returns whether the `PartialState` has been initialized)r'   r   s    r*   rt   zPartialState.initialized6  s     !R''r)   c                B    | j         t          j        k    o
| j        dk    S )P
        Whether the Accelerator is configured for distributed training
        r	   )rL   r
   rz   rO   r   s    r*   use_distributedzPartialState.use_distributed;  s#    
 $(::Ut?QTU?UUr)   c                (    | j         | j        dz
  k    S )3Returns whether the current process is the last oner	   )rP   rO   r   s    r*   is_last_processzPartialState.is_last_processB  s     !T%7!%;;;r)   c                P    | j         t          j        k    r| j        dk    n| j        S )7Returns whether the current process is the main processr   )rL   r
   MEGATRON_LMrP   r   r   s    r*   is_main_processzPartialState.is_main_processG  s-     (,'<@['['[D!##aeau	
r)   c                P    | j         t          j        k    r| j        dk    n| j        S )IReturns whether the current process is the main process on the local noder   )rL   r
   r   rN   r   r   s    r*   is_local_main_processz"PartialState.is_local_main_processN  s0    
 $(CCC $))%	
r)   c           	     ^   | j         t          j        t          j        t          j        t          j        t          j        t          j        t          j        t          j	        fv r t          j                                         dS | j         t          j        k    rt          j        d           dS 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)rL   r
   	MULTI_GPU	MULTI_MLU
MULTI_MUSA	MULTI_NPUr   r   r   FSDPrx   r   barrierXLAr   
rendezvousr   s    r*   wait_for_everyonezPartialState.wait_for_everyoneW  s    ,  %%&%%%% 	%
 	
 	
 %%'''''"o&999M>????? :9r)   is_mainc              #  n   K   |s|                                   d V  |r|                                   d S d S r-   )r   )r7   r   s     r*   _goes_firstzPartialState._goes_first{  sS       	%""$$$ 	%""$$$$$	% 	%r)   inputs"list | tuple | dict | torch.Tensorapply_paddingc              #  2   K    j         dk    r|V  dS t          |          t          |t                    rvt          |t	          |                                          d                            t          fd|                                D                       st          d          t           j                   \  } j
        z  t           j
        |          z   }|z    j
        |k     rdndz   } f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`, `dict` of `list`/`tuple`/`torch.Tensor`, or `datasets.Dataset`):
                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  >   K   | ]}t          |          k    V  d S r-   )len).0vlengths     r*   	<genexpr>z7PartialState.split_between_processes.<locals>.<genexpr>  s.      AAAs1vv'AAAAAAr)   z6All values in the dictionary must have the same lengthc                   t          | t          t          t          j        f          r|t          |           k    r| dd          }n
| ||         }rit          |t          j                  r-ddlm}m}  ||j	                  } ||| d                   }n"||d         gdz   t          |          z
  z  z  }|S t          | t                    r/|                                 D ]} 
| |         ||          | |<   | S t                      rddlm} t          | |          r|t          |           k    rt          |           dz
  }|t          |           k    rt          |           }t          t          ||                    }	r|	|dz
  gdz   t          |	          z
  z  z  }	|                     |	          S | S )Nr\   r   )pad_across_processessend_to_device)	pad_indexr	   )Dataset)
isinstancelisttuplerx   Tensorr   accelerate.utilsr   r   rK   dictkeysr   datasetsr   rangeselect)r   start_index	end_indexresultr   r   tensorized_resultkeyr   result_idcs_split_valuesr   num_samples_per_processr7   s             r*   r   z;PartialState.split_between_processes.<locals>._split_values  s   &4"=>>  #f++--#BCC[FF#K	$9:F  ]!&%,77 ]YYYYYYYY -;N64;,O,O)!5!56GSYZ\S]!^!^!^6":,2IA2MPSTZP[P[2["\\FD)) !;;== U UC"/-s[)"T"TF3KK(** :000000!&'22 :&#f++55*-f++/K$s6{{22(+FI&*5i+H+H&I&I( n'IM?>UXY>Y\_`k\l\l>l+mmK%}}[999r)   )rO   r   r   r   r   r   allvaluesr|   divmodrP   min)	r7   r   r   
num_extrasr   r   r   r   r   s	   ` `   @@@r*   split_between_processesz$PartialState.split_between_processes  sS     N ""LLLFVfd## 	[V[[]] 3 3A 6788FAAAAAAAAA [ !YZZZ.4VT=O.P.P+(+BBSI[]gEhEhh"99$BTWaBaBaQQghi	!	 !	 !	 !	 !	 !	 !	 !	F mFK;;;;;;;r)   c              #  J   K   |                      | j                  E d{V  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)r   r   r   s    r*   main_process_firstzPartialState.main_process_first  s7      & ##D$899999999999r)   c              #  J   K   |                      | j                  E d{V  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)r   r   r   s    r*   local_main_process_firstz%PartialState.local_main_process_first  s7      & ##D$>???????????r)   NfunctionCallable[..., Any]c                \    | 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.)rt   r|   r   r   r0   r7   r   s     r*   on_main_processzPartialState.on_main_process  s?    0  	vtuuu 	t'; 	Or)   c                0    | 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"
        ```
        )r   r   r0   r   s     r*   on_local_main_processz"PartialState.on_local_main_process%  s$    6 % 	T-A 	Or)   c                0    | 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"
        ```
        )r   r   r0   r   s     r*   on_last_processzPartialState.on_last_processD  s$    0  	t'; 	Or)   rP   r}   c                h    |t          | j        |          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)rP   )r   
on_processrP   r   r0   )r7   r   rP   s      r*   r   zPartialState.on_process`  s@    6 4?-HHHH-//9M/Or)   rN   c                h    |t          | j        |          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)rN   )r   on_local_processrN   r   r0   )r7   r   rN   s      r*   r   zPartialState.on_local_process  sC    < 40FYZZZZ$(;;;TEY;Or)   c                0    | j         rt          |i | d S d S r-   )r   printr7   r.   r/   s      r*   r   zPartialState.print  s0    % 	#4"6"""""	# 	#r)   torch.devicec                    t                      r#dt          j        d<   t          j        d          S t                      rt          j        d          S t                      rt          j        d          S t                      rt          j        d          S t          j        	                                rt          j        d          S t                      rt          j        d          S t          j        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()`
        - MLU if `is_mlu_available()`
        - MUSA if `is_musa_available()`
        - NPU if `is_npu_available()`
        - CPU otherwise
        1PYTORCH_ENABLE_MPS_FALLBACKmpsmlumusanpuro   xpurQ   )r   ru   rv   rx   rK   r   r   r   ro   is_availabler   r   s    r*   default_devicezPartialState.default_device  s      	'8;BJ45<&&& 	'<&&&   	'<'''  	'<&&&Z$$&& 	'<''' 	'<&&&<&&&r)   rI   tuple[str, DistributedType]c                   d}|rddl }d}t          j        }nt                      rd}t          j        }nt          t          j                            dd                    dk    r|st                      rd}t          j
        }nht                      rd}t          j        }nKt                      rd	}t          j        }n.t          j                                        r|d
}t          j        }|t          t          j                            dd                    dk    st%          g dd          dk    r|st'                      rt          j        }nt          j        }|dv rQt-                      rCt%          dgd          dk    s|t          j        k    rt/                      dk    rddl}nddl}d}n'|dv r!t          j                                        rd}nd}|t          j        }||fS )zhPrepares any imports needed before initializing the distributed backend and sets `self.backend` properlyNr   smddprZ   r[   r\   cnclmcclhcclnccl)PMI_SIZEOMPI_COMM_WORLD_SIZEMV2_COMM_WORLD_SIZErb   r	   )NcclCCL_WORKER_COUNTz1.12r  )Nrg   rg   gloo),smdistributed.dataparallel.torch.torch_smddpr
   r   r   r   r}   ru   rv   rw   r   r   r   r   r   r   rx   ro   r  r   r   r   r   r   r   oneccl_bindings_for_pytorch	torch_cclr   is_mpi_availablerz   )r7   rQ   sagemaker_dprI   rL   smdistributedr  r  s           r*   r{   zPartialState._prepare_backend  s,      	=????G.8#%% 	=G.2b1122b888!! = #2#<  "$$ = #2#=   "## = #2#<  ((** =?$G#2#< #
|R0011R77 i i iklmmpqqq =+-- =#2#<  #2#<  =(($&& )%'9&:A>>BBFVZiZsFsFs"$$..66666$$$$M))e.?.P.P.R.R) #.1(((r)   c                   | j         dS | j        t          j        k    r)| j        rt          j         d          n| j        | _         dS t          | j                                      d          d         	                    dd          
                                }|dvrt          d| j         d	| d
          |dk    rt          j                    | _         dS |dk    rd}t          t
          |          }| j        |                                z  }t          j         ||          | _         |                    | j                    dS )zZ
        Sets the device in `self.device` to the current distributed environment.
        NrQ   .r\   MULTI_r   )rQ   gpur  r  r  r  rZ   zCan't set device for z (z6), verify we should be calling `_set_device()` for it!rZ   r   ro   )rK   rL   r
   rz   rG   rx   r	  r   splitreplacelowerr|   r   
xla_devicegetattrrN   device_countr   )r7   rK   device_moduledevice_indexs       r*   r   zPartialState.set_device  s>    ;"F O$66615S%,u---@SDKFT*++11#66r:BB8RPPVVXXKKK(=   U??-//DKKK#E622M3m6P6P6R6RRL,v|<<DK$$T[11111r)   c                    | j         r|dS t          j                                        r!t          j                            |           dS dS )zn
        Destroys the process group. If one is not specified, the default process group is destroyed.
        N)rM   rx   r   r+   destroy_process_groupr7   groups     r*   r*  z"PartialState.destroy_process_group  sV      	%-F++-- 	;33E:::::	; 	;r)   namec                `    || j         v rt          d| d          t          d| d          )Nz(`PartialState` object has no attribute `zy`. This happens if `PartialState._reset_state()` was called and an `Accelerator` or `PartialState` was not reinitialized.z('PartialState' object has no attribute ''_known_attrsAttributeErrorr7   r-  s     r*   __getattr__zPartialState.__getattr__#  sZ     4$$$ L4 L L L   OOOOPPPr)   r@   )rQ   r$   )r#   r   r#   r$   )r   r$   r   r   r   r$   r-   )r   r   NN)r   r   rP   r}   )r   r   rN   r}   )r#   r   )FFN)rQ   r$   rI   r   r#   r
  r-  r   )"rA   rB   rC   rD   
SharedDictr'   r1  r8   r   staticmethodr   propertyrt   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r	  r{   r   r*  r4  r(   r)   r*   rF   rF   s   s       $ $L JLLM  L}E }E }E }E }E~
 
 
 
 + + \+ ( ( ( X( V V XV < < < X< 
 
 
 X
 
 
 
 X
"@ "@ "@H% % % % V< V< V< V< ^V<p : : ^:( @ @ ^@(    <    >   8    B" " " " "H# # # ' ' ' X': EI9) 9) 9) 9) 9)v2 2 20; ; ; ;
Q 
Q 
Q 
Q 
Q 
Qr)   rF   c                     e Zd ZdZ e            Zej        g dz   Z	 	 	 	 	 	 	 d%d&d
Ze	d'd            Z
d Zd(dZe	d             Zed)d*d            Zd+dZe	d             Ze	d             Ze	d'd            Ze	d'd            Ze	d'd            Zd Zed)d,d            Zed             Zed             Ze	d             Zed-d!            Zed+d-d"            Z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.
    )deepspeed_pluginuse_ipexfsdp_pluginmegatron_lm_plugindynamo_pluginNFmixed_precisionr   rQ   r$   _from_acceleratorc                   | j         | _        t          d          rd}t          j         i k    rt          |fi | | j                            t          j                    |                     ||           | j        sd | _        d | _        |t          dd          n|
                                }|dk    rgt                      st          d          t                      s<t                              dt           j                                         d           d	}|| _        |st          d
          | j        t*          j        k    rdn|| _        | j        t*          j        k    rt3          d          r|dk    rt4          j                            d          rAt;          d          t4          j        d<   t;          d          t4          j        d<   d| _        nt;          d          t4          j        d<   t;          d          t4          j        d<   d| _        nt4          j                            dd          dk    r|s|| _        t*          j        | _        nd| j        t*          j        t*          j         t*          j!        t*          j"        t*          j#        fv rt4          j                            dd          dk    s|=t*          j$        | _        | j        dk    r|%                    | j                   || _&        t4          j                            dd          dk    rF| j        t*          j#        fvr2t*          j'        | _        |%                    | j                   || _(        nV| j        t*          j)        t*          j#        t*          j*        fv r,tW                      rt          dd          | _        nd| _        | j        j,        tZ          j*        k    r6| j        dk    r+| j.        j/        dk    rdt           j0        j        j1        _2        | j        j,        tZ          j*        k    r6| j        dk    r+| j.        j/        dk    rdt           j0        j3        j1        _2        | j        t          j         d<   d S d S )NACCELERATE_USE_CPUTACCELERATE_MIXED_PRECISIONnofp8zPUsing `fp8` precision requires `transformer_engine` or `MS-AMP` to be installed.z-The current device has compute capability of z which is insufficient for FP8 mixed precision training (requires a GPU Hopper/Ada Lovelace or higher, compute capability of 8.9 or higher). Will use FP16 instead.fp16zPlease make sure to properly initialize your accelerator via `accelerator = Accelerator()` before using any functionality from the `accelerate` library.rl   bf16ACCELERATE_DOWNCAST_BF16r   XLA_USE_BF16r	   XLA_DOWNCAST_BF16Fr]   rW   rX   ACCELERATE_USE_FSDPACCELERATE_USE_MEGATRON_LMACCELERATE_USE_IPEXdefaultro   r  rL   )4r'   rs   r   rF   update_check_initializedrt   deepspeed_pluginsr>  r   r#  r   r|   r   loggerwarningrx   ro   get_device_capabilityrA  rL   r
   r   rH   r   r   ru   rv   rw   r   downcast_bfloatr   r   r   r   r   r   set_mixed_precisionr?  r   r@  r   rz   r   rI   r   rK   r   backendsmatmul
allow_tf32r  )	r7   rB  rQ   rA  r=  r?  r@  rC  r/   s	            r*   r8   zAcceleratorState.__init__N  sT    *344 	C%++'''''\7888555 N	S%)D" DM #* &&BDIII$**,, 
 %''')) 
-$j   .// -NNb
HhHhHjHj b b b  
 '-O!.D$  T  
 -1,A_E^,^,^DDdsD!$(;;;@Vdh@i@i@i;"f,,z~~&@AA 558VV
>2:=a&&
#67/3,,58VV
>2:=a&&
#67/4, :GDDNNWZN)9&(7(A%%&))*))+   :>>"7AAVKK{Of,;,@D),44#778MNNN'2D$:>>">HHFRRW[Wl#-u X X -<,GD)&::4;PQQQ.@D+&?+DoF_apas*ttt$&& *$78MW[$\$\$\DMM$)DM"*m.>>>)T11K$..8<#*5"*m.>>>)T11K$..8<#*5=A=RL&'9:::]N	S N	Sr)   r#   c                ,    | j         t          j         k    S r-   )r'   rF   r   s    r*   rt   zAcceleratorState.initialized  s    !\%???r)   c                    t                                                      d| j         dz   }| j        t          j        k    r|d| j        j         dz  }|S )Nz
Mixed precision type: r   zds_config: )rF   r   rB  rL   r
   r   r=  deepspeed_config)r7   reprs     r*   r   zAcceleratorState.__repr__  s]    ~~&&((+^dFZ+^+^+^^ O$===L$"7"HLLLLDr)   c                    | j         rd}|r3| j        j        dk    r#t          |                    d                    |I|| j        k    r@| j        t          j        k    r-t          |                    d| d                    dS dS dS 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()`.rQ   zcpu=True)flagNzmixed_precision='r/  )	rt   rK   r   r|   formatrH   rL   r
   r   )r7   rB  rQ   errs       r*   rT  z#AcceleratorState._check_initialized  s     		Z _C >t{'500 !<!<===+#t'<<<)_-FFF 1W_1W1W1W!X!XYYY		Z 		Z
 ,+<<FFr)   c                   | j         t          j        k    ri| j        j        }|                    di                               dd          rd}n7|                    di                               dd          rd}n
d}n| j        }|S )NrI  enabledFrJ  rG  )rL   r
   r   r=  r`  rw   rH   )r7   configrB  s      r*   rB  z AcceleratorState.mixed_precision  s     O$===*;Fzz&"%%)))U;; '"(FB''++Iu== '"("&"3Or)   reset_partial_statec                |    t           j                                         | rt                                           dS dS r   )r&   r'   r   rF   r   )ri  s    r*   r   zAcceleratorState._reset_state  sC     	&,,... 	(%%'''''	( 	(r)   c                H    t                                          |           dS )z
        Destroys the process group. If one is not specified, the default process group is destroyed.

        If `self.fork_lauched` is `True` and `group` is `None`, nothing happens.
        N)rF   r*  r+  s     r*   r*  z&AcceleratorState.destroy_process_group  s"     	,,U33333r)   c                (    t                      j        S r-   )rF   rM   r   s    r*   rM   zAcceleratorState.fork_launched  s    ~~++r)   c                (    t                      j        S )r   )rF   r   r   s    r*   r   z AcceleratorState.use_distributed  s    
 ~~--r)   c                (    t                      j        S )r   )rF   r   r   s    r*   r   z AcceleratorState.is_last_process       ~~--r)   c                (    t                      j        S )r   )rF   r   r   s    r*   r   z AcceleratorState.is_main_process  ro  r)   c                (    t                      j        S )r   )rF   r   r   s    r*   r   z&AcceleratorState.is_local_main_process  s     ~~33r)   c                F    t                                                       d S r-   )rF   r   r   s    r*   r   z"AcceleratorState.wait_for_everyone  s    ((*****r)   r   r   r   c              #     K   t                                          ||          5 }|V  ddd           dS # 1 swxY w Y   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)rF   r   )r7   r   r   s      r*   r   z(AcceleratorState.split_between_processes  s      N ^^33F-3XX 	\bLLL	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   8<<c              #     K   t                                                      5  dV  ddd           dS # 1 swxY w Y   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)rF   r   r   s    r*   r   z#AcceleratorState.main_process_first+  s       ^^..00 	 	EEE	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	   599c              #     K   t                                                      5  dV  ddd           dS # 1 swxY w Y   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)rF   r   r   s    r*   r   z)AcceleratorState.local_main_process_first5  s       ^^4466 	 	EEE	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	ru  c                R    | j         t          j        k    rdS ddlm}  ||           S )zp
        Returns the currently active DeepSpeedPlugin.

        If not using deepspeed, returns `None`.
        Nr   )get_active_deepspeed_plugin)rL   r
   r   accelerate.utils.deepspeedrx  )r7   rx  s     r*   r=  z!AcceleratorState.deepspeed_plugin?  s=      O$===4JJJJJJ**4000r)   r-  c                    | j         |         S )zH
        Returns the DeepSpeedPlugin with the given plugin_key.
        )rU  r3  s     r*   get_deepspeed_pluginz%AcceleratorState.get_deepspeed_pluginM  s    
 %d++r)   c                    | j                                         D ]\  }}||k    r|                                  | j         |                             d           dS )zj
        Activates the DeepSpeedPlugin with the given `name`, and will disable all other plugins.
        T)_from_accelerator_stateN)rU  items	_unselectr   )r7   r-  r   plugins       r*   select_deepspeed_pluginz(AcceleratorState.select_deepspeed_pluginT  sg    
  17799 	# 	#KCd{{  """t$++D+IIIIIr)   c                8     t                      j        |i | d S r-   )rF   r   r   s      r*   r   zAcceleratorState.print^  s$    d-f-----r)   c                `    || j         v rt          d| d          t          d| d          )Nz,`AcceleratorState` object has no attribute `z}`. This happens if `AcceleratorState._reset_state()` was called and an `Accelerator` or `PartialState` was not reinitialized.z,'AcceleratorState' object has no attribute 'r/  r0  r3  s     r*   r4  zAcceleratorState.__getattr__a  sZ     4$$$ Lt L L L   SDSSSTTTr)   )NFNNNNF)rB  r   rQ   r$   rC  r$   r5  r7  r@   )ri  r$   r-   r6  r8  )!rA   rB   rC   rD   r9  r'   rF   r1  r8   r;  rt   r   rT  rB  r:  r   r*  rM   r   r   r   r   r   r   r   r   r   r=  r   r{  r  r   r4  r(   r)   r*   r&   r&   0  s        ( JLLM, 0 0 0 L  $"'`S `S `S `S `SD @ @ @ X@  Z Z Z Z   X ( ( ( ( \(4 4 4 4 , , X, . . X. . . . X. . . . X. 4 4 4 X4+ + + ' ' ' ' ^'R   ^   ^ 1 1 X1 , , , , J J J J J. . .
U 
U 
U 
U 
U 
Ur)   r&   c                  <   e Zd ZdZ e            ZdddZedd            Zedd
            Z	edd            Z
edd            Zedd            Zedd            Zd Zed             Zej        d             Zd Zd Zd Zedd            Zed             ZdS )GradientStatea  
    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
        - **is_xla_gradients_synced** (`bool`) -- Whether the XLA gradients have been synchronized. It is initialized
          as false. Once gradients have been reduced before the optimizer step, this flag is set to true. Subsequently,
            after each step, the flag is reset to false. FSDP will always synchronize the gradients, hence
            is_xla_gradients_synced is always true.
    Ngradient_accumulation_plugin$Optional[GradientAccumulationPlugin]c                   | j         | _        | j        s:d| _        d | _        d g| _        ||                                ni | _        d| _        |8| j        |                                k    r|                                | _        d S d S d S )NTF)	r'   rs   rt   sync_gradientsactive_dataloaderdataloader_references	to_kwargsplugin_kwargs_is_xla_gradients_synced)r7   r  s     r*   r8   zGradientState.__init__  s    * 	2"&D%)D"*.D&<X<d,66888jl  -2D) (38JNjNtNtNvNv8v8v!=!G!G!I!ID 438v8vr)   r#   r}   c                8    | j                             dd          S )z.Returns the number of steps to accumulate over	num_stepsr	   r  rw   r   s    r*   r  zGradientState.num_steps  s     !%%k1555r)   r$   c                8    | j                             dd          S )z0Returns whether the scheduler should be adjustedadjust_schedulerFr  r   s    r*   r  zGradientState.adjust_scheduler  s     !%%&8%@@@r)   c                8    | 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  r   s    r*   r  z"GradientState.sync_with_dataloader  s     !%%&<dCCCr)   c                "    t           j        i k    S )z8Returns whether the `GradientState` has been initialized)r  r'   r   s    r*   rt   zGradientState.initialized  s     *b00r)   c                ,    | j         sdS | j        j        S )zAReturns whether we have reached the end of the current dataloaderF)in_dataloaderr  end_of_dataloaderr   s    r*   r  zGradientState.end_of_dataloader  s      ! 	5%77r)   c                ,    | j         sdS | j        j        S )zOReturns the number of extra samples that were added from padding the dataloaderr\   )r  r  	remainderr   s    r*   r  zGradientState.remainder  s      ! 	2%//r)   c           	     H    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: r   )r  r  r  r  r   s    r*   r   zGradientState.__repr__  s[    Dt2 D D-1-CD D$(ND D .2-?D D D	
r)   c                6    t          dd          rdS | j        S )zReturns the value of is_xla_gradients_synced. FSDP will always synchronize the gradients, hence is_xla_gradients_synced is always true.rN  FrQ  T)r   r  r   s    r*   is_xla_gradients_syncedz%GradientState.is_xla_gradients_synced  s(     4eDDD 	4,,r)   c                    || _         dS )z+Set the _is_xla_gradients_synced attribute.N)r  )r7   	is_synceds     r*   r  z%GradientState.is_xla_gradients_synced  s     )2%%%r)   c                    || _         | j         rFt          d          r8t                      j        t          j        k    rt          j                     dS dS dS dS )zhPrivate function that sets whether gradients should be synchronized. Users should not have to call this.Trl   N)r  r   rF   rL   r
   r   r   	mark_step)r7   r  s     r*   _set_sync_gradientsz!GradientState._set_sync_gradients  sm    , 	&D999	 /?3FFFLNNNNN	 	 	 	 GFr)   c                R    || _         | 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r7   
dataloaders     r*   _add_dataloaderzGradientState._add_dataloader  s*    !+"))$*@AAAAAr)   c                ^    | 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.r\   N)r  remover  r  s     r*   _remove_dataloaderz GradientState._remove_dataloader  s/    "))*555!%!;B!?r)   c                    | j         duS )z6Returns whether the current process is in a dataloaderN)r  r   s    r*   r  zGradientState.in_dataloader  s     %T11r)   c                 B    t           j                                         dS r   )r  r'   r   r(   r)   r*   r   zGradientState._reset_state  s     	#))+++++r)   r-   )r  r  )r#   r}   r5  )rA   rB   rC   rD   r9  r'   r8   r;  r  r  r  rt   r  r  r   r  setterr  r  r  r  r:  r   r(   r)   r*   r  r  n  s        , JLLMJ J J J J 6 6 6 X6 A A A XA D D D XD 1 1 1 X1 8 8 8 X8 0 0 0 X0
 
 
 - - X- #2 2 $#2	 	 	B B B
@ @ @
 2 2 2 X2 , , \, , ,r)   r  r5  )<
__future__r   loggingru   	threadingr   
contextlibr   	functoolsr   typingr   r   r   rx   utilsr
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    utils.dataclassesr!   torch_xla.core.xla_modelcore	xla_modelr   	torch_mlu
torch_musa	torch_npu	getLoggerrA   rV  r+   r0   localr2   r   r9  rF   r&   r  r(   r)   r*   <module>r     sV   # " " " " "  				      % % % % % %       * * * * * * * * * *                                                  2 8 7 7 7 7 7  *)))))))))''' %((( ''' 		8	$	$0 0 0 0      IO   8 0/11LTT7L
z
Q z
Q z
Q z
Q z
Q z
Q z
Q z
Qz{U {U {U {U {U {U {U {U|	{, {, {, {, {, {, {, {, {, {,r)   