
    g>                    B   d Z ddlZddl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
mZ ddlmZ ddlmZmZmZmZmZmZmZmZmZmZ ddlZddlmZmZmZmZmZ dd	l m!Z!m"Z" dd
l#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+m,Z,  G d d          Z- G d dej.                  Z/ G d dej0        e/          Z1e
 G d de-                      Z2 G d de1          Z3e
 G d de-                      Z4e
 G d de-                      Z5e
 G d de-                      Z6ed         Z7ed         Z8ed         Z9ed          Z:e
 G d! d"e-                      Z;ed#         Z<e
 G d$ d%e-                      Z= G d& d'e>ej0                  Z? G d( d)e>ej0                  Z@ G d* d+e>ej0                  ZA G d, d-e>ej0                  ZB G d. d/e>e1          ZC G d0 d1e1          ZD G d2 d3e>e1          ZE G d4 d5e1          ZF G d6 d7ej0                  ZGe
 G d8 d9                      ZHe
 G d: d;                      ZIe
 G d< d=                      ZJe
 G d> d?e-                      ZKe
 G d@ dAe-                      ZLe
 G dB dC                      ZMe
 G dD dE                      ZNe
 G dF dG                      ZOi ZPdHe>fdIZQ eQdJ          dK             ZR eQdL          dM             ZS eQdN          dO             ZT eQdP          dQ             ZUe
 G dR dS                      ZVdT ZWdS )Uz1
General namespace and dataclass related classes
    N)contextmanager)	dataclassfield)	timedelta)
AnyCallableDictIterableListLiteralOptionalTupleUnionget_args   )FSDP_AUTO_WRAP_POLICYFSDP_BACKWARD_PREFETCHFSDP_SHARDING_STRATEGY(MITA_PROFILING_AVAILABLE_PYTORCH_VERSION'XPU_PROFILING_AVAILABLE_PYTORCH_VERSION)parse_flag_from_envstr_to_bool)is_cuda_availableis_mlu_availableis_msamp_availableis_npu_availableis_transformer_engine_availableis_xpu_available)compare_versionsis_torch_versionc                       e Zd ZdZd Zd ZdS )KwargsHandlerzP
    Internal mixin that implements a `to_kwargs()` method for a dataclass.
    c                 4    t          j        | j                  S N)copydeepcopy__dict__selfs    X/var/www/html/ai-engine/env/lib/python3.11/site-packages/accelerate/utils/dataclasses.pyto_dictzKwargsHandler.to_dict8   s    }T]+++    c                    ddl m}  |            5  |                                                                 ddd           n# 1 swxY w Y   |                                 }fd|                                D             S )zv
        Returns a dictionary containing the attributes with values different from the default of this class.
        r   )clear_environmentNc                 4    i | ]\  }}|         |k    ||S  r0   ).0kvdefault_dicts      r*   
<dictcomp>z+KwargsHandler.to_kwargs.<locals>.<dictcomp>E   s-    KKKAl1o6J6J16J6J6Jr,   )otherr.   	__class__r+   items)r)   r.   	this_dictr4   s      @r*   	to_kwargszKwargsHandler.to_kwargs;   s    
 	-,,,,,   	6 	6>>++3355L	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6 	6LLNN	KKKK!2!2KKKKs   'AA	A	N)__name__
__module____qualname____doc__r+   r:   r0   r,   r*   r"   r"   3   sA         , , ,
L 
L 
L 
L 
Lr,   r"   c                       e Zd ZdZd ZdS )EnumWithContainsz\A metaclass that adds the ability to check if `self` contains an item with the `in` operatorc                 B    	  | |           n# t           $ r Y dS w xY wdS )NFT)
ValueError)clsitems     r*   __contains__zEnumWithContains.__contains__K   s=    	CIIII 	 	 	55	ts    
N)r;   r<   r=   r>   rE   r0   r,   r*   r@   r@   H   s)        bb    r,   r@   c                   .    e Zd ZdZd Zed             ZdS )BaseEnumzDAn enum class that can get the value of an item with `str(Enum.key)`c                     | j         S r$   )valuer(   s    r*   __str__zBaseEnum.__str__V   s
    zr,   c                 F    t          t          t          |                     S )z.Method to list all the possible items in `cls`)listmapstr)rC   s    r*   rL   zBaseEnum.listY   s     CSMM"""r,   N)r;   r<   r=   r>   rJ   classmethodrL   r0   r,   r*   rG   rG   S   sD        JJ   # # [# # #r,   rG   )	metaclassc                   0    e Zd ZU dZdZeed<   dZeed<   dS )AutocastKwargsa  
    Use this object in your [`Accelerator`] to customize how `torch.autocast` behaves. Please refer to the
    documentation of this [context manager](https://pytorch.org/docs/stable/amp.html#torch.autocast) for more
    information on each argument.

    Example:

    ```python
    from accelerate import Accelerator
    from accelerate.utils import AutocastKwargs

    kwargs = AutocastKwargs(cache_enabled=True)
    accelerator = Accelerator(kwargs_handlers=[kwargs])
    ```
    TenabledNcache_enabled)r;   r<   r=   r>   rS   bool__annotations__rT   r0   r,   r*   rR   rR   _   s>            GTM4r,   rR   c                   &    e Zd ZdZdZdZdZdZdZdS )DDPCommunicationHookTypea  
    Represents a type of communication hook used in DDP.

    Values:

        - **NO** -- no communication hook
        - **FP16** -- DDP communication hook to compress the gradients in FP16
        - **BF16** -- DDP communication hook to compress the gradients in BF16
        - **POWER_SGD** -- DDP communication hook to use PowerSGD
        - **BATCHED_POWER_SGD** -- DDP communication hook to use batched PowerSGD
    nofp16bf16	power_sgdbatched_power_sgdN)	r;   r<   r=   r>   NOFP16BF16	POWER_SGDBATCHED_POWER_SGDr0   r,   r*   rX   rX   u   s6        
 
 
BDDI+r,   rX   c                       e Zd ZU dZdZeed<   dZeed<   dZ	eed<   dZ
eed	<   dZeed
<   dZeed<   dZeed<   ej        Zeed<   ej        Zeej        ej        ej        f         ed<    ee          Zeed<   d fd	Zd Z xZS )DistributedDataParallelKwargsa  
    Use this object in your [`Accelerator`] to customize how your model is wrapped in a
    `torch.nn.parallel.DistributedDataParallel`. Please refer to the documentation of this
    [wrapper](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html) for more
    information on each argument.

    <Tip warning={true}>

    `gradient_as_bucket_view` is only available in PyTorch 1.7.0 and later versions.

    `static_graph` is only available in PyTorch 1.11.0 and later versions.

    </Tip>

    Example:

    ```python
    from accelerate import Accelerator
    from accelerate.utils import DistributedDataParallelKwargs

    kwargs = DistributedDataParallelKwargs(find_unused_parameters=True)
    accelerator = Accelerator(kwargs_handlers=[kwargs])
    ```
    r   dimTbroadcast_buffers   bucket_cap_mbFfind_unused_parameterscheck_reductiongradient_as_bucket_viewstatic_graph	comm_hookcomm_wrapper)default_factorycomm_state_optionrm   rn   rp   c                     fdt                                                                                      D             S )Nc                 $    i | ]\  }}|v	||S r0   r0   )r1   r2   r3   ignore_keyss      r*   r5   z9DistributedDataParallelKwargs.to_dict.<locals>.<dictcomp>   s)    SSSAa{>R>R1>R>R>Rr,   )superr+   r8   )r)   rt   r7   s    `r*   r+   z%DistributedDataParallelKwargs.to_dict   s8    SSSS!2!2!8!8!:!:SSSSr,   c                    ddl m}m} t          j        |j        t          j        |j        t          j        |j        t          j	        |j
        i}t          j        |j        t          j        |j        i}|                    | j                  }|                    | j                  }|r|r ||          }|rL| j        t          j        t          j	        fv r |j        di | j        nd }|                    ||           d S d S )Nr   )default_hookspowerSGD_hook)statehookr$   )+torch.distributed.algorithms.ddp_comm_hooksrw   rx   rX   r_   fp16_compress_hookr`   bf16_compress_hookra   rb   batched_powerSGD_hookfp16_compress_wrapperbf16_compress_wrappergetrm   rn   PowerSGDStaterp   register_comm_hook)	r)   modelrw   rx   hook_mapwrapper_maprz   wrapperry   s	            r*   r   z0DistributedDataParallelKwargs.register_comm_hook   s7   \\\\\\\\ %)=+K$)=+K$.0K$68[	>
 %)=+N$)=+NA

 $,<<#?#?&1ood6G&H&H 	!G 	!74==D 		 >&>&HJbJt%uuu ,+KKD4JKKK 
 $$ %     		 		r,   )rq   )r;   r<   r=   r>   re   intrV   rf   rU   rh   ri   rj   rk   rl   rX   r^   rm   rn   r   r_   r`   r   dictrp   r+   r   __classcell__)r7   s   @r*   rd   rd      s<         2 CLLL"t"""M3#(D(((!OT!!!$)T)))L$*B*EI'EEE 	!# ' #%=%BD\Daa $ $ $ $eD999t999T T T T T T      r,   rd   c                   Z    e Zd ZU dZdZeed<   dZeed<   dZeed<   dZ	e
ed	<   d
Zeed<   dS )GradScalerKwargsa  
    Use this object in your [`Accelerator`] to customize the behavior of mixed precision, specifically how the
    `torch.cuda.amp.GradScaler` used is created. Please refer to the documentation of this
    [scaler](https://pytorch.org/docs/stable/amp.html?highlight=gradscaler) for more information on each argument.

    <Tip warning={true}>

    `GradScaler` is only available in PyTorch 1.5.0 and later versions.

    </Tip>

    Example:

    ```python
    from accelerate import Accelerator
    from accelerate.utils import GradScalerKwargs

    kwargs = GradScalerKwargs(backoff_filter=0.25)
    accelerator = Accelerator(kwargs_handlers=[kwargs])
    ```
    g      @
init_scaleg       @growth_factorg      ?backoff_factori  growth_intervalTrS   N)r;   r<   r=   r>   r   floatrV   r   r   r   r   rS   rU   r0   r,   r*   r   r      sn          ,  JM5NEOSGTr,   r   c                   h    e Zd ZU dZdZee         ed<   dZee         ed<   dZ	ee
         ed<   d ZdS )InitProcessGroupKwargsa  
    Use this object in your [`Accelerator`] to customize the initialization of the distributed processes. Please refer
    to the documentation of this
    [method](https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group) for more
    information on each argument.

    Note: If `timeout` is set to `None`, the default will be based upon how `backend` is set.

    ```python
    from datetime import timedelta
    from accelerate import Accelerator
    from accelerate.utils import InitProcessGroupKwargs

    kwargs = InitProcessGroupKwargs(timeout=timedelta(seconds=800))
    accelerator = Accelerator(kwargs_handlers=[kwargs])
    ```
    ncclbackendNinit_methodtimeoutc                 `    | j         &| j        dk    rdnd}t          |          | _         d S d S )Nr   i  iX  )seconds)r   r   r   )r)   r   s     r*   __post_init__z$InitProcessGroupKwargs.__post_init__  s=    <"lf44dd#G$W555DLLL  r,   )r;   r<   r=   r>   r   r   rN   rV   r   r   r   r   r0   r,   r*   r   r      sn          $ $GXc]###!%K#%%%#'GXi '''6 6 6 6 6r,   r   )MSAMPTEO1O2)E4M3HYBRID)maxmost_recentc                       e Zd ZU dZdZeed<   dZeed<   dZ	e
ed<   dZeed<   dZeed<   dZeed<   dZeed	<   dZeed
<   dZeeeef         ed<   d ZdS )FP8RecipeKwargsa  
    Use this object in your [`Accelerator`] to customize the initialization of the recipe for FP8 mixed precision
    training with `transformer-engine` or `ms-amp`.

    <Tip>

        For more information on `transformer-engine` args, please refer to the API
        [documentation](https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/api/common.html).

        For more information on the `ms-amp` args, please refer to the Optimization Level
        [documentation](https://azure.github.io/MS-AMP/docs/user-tutorial/optimization-level).

    </Tip>

    ```python
    from accelerate import Accelerator
    from accelerate.utils import FP8RecipeKwargs

    kwargs = FP8RecipeKwargs(backend="te", fp8_format="HYBRID")
    accelerator = Accelerator(mixed_precision="fp8", kwargs_handlers=[kwargs])
    ```

    To use MS-AMP as an engine, pass `backend="msamp"` and the `optimization_level`:

    ```python
    kwargs = FP8RecipeKwargs(backend="msamp", optimization_level="02")
    ```

    Args:
        backend (`str`, *optional*):
            Which FP8 engine to use. Must be one of `"msamp"` (MS-AMP) or `"te"` (TransformerEngine). If not passed,
            will use whichever is available in the environment, prioritizing MS-AMP.
        use_autocast_during_eval (`bool`, *optional*, default to `False`):
            Whether to use FP8 autocast during eval mode. Generally better metrics are found when this is `False`.
        margin (`int`, *optional*, default to 0):
            The margin to use for the gradient scaling.
        interval (`int`, *optional*, default to 1):
            The interval to use for how often the scaling factor is recomputed.
        fp8_format (`str`, *optional*, default to "HYBRID"):
            The format to use for the FP8 recipe. Must be one of `HYBRID` or `E4M3`. (Generally `HYBRID` for training,
            `E4M3` for evaluation)
        amax_history_len (`int`, *optional*, default to 1024):
            The length of the history to use for the scaling factor computation
        amax_compute_algo (`str`, *optional*, default to "most_recent"):
            The algorithm to use for the scaling factor computation. Must be one of `max` or `most_recent`.
        override_linear_precision (`tuple` of three `bool`, *optional*, default to `(False, False, False)`):
            Whether or not to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision.
        optimization_level (`str`), one of `O1`, `O2`. (default is `O2`):
            What level of 8-bit collective communication should be used with MS-AMP. In general:
                * O1: Weight gradients and `all_reduce` communications are done in fp8, reducing GPU
                    memory usage and communication bandwidth
                * O2: First-order optimizer states are in 8-bit, and second order states are in FP16.
                    Only available when using Adam or AdamW. This maintains accuracy and can potentially save the
                    highest memory.
                * 03: Specifically for DeepSpeed, implements capabilities so weights and master weights of models
                    are stored in FP8. If `fp8` is selected and deepspeed is enabled, will be used by default. (Not
                    available currently).
    Nr   use_autocast_during_eval	opt_levelmargininterval
fp8_formatamax_history_lenamax_compute_algooverride_linear_precisionc                 |   d}t                      rdnd}| j        (t          j                            |dz   |          | _        | j                                        | _        | j        t          t                    vrt          d          | j        dk    ryt                      st          d          | j
        t          |dz             | _
        | j        5t          t          j                            |d	z   d
                    | _        | j        5t          t          j                            |dz   d                    | _        | j        (t          j                            |dz   d          | _        | j                                        | _        | j        t          t                     vr8t          dd                    t          t                                d          | j        (t          j                            |dz   d          | _        | j                                        | _        | j        t          t(                    vr7t          dd                    t          t(                                         | j        5t          t          j                            |dz   d                    | _        | j        Bt          |dz             }t          |dz             }t          |dz             }|||f| _        d S d S | j        dk    rt                      st          d          | j        (t          j                            |dz   d          | _        | j        t          t0                    vr9t          dd                    t          t0                                         d S d S )NACCELERATE_FP8_msampteBACKENDz6`backend` must be 'MSAMP' or 'TE' (TransformerEngine).r   zhTransformerEngine is not available. Please either install it, or use the 'MSAMP' backend (if installed).USE_AUTOCAST_DURING_EVALMARGINr   INTERVALr   FORMATr   z`fp8_format` must be one of z or .AMAX_COMPUTE_ALGOr   z#`amax_compute_algo` must be one of AMAX_HISTORY_LEN   OVERRIDE_FPROPOVERRIDE_DGRADOVERRIDE_WGRADr   zZMS-AMP is not available. Please either install it, or use the 'TE' backend (if installed).	OPT_LEVELr   z$`optimization_level` must be one of )r   r   osenvironr   upperr   BackendrB   r   r   r   r   r   r   r   	FP8Formatjoinr   lowerAmaxComputeAlgorithmr   r   r   OptLevel)r)   
env_prefixdefault_backendfpropdgradwgrads         r*   r   zFP8RecipeKwargs.__post_init__a  sZ   &
%7%9%9C''t<:>>*y*@/RRDL|))++<x0000UVVV<4244  ~   ,40CJQkDk0l0l-{"!"*..h1F"J"JKK}$ #BJNN:
3JA$N$N O O&"$*..h1F"Q"Q"o3355DOhy&9&999 !cHU^L_L_@`@`!c!c!cddd%-)+
EX8XZg)h)h&%)%;%A%A%C%CD"%X6J-K-KKK !tv{{S[\pSqSqGrGr!t!tuuu$,(+BJNN:HZ;Z\`,a,a(b(b%-5+J9I,IJJ+J9I,IJJ+J9I,IJJ271F...	 65
 \W$$%''  p   ~%!#
[0H$!O!O~Xh%7%777 !iT\]eTfTfHgHg!i!ijjj %$ 87r,   )r;   r<   r=   r>   r   r   rV   r   rU   r   r   r   r   r   r   r   r   r   r   r   r   r   r0   r,   r*   r   r     s         9 9v GW%)d)))IxFCHc J	    c   .2+2229=uT4%56===-k -k -k -k -kr,   r   )cpuxpumtiacudac                   "   e Zd ZU dZdZeee                  ed<   dZ	ee
eef                  ed<   dZee         ed<   dZeed<   dZeed<   dZeed	<   dZeed
<   dZeed<   dZee         ed<   dedej        j        fdZdej        j        fdZdS )ProfileKwargsu.
  
    Use this object in your [`Accelerator`] to customize the initialization of the profiler. Please refer to the
    documentation of this [context manager](https://pytorch.org/docs/stable/profiler.html#torch.profiler.profile) for
    more information on each argument.

    <Tip warning={true}>

    `torch.profiler` is only available in PyTorch 1.8.1 and later versions.

    </Tip>

    Example:

    ```python
    from accelerate import Accelerator
    from accelerate.utils import ProfileKwargs

    kwargs = ProfileKwargs(activities=["cpu", "cuda"])
    accelerator = Accelerator(kwargs_handlers=[kwargs])
    ```

    Args:
        activities (`List[str]`, *optional*, default to `None`):
            The list of activity groups to use in profiling. Must be one of `"cpu"`, `"xpu"`, `"mtia"`, or `"cuda"`.
        schedule_option (`Dict[str, int]`, *optional*, default to `None`):
            The schedule option to use for the profiler. Available keys are `wait`, `warmup`, `active`, `repeat` and
            `skip_first`. The profiler will skip the first `skip_first` steps, then wait for `wait` steps, then do the
            warmup for the next `warmup` steps, then do the active recording for the next `active` steps and then
            repeat the cycle starting with `wait` steps. The optional number of cycles is specified with the `repeat`
            parameter, the zero value means that the cycles will continue until the profiling is finished.
        on_trace_ready (`Callable`, *optional*, default to `None`):
            Callable that is called at each step when schedule returns `ProfilerAction.RECORD_AND_SAVE` during the
            profiling.
        record_shapes (`bool`, *optional*, default to `False`):
            Save information about operator’s input shapes.
        profile_memory (`bool`, *optional*, default to `False`):
            Track tensor memory allocation/deallocation
        with_stack (`bool`, *optional*, default to `False`):
            Record source information (file and line number) for the ops.
        with_flops (`bool`, *optional*, default to `False`):
            Use formula to estimate the FLOPS of specific operators
        with_modules (`bool`, *optional*, default to `False`):
            Record module hierarchy (including function names) corresponding to the callstack of the op.
        output_trace_dir (`str`, *optional*, default to `None`):
            Exports the collected trace in Chrome JSON format. Chrome use 'chrome://tracing' view json file. Defaults
            to None, which means profiling does not store json files.
    N
activitiesschedule_optionon_trace_readyFrecord_shapesprofile_memory
with_stack
with_flopswith_modulesoutput_trace_diractivityreturnc                 r   t           j        j        j        t           j        j        j        d}t          dt                    rt           j        j        j        |d<   t          dt                    rt           j        j        j	        |d<   ||vr#t          d| dt          |           d          ||         S )zGet the profiler activity from the string.

        Args:
            activity (str): The profiler activity name.

        Returns:
            torch.profiler.ProfilerActivity: The profiler activity.
        )r   r   z>=r   r   zInvalid profiler activity: . Must be one of r   )torchprofilerProfilerActivityCPUCUDAr    r   XPUr   MTIArB   rL   )r)   r   profiler_activity_maps      r*   _get_profiler_activityz$ProfileKwargs._get_profiler_activity  s     >26N38M
 M

 D"IJJ 	O+0>+J+N!%(D"JKK 	Q,1N,K,P!&)000t8ttVZ[pVqVqtttuuu$X..r,   c           
          d} j          fd j         D             }d} j        t          j        j        di  j        }t          j                            || j         j         j         j	         j
         j                  S )z
        Build a profiler object with the current configuration.

        Returns:
            torch.profiler.profile: The profiler object.
        Nc                 :    g | ]}                     |          S r0   )r   )r1   r   r)   s     r*   
<listcomp>z'ProfileKwargs.build.<locals>.<listcomp>  s'    ```H$55h??```r,   )r   scheduler   r   r   r   r   r   r0   )r   r   r   r   r   profiler   r   r   r   r   r   )r)   r   r   s   `  r*   buildzProfileKwargs.build  s     8<
?&````PTP_```J6:+~.FF1EFFH~%%!.,.* & 	
 	
 		
r,   )r;   r<   r=   r>   r   r   r   r   rV   r   r	   rN   r   r   r   r   rU   r   r   r   r   r   r   r   r   r   r   r0   r,   r*   r   r     s        . .` 48J./077704OXd38n-444)-NHX&---M4 ND   JJL$&*hsm***//? /ENDc / / / /2
u~- 
 
 
 
 
 
r,   r   c                   >    e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdS )DistributedTypea=  
    Represents a type of distributed environment.

    Values:

        - **NO** -- Not a distributed environment, just a single process.
        - **MULTI_CPU** -- Distributed on multiple CPU nodes.
        - **MULTI_GPU** -- Distributed on multiple GPUs.
        - **MULTI_MLU** -- Distributed on multiple MLUs.
        - **MULTI_MUSA** -- Distributed on multiple MUSAs.
        - **MULTI_NPU** -- Distributed on multiple NPUs.
        - **MULTI_XPU** -- Distributed on multiple XPUs.
        - **DEEPSPEED** -- Using DeepSpeed.
        - **XLA** -- Using TorchXLA.
    r^   	MULTI_CPU	MULTI_GPU	MULTI_NPU	MULTI_MLU
MULTI_MUSA	MULTI_XPU	DEEPSPEEDFSDPXLAMEGATRON_LMN)r;   r<   r=   r>   r^   r   r   r   r   r   r   r   r   r   r   r0   r,   r*   r   r     sQ         " 
BIIIIJIID
CKKKr,   r   c                       e Zd ZdZdZdZdZdS )SageMakerDistributedTypea+  
    Represents a type of distributed environment.

    Values:

        - **NO** -- Not a distributed environment, just a single process.
        - **DATA_PARALLEL** -- using sagemaker distributed data parallelism.
        - **MODEL_PARALLEL** -- using sagemaker distributed model parallelism.
    r^   DATA_PARALLELMODEL_PARALLELN)r;   r<   r=   r>   r^   r   r   r0   r,   r*   r   r   #  s)          
B#M%NNNr,   r   c                       e Zd ZdZdZdZdS )FP8BackendTypez
    Represents the backend used for FP8.

    Values:

        - **TE** -- using TransformerEngine.
        - **MSAMP** -- using msamp.
    r   r   N)r;   r<   r=   r>   r   r   r0   r,   r*   r   r   4  s$          
BEEEr,   r   c                       e Zd ZdZdZdZdS )ComputeEnvironmentz
    Represents a type of the compute environment.

    Values:

        - **LOCAL_MACHINE** -- private/custom cluster hardware.
        - **AMAZON_SAGEMAKER** -- Amazon SageMaker as compute environment.
    LOCAL_MACHINEAMAZON_SAGEMAKERN)r;   r<   r=   r>   r  r  r0   r,   r*   r  r  C  s'          $M)r,   r  c                   N    e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
ZdZdZdZdZdZdZdS )DynamoBackenda	  
    Represents a dynamo backend (see https://pytorch.org/docs/stable/torch.compiler.html).

    Values:

        - **NO** -- Do not use torch dynamo.
        - **EAGER** -- Uses PyTorch to run the extracted GraphModule. This is quite useful in debugging TorchDynamo
          issues.
        - **AOT_EAGER** -- Uses AotAutograd with no compiler, i.e, just using PyTorch eager for the AotAutograd's
          extracted forward and backward graphs. This is useful for debugging, and unlikely to give speedups.
        - **INDUCTOR** -- Uses TorchInductor backend with AotAutograd and cudagraphs by leveraging codegened Triton
          kernels. [Read
          more](https://dev-discuss.pytorch.org/t/torchinductor-a-pytorch-native-compiler-with-define-by-run-ir-and-symbolic-shapes/747)
        - **AOT_TS_NVFUSER** -- nvFuser with AotAutograd/TorchScript. [Read
          more](https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593)
        - **NVPRIMS_NVFUSER** -- nvFuser with PrimTorch. [Read
          more](https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593)
        - **CUDAGRAPHS** -- cudagraphs with AotAutograd. [Read more](https://github.com/pytorch/torchdynamo/pull/757)
        - **OFI** -- Uses Torchscript optimize_for_inference. Inference only. [Read
          more](https://pytorch.org/docs/stable/generated/torch.jit.optimize_for_inference.html)
        - **FX2TRT** -- Uses Nvidia TensorRT for inference optimizations. Inference only. [Read
          more](https://github.com/pytorch/TensorRT/blob/master/docsrc/tutorials/getting_started_with_fx_path.rst)
        - **ONNXRT** -- Uses ONNXRT for inference on CPU/GPU. Inference only. [Read more](https://onnxruntime.ai/)
        - **TENSORRT** -- Uses ONNXRT to run TensorRT for inference optimizations. [Read
          more](https://github.com/onnx/onnx-tensorrt)
        - **AOT_TORCHXLA_TRACE_ONCE** -- Uses Pytorch/XLA with TorchDynamo optimization, for training. [Read
          more](https://github.com/pytorch/xla/blob/r2.0/docs/dynamo.md)
        - **TORCHXLA_TRACE_ONCE** -- Uses Pytorch/XLA with TorchDynamo optimization, for inference. [Read
          more](https://github.com/pytorch/xla/blob/r2.0/docs/dynamo.md)
        - **IPEX** -- Uses IPEX for inference on CPU. Inference only. [Read
          more](https://github.com/intel/intel-extension-for-pytorch).
        - **TVM** -- Uses Apach TVM for inference optimizations. [Read more](https://tvm.apache.org/)

    r^   EAGER	AOT_EAGERINDUCTORAOT_TS_NVFUSERNVPRIMS_NVFUSER
CUDAGRAPHSOFIFX2TRTONNXRTTENSORRTAOT_TORCHXLA_TRACE_ONCETORCHXLA_TRACE_ONCEIPEXTVMN)r;   r<   r=   r>   r^   r  r  r	  r
  r  r  r  r  r  r  r  r  r  r  r0   r,   r*   r  r  R  sh        ! !H 
BEIH%N'OJ
CFFH7/D
CCCr,   r  c                   2    e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
S )
LoggerTypea  Represents a type of supported experiment tracker

    Values:

        - **ALL** -- all available trackers in the environment that are supported
        - **TENSORBOARD** -- TensorBoard as an experiment tracker
        - **WANDB** -- wandb as an experiment tracker
        - **COMETML** -- comet_ml as an experiment tracker
        - **DVCLIVE** -- dvclive as an experiment tracker
    allaimtensorboardwandbcomet_mlmlflowclearmldvcliveN)r;   r<   r=   r>   ALLAIMTENSORBOARDWANDBCOMETMLMLFLOWCLEARMLDVCLIVEr0   r,   r*   r  r    sB        	 	 C
CKEGFGGGGr,   r  c                   "    e Zd ZdZdZdZdZdZdS )PrecisionTypezRepresents a type of precision used on floating point values

    Values:

        - **NO** -- using full precision (FP32)
        - **FP16** -- using half precision
        - **BF16** -- using brain floating point precision
    rY   fp8rZ   r[   N)r;   r<   r=   r>   r^   FP8r_   r`   r0   r,   r*   r(  r(    s.          
B
CDDDDr,   r(  c                   .    e Zd ZdZdZdZdZdZdZdZ	dZ
d	S )
RNGTyper   r   mlumusanpuxlar   	generatorN)r;   r<   r=   TORCHr   MLUMUSANPUr   r   	GENERATORr0   r,   r*   r,  r,    s6        ED
CD
C
C
CIIIr,   r,  c                       e Zd ZdZdZdZdZdS )CustomDtypezd
    An enum that contains multiple custom dtypes that can be used for `infer_auto_device_map`.
    r)  int4int2N)r;   r<   r=   r>   r*  INT4INT2r0   r,   r*   r8  r8    s)          CDDDDr,   r8  c                   8    e Zd ZU ej        ed<   ej        ed<   dS )TensorInformationshapedtypeN)r;   r<   r=   r   SizerV   r@  r0   r,   r*   r>  r>    s.         :;r,   r>  c                      e Zd ZU dZ edddi          Zeed<    edddi          Zeed	<    ed
ddi          Z	eed<    edddi          Z
eed<    edddi          Zeed<    edddi          Zeed<   dS )DataLoaderConfigurationa	  
    Configuration for dataloader-related items when calling `accelerator.prepare`.

    Args:
        split_batches (`bool`, defaults to `False`):
            Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. If
            `True`, the actual batch size used will be the same on any kind of distributed processes, but it must be a
            round multiple of `num_processes` you are using. If `False`, actual batch size used will be the one set in
            your script multiplied by the number of processes.
        dispatch_batches (`bool`, defaults to `None`):
            If set to `True`, the dataloader prepared by the Accelerator is only iterated through on the main process
            and then the batches are split and broadcast to each process. Will default to `True` for `DataLoader` whose
            underlying dataset is an `IterableDataset`, `False` otherwise.
        even_batches (`bool`, defaults to `True`):
            If set to `True`, in cases where the total batch size across all processes does not exactly divide the
            dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among
            all workers.
        use_seedable_sampler (`bool`, defaults to `False`):
            Whether or not use a fully seedable random sampler ([`data_loader.SeedableRandomSampler`]). Ensures
            training results are fully reproducable using a different sampling technique. While seed-to-seed results
            may differ, on average the differences are neglible when using multiple different seeds to compare. Should
            also be ran with [`~utils.set_seed`] for the best results.
        non_blocking (`bool`, defaults to `False`):
            If set to `True`, the dataloader prepared by the Accelerator will utilize non-blocking host-to-device
            transfers, allowing for better overlap between dataloader communication and computation. Recommended that
            the prepared dataloader has `pin_memory` set to `True` to work properly.
        use_stateful_dataloader (`bool`, defaults to `False`):
            If set to `True`, the dataloader prepared by the Accelerator will be backed by
            [torchdata.StatefulDataLoader](https://github.com/pytorch/data/tree/main/torchdata/stateful_dataloader).
            This requires `torchdata` version 0.8.0 or higher that supports StatefulDataLoader to be installed.
    Fhelpau  Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. If `True` the actual batch size used will be the same on any kind of distributed processes, but it must be a round multiple of the `num_processes` you are using. If `False`, actual batch size used will be the one set in your script multiplied by the number of processes.defaultmetadatasplit_batchesNa  If set to `True`, the dataloader prepared by the Accelerator is only iterated through on the main process and then the batches are split and broadcast to each process. Will default to `True` for `DataLoader` whose underlying dataset is an `IterableDataset`, `False` otherwise.dispatch_batchesTzIf set to `True`, in cases where the total batch size across all processes does not exactly divide the dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among all workers.even_batchesap  Whether or not use a fully seedable random sampler ([`data_loader.SeedableRandomSampler`]).Ensures training results are fully reproducable using a different sampling technique. While seed-to-seed results may differ, on average the differences are neglible when usingmultiple different seeds to compare. Should also be ran with [`~utils.set_seed`] for the best results.use_seedable_samplera  If set to `True`, the dataloader prepared by the Accelerator will utilize non-blocking host-to-device transfers, allowing for better overlap between dataloader communication and computation.  Recommended that the prepared dataloader has `pin_memory` set to `True` to work properly.non_blockinga  If set to `True`, the dataloader prepared by the Accelerator will be backed by [torchdata.StatefulDataLoader](https://github.com/pytorch/data/tree/main/torchdata/stateful_dataloader). This requires `torchdata` version 0.8.0 or higher that supports StatefulDataLoader to be installed.use_stateful_dataloader)r;   r<   r=   r>   r   rH  rU   rV   rI  rJ  rK  rL  rM  r0   r,   r*   rC  rC    s         @  % E
  M4    #U N
  d     
  L$    "' u
" " "$     T
  L$    %*E [
% % %T     r,   rC  c                      e Zd ZU dZ edddi          Zeed<    edddi          Zeed<    ed	dd
i          Z	e
ed<    edddi          Zeed<    edddi          Zeed<    ed	ddi          Ze
ed<   ddefdZd ZdS )ProjectConfigurationa  
    Configuration for the Accelerator object based on inner-project needs.

    Args:
        project_dir (`str`, defaults to `None`):
            A path to a directory for storing data.
        logging_dir (`str`, defaults to `None`):
            A path to a directory for storing logs of locally-compatible loggers. If None, defaults to `project_dir`.
        automatic_checkpoint_naming (`bool`, defaults to `False`):
            Whether saved states should be automatically iteratively named.
        total_limit (`int`, defaults to `None`):
            The maximum number of total saved states to keep.
        iteration (`int`, defaults to `0`):
            The current save iteration.
        save_on_each_node (`bool`, defaults to `False`):
            When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on
            the main one.
    NrD  z'A path to a directory for storing data.rE  project_dirziA path to a directory for storing logs of locally-compatible loggers. If None, defaults to `project_dir`.logging_dirFz?Whether saved states should be automatically iteratively named.automatic_checkpoint_namingz1The maximum number of total saved states to keep.total_limitr   zThe current save iteration.	iterationzxWhen doing multi-node distributed training, whether to save models and checkpoints on each node, or only on the main onesave_on_each_nodec                 4    || _         | j        	|| _        dS dS )zISets `self.project_dir` and `self.logging_dir` to the appropriate values.N)rP  rQ  )r)   rP  s     r*   set_directoriesz$ProjectConfiguration.set_directoriesV  s)    &#*D $#r,   c                 :    |                      | j                   d S r$   )rW  rP  r(   s    r*   r   z"ProjectConfiguration.__post_init__\  s    T-.....r,   r$   )r;   r<   r=   r>   r   rP  rN   rV   rQ  rR  rU   rS  r   rT  rU  rW  r   r0   r,   r*   rO  rO  !  s         & uTV=f4ghhhKhhhu
  K    ).[\) ) )   
 uMN  K   
 U78  Is   
 $e(
  t   + +3 + + + +/ / / / /r,   rO  c                       e Zd ZU dZ edddi          Zeed<    edddi          Ze	ed	<    eddd
i          Z
e	ed<    edddi          Ze	ed<   dS )GradientAccumulationPlugina  
    A plugin to configure gradient accumulation behavior. You can only pass one of `gradient_accumulation_plugin` or
    `gradient_accumulation_steps` to [`Accelerator`]. Passing both raises an error.

    Parameters:
        num_steps (`int`):
            The number of steps to accumulate gradients for.
        adjust_scheduler (`bool`, *optional*, defaults to `True`):
            Whether to adjust the scheduler steps to account for the number of steps being accumulated. Should be
            `True` if the used scheduler was not adjusted for gradient accumulation.
        sync_with_dataloader (`bool`, *optional*, defaults to `True`):
            Whether to synchronize setting the gradients when at the end of the dataloader.
        sync_each_batch (`bool`, *optional*):
                Whether to synchronize setting the gradients at each data batch. Seting to `True` may reduce memory
                requirements when using gradient accumulation with distributed training, at expense of speed.

    Example:

    ```python
    from accelerate.utils import GradientAccumulationPlugin

    gradient_accumulation_plugin = GradientAccumulationPlugin(num_steps=2)
    accelerator = Accelerator(gradient_accumulation_plugin=gradient_accumulation_plugin)
    ```
    NrD  z0The number of steps to accumulate gradients for.rE  	num_stepsTzWhether to adjust the scheduler steps to account for the number of steps being accumulated. Should be `True` if the used scheduler was not adjusted for gradient accumulation.adjust_schedulerzWhether to synchronize setting the gradients when at the end of the dataloader. Should only be set to `False` if you know what you're doing.sync_with_dataloaderFzWhether to synchronize setting the gradients at each data batch. Setting to `True` may reduce memory requirements when using gradient accumulation with distributed training, at expense of speed.sync_each_batch)r;   r<   r=   r>   r   r[  r   rV   r\  rU   r]  r^  r0   r,   r*   rZ  rZ  `  s          4 U46;m2noooIsooo"U  E
  d    "'  c
" " "$    "E  Y
  OT     r,   rZ  c                   *   e Zd ZU dZ edddd eD              i          Zeed<    edddi          Ze	ed	<    eddd
i          Z
eed<    edddi          Zeed<    edddi          Zeed<    edddi          Zeed<   d Zd ZdS )TorchDynamoPlugina  
    This plugin is used to compile a model with PyTorch 2.0

    Args:
        backend (`DynamoBackend`, defaults to `None`):
            A valid Dynamo backend. See https://pytorch.org/docs/stable/torch.compiler.html for more details.
        mode (`str`, defaults to `None`):
            Possible options are 'default', 'reduce-overhead' or 'max-autotune'.
        fullgraph (`bool`, defaults to `None`):
            Whether it is ok to break model into several subgraphs.
        dynamic (`bool`, defaults to `None`):
            Whether to use dynamic shape for tracing.
        options (`Any`, defaults to `None`):
            A dictionary of options to pass to the backend.
        disable (`bool`, defaults to `False`):
            Turn torch.compile() into a no-op for testing
    NrD  zPossible options are c                 @    g | ]}|j                                         S r0   )rI   r   )r1   bs     r*   r   zTorchDynamoPlugin.<listcomp>  s"    2Z2Z2Zq17==??2Z2Z2Zr,   rE  r   zCPossible options are 'default', 'reduce-overhead' or 'max-autotune'modez6Whether it is ok to break model into several subgraphs	fullgraphz(Whether to use dynamic shape for tracingdynamicz/A dictionary of options to pass to the backend.optionsFz-Turn torch.compile() into a no-op for testingdisablec                     d}| j         (t          j                            |dz   d          | _         t	          | j                                                   | _         | j        (t          j                            |dz   d          | _        | j        9t          t          j                            |dz   d                    dk    | _        | j	        ;t          t          j                            |d	z   d                    dk    | _	        d S d S )
NACCELERATE_DYNAMO_r   rY   MODErF  USE_FULLGRAPHFalser   USE_DYNAMIC)
r   r   r   r   r  r   rc  rd  r   re  r)   prefixs     r*   r   zTorchDynamoPlugin.__post_init__  s    %<:>>&9*<dCCDL$T\%7%7%9%9::9
v	BBDI>!(8PRY)Z)Z[[_``DN<&rz~~f}6Lg'V'VWW[\\DLLL  r,   c                 |    t          j        | j                  }|d         j                                        |d<   |S )Nr   )r%   r&   r'   rI   r   )r)   dynamo_configs     r*   r+   zTorchDynamoPlugin.to_dict  s7    dm44#0#;#A#G#G#I#Ii r,   )r;   r<   r=   r>   r   r  r   rV   rc  rN   rd  rU   re  rf  r   rg  r   r+   r0   r,   r*   r`  r`    sW         $ #U\2Z2ZM2Z2Z2Z\\]  G]    (mn  D#    eDF<t3uvvvItvvvE$&:d1efffGTfff59j0klllGSlllE%6;j2klllGTlll
] 
] 
]    r,   r`  c                      e Zd ZU dZ edddi          Zeed<    edddi          Ze	ed<    eddd	i          Z
eed
<    edddi          Ze	ed<    edddi          Zeed<    edddi          Zeed<    edddi          Zeed<    edddi          Zeed<    edddi          Zeed<    edddi          Zeed<    edddi          Zeed<    edddi          Zeed<    edddi          Zeed<    edddi          Zeed                   ed!<   d" Zd6d#Zd$ Zd7d%Zd8d'Zd( Z d) Z!d* Z"e#d9d,            Z$d- Z%d. Z&d9d/efd0Z'd1 Z(d2efd3Z)e*d4             Z+e+j,        d5             Z+dS ):DeepSpeedPluginaW	  
    This plugin is used to integrate DeepSpeed.

    Args:
        hf_ds_config (`Any`, defaults to `None`):
            Path to DeepSpeed config file or dict or an object of class `accelerate.utils.deepspeed.HfDeepSpeedConfig`.
        gradient_accumulation_steps (`int`, defaults to `None`):
            Number of steps to accumulate gradients before updating optimizer states. If not set, will use the value
            from the `Accelerator` directly.
        gradient_clipping (`float`, defaults to `None`):
            Enable gradient clipping with value.
        zero_stage (`int`, defaults to `None`):
            Possible options are 0, 1, 2, 3. Default will be taken from environment variable.
        is_train_batch_min (`bool`, defaults to `True`):
            If both train & eval dataloaders are specified, this will decide the `train_batch_size`.
        offload_optimizer_device (`str`, defaults to `None`):
            Possible options are none|cpu|nvme. Only applicable with ZeRO Stages 2 and 3.
        offload_param_device (`str`, defaults to `None`):
            Possible options are none|cpu|nvme. Only applicable with ZeRO Stage 3.
        offload_optimizer_nvme_path (`str`, defaults to `None`):
            Possible options are /nvme|/local_nvme. Only applicable with ZeRO Stage 3.
        offload_param_nvme_path (`str`, defaults to `None`):
            Possible options are /nvme|/local_nvme. Only applicable with ZeRO Stage 3.
        zero3_init_flag (`bool`, defaults to `None`):
            Flag to indicate whether to save 16-bit model. Only applicable with ZeRO Stage-3.
        zero3_save_16bit_model (`bool`, defaults to `None`):
            Flag to indicate whether to save 16-bit model. Only applicable with ZeRO Stage-3.
        transformer_moe_cls_names (`str`, defaults to `None`):
            Comma-separated list of Transformers MoE layer class names (case-sensitive). For example,
            `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention`, `JetMoEBlock`, etc.
        enable_msamp (`bool`, defaults to `None`):
            Flag to indicate whether to enable MS-AMP backend for FP8 training.
        msasmp_opt_level (`Optional[Literal["O1", "O2"]]`, defaults to `None`):
            Optimization level for MS-AMP (defaults to 'O1'). Only applicable if `enable_msamp` is True. Should be one
            of ['O1' or 'O2'].
    NrD  zkpath to DeepSpeed config file or dict or an object of class `accelerate.utils.deepspeed.HfDeepSpeedConfig`.rE  hf_ds_configzNumber of steps to accumulate gradients before updating optimizer states. If not set, will use the value from the `Accelerator` directly.gradient_accumulation_stepsz#Enable gradient clipping with valuegradient_clippingzMPossible options are 0,1,2,3; Default will be taken from environment variable
zero_stageTzUIf both train & eval dataloaders are specified, this will decide the train_batch_sizeis_train_batch_minzMPossible options are none|cpu|nvme. Only applicable with ZeRO Stages 2 and 3.offload_optimizer_devicezFPossible options are none|cpu|nvme. Only applicable with ZeRO Stage 3.offload_param_devicezJPossible options are /nvme|/local_nvme. Only applicable with ZeRO Stage 3.offload_optimizer_nvme_pathoffload_param_nvme_pathz{Flag to indicate whether to enable `deepspeed.zero.Init` for constructing massive models.Only applicable with ZeRO Stage-3.zero3_init_flagzQFlag to indicate whether to save 16-bit model. Only applicable with ZeRO Stage-3.zero3_save_16bit_modelzcomma-separated list of transformers MoE layer class names (case-sensitive), e.g :  `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ...transformer_moe_cls_nameszCFlag to indicate whether to enable MS-AMP backend for FP8 training.enable_msampz}Optimization level for MS-AMP (defaults to 'O1'). Only applicable if `enable_msamp` is True. Should be one of ['O1' or 'O2'].r   msamp_opt_levelc           	      
    ddl m}  j        Jt          j                            dd          }|                                rt          |          n| _         j        <t          j                            dd          }|dk    r|nt          |           _         j
        2t          t          j                            dd                     _
         j        %t          j                            dd	           _         j        %t          j                            d
d	           _         j        %t          j                            dd	           _         j        %t          j                            dd	           _         j        )t          j                            dd          dk     _         j        )t          j                            dd           dk     _         j        %t          j                            dd           _         j        %t          j                            dd	           _        t'           j        t(                    s;t'           j        t*                    r j        d	k    st'           j        |          r3t'           j        |          s | j                   _        d j        j        vrd j        j        d<   d j        j        vrt/          d                                            ddddddddd} fd |                                D             }|                                D ]}  j        |fi |d!d"i  j                                         |                                D ]8\  }} j                            |          }||dk    rt=           ||           9npdd j         j
         j         j        d#k    r j        nd d$ j         j        d#k    r j        nd d$ j        d%d&}	 j        r
 j        |	d<    ||	           _         j        j         _        t          d'           j        d(<    j         ZtC          t          j                            d)t+           j        "                                                              dk     _          j         r4 j        "                                stG          j$        d*           d" _          %                    d"            j        rOd+ j        vrH j
        d,k    rtM          d-           j        d.vrt/          d/          d0 j        d1 j        d+<   d S d S d S )2Nr   )HfDeepSpeedConfig&ACCELERATE_GRADIENT_ACCUMULATION_STEPSautoACCELERATE_GRADIENT_CLIPPINGACCELERATE_DEEPSPEED_ZERO_STAGE   -ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_DEVICEnone)ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_DEVICE0ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_NVME_PATH,ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_NVME_PATH+ACCELERATE_DEEPSPEED_ZERO3_SAVE_16BIT_MODELfalsetrueACCELERATE_FP8_BACKENDr   ACCELERATE_FP8_OPT_LEVELr    ACCELERATE_DEEPSPEED_CONFIG_FILEru  zero_optimizationzDPlease specify the ZeRO optimization config in the DeepSpeed config.rv  zzero_optimization.stagez*zero_optimization.offload_optimizer.devicez&zero_optimization.offload_param.devicez)zero_optimization.offload_param.nvme_pathz-zero_optimization.offload_optimizer.nvme_pathz;zero_optimization.stage3_gather_16bit_weights_on_model_save)ru  rv  rw  ry  rz  r|  r{  r~  c                 X    i | ]&\  }}t          |          |t          |          'S r$   )getattr)r1   r2   r3   r)   s      r*   r5   z1DeepSpeedPlugin.__post_init__.<locals>.<dictcomp>k  s;    wwwdaZabfhiZjZjZvaq))ZvZvZvr,   
must_matchFnvme)device	nvme_path)stageoffload_optimizeroffload_param)stage3_gather_16bit_weights_on_model_save)train_batch_sizetrain_micro_batch_size_per_gpuru  r  infsteps_per_printACCELERATE_DEEPSPEED_ZERO3_INITzSDeepSpeed Zero3 Init flag is only applicable for ZeRO Stage 3. Setting it to False.r      zSMS-AMP is not supported for ZeRO Stage 3. Please use ZeRO Stage 0, 1, or 2 instead.r   zGInvalid optimization level for MS-AMP. Please use one of ['O1' or'O2'].TrS   r   )'	deepspeedr  ru  r   r   r   isdigitr   rv  r   rw  ry  rz  r{  r|  r~  r  r  rt  
isinstancer   rN   configrB   _deepspeed_config_checksr8   keys
fill_matchset_stage_and_offload	get_valuesetattrdeepspeed_configr}  r   is_zero3warningswarn_set_selectedNotImplementedError)
r)   r  gasrv  plugin_to_config_mappingkwargskeyrI   config_valuer  s
   `         r*   r   zDeepSpeedPlugin.__post_init__,  s   000000+3*..!I6RRC;>;;==/Qs3xxxcD,!) "
/Mv V V:Kv:U:U%6%6[`ar[s[sD"?"!"*..1RTU"V"VWWDO(0,.JNN;jlr,s,sD)$,(*
7bdj(k(kD%+3/1z~~BF0 0D, '/+-:>>:hjp+q+qD(&.
LgVVZ`` ' $ "
/G N NRY YD'#%:>>2Ld#S#SD $ "
/QSY Z ZDt($//8	:4,c228	:7;7HF7R7R$+->?? 8S d/1BCC I$5$5d6G$H$H!,D4E4LLLJK!()FG"$*;*BBB !ghhh))+++/L%87,X(P+V/^*g	( 	($ xwww6N6T6T6V6VwwwF{{}} A A@@v@@%@@@@@33555 7<<>> 5 5
U#0::5AA+0F0FD#|4445 %+28/3/O!_"&"?8FBB &*%E%E!	* * #'";EIE^bhEhEhT%A%Anr& & BFA\& &	 F& % E.2.D*+ 1 1& 9 9D $ 1 838<</0'BJNN+LcRVRcRlRlRnRnNoNoppqquvv    	)(9(B(B(D(D 	)Moppp#(D  	5!!!  	b0E!E!E!##)i   #<77 !jkkk9=DL`-a-aD!'***	b 	b!E!Er,   c                    |g n|}| j                             |          \  }}|d S |                    |          dk    r'||v r||         ||<   d S t          d| d| d          |sd S |                    |          }|9||v r7|||         k    r-|                    d| d| d| d||                     d S d S d S d S )Nr  `z'` not found in kwargs. Please specify `zZ` without `auto` (set to correct value) in the DeepSpeed config file or pass it in kwargs.z- ds =z vs arg )rt  find_config_noder   rB   append)r)   ds_key_long
mismatchesr  r  r  ds_keyds_vals           r*   r  zDeepSpeedPlugin.fill_match  s4   %-RR:
*;;KHH>F::f''f$$!'!4v ) ) )'2) ) )    	FF##+"7"7,,,!!"k+"k"k"k"k"k"kV\]hVi"k"klllll "7"7,,r,   c                 J    | j                             |          }|dS |dk    S )NFr  rt  r  )r)   r  vals      r*   is_autozDeepSpeedPlugin.is_auto  s,    ))+66;5&= r,   c                 8    | j                             ||          S r$   r  )r)   r  rF  s      r*   r  zDeepSpeedPlugin.get_value  s     **;@@@r,    c           	      b   |g n|}|| j         }|                                D ]G\  }}t          |t                    r | j        d
||z   dz   |||d| 3 | j        ||z   |fd|i| Ht          |          dk    r.|dk    r*d                    |          }t          d| d	          dS dS )z=Process the DeepSpeed config with the values from the kwargs.Nr   )ro  r  r  r  r  r   r  
zSPlease correct the following DeepSpeed config values that mismatch kwargs  values:
zF
The easiest method is to set these DeepSpeed config values to 'auto'.r0   )	r  r8   r  r   deepspeed_config_processr  lenr   rB   )	r)   ro  r  r  r  r  r  rI   mismatches_msgs	            r*   r  z(DeepSpeedPlugin.deepspeed_config_process  s   %-RR:
>*F ,,.. 	[ 	[JC%&& [-- !C<#-*U_i ms     jZZZZSYZZZZz??Q6R<<!YYz22Nu+u u u   <<r,   c                    | j         }|dk    |dv d}|dk    rd|vrddd|d<   n|dv rd|vrddi|d<   |dk    r| j        rd	|vrd| j        d
|d	<   |dk    rm|dk    rdnd}t          |                    |i                               dd                                                    dk    rt          d| d| d          dD ]}||vrddi||<    | j        dddi|  | j        dddi| d S )NrZ   )r[   r)  )fp16.enabledbf16.enabledT)rS   	auto_castr[   rS   r)  r   r  rY   rl  r  z*`--mixed_precision` arg cannot be set to `z` when `z&` is set in the DeepSpeed config file.)rZ   r[   Fr  r  r  )r  )r  )r  r  r  rN   r   r   rB   r  )r)   mixed_precision	ds_configr  
diff_dtyper@  s         r*   set_mixed_precisionz#DeepSpeedPlugin.set_mixed_precision  s   )	+v5+>
 

 f$$Y&&044$H$H	&!//Y&&%.$5	&!e##(9#i''15DDX%Y%Y	'"d""#2f#<#<&J9==R0044YHHIIOOQQU[[[  M  M  MZd  M  M  M   & 	6 	6EI%%$-u#5	% CC5CFCCCCC5CFCCCCCr,   c                    ddl m} t          j        | j                  }| j        r |            st          d          d|vs|d         dk    rd|d<   d|vs|d         dk    rd|d<   |                    dd           dk    r|d= t          dd	d
          r	ddl	m
}m} nddlm
}m}  |              ||          | _        d S )Nr   )is_transformers_availablezoWhen `zero3_init_flag` is set, it requires Transformers to be installed. Please run `pip install transformers`.ru  r  r  r  transformers<z4.33r   )r  unset_hf_deepspeed_config)importsr  r%   r&   r  r}  	Exceptionr   r   transformers.deepspeedr  r  transformers.integrationsdschf)r)   r  r  r  r  s        r*   set_deepspeed_weakrefz%DeepSpeedPlugin.set_deepspeed_weakref  s9   666666M$"788	 	,,.. =   )	99YGd=eio=o=o78I34+9<<	Jj@kou@u@u:;I67==+T22f<<,-NC88 	_[[[[[[[[[^^^^^^^^!!###&&y11


r,   c                     | j         S r$   )r}  r(   s    r*   is_zero3_init_enabledz%DeepSpeedPlugin.is_zero3_init_enabled  s    ##r,   Fc              #      K   | j         }||k    rd V  d S || _         d | _        |                                  d V  || _         d | _        |                                  d S r$   )r}  r  r  )r)   enableolds      r*   zero3_init_context_managerz*DeepSpeedPlugin.zero3_init_context_manager  su      "&==EEEEE#)D DJ&&(((EEE#&D DJ&&(((((r,   c                     g dd D             t           j                            dd                              d          }t	          fd|D                       rt          d d          d S )	N)	r  r  r  r  r  r  r  r  ACCELERATE_MIXED_PRECISIONc                     g | ]>}|                     d d                               dd                                          ?S )ACCELERATE_r  
DEEPSPEED_)replacer   )r1   names     r*   r   z<DeepSpeedPlugin._deepspeed_config_checks.<locals>.<listcomp>/  sO     (
 (
 (
RVDLL++33L"EEKKMM(
 (
 (
r,   ACCELERATE_CONFIG_DS_FIELDSr  ,c              3       K   | ]}|v V  	d S r$   r0   )r1   r  env_variable_names_to_ignores     r*   	<genexpr>z;DeepSpeedPlugin._deepspeed_config_checks.<locals>.<genexpr>5  s)      hht33hhhhhhr,   z_When using `deepspeed_config_file`, the following accelerate config variables will be ignored: am  .
Please specify them appropriately in the DeepSpeed config file.
If you are using an accelerate config file, remove others config variables mentioned in the above specified list.
The easiest method is to create a new config following the questionnaire via `accelerate config`.
It will only ask for the necessary config variables when using `deepspeed_config_file`.)r   r   r   splitanyrB   )r)   'deepspeed_fields_from_accelerate_configr  s     @r*   r  z(DeepSpeedPlugin._deepspeed_config_checks#  s    
(
 
(
 
(
$(
 (
Zv(
 (
 (
$ 35*..A^`b2c2c2i2ijm2n2n/hhhh@ghhhhh 	j  sO j j j  	 	r,   c                    | j         %t          j                            dd           | _         | j         t	          ddd          rt          d          ddlm} | j                             d          }g }|D ]<}t          ||          }|t          d	| d
          |                    |           = |||           d S d S )N(ACCELERATE_DEEPSPEED_MOE_LAYER_CLS_NAMESr  r  z0.14.0zPDeepSpeed version must be >= 0.14.0 to use MOE support. Please update DeepSpeed.r   )set_z3_leaf_modulesr  z1Could not find a transformer layer class called 'z' to wrap in the model.)r  r   r   r   r   ImportErrordeepspeed.utilsr  r  get_module_class_from_namer  r  )r)   r   r  class_namestransformer_moe_clslayer_classtransformer_clss          r*   set_moe_leaf_modulesz$DeepSpeedPlugin.set_moe_leaf_modules>  s   )1-/Z^^<fhl-m-mD*)5S(;; v!"tuuu;;;;;;8>>sCCK"$* @ @"<UK"P"P"*#pKppp   (..????':;;;;; 65r,   _from_accelerator_statec                 z    |st          d          |                                  |                     d           dS )z_
        Sets the HfDeepSpeedWeakref to use the current deepspeed plugin configuration
        zxA `DeepSpeedPlugin` object must be enabled manually by calling `AcceleratorState().enable_deepspeed_plugin(plugin_key)`.TN)rB   r  r  )r)   r  s     r*   selectzDeepSpeedPlugin.selectR  sR     ' 	 K   	""$$$4     r,   c                 0    |                      d           d S )NF)r  r(   s    r*   	_unselectzDeepSpeedPlugin._unselect]  s    5!!!!!r,   rI   c                     || _         dS )z=
        Private setter for the 'enabled' attribute.
        N	_selectedr)   rI   s     r*   r  zDeepSpeedPlugin._set_selected`  s     r,   c                     | j         S r$   r  r(   s    r*   selectedzDeepSpeedPlugin.selectedf  s
    ~r,   c                      t          d          )Nz\'enabled' can only be set through calling 'AcceleratorState().enable_deepspeed_plugin(key)'.)r  r
  s     r*   r  zDeepSpeedPlugin.selectedj  s    !j
 
 	
r,   )NTr$   )r  NNT)F)-r;   r<   r=   r>   r   rt  r   rV   ru  r   rv  r   rw  rx  rU   ry  rN   rz  r{  r|  r}  r~  r  r  r  r   r   r   r  r  r  r  r  r  r  r   r  r  r  r  r  r  propertyr  setterr0   r,   r*   rs  rs    s{        # #J   B
  L#    (-u  `
( ( (     %uTVEj<klllullleij  J     %uqr         %*Eij% % %c    !&bc! ! !#    (-ufg( ( (    $)5fg$ $ $S    "E 1
  OT    $)5mn$ $ $D    &+U d
& & &s    _`  L$    6;U  T
6 6 6OXgj12   wb wb wbrm m m m2! ! !A A A A   &D D D<2 2 22$ $ $ ) ) ) ^)  6< < <(	! 	!d 	! 	! 	! 	!" " "4       X _
 
 _
 
 
r,   rs  c                   6   e Zd ZU dZ edddi          Zeedf         ed<    edddi          Z	eed	f         ed
<    edddi          Z
eeedf                  ed<    edddi          Zeeeed         f                  ed<    edddi          Zeedf         ed<    edddi          Zeeej        j                          ed<    edddi          Zeedf         ed<    edddi          Zeed                  ed<    edddi          Zeed                  ed<    eddd i          Zeed!<    eddd"i          Zeed#<    eddd$i          Zeeej        j        gdf                  ed%<    eddd&i          Zeed'<    eddd(i          Zeed)<    eddd*i          Zeed+<    eddd,i          Z eed-<    eddd.i          Z!ee"e                  ed/<    eddd0i          Z#ee$         ed1<   d2 Z%d7d3Z&d4 Z'd8d6Z(dS )9FullyShardedDataParallelPlugina  
    This plugin is used to enable fully sharded data parallelism.

    Args:
        sharding_strategy (`Union[str, torch.distributed.fsdp.ShardingStrategy]`, defaults to `'FULL_SHARD'`):
            Sharding strategy to use. Should be either a `str` or an instance of
            `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`.
        backward_prefetch (`Union[str, torch.distributed.fsdp.BackwardPrefetch]`, defaults to `'NO_PREFETCH'`):
            Backward prefetch strategy to use. Should be either a `str` or an instance of
            `torch.distributed.fsdp.fully_sharded_data_parallel.BackwardPrefetch`.
        mixed_precision_policy (`Optional[Union[dict, torch.distributed.fsdp.MixedPrecision]]`, defaults to `None`):
            A config to enable mixed precision training with FullyShardedDataParallel. If passing in a `dict`, it
            should have the following keys: `param_dtype`, `reduce_dtype`, and `buffer_dtype`.
        auto_wrap_policy (`Optional(Union[Callable, Literal["transformer_based_wrap", "size_based_wrap", "no_wrap"]]), defaults to `NO_WRAP`):
            A callable or string specifying a policy to recursively wrap layers with FSDP. If a string, it must be one
            of `transformer_based_wrap`, `size_based_wrap`, or `no_wrap`. See
            `torch.distributed.fsdp.wrap.size_based_wrap_policy` for a direction on what it should look like.
        cpu_offload (`Union[bool, torch.distributed.fsdp.CPUOffload]`, defaults to `False`):
            Whether to offload parameters to CPU. Should be either a `bool` or an instance of
            `torch.distributed.fsdp.fully_sharded_data_parallel.CPUOffload`.
        ignored_modules (`Optional[Iterable[torch.nn.Module]]`, defaults to `None`):
            A list of modules to ignore when wrapping with FSDP.
        state_dict_type (`Union[str, torch.distributed.fsdp.StateDictType]`, defaults to `'FULL_STATE_DICT'`):
            State dict type to use. If a string, it must be one of `full_state_dict`, `local_state_dict`, or
            `sharded_state_dict`.
        state_dict_config (`Optional[Union[torch.distributed.fsdp.FullStateDictConfig, torch.distributed.fsdp.ShardedStateDictConfig]`, defaults to `None`):
            State dict config to use. Is determined based on the `state_dict_type` if not passed in.
        optim_state_dict_config (`Optional[Union[torch.distributed.fsdp.FullOptimStateDictConfig, torch.distributed.fsdp.ShardedOptimStateDictConfig]`, defaults to `None`):
            Optim state dict config to use. Is determined based on the `state_dict_type` if not passed in.
        limit_all_gathers (`bool`, defaults to `True`):
            Whether to have FSDP explicitly synchronizes the CPU thread to prevent too many in-flight all-gathers. This
            bool only affects the sharded strategies that schedule all-gathers. Enabling this can help lower the number
            of CUDA malloc retries.
        use_orig_params (`bool`, defaults to `False`):
            Whether to use the original parameters for the optimizer.
        param_init_fn (`Optional[Callable[[torch.nn.Module], None]`, defaults to `None`):
            A `Callable[torch.nn.Module] -> None` that specifies how modules that are currently on the meta device
            should be initialized onto an actual device. Only applicable when `sync_module_states` is `True`. By
            default is a `lambda` which calls `to_empty` on the module.
        sync_module_states (`bool`, defaults to `False`):
            Whether each individually wrapped FSDP unit should broadcast module parameters from rank 0 to ensure they
            are the same across all ranks after initialization. Defaults to `False` unless `cpu_ram_efficient_loading`
            is `True`, then will be forcibly enabled.
        forward_prefetch (`bool`, defaults to `False`):
            Whether to have FSDP explicitly prefetches the next upcoming all-gather while executing in the forward
            pass. only use with Static graphs.
        activation_checkpointing (`bool`, defaults to `False`):
            A technique to reduce memory usage by clearing activations of certain layers and recomputing them during a
            backward pass. Effectively, this trades extra computation time for reduced memory usage.
        cpu_ram_efficient_loading (`bool`, defaults to `None`):
            If True, only the first process loads the pretrained model checkoint while all other processes have empty
            weights. Only applicable for Transformers. When using this, `sync_module_states` needs to be `True`.
        transformer_cls_names_to_wrap (`Optional[List[str]]`, defaults to `None`):
            A list of transformer layer class names to wrap. Only applicable when `auto_wrap_policy` is
            `transformer_based_wrap`.
        min_num_params (`Optional[int]`, defaults to `None`):
            The minimum number of parameters a module must have to be wrapped. Only applicable when `auto_wrap_policy`
            is `size_based_wrap`.
    NrD  zSharding strategy to use. Should be either a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`. Defaults to 'FULL_SHARD'rE  z'torch.distributed.fsdp.ShardingStrategysharding_strategyzBackward prefetch strategy to use. Should be either a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.BackwardPrefetch`. Defaults to 'NO_PREFETCH'z'torch.distributed.fsdp.BackwardPrefetchbackward_prefetchzA config to enable mixed precision training with FullyShardedDataParallel. If passing in a `dict`, it should have the following keys: `param_dtype`, `reduce_dtype`, and `buffer_dtype`.z%torch.distributed.fsdp.MixedPrecisionmixed_precision_policya$  A callable or string specifying a policy to recursively wrap layers with FSDP. If a string, it must be one of `transformer_based_wrap`, `size_based_wrap`, or `no_wrap`. Defaults to `NO_WRAP`. See `torch.distributed.fsdp.wrap.size_based_wrap_policy` for a direction on what it should look like)transformer_based_wrapsize_based_wrapno_wrapauto_wrap_policyzWhether to offload parameters to CPU. Should be either a `bool` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.CPUOffload`. Defaults to `False`z!torch.distributed.fsdp.CPUOffloadcpu_offloadz4A list of modules to ignore when wrapping with FSDP.ignored_moduleszState dict type to use. If a string, it must be one of `full_state_dict`, `local_state_dict`, or `sharded_state_dict`. Defaults to `FULL_STATE_DICT`z$torch.distributed.fsdp.StateDictTypestate_dict_typezXState dict config to use. Is determined based on the `state_dict_type` if not passed in.)z*torch.distributed.fsdp.FullStateDictConfigz-torch.distributed.fsdp.ShardedStateDictConfigstate_dict_configz^Optim state dict config to use. Is determined based on the `state_dict_type` if not passed in.)z/torch.distributed.fsdp.FullOptimStateDictConfigz2torch.distributed.fsdp.ShardedOptimStateDictConfigoptim_state_dict_configTzWhether to have FSDP explicitly synchronizes the CPU thread to prevent too many in-flight all-gathers. This bool only affects the sharded strategies that schedule all-gathers. Enabling this can help lower the number of CUDA malloc retries.limit_all_gatherszMWhether to use the original parameters for the optimizer. Defaults to `False`use_orig_paramsa  A Callable[torch.nn.Module] -> None that specifies how modules that are currently on the meta device should be initialized onto an actual device. Only applicable when `sync_module_states` is `True`. By default is a `lambda` which calls `to_empty` on the module.param_init_fnzWhether each individually wrapped FSDP unit should broadcast module parameters from rank 0 to ensure they are the same across all ranks after initialization. Defaults to `False` unless `cpu_ram_efficient_loading` is `True`, then will be forcibly enabled.sync_module_stateszWhether to have FSDP explicitly prefetches the next upcoming all-gather while executing in the forward pass. only use with Static graphs. Defaults to `False`forward_prefetchzA technique to reduce memory usage by clearing activations of certain layers and recomputing them during a backward pass. Effectively, this trades extra computation time for reduced memory usage. Defaults to `False`activation_checkpointingu   If True, only the first process loads the pretrained model checkoint while all other processes have empty weights. Only applicable for 🤗 Transformers. When using this, `sync_module_states` needs to be `True`. Defaults to `False`.cpu_ram_efficient_loadingzuA list of transformer layer class names to wrap. Only applicable when `auto_wrap_policy` is `transformer_based_wrap`.transformer_cls_names_to_wrapzThe minimum number of parameters a module must have to be wrapped. Only applicable when `auto_wrap_policy` is `size_based_wrap`.min_num_paramsc           	          ddl m}m}m} d}| j        (t
          j                            |dz   d          | _        t          | j        t                    r| j        
                                t          v r3t          j        | j        
                                          dz   | _        t          | j        t                    s| j                                        r# |t          | j                            | _        n$|| j        
                                         | _        | j        9t!          t
          j                            |dz   d                    dk    | _        t          | j        t"                    r || j        	          | _        | j        (t
          j                            |d
z   d           | _        t          | j        t                    r$| j        
                                dk    rd | _        | j        t          | j        |          st          | j        t                    rS| j        
                                t&          v r3t'          j        | j        
                                          dz   | _        t          | j        t                    s| j                                        r# |t          | j                            | _        n$|| j        
                                         | _        |                                  | j        (t
          j                            |dz   d          | _        t          | j        t                    r| j        
                                t,          vr8t/          d| j         dt1          t-          j                                         ddlm}m} | j        
                                dk    rp|| _        | j        (t
          j                            |dz   d           | _        t          | j        t                    r| j                            d          | _        n| j        
                                dk    r|| _        | j        6t          t
          j                            |dz   d                    | _        nkt          | j        t                    s,t/          d| j         dtA          | j                             n$| j        
                                dk    rd | _        | j!        9t!          t
          j                            |dz   d                    dk    | _!        | j"        9t!          t
          j                            |dz   d                    dk    | _"        | j#        9t!          t
          j                            |dz   d                    dk    | _#        | j$        9t!          t
          j                            |dz   d                    dk    | _$        | j%        9t!          t
          j                            |dz   d                    dk    | _%        | j%        r"| j"        stM          j'        d           d| _"        t          | j(        tR                    r| *                    | j(                   | j"        rtW                      rtX          j-        .                                nt_                      rtX          j0        .                                nitc                      rtX          j2        .                                n<tg                      rtX          j4        .                                ntk          d          fd | _6        d S d S )!Nr   )BackwardPrefetch
CPUOffloadShardingStrategyFSDP_SHARDING_STRATEGY
FULL_SHARDr   OFFLOAD_PARAMSrl  )offload_paramsBACKWARD_PREFETCHNO_PREFETCHAUTO_WRAP_POLICYNO_WRAPzInvalid auto wrap policy: r   size_based_auto_wrap_policytransformer_auto_wrap_policyTRANSFORMER_BASED_WRAPTRANSFORMER_CLS_TO_WRAPr  SIZE_BASED_WRAPMIN_NUM_PARAMSz)`min_num_params` must be an integer. Got z	 of type USE_ORIG_PARAMSSYNC_MODULE_STATESFORWARD_PREFETCHACTIVATION_CHECKPOINTINGCPU_RAM_EFFICIENT_LOADINGzosync_module_states cannot be False since efficient cpu ram loading enabled. Setting sync_module_states to True.TzWThere are currently no available devices found, must be one of 'XPU', 'CUDA', or 'NPU'.c                 2    |                      d          S )NF)r  recurse)to_empty)xr  s    r*   <lambda>z>FullyShardedDataParallelPlugin.__post_init__.<locals>.<lambda>  s    1::VU:+S+S r,   )7torch.distributed.fsdpr(  r)  r*  r  r   r   r   r  rN   r   r   indexr   r  r  r   rU   r  r   set_state_dict_typer  r   rB   rL   r  torch.distributed.fsdp.wrapr5  r6  r%  r  r&  typer  r!  r"  r#  r$  r  r  r  r   r  r   r   r/  current_devicer   r-  r   r   r   r   RuntimeErrorr   )r)   r(  r)  r*  r   r5  r6  r  s          @r*   r   z,FullyShardedDataParallelPlugin.__post_init__,  s   	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 
!)%'Z^^JAT4TVb%c%cD"d,c22 	Z%++--1GGG)?)EdF\FbFbFdFd)e)ehi)i&$0#66 Z$:P:X:X:Z:Z Z)9)9#d>T:U:U)V)V&&)9$:P:V:V:X:X)Y&#*2:>>*GW:WY`+a+abbfggDd&-- 	K)z9IJJJD!)%'Z^^JAT4TVZ%[%[D"d,c22 	*t7M7S7S7U7UYf7f7f%)D"!-jAWYi6j6j-$0#66 j4;Q;W;W;Y;Y]s;s;s)?)EdF\FbFbFdFd)e)ehi)i&$0#66 Z$:P:X:X:Z:Z Z)9)9#d>T:U:U)V)V&&)9$:P:V:V:X:X)Y&  """ ($&JNN:@R3RT]$^$^D!d+S11 	-$**,,4III }1F}}Y]^s^x^z^zY{Y{}}   nmmmmmmm$**,,0HHH(D%5=9;
UnHnpt9u9uD6d@#FF g9=9[9a9abe9f9fD6&,,..2CCC(C%&.*-bjnnZJZ=Z\].^.^*_*_D''#D$7== $}DDW}}bfgkgzb{b{}}   &,,..);;(,%'#.rz~~jK\>\^e/f/f#g#gkl#lD "*&1"*..NbAbdk2l2l&m&mqr&rD# ($/
zL^?^`g0h0h$i$imn$nD!(0BJNN:8R+RT[\\]]abb ) )1BJNN:8S+SU\]]^^bcc * ) 	+$2I 	+M6   '+D#d1488 	B$$T%@AAA" 	T!! 1133!## 	1133"$$ 2244!## 1133"m  
 "T!S!S!SD	T 	Tr,   c                    ddl m}m}m}m}m} ||| _        | j        %t          j        	                    dd          | _        t          | j        t                    r`| j                                        r# |t          | j                            | _        n$|| j                                                 | _        | j        |j        k    r6| j         |dd          | _        | j         |dd          | _        dS dS | j        |j        k    r2| j         |d          | _        | j         |d          | _        dS dS dS )	zI
        Set the state dict config based on the `StateDictType`.
        r   )FullOptimStateDictConfigFullStateDictConfigShardedOptimStateDictConfigShardedStateDictConfigStateDictTypeNFSDP_STATE_DICT_TYPEFULL_STATE_DICTT)offload_to_cpu
rank0_only)rT  )2torch.distributed.fsdp.fully_sharded_data_parallelrM  rN  rO  rP  rQ  r  r   r   r   r  rN   r  r   r   rS  r  r  SHARDED_STATE_DICT)r)   r  rM  rN  rO  rP  rQ  s          r*   rG  z2FullyShardedDataParallelPlugin.set_state_dict_type  s   	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 &#2D '#%:>>2HJ[#\#\D d*C00 	S#++-- S'4}S9M5N5N'O'O$$'4T5I5O5O5Q5Q'R$=#@@@%-)<)<D]a)b)b)b&+3/G/GW[hl/m/m/m,,, 43!]%EEE%-)?)?t)T)T)T&+3/J/JZ^/_/_/_,,,	 FE 43r,   c                    ddl m}m} t          |dd          }|t	          |          ng }| j        |k    r| j        || _        t                      }| j        D ]<}t          ||          }|t          d| d          |
                    |           =t          j        | j        |          | _        dS | j        |k    r;| j        dk    r't          j        | j        | j                  | _        dS d| _        dS dS )	z
        Given `model`, creates an `auto_wrap_policy` baesd on the passed in policy and if we can use the
        `transformer_cls_to_wrap`
        r   r4  _no_split_modulesNz+Could not find the transformer layer class z in the model.)transformer_layer_cls)r&  )rH  r5  r6  r  rL   r  r%  setr  rB   add	functoolspartialr&  )	r)   r   r5  r6  no_split_modules%default_transformer_cls_names_to_wraptransformer_cls_to_wrapr  r   s	            r*   set_auto_wrap_policyz3FullyShardedDataParallelPlugin.set_auto_wrap_policy  sS   
 	jiiiiiii #5*=tDDJZJf5E0F0F0Fln- $@@@195Z2&)ee##A = ="<UK"P"P"*$%nS^%n%n%nooo'++O<<<<$-$5%=T% % %D!!! "&AAA"Q&&(1(9$:O`d`s(t(t(t%%%(,%%% BAr,   Fc           	         	 t           j        t           j        t           j        t           j        d	|}t	          |t
                    rM	                    |d          }|4t          d| dt          		                                                     ndt	          |t           j
                  rJ|	                                vr4t          d| dt          	                                                     |rt           j        n|}ddlm} |s j         ||||           _        dS t	           j        t                    r fddD             }	fd	 j                                        D             }|s|r9t          d
 j         dt          	                                                      |di  j         _        dS dS )z(Sets the mixed precision policy for FSDP)r)  rZ   r[   fp32NzInvalid mixed precision: r   r   )MixedPrecision)param_dtypereduce_dtypebuffer_dtypec                 &    g | ]}|j         v|S r0   )r  )r1   r2   r)   s     r*   r   zFFullyShardedDataParallelPlugin.set_mixed_precision.<locals>.<listcomp>  s.       aW[WrNrNrNrNrNrr,   c                 F    g | ]\  }}|                                 v|S r0   )values)r1   r2   r3   mixed_precision_mappings      r*   r   zFFullyShardedDataParallelPlugin.set_mixed_precision.<locals>.<listcomp>  s;       aQNeNlNlNnNnEnEnEnEnEnr,   z Invalid mixed precision policy: zf. Must be a `dict` with keys `param_dtype`, `reduce_dtype`, and `buffer_dtype`. Values must be one of r0   )r   bfloat16float16float32r  rN   r   rB   rL   r  r@  rk  rV  re  r  r   r8   )
r)   r  buffer_autocastoverrider@  buffer_typere  missing_keysinvalid_valuesrl  s
   `        @r*   r  z2FullyShardedDataParallelPlugin.set_mixed_precision  s`    >MNM	#
 #
  os++ 		+//FFE} xxxRVWnWsWsWuWuRvRvxx    55 	/QhQoQoQqQq:q:qvOvvdSjSqSqSsSsNtNtvv   (7AemmEUUUUUU 	Xt2:*8.!K+ + +D''' 3T:: 	X   J  L   "9??AA  N  ~  Vt7R V V-12I2P2P2R2R-S-SV V  
 +9.*W*W4;V*W*WD'''	X 	Xr,   r$   )FF))r;   r<   r=   r>   r   r  r   rN   rV   r  r  r   r   r  r   r   r  rU   r  r
   r   nnModuler  r  r  r  r  r   r!  r"  r#  r$  r%  r   r&  r   r   rG  rb  r  r0   r,   r*   r  r  q  sN        : :x PUu  {
P P PuS"KKL    PUu  E
P P PuS"KKL    ^c]b |
^ ^ ^HU41X+X%YZ    	 N	
 	
 	
 huXw7m/n%nop    EJE  }
E E EKt@@A    <A5PQ< < <OXhux78   
 KP%  k
K K KOU3 FFG    	tu	 	 	 x=	
    	t
	 	 	 Xuv    $e N
  t    "Eij  OT    BG B
B B BM8Heho%6%<=>     %u T
         #U o
  d    &+U <
& & &d    ',e D
' ' 't    :?  L
: : :!8DI#6    %*E  W
% % %NHSM   mT mT mT^"` "` "` "`H- - ->*X *X *X *X *X *Xr,   r  c                      e Zd ZU dZ edddi          Zeed<    edddi          Zeed<    eddd	i          Z	eed
<    edddi          Z
eed<    edddi          Zeed<    edddi          Zeed<    edddi          Zeed<    edddi          Zeed<    edddi          Zeed<    edddi          Zeed<    edddi          Zeed<    edddi          Zeed<    edddi          Zeed <    eddd!i          Zeed"<    eddd#i          Zeed$<    ed%dd&i          Zeed'<    eddd(i          Zeed)<    eddd*i          Zeed+<    eddd,i          Zeed-<    eddd.i          Zeed/<    eddd0i          Zeed1<    ed2dd3i          Zeed4<    eddd5i          Z e!e         ed6<    eddd7i          Z"e#e$         ed8<    eddd9i          Z%e#e$         ed:<    ed;dd<i          Z&eed=<    ed>dd?i          Z'eed@<    edddAi          Z(eedB<    edddCi          Z)eedD<    edddEi          Z*eedF<    edddGi          Z+eedH<    ed>ddIi          Z,eedJ<    edKddLi          Z-eedM<    edNddOi          Z.eedP<    ed>ddQi          Z/eedR<    edddSi          Z0e#e1         edT<    edddUi          Z2e#e3ee1f                  edV<    edddWi          Z4e#e$         edX<    edddYi          Z5e#e$         edZ<    eddd[i          Z6e#e$         ed\<    eddd]i          Z7e#e$         ed^<    eddd_i          Z8e#e$         ed`<    edddai          Z9e#e3ee1f                  edb<   dc Z:djddZ;de Z<df Z=dg Z>dh Z?di Z@dS )kMegatronLMPlugina  
    Plugin for Megatron-LM to enable tensor, pipeline, sequence and data parallelism. Also to enable selective
    activation recomputation and optimized fused kernels.

    Args:
        tp_degree (`int`, defaults to `None`):
            Tensor parallelism degree.
        pp_degree (`int`, defaults to `None`):
            Pipeline parallelism degree.
        num_micro_batches (`int`, defaults to `None`):
            Number of micro-batches.
        gradient_clipping (`float`, defaults to `None`):
            Gradient clipping value based on global L2 Norm (0 to disable).
        sequence_parallelism (`bool`, defaults to `None`):
            Enable sequence parallelism.
        recompute_activations (`bool`, defaults to `None`):
            Enable selective activation recomputation.
        use_distributed_optimizr (`bool`, defaults to `None`):
            Enable distributed optimizer.
        pipeline_model_parallel_split_rank (`int`, defaults to `None`):
            Rank where encoder and decoder should be split.
        num_layers_per_virtual_pipeline_stage (`int`, defaults to `None`):
            Number of layers per virtual pipeline stage.
        is_train_batch_min (`str`, defaults to `True`):
            If both tran & eval dataloaders are specified, this will decide the `micro_batch_size`.
        train_iters (`int`, defaults to `None`):
            Total number of samples to train over all training runs. Note that either train-iters or train-samples
            should be provided when using `MegatronLMDummyScheduler`.
        train_samples (`int`, defaults to `None`):
            Total number of samples to train over all training runs. Note that either train-iters or train-samples
            should be provided when using `MegatronLMDummyScheduler`.
        weight_decay_incr_style (`str`, defaults to `'constant'`):
            Weight decay increment function. choices=["constant", "linear", "cosine"].
        start_weight_decay (`float`, defaults to `None`):
            Initial weight decay coefficient for L2 regularization.
        end_weight_decay (`float`, defaults to `None`):
            End of run weight decay coefficient for L2 regularization.
        lr_decay_style (`str`, defaults to `'linear'`):
            Learning rate decay function. choices=['constant', 'linear', 'cosine'].
        lr_decay_iters (`int`, defaults to `None`):
            Number of iterations for learning rate decay. If None defaults to `train_iters`.
        lr_decay_samples (`int`, defaults to `None`):
            Number of samples for learning rate decay. If None defaults to `train_samples`.
        lr_warmup_iters (`int`, defaults to `None`):
            Number of iterations to linearly warmup learning rate over.
        lr_warmup_samples (`int`, defaults to `None`):
            Number of samples to linearly warmup learning rate over.
        lr_warmup_fraction (`float`, defaults to `None`):
            Fraction of lr-warmup-(iters/samples) to linearly warmup learning rate over.
        min_lr (`float`, defaults to `0`):
            Minumum value for learning rate. The scheduler clip values below this threshold.
        consumed_samples (`List`, defaults to `None`):
            Number of samples consumed in the same order as the dataloaders to `accelerator.prepare` call.
        no_wd_decay_cond (`Optional`, defaults to `None`):
            Condition to disable weight decay.
        scale_lr_cond (`Optional`, defaults to `None`):
            Condition to scale learning rate.
        lr_mult (`float`, defaults to `1.0`):
            Learning rate multiplier.
        megatron_dataset_flag (`bool`, defaults to `False`):
            Whether the format of dataset follows Megatron-LM Indexed/Cached/MemoryMapped format.
        seq_length (`int`, defaults to `None`):
            Maximum sequence length to process.
        encoder_seq_length (`int`, defaults to `None`):
            Maximum sequence length to process for the encoder.
        decoder_seq_length (`int`, defaults to `None`):
            Maximum sequence length to process for the decoder.
        tensorboard_dir (`str`, defaults to `None`):
            Path to save tensorboard logs.
        set_all_logging_options (`bool`, defaults to `False`):
            Whether to set all logging options.
        eval_iters (`int`, defaults to `100`):
            Number of iterations to run for evaluation validation/test for.
        eval_interval (`int`, defaults to `1000`):
            Interval between running evaluation on validation set.
        return_logits (`bool`, defaults to `False`):
            Whether to return logits from the model.
        custom_train_step_class (`Optional`, defaults to `None`):
            Custom train step class.
        custom_train_step_kwargs (`Optional`, defaults to `None`):
            Custom train step kwargs.
        custom_model_provider_function (`Optional`, defaults to `None`):
            Custom model provider function.
        custom_prepare_model_function (`Optional`, defaults to `None`):
            Custom prepare model function.
        custom_megatron_datasets_provider_function (`Optional`, defaults to `None`):
            Custom megatron train_valid_test datasets provider function.
        custom_get_batch_function (`Optional`, defaults to `None`):
            Custom get batch function.
        custom_loss_function (`Optional`, defaults to `None`):
            Custom loss function.
        other_megatron_args (`Optional`, defaults to `None`):
            Other Megatron-LM arguments. Please refer Megatron-LM.
    NrD  ztensor parallelism degree.rE  	tp_degreezpipeline parallelism degree.	pp_degreeznumber of micro-batches.num_micro_batchesz>gradient clipping value based on global L2 Norm (0 to disable)rv  zenable sequence parallelismsequence_parallelismz)enable selective activation recomputationrecompute_activationszenable distributed optimizeruse_distributed_optimizerz/Rank where encoder and decoder should be split."pipeline_model_parallel_split_rankz,Number of layers per virtual pipeline stage.%num_layers_per_virtual_pipeline_stageTzUIf both train & eval dataloaders are specified, this will decide the micro_batch_sizerx  zTotal number of iterations to train over all training runs. Note that either train-iters or train-samples should be provided when using `MegatronLMDummyScheduler`train_iterszTotal number of samples to train over all training runs. Note that either train-iters or train-samples should be provided when using `MegatronLMDummyScheduler`train_samplesconstantzKWeight decay increment function. choices=["constant", "linear", "cosine"]. weight_decay_incr_stylez7Initial weight decay coefficient for L2 regularization.start_weight_decayz:End of run weight decay coefficient for L2 regularization.end_weight_decaylinearzGLearning rate decay function. choices=['constant', 'linear', 'cosine'].lr_decay_stylezPNumber of iterations for learning rate decay. If None defaults to `train_iters`.lr_decay_iterszONumber of samples for learning rate decay. If None defaults to `train_samples`.lr_decay_samplesz;number of iterations to linearly warmup learning rate over.lr_warmup_itersz8number of samples to linearly warmup learning rate over.lr_warmup_sampleszLfraction of lr-warmup-(iters/samples) to linearly warmup learning rate over.lr_warmup_fractionr   zPMinumum value for learning rate. The scheduler clip values below this threshold.min_lrz^Number of samples consumed in the same order as the dataloaders to `accelerator.prepare` call.consumed_samplesz"Condition to disable weight decay.no_wd_decay_condz!Condition to scale learning rate.scale_lr_cond      ?zLearning rate multiplier.lr_multFzUWhether the format of dataset follows Megatron-LM Indexed/Cached/MemoryMapped format.megatron_dataset_flagz#Maximum sequence length to process.
seq_lengthz3Maximum sequence length to process for the encoder.encoder_seq_lengthz3Maximum sequence length to process for the decoder.decoder_seq_lengthzPath to save tensorboard logs.tensorboard_dirz#Whether to set all logging options.set_all_logging_optionsd   z?Number of iterations to run for evaluation validation/test for.
eval_itersi  z6Interval between running evaluation on validation set.eval_intervalz(Whether to return logits from the model.return_logitszCustom train step class.custom_train_step_classzCustom train step kwargs.custom_train_step_kwargszCustom model provider function.custom_model_provider_functionzCustom prepare model function.custom_prepare_model_functionz<Custom megatron train_valid_test datasets provider function.*custom_megatron_datasets_provider_functionzCustom get batch function.custom_get_batch_functionzCustom loss function.custom_loss_functionz5Other Megatron-LM arguments. Please refer Megatron-LMother_megatron_argsc                 j   d}| j         5t          t          j                            |dz   d                    | _         | j        5t          t          j                            |dz   d                    | _        | j        5t          t          j                            |dz   d                    | _        | j        5t          t          j                            |dz   d                    | _        | j	        9t          t          j                            |dz   d	                    dk    | _	        | j        9t          t          j                            |d
z   d	                    dk    | _        | j        9t          t          j                            |dz   d	                    dk    | _        | j        dk    s| j        rd| _        nd| _        | j        gt          | j                  dk    r| j                            ddg           n2t          | j                  dk    r| j                            d           i d| j         d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        d| j        | _        | j	        r
d | j        d!<   | j        *| j        | j        d"<   | j        r|                                  | j        !| j                            | j                   d S d S )#NMEGATRON_LM_	TP_DEGREEr   	PP_DEGREENUM_MICRO_BATCHESGRADIENT_CLIPPINGr  RECOMPUTE_ACTIVATIONSrl  USE_DISTRIBUTED_OPTIMIZERSEQUENCE_PARALLELISMlocalr   r   r  tensor_model_parallel_sizepipeline_model_parallel_sizer  r  DDP_implr~  sequence_parallel	clip_gradr{  r  r  r  r  r  r  r  	selectiverecompute_granularityr  ) ry  r   r   r   r   rz  r{  rv  r   r}  r   r~  r|  r  r  r  extendr  r  r  r  r  r  r  r  r  megatron_lm_default_argsr  r  set_tensorboard_logging_optionsr  updatern  s     r*   r   zMegatronLMPlugin.__post_init__  sj   >! 0Da!H!HIIDN>! 0Da!H!HIIDN!)%(AT8TVW)X)X%Y%YD"!)%*2:>>&CV:VX[+\+\%]%]D"%-)4RZ^^FMdDdfm5n5n)o)ost)tD&)1BJNN64O+OQXYYZZ^__ * $,(3BJNN6LbCbdk4l4l(m(mqr(rD%>A!?#DMM#DM ,4())Q..%,,aV4444T*++q00%,,Q///)
($.)
*DN)
 1$2Y)
 4T5_	)

 )
 ()G)
  !:)
 /)
  !7)
  5)
  5)
 T/)
 t|)
 $T%?)
 $/)
  T/!)
%$ % 	QEPD)*AB+?C?SD)*;<+ 744666#/)001IJJJJJ 0/r,   c                     |j         j                                        }t                                          D ] }||v rt          |         | ||            d S !t          d| d          )Nz0Accelerate Megatron-LM integration not supports z1 model. You can add your own model config parser.)r  
model_typer   !MODEL_CONFIGS_TO_MEGATRON_PARSERSr  rB   )r)   r   
batch_datamodel_config_typer  s        r*   set_network_size_argsz&MegatronLMPlugin.set_network_size_argsJ  s    !L399;;;@@BB 	 	J...1*=dE:VVV / 8?P 8 8 8
 
 	
r,   c                 z    |dk    rd| j         d<   d S |dk    r"d| j         d<   d| _        | j        | j         d<   d S d S )NrZ   Tr[   r  r  )r  r  )r)   r  s     r*   r  z$MegatronLMPlugin.set_mixed_precisionU  s\    f$$48D)&111&&48D)&1#DM8<D)*555 '&r,   c                     || _         || _        ||z  | j        z  | _        | j         | j        d<   | j        | j        d<   | j        | j        d<   d S )Ndata_parallel_sizemicro_batch_sizeglobal_batch_size)r  r  r{  r  r  )r)   r  	dp_degrees      r*   set_training_argsz"MegatronLMPlugin.set_training_args]  sa    "+ 0!*-=!=@V!V>B>U%&:;<@<Q%&89=A=S%&9:::r,   c                    |j         j                                        }d|v rVd| j        d<   |j        d         d         | j        d<   |j        d         d         | j        d<   |j        d         | j        d	<   n7d
|v r d
| j        d<   |j        d         | j        d<   nt          d| d          |j        d         | j        d<   |j        d         | j        d<   d S )Nadam	optimizerbetasr   
adam_beta1r   
adam_beta2epsadam_epssgdmomentumsgd_momentumz
Optimizer z  is not supported by Megatron-LMlrweight_decay)r7   r;   r   r  defaultsrB   )r)   r  optimizer_names      r*   set_optimizer_typez#MegatronLMPlugin.set_optimizer_typee  s    ",5;;==^##9?D)+6:C:LW:UVW:XD),7:C:LW:UVW:XD),78A8J58QD)*55n$$9>D)+6<E<Nz<ZD).99Z.ZZZ[[[.7.@.F%d+8A8J>8Z%n555r,   c                 z   | j         <|j        | j        d         z  | _         | j        d | _        t	          j        d           | j        <|j        | j        d         z  | _        | j        t	          j        d           d| _        | j         | j        d<   | j        | j        d<   | j        | j        d<   | j        | j        d<   | j	        | j        d	<   | j
        | j        d
<   | j        | j        d<   | j        | j        d<   | j        | j        d<   | j        | j        d<   | j        | j        d<   | j        | j        d<   d S )Nr  zXIgnoring `train_samples` as `train_iters` based on scheduler is being used for training.z`Ignoring `lr_warmup_samples` as `lr_warmup_iters` based on scheduler is being used for training.r   r  r  r  r  r  r  r  r  r  r  r  r  )r  total_num_stepsr  r  r  r  r  warmup_num_stepsr  r  r  r  r  r  r  r  r  )r)   	schedulers     r*   set_scheduler_argsz#MegatronLMPlugin.set_scheduler_argsu  sh   #(8D<YZn<ooD!-%)"n   '#,#=A^_sAt#tD %1v   &'D"7;7G%m4;?;O%&789=9K%o6=A=S%&9::>:M%&67<@<Q%&89>B>U%&:;:>:M%&67CGC_%&?@>B>U%&:;<@<Q%&8926+%h///r,   c                    ddl m} t          j                    } ||          }|                                }t          |d                   | _        | j                                        D ]X\  }}|                    d          rd| j	        |<   %|                    d          rd| j	        |
                    dd          <   Yd S )Nr   )_add_logging_argslog_Tno_log_no_r  )megatron.argumentsr  argparseArgumentParserparse_known_argsvarsdataset_argsr8   
startswithr  r  )r)   r  parserlogging_argsr  rI   s         r*   r  z0MegatronLMPlugin.set_tensorboard_logging_options  s    888888(**""6**..00 a11+1133 	M 	MJC~~f%% M59-c22	** MHL-ckk%.D.DE		M 	Mr,   r$   )Ar;   r<   r=   r>   r   ry  r   rV   rz  r{  rv  r   r|  rU   r}  r~  r  r  rx  rN   r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r   r   r  r  r  r  r  r  r  r  r  r  r  r  r   r  r	   r  r  r  r  r  r  r   r  r  r  r  r  r  r0   r,   r*   rx  rx    s	        ] ]~ U46;W2XYYYIsYYYU46;Y2Z[[[Is[[["U46C]:^___s___$u(hi     u    "'78" " "$    #(%EF# # #4    ',e89' ' 't    /4e(YZ/ / /&    27(VW2 2 2)3    $eqr      u u
  K     u
  M3    $)5gh$ $ $S    !&ST! ! !    $eVW  e     %cd  NC     %lm  NC    "Ekl  c    !5WX  OS    #UTU  s    !&hi! ! !    Elm  FE    #(%t
# # #d3i    ,15QuHv+w+w+whx(www(-dfNqEr(s(s(sM8H%sssU3&:U1VWWWGUWWW"'%qr# # #4    e?@  J    $eOP      $eOP      !5:;  OS    %*E?@% % %T    ev'hi  J    (`a  M3     %DE  M4    .3U45. . .Xc]    :?56: : :htCH~6    :?;<: : :"HX$6    9>:;9 9 9!8H#5    FKUXYF F F.0B    5:E675 5 5x1    05u120 0 0(8,    5:EQR5 5 5$sCx.1   
7K 7K 7Kr	
 	
 	
 	
F F FT T T[ [ [ > > >:M M M M Mr,   rx  r  c                       fd}|S )Nc                 \     t          j                    fd            } t          <   |S )Nc                       | i |S r$   r0   )argsr  funcs     r*   r   z\add_model_config_to_megatron_parser.<locals>.add_model_config_parser_helper.<locals>.wrapper  s    4((((r,   )r]  wrapsr  )r  r   r  s   ` r*   add_model_config_parser_helperzKadd_model_config_to_megatron_parser.<locals>.add_model_config_parser_helper  sD    				) 	) 	) 	) 
		) 9=)*5r,   r0   )r  r  s   ` r*   #add_model_config_to_megatron_parserr    s$         *)r,   zmegatron-bertc                    d}|j         j        }|j         j        }|j         j        }|j         j        }|j         j        }|j         j        }	d}
d|j        j        	                                v rd}
| j
        (| j        t          j        d           | j        | _
        n6| j        | j        | _
        n"||d         j        d         | _
        n|| _
        | j
        | j        d<   || j        d	<   || j        d
<   || j        d<   || j        d<   || j        d<   |
| j        d<   |	| j        d<   |j         j        | j        d<   || j        d<   d S )NbertFmaskedlmTzOBoth `seq_length` and `encoder_seq_length` are set. Using `encoder_seq_length`.	input_idsr   r  model_type_name
num_layershidden_sizenum_attention_headsmax_position_embeddingspretraining_flagorig_vocab_sizemodel_return_dict
num_labels)r  num_hidden_layersr  r  r  r  
vocab_sizer7   r;   r   r  r  r  r  r?  r  return_dict)megatron_lm_pluginr   r  r  r  r  r  r  r  r  r  s              r*   parse_bert_configr    s   O/J,*K,:#lB(Jl-OU_-335555$00<Mklll(:(M%%		.	:(:(M%%		(2;(?(Ea(H%%(?%@R@]/=ET/0AB@J/=AL/>I\/0EFMd/0IJFV/0BCET/0ABGL|G_/0CD@J/===r,   gpt2c                 T   d}|j         j        }|j         j        }|j         j        }|j         j        }|j         j        }d}	| j        (| j        t          j	        d           | j        | _        n6| j        | j        | _        n"||d         j
        d         | _        n|| _        | j        | j        d<   | j        | j        d<   d| j        d	<   || j        d
<   || j        d<   || j        d<   || j        d<   || j        d<   |	| j        d<   || j        d<   |j         j        | j        d<   d S )NgptTzOBoth `seq_length` and `decoder_seq_length` are set. Using `decoder_seq_length`.r  r   r  r  GPT2BPETokenizertokenizer_typer  r  r  r  r  r  r  r  )r  n_layern_embdn_headn_positionsr  r  r  r  r  r?  r  r  r  
r  r   r  r  r  r  r  r  r  r  s
             r*   parse_gpt2_configr    se   O%J,%K,-#l6l-O$00<Mklll(:(M%%		.	:(:(M%%		(2;(?(Ea(H%%(?%@R@]/=CUCc/@DV/0@AET/0AB@J/=AL/>I\/0EFMd/0IJFV/0BCET/0ABGL|G_/0CDDDr,   t5c                 H   d}|j         j        }|j         j        }|j         j        }t	          |j         d          r|j         j        nd}|j         j        }d}	| j        "||d         j        d         | _        n|| _        | j	        "||d         j        d         | _	        n|| _	        | j        | j
        d<   | j	        | j
        d	<   || j
        d
<   || j
        d<   || j
        d<   || j
        d<   || j
        d<   |	| j
        d<   || j
        d<   |j         j        | j
        d<   d S )Nr  r  r   Tr  r   labelsr  r  r  r  r  r  r  r  r  r  )r  r  d_model	num_headshasattrr  r  r  r?  r  r  r  r  s
             r*   parse_t5_configr    sa   O(J,&K,0:A%,P]:^:^hel66dhl-O,4!4>{4K4QRS4T114K1,4!4>x4H4Nq4Q114K1HZHm/0DEHZHm/0DEET/0AB@J/=AL/>I\/0EFMd/0IJFV/0BCET/0ABGL|G_/0CDDDr,   llamac                 D   d}|j         j        }d}|j         j        }|j         j        }|j         j        }|j         j        }	t          |j         dd           }
| j        @|
|
| _        n6| j        | j        | _        n"||d         j	        d         | _        n|	| _        | j
        | j        d<   d| j        d<   || j        d	<   || j        d
<   || j        d<   || j        d<   || j        d<   || j        d<   |	| j        d<   | j        | j        d<   |j         j        | j        d<   d S )Nr  Tmax_sequence_lengthr  r   r  Llama2Tokenizerr	  r  r  r  r  r  r  r  r  r  )r  r   r  r  r  r  r  r  r  r?  r  r  r  )r  r   r  r  r  r  r  r  r  r  r  s              r*   parse_llama_configr  	  sb   O/J,*K,:l-O#lB'<dCCJ$,!,6))2>,>,Q))#,6{,C,I!,L)),C)CUCc/@DU/0@AET/0AB@J/=FV/0BCAL/>I\/0EFET/0ABMd/0IJ@R@]/=GL|G_/0CDDDr,   c                      e Zd ZU dZ edddi          Zeed<    edddi          Ze	ed	<    eddd
i          Z
eed<    edddi          Zeed<    edddi          Zeed<    edddi          Zeed<    edddi          Zej        ed<    edddi          Zee         ed<    edddi          Zee         ed<   d ZdS )BnbQuantizationConfiga  
    A plugin to enable BitsAndBytes 4bit and 8bit quantization

    Args:
        load_in_8bit (`bool`, defaults to `False`):
            Enable 8bit quantization.
        llm_int8_threshold (`float`, defaults to `6.0`):
            Value of the outliner threshold. Only relevant when `load_in_8bit=True`.
        load_in_4_bit (`bool`, defaults to `False`):
            Enable 4bit quantization.
        bnb_4bit_quant_type (`str`, defaults to `fp4`):
            Set the quantization data type in the `bnb.nn.Linear4Bit` layers. Options are {'fp4','np4'}.
        bnb_4bit_use_double_quant (`bool`, defaults to `False`):
            Enable nested quantization where the quantization constants from the first quantization are quantized
            again.
        bnb_4bit_compute_dtype (`bool`, defaults to `fp16`):
            This sets the computational type which might be different than the input time. For example, inputs might be
            fp32, but computation can be set to bf16 for speedups. Options are {'fp32','fp16','bf16'}.
        torch_dtype (`torch.dtype`, defaults to `None`):
            This sets the dtype of the remaining non quantized layers. `bitsandbytes` library suggests to set the value
            to `torch.float16` for 8 bit model and use the same dtype as the compute dtype for 4 bit model.
        skip_modules (`List[str]`, defaults to `None`):
            An explicit list of the modules that we don't quantize. The dtype of these modules will be `torch_dtype`.
        keep_in_fp32_modules (`List`, defaults to `None`):
            An explicit list of the modules that we don't quantize. We keep them in `torch.float32`.
    FrD  zenable 8bit quantization.rE  load_in_8bit      @zEvalue of the outliner threshold. only relevant when load_in_8bit=Truellm_int8_thresholdzenable 4bit quantization.load_in_4bitfp4z\set the quantization data type in the `bnb.nn.Linear4Bit` layers. Options are {'fp4','np4'}.bnb_4bit_quant_typezlenable nested quantization where the quantization constants from the first quantization are quantized again.bnb_4bit_use_double_quantrZ   zThis sets the computational type which might be different than the input time. For example, inputs might be fp32, but computation can be set to bf16 for speedups. Options are {'fp32','fp16','bf16'}.bnb_4bit_compute_dtypeNzthis sets the dtype of the remaining non quantized layers. `bitsandbytes` library suggests to set the valueto `torch.float16` for 8 bit model and use the same dtype as the compute dtype for 4 bit model torch_dtypezian explicit list of the modules that we don't quantize. The dtype of these modules will be `torch_dtype`.skip_moduleszXan explicit list of the modules that we don't quantize. We keep them in `torch.float32`.keep_in_fp32_modulesc                    t          | j        t                    st          d          t          | j        t                    st          d          | j        r| j        rt          d          | j        s| j        st          d          t          | j        t          t          f          st          d          t          | j        t                    st          d          | j        dvrt          d| j                   t          | j
        t                    st          d	          t          | j        t                    rn| j        d
k    rt          j        | _        n| j        dk    rt          j        | _        nb| j        dk    rt          j        | _        nEt          d| j                   t          | j        t          j                  st          d          | j        )t          | j        t$                    st          d          | j        )t          | j        t$                    st          d          | j        rt(          j        | _        | j        rt          j        | _        | j        r| j        dk    rt1          j        d           t          | j        t                    rn| j        d
k    rt          j        | _        nQ| j        dk    rt          j        | _        n4| j        dk    rt          j        | _        nt          d| j                   | j        r| j        t          j        | _        | j        r| j        | j        | _        t          | j        t          j                  st          d          dS )z~
        Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
        zload_in_8bit must be a booleanzload_in_4bit must be a booleanz-load_in_4bit and load_in_8 can't be both Truez.load_in_4bit and load_in_8 can't be both Falsez,llm_int8_threshold must be a float or an intz$bnb_4bit_quant_type must be a string)r"  nf4z7bnb_4bit_quant_type must be in ['fp4','nf4'] but found z+bnb_4bit_use_double_quant must be a booleanrd  rZ   r[   zCbnb_4bit_compute_dtype must be in ['fp32','fp16','bf16'] but found z8bnb_4bit_compute_dtype must be a string or a torch.dtypeNz&skip_modules must be a list of stringsz/keep_in_fp_32_modules must be a list of stringsr  z<llm_int8_threshold can only be used for model loaded in 8bitz8torch_dtype must be in ['fp32','fp16','bf16'] but found z!torch_dtype must be a torch.dtype)r  r  rU   rB   r!  r   r   r   r#  rN   r$  r%  r   ro  rn  rm  r@  r'  rL   r(  r8  r;  target_dtypeint8r  r  r&  r(   s    r*   r   z#BnbQuantizationConfig.__post_init__	  s    $+T22 	?=>>>$+T22 	?=>>> 	N!2 	NLMMM  	O): 	OMNNN$1C<@@ 	MKLLL$2C88 	sCDDD%^;;qW[Woqqrrr$8$?? 	LJKKKd1377 	Y*f44.3m++,66.3m++,66.3n++ wZ^Zuww   D7EE 	YWXXX(D<Mt1T1T(EFFF$0DD]_c9d9d0NOOO 	1 + 0D 	+ %
D 	Z!8C!?!?MXYYYd&,, 	p6))#(=  !V++#(=  !V++#(>   !n\`\l!n!nooo 	-!1!9$}D 	;!1!9#:D$*EK88 	B@AAA	B 	Br,   )r;   r<   r=   r>   r   r  rU   rV   r   r   r!  r#  rN   r$  r%  r&  r   r@  r'  r   r(  r   r0   r,   r*   r  r  2	  s         6 u@[7\]]]L$]]] %v'no! ! !    u@[7\]]]L$]]]$ur
         ',e  C
' ' 't    $)5 i
$ $ $D     %u n
     K    $e
  L$s)    ',etu' ' '$s)   
HB HB HB HB HBr,   r  c                     t          |                                           }| j        j        |k    r| j        S t	          |          dk    rdS |D ]}t          ||          }||c S dS )z
    Gets a class from a module by its name.

    Args:
        module (`torch.nn.Module`): The module to get the class from.
        name (`str`): The name of the class.
    r   N)rL   childrenr7   r;   r  r  )moduler  modules_childrenchild_modulemodule_classs        r*   r  r  	  s     FOO--.. D((			!	#	#, 	$ 	$L5lDIIL'#### (	$ 	$r,   )Xr>   r  r%   enumr]  r   r  
contextlibr   dataclassesr   r   datetimer   typingr   r   r	   r
   r   r   r   r   r   r   r   	constantsr   r   r   r   r   environmentr   r   r  r   r   r   r   r   r   versionsr   r    r"   EnumMetar@   EnumrG   rR   rX   rd   r   r   r   r   r   r   r   r   r   rN   r   r   r   r  r  r  r(  r,  r8  r>  rC  rO  rZ  r`  rs  r  rx  r  r  r  r  r  r  r  r  r0   r,   r*   <module>r=     s           				  % % % % % % ( ( ( ( ( ( ( (       a a a a a a a a a a a a a a a a a a a a a a a a               : 9 9 9 9 9 9 9                9 8 8 8 8 8 8 8L L L L L L L L*    t}   	# 	# 	# 	# 	#ty$4 	# 	# 	# 	#     ]   *, , , , ,x , , ,( I I I I IM I I IX     }   < 6 6 6 6 6] 6 6 6< -
 :$%	34  sk sk sk sk skm sk sk skn 78  k
 k
 k
 k
 k
M k
 k
 k
\         c49      >& & & & &sDI & & &"    S$)   * * * * *di * * *3 3 3 3 3C 3 3 3l       ,    C        h       $)           
 Q Q Q Q Q Q Q Qh ;/ ;/ ;/ ;/ ;/ ;/ ;/ ;/| - - - - - - - -` . . . . . . . .b j
 j
 j
 j
 j
 j
 j
 j
Z VX VX VX VX VX VX VX VXr QM QM QM QM QM QM QM QMh %' !	*C 	* 	* 	* 	* %$_55K K 65KB %$V,,` ` -,`> %$T**` ` +*`< %$W--` ` .-`B VB VB VB VB VB VB VB VBr$ $ $ $ $r,   