
    ;i                    L   S r SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKJ	r	  SSK
Jr  SSKJrJr  SSKJr  SSKJrJrJrJrJrJrJr  SSKrSS	KJrJrJrJrJrJ r J!r!J"r"J#r#  SS
K$J%r%J&r&  SSK'J(r(J)r)J*r*J+r+J,r,J-r-J.r.J/r/  SSK0J1r1J2r2  \(       a  SSK3J4r4  \Rj                  " \65      r7 " S S5      r8 " S S\Rr                  5      r: " S S\Rv                  \:S9r<\ " S S\85      5       r= " S S\<5      r>\ " S S\85      5       r?\ " S S\85      5       r@\ " S S\85      5       rA\S   rB\S    rC\S!   rD\S"   rE\ " S# S$\85      5       rF\ " S% S&\85      5       rG\ " S' S(\85      5       rH\ " S) S*\G\H5      5       rI\S+   rJ\ " S, S-\85      5       rK " S. S/\L\Rv                  5      rM " S0 S1\L\Rv                  5      rN " S2 S3\L\Rv                  5      rO " S4 S5\L\Rv                  5      rP " S6 S7\L\<5      rQ " S8 S9\<5      rR " S: S;\L\<5      rS " S< S=\<5      rT " S> S?\Rv                  5      rU\ " S@ SA5      5       rV\ " SB SC5      5       rW\ " SD SE5      5       rX\ " SF SG\85      5       rY\ " SH SI\85      5       rZ\ " SJ SK5      5       r[\ " SL SM5      5       r\\ " SN SO5      5       r]\ " SP SQ5      5       r^\ " SR SS5      5       r_\ " ST SU5      5       r`0 raSV\L4SW jrb\b" SX5      SY 5       rc\b" SZ5      S[ 5       rd\b" S\5      S] 5       re\b" S^5      S_ 5       rf\ " S` Sa5      5       rgSb rhg)cz1
General namespace and dataclass related classes
    N)Iterable)contextmanager)	dataclassfield)	timedelta)TYPE_CHECKINGAnyCallableLiteralOptionalUnionget_args   )	!BETA_CP_AVAILABLE_PYTORCH_VERSION!BETA_TP_AVAILABLE_PYTORCH_VERSION&BETA_TP_AVAILABLE_TRANSFORMERS_VERSIONFSDP2_PYTORCH_VERSION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_hpu_availableis_mlu_availableis_msamp_availableis_musa_availableis_npu_availableis_transformer_engine_availableis_xpu_available)compare_versionsis_torch_version)Float8LinearConfigc                   $    \ rS rSrSrS rS rSrg)KwargsHandlerC   zH
Internal mixin that implements a `to_kwargs()` method for a dataclass.
c                 B    [         R                  " U R                  5      $ N)copydeepcopy__dict__selfs    l/home/dmtnaga/Documents/work/airagagent/rag_env/lib/python3.13/site-packages/accelerate/utils/dataclasses.pyto_dictKwargsHandler.to_dictH   s    }}T]]++    c                    SSK Jn  U" 5          U R                  5       R                  5       nSSS5        U R                  5       nUR	                  5        VVs0 s H  u  pEWU   U:w  d  M  XE_M     snn$ ! , (       d  f       NN= fs  snnf )zf
Returns a dictionary containing the attributes with values different from the default of this class.
r   )clear_environmentN)environmentr5   	__class__r1   items)r/   r5   default_dict	this_dictkvs         r0   	to_kwargsKwargsHandler.to_kwargsK   so    
 	3 >>+335L !LLN	!*!2K!2l1o6J!2KK !  Ls   A5B+B5
B N)__name__
__module____qualname____firstlineno____doc__r1   r=   __static_attributes__r?   r3   r0   r'   r'   C   s    ,
Lr3   r'   c                       \ rS rSrSrS rSrg)EnumWithContainsX   z\A metaclass that adds the ability to check if `self` contains an item with the `in` operatorc                 6     U " U5        g! [          a     gf = f)NFT)
ValueError)clsitems     r0   __contains__EnumWithContains.__contains__[   s'    	I   		s    
r?   N)r@   rA   rB   rC   rD   rM   rE   r?   r3   r0   rG   rG   X   s
    br3   rG   c                   .    \ rS rSrSrS r\S 5       rSrg)BaseEnumc   zDAn enum class that can get the value of an item with `str(Enum.key)`c                     U R                   $ r*   )valuer.   s    r0   __str__BaseEnum.__str__f   s    zzr3   c                 4    [        [        [        U 5      5      $ )z.Method to list all the possible items in `cls`)listmapstr)rK   s    r0   rW   BaseEnum.listi   s     CSM""r3   r?   N)	r@   rA   rB   rC   rD   rT   classmethodrW   rE   r?   r3   r0   rP   rP   c   s    J # #r3   rP   )	metaclassc                   <    \ rS rSr% SrSr\\S'   Sr\	\   \S'   Sr
g)AutocastKwargso   a  
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_enabledr?   )r@   rA   rB   rC   rD   r`   bool__annotations__ra   r   rE   r?   r3   r0   r^   r^   o   s!      GT$(M8D>(r3   r^   c                   ,    \ rS rSrSrSrSrSrSrSr	Sr
g	)
DDPCommunicationHookType   a  
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_sgdr?   N)r@   rA   rB   rC   rD   NOFP16BF16	POWER_SGDBATCHED_POWER_SGDrE   r?   r3   r0   re   re      s#    
 
BDDI+r3   re   c                   <  ^  \ rS rSr% SrSr\\S'   Sr\	\S'   Sr
\\S'   S	r\	\S
'   S	r\	\S'   S	r\	\S'   S	r\	\S'   \R                   r\\S'   \R                   r\\R                   \R(                  \R*                  4   \S'   \" \S9r\\S'   SU 4S jjrS rSrU =r$ )DistributedDataParallelKwargs   a  
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_optionc                    > [         TU ]  5       R                  5        VVs0 s H  u  p#X!;  d  M  X#_M     snn$ s  snnf r*   )superr1   r8   )r/   ignore_keysr;   r<   r7   s       r0   r1   %DistributedDataParallelKwargs.to_dict   s8    !&!2!8!8!:S!:a>R!:SSSs   ::c                    SSK JnJn  [        R                  UR
                  [        R                  UR                  [        R                  UR                  [        R                  UR                  0n[        R                  UR                  [        R                  UR                  0nUR                  U R                  5      nUR                  U R                  5      nU(       a  U(       a  U" U5      nU(       a]  U R                  [        R                  [        R                  4;   a  UR                   " S0 U R"                  D6OS nUR%                  UUS9  g g )Nr   )default_hookspowerSGD_hook)statehookr*   )+torch.distributed.algorithms.ddp_comm_hooksr   r   re   rm   fp16_compress_hookrn   bf16_compress_hookro   rp   batched_powerSGD_hookfp16_compress_wrapperbf16_compress_wrappergetr|   r}   PowerSGDStater   register_comm_hook)	r/   modelr   r   hook_mapwrapper_mapr   wrapperr   s	            r0   r   0DistributedDataParallelKwargs.register_comm_hook   s!   	
 %))=+K+K$))=+K+K$..0K0K$668[8[	>
 %))=+N+N$))=+N+NA

 $,<<#?&1ood6G6G&HG4=D >>,66,>> ++KD4J4JK   $$ %  r3   r?   ))r|   r}   r   )r@   rA   rB   rC   rD   rt   intrc   ru   rb   rw   rx   ry   rz   r{   re   rl   r|   r}   r   rm   rn   r   dictr   r1   r   rE   __classcell__r7   s   @r0   rr   rr      s    2 CL"t"M3#(D(!OT!$)T)L$*B*E*EI'E
 	!##	 ' ## %% %%	' $
 $D9t9T% %r3   rr   c                   `    \ rS rSr% SrSr\\S'   Sr\\S'   Sr	\\S'   S	r
\\S
'   Sr\\S'   Srg)GradScalerKwargs   a  
Use this object in your [`Accelerator`] to customize the behavior of mixed precision, specifically how the
`torch.amp.GradScaler` or `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}>

`torch.cuda.amp.GradScaler` is only available in PyTorch 1.5.0 and later versions, and `torch.amp.GradScaler` is
only available in PyTorch 2.4.0 and later versions.

</Tip>

Example:

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

kwargs = GradScalerKwargs(backoff_factor=0.25)
accelerator = Accelerator(kwargs_handlers=[kwargs])
```
g      @
init_scaleg       @growth_factorg      ?backoff_factori  growth_intervalTr`   r?   N)r@   rA   rB   rC   rD   r   floatrc   r   r   r   r   r`   rb   rE   r?   r3   r0   r   r      s;    .  JM5NEOSGTr3   r   c                   \    \ rS rSr% SrSr\\   \S'   Sr	\\   \S'   Sr
\\   \S'   S rS	rg)
InitProcessGroupKwargsi  am  
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                 d    U R                   c#  U R                  S:w  a  SOSn[        US9U l         g g )Nr   i  iX  )seconds)r   r   r   )r/   r   s     r0   __post_init__$InitProcessGroupKwargs.__post_init__'  s/    <<"llf4d#G$W5DL  r3   )r   )r@   rA   rB   rC   rD   r   r   rY   rc   r   r   r   r   rE   r?   r3   r0   r   r     s9    $ $GXc]#!%K#%#'GXi '6r3   r   )MSAMPTEO1O2)HYBRIDE4M3E5M2)maxmost_recentc                   B    \ rS rSr% SrSr\S   \S'   Sr\\	   \S'   Sr
g)AORecipeKwargsi5  a  
Use this object in your [`Accelerator`] to customize the initialization of the recipe for FP8 mixed precision
training with `torchao` FP8.

Args:
    config (`torchao.float8.Float8LinearConfig`, *optional*, default to `None`):
        The configuration for the FP8 training. In general, the default config should be sufficient.
    module_filter_func (`Callable`, *optional*, default to `None`):
        Optional function that must take in a module and layer name, and returns a boolean indicating whether the
        module should be converted to FP8. Defaults to `accelerate.utils.ao.filter_linear_layers`. See it for an
        example.
Nr%   configmodule_filter_funcr?   )r@   rA   rB   rC   rD   r   r   rc   r   r
   rE   r?   r3   r0   r   r   5  s)     .2FH)*1-1*1r3   r   c                       \ rS rSr% SrSr\\   \S'   Sr	\\
   \S'   Sr\\
   \S'   Sr\\S'   Sr\\
   \S'   Sr\\S	'   Sr\\\\4   \S
'   Sr\\   \S'   S rSrg)TERecipeKwargsiH  a  
Use this object in your [`Accelerator`] to customize the initialization of the recipe for FP8 mixed precision
training with `transformer-engine`.

<Tip>

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

</Tip>

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

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

Args:
    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`, `E4M3` or `E5M2`. (Generally `HYBRID` for
        training, `E4M3` or `E5M2` 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.
Nuse_autocast_during_evalmargininterval
fp8_formatamax_history_lenamax_compute_algooverride_linear_precisionuse_mxfp8_block_scalingc                     Sn[        5       (       d  [        S5      eU R                  c  [        US-   5      U l        U R                  c1  [        [        R                  R                  US-   S5      5      U l        U R                  c1  [        [        R                  R                  US-   S5      5      U l	        U R                  c(  [        R                  R                  US-   S	5      U l
        U R                  R                  5       U l
        U R                  [        [        5      ;  a+  [        S
SR                  [        [        5      5       S35      eU R                   c(  [        R                  R                  US-   S5      U l        U R                   R#                  5       U l        U R                   [        [$        5      ;  a*  [        SSR                  [        [$        5      5       35      eU R&                  c1  [        [        R                  R                  US-   S5      5      U l        U R(                  c3  [        US-   5      n[        US-   5      n[        US-   5      nX#U4U l        U R*                  c  [        US-   5      U l        g g )NACCELERATE_FP8_zQTransformerEngine is not available. Please install it or use a different backend.USE_AUTOCAST_DURING_EVALMARGINr   INTERVALr   FORMATr   z`fp8_format` must be one of  or .AMAX_COMPUTE_ALGOr   z#`amax_compute_algo` must be one of AMAX_HISTORY_LEN   OVERRIDE_FPROPOVERRIDE_DGRADOVERRIDE_WGRADUSE_MXFP8_BLOCK_SCALING)r!   ImportErrorr   r   r   r   osenvironr   r   r   upperr   	FP8FormatrJ   joinr   lowerAmaxComputeAlgorithmr   r   r   )r/   
env_prefixfpropdgradwgrads        r0   r   TERecipeKwargs.__post_init__x  s   &
.00qrr((0,?
Mg@g,hD);;bjjnnZ(-BAFGDK== 

zJ/F JKDM??" jjnnZ(-BHMDO////1??(9"55;FKKQZH[<\;]]^_``!!)%'ZZ^^JAT4TVc%dD"!%!7!7!=!=!?!!2F)GGB6;;xXlOmCnBopqq  ($'

zDV7VX\(]$^D!))1'
5E(EFE'
5E(EFE'
5E(EFE.3E-BD*''/+>zLe?e+fD( 0r3   )r   r   r   r   r   r   r   r   )r@   rA   rB   rC   rD   r   r   rb   rc   r   r   r   r   r   r   r   r   r   tupler   r   rE   r?   r3   r0   r   r   H  s    #J 04htn3 FHSM "Hhsm" J	 &*hsm*.2+29=uT4%56=.2Xd^2gr3   r   c                   .    \ rS rSr% SrSr\\S'   S rSr	g)MSAMPRecipeKwargsi  z
Use this object in your [`Accelerator`] to customize the initialization of the recipe for FP8 mixed precision
training with `ms-amp`.
N	opt_levelc                     SnU R                   c(  [        R                  R                  US-   S5      U l         U R                   [	        [
        5      ;  a*  [        SSR                  [	        [
        5      5       35      eg )Nr   	OPT_LEVELr   z`opt_level` must be one of r   )r   r   r   r   r   OptLevelrJ   r   )r/   r   s     r0   r   MSAMPRecipeKwargs.__post_init__  se    &
>>!ZZ^^J,DdKDN>>(!33:6;;xPXGY;Z:[\]] 4r3   )r   )
r@   rA   rB   rC   rD   r   r   rc   r   rE   r?   r3   r0   r   r     s    
 Ix^r3   r   c                   <   ^  \ rS rSr% SrSr\\S'   U 4S jrSr	U =r
$ )FP8RecipeKwargsi  z}
Deprecated. Please use one of the proper FP8 recipe kwargs classes such as `TERecipeKwargs` or `MSAMPRecipeKwargs`
instead.
Nr   c                 z  > Sn[         R                  " S[        5        [        5       (       a  SOSnU R                  c(  [
        R                  R                  US-   U5      U l        U R                  R                  5       U l        U R                  [        [        5      ;  a  [        S5      e[        TU ]5  5         g )Nr   zFP8RecipeKwargs is deprecated and will be removed in Accelerate v2.0.0. Please use one of the proper FP8 recipe kwargs classes such as TERecipeKwargs or MSAMPRecipeKwargs instead.msampteBACKENDzO`backend` must be 'MSAMP' or 'TE' (TransformerEngine) to use `FP8RecipeKwargs`.)warningswarnFutureWarningr   r   r   r   r   r   r   BackendrJ   r   r   )r/   r   default_backendr7   s      r0   r   FP8RecipeKwargs.__post_init__  s    &
z	

 &8%9%9't<<::>>*y*@/RDL||))+<<x00noor3   )r   )r@   rA   rB   rC   rD   r   r   rc   r   rE   r   r   s   @r0   r   r     s    
 GW   r3   r   )cpuxpumtiacudahpuc                   0   \ rS rSr% SrSr\\\      \	S'   Sr
\\\\4      \	S'   Sr\\   \	S'   Sr\\	S'   Sr\\	S	'   Sr\\	S
'   Sr\\	S'   Sr\\	S'   Sr\\   \	S'   S\S\R0                  R                  4S jrS\R0                  R4                  4S jrSrg)ProfileKwargsi  u	  
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"`, "hpu" 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                  R                  R                  [         R                  R                  R                  S.n[        5       (       a'  [         R                  R                  R                  US'   [        S[        5      (       aJ  [         R                  R                  5       (       a'  [         R                  R                  R                  US'   [        S[        5      (       aJ  [         R                  R                  5       (       a'  [         R                  R                  R                  US'   X;  a  [        SU S[!        U5       S35      eX!   $ )	zGet the profiler activity from the string.

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

Returns:
    torch.profiler.ProfilerActivity: The profiler activity.
)r   r   r   >=r   r   zInvalid profiler activity: . Must be one of r   )torchprofilerProfilerActivityCPUCUDAr   HPUr$   r   r   is_availableXPUr   r   MTIArJ   rW   )r/   r  profiler_activity_maps      r0   _get_profiler_activity$ProfileKwargs._get_profiler_activity  s    >>2266NN3388M

 +0>>+J+J+N+N!%(D"IJJyy%%''/4~~/N/N/R/R%e,D"JKKzz&&((050O0O0T0T%f-0:8*DUVZ[pVqUrrstuu$..r3   c                    SnU R                   b*  U R                    Vs/ s H  o R                  U5      PM     nnSnU R                  b*  [        R                  R
                  " S0 U R                  D6n[        R                  R                  UUU R                  U R                  U R                  U R                  U R                  U R                  S9$ s  snf )zt
Build a profiler object with the current configuration.

Returns:
    torch.profiler.profile: The profiler object.
N)r   scheduler   r   r   r  r  r  r?   )r   r  r   r
  r  r  profiler   r   r   r  r  r  )r/   r   r  r  s       r0   buildProfileKwargs.build   s     8<
??&PTP_P_`P_H55h?P_J`6:+~~..F1E1EFH~~%%!..,,..** & 	
 		
 as   Cr?   )r@   rA   rB   rC   rD   r   r   rW   r  rc   r   r   rY   r   r   r
   r   rb   r   r  r  r  r  r
  r  r  r  r  rE   r?   r3   r0   r   r     s    /b 48J./0704OXd38n-4)-NHX&-M4 ND JJL$&*hsm*//? /ENNDcDc /<
u~~-- 
r3   r   c                   L    \ rS rSrSrSrSrSrSrSr	Sr
S	rS
rSrSrSrSrSrSrg)DistributedTypei:  ay  
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_SDAA** -- Distributed on multiple SDAAs.
    - **MULTI_MUSA** -- Distributed on multiple MUSAs.
    - **MULTI_NPU** -- Distributed on multiple NPUs.
    - **MULTI_XPU** -- Distributed on multiple XPUs.
    - **MULTI_HPU** -- Distributed on multiple HPUs.
    - **DEEPSPEED** -- Using DeepSpeed.
    - **XLA** -- Using TorchXLA.
rl   	MULTI_CPU	MULTI_GPU	MULTI_NPU	MULTI_MLU
MULTI_SDAA
MULTI_MUSA	MULTI_XPU	DEEPSPEEDFSDPXLAMEGATRON_LM	MULTI_HPUr?   N)r@   rA   rB   rC   rD   rl   r  r  r  r   r!  r"  r#  r$  r%  r&  r'  r(  rE   r?   r3   r0   r  r  :  sJ    & 
BIIIIJJIID
CKIr3   r  c                   $    \ rS rSrSrSrSrSrSrg)SageMakerDistributedTypei]  a  
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.
rl   DATA_PARALLELMODEL_PARALLELr?   N)	r@   rA   rB   rC   rD   rl   r+  r,  rE   r?   r3   r0   r*  r*  ]  s     
B#M%Nr3   r*  c                   (    \ rS rSrSrSrSrSrSrSr	g)	FP8BackendTypein  zy
Represents the backend used for FP8.

Values:

    - **TE** -- using TransformerEngine.
    - **MSAMP** -- using msamp.
rl   r   r   AOr?   N)
r@   rA   rB   rC   rD   rl   r   r   r/  rE   r?   r3   r0   r.  r.  n  s     
B	BE	Br3   r.  c                        \ rS rSrSrSrSrSrg)ComputeEnvironmenti  z
Represents a type of the compute environment.

Values:

    - **LOCAL_MACHINE** -- private/custom cluster hardware.
    - **AMAZON_SAGEMAKER** -- Amazon SageMaker as compute environment.
LOCAL_MACHINEAMAZON_SAGEMAKERr?   N)r@   rA   rB   rC   rD   r2  r3  rE   r?   r3   r0   r1  r1    s     $M)r3   r1  c                   X    \ rS rSrSrSrSrSrSrSr	Sr
S	rS
rSrSrSrSrSrSrSrSrSrg)DynamoBackendi  a	  
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 Apache TVM for inference optimizations. [Read more](https://tvm.apache.org/)
    - **HPU_BACKEND** -- Uses HPU backend for inference optimizations.

rl   EAGER	AOT_EAGERINDUCTORAOT_TS_NVFUSERNVPRIMS_NVFUSER
CUDAGRAPHSOFIFX2TRTONNXRTTENSORRTAOT_TORCHXLA_TRACE_ONCETORCHXLA_TRACE_ONCEIPEXTVMHPU_BACKENDr?   N)r@   rA   rB   rC   rD   rl   r6  r7  r8  r9  r:  r;  r<  r=  r>  r?  r@  rA  rB  rC  rD  rE   r?   r3   r0   r5  r5    s\    "J 
BEIH%N'OJ
CFFH7/D
CKr3   r5  c                   @    \ rS rSrSrSrSrSrSrSr	Sr
S	rS
rSrSrSrg)
LoggerTypei  a=  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
    - **TRACKIO** -- trackio as an experiment tracker
    - **COMETML** -- comet_ml as an experiment tracker
    - **MLFLOW** -- mlflow as an experiment tracker
    - **CLEARML** -- clearml as an experiment tracker
    - **DVCLIVE** -- dvclive as an experiment tracker
    - **SWANLAB** -- swanlab as an experiment tracker
allaimtensorboardwandbtrackiocomet_mlmlflowclearmldvcliveswanlabr?   N)r@   rA   rB   rC   rD   ALLAIMTENSORBOARDWANDBTRACKIOCOMETMLMLFLOWCLEARMLDVCLIVESWANLABrE   r?   r3   r0   rF  rF    s;     C
CKEGGFGGGr3   rF  c                   (    \ rS rSrSrSrSrSrSrSr	g)	PrecisionTypei  zRepresents 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
rg   fp8rh   ri   r?   N)
r@   rA   rB   rC   rD   rl   FP8rm   rn   rE   r?   r3   r0   r\  r\    s     
B
CDDr3   r\  c                   <    \ rS rSrSrSrSrSrSrSr	Sr
S	rS
rSrSrg)RNGTypei  r
  r   mlusdaamusanpuxlar   r   	generatorr?   N)r@   rA   rB   rC   TORCHr  MLUSDAAMUSANPUr&  r  r  	GENERATORrE   r?   r3   r0   r`  r`    s4    ED
CDD
C
C
C
CIr3   r`  c                   $    \ rS rSrSrSrSrSrSrg)CustomDtypei  z\
An enum that contains multiple custom dtypes that can be used for `infer_auto_device_map`.
r]  int4int2r?   N)	r@   rA   rB   rC   rD   r^  INT4INT2rE   r?   r3   r0   rn  rn    s     CDDr3   rn  c                   R    \ rS rSr% \R
                  \S'   \R                  \S'   Srg)TensorInformationi  shapedtyper?   N)	r@   rA   rB   rC   r
  Sizerc   rv  rE   r?   r3   r0   rt  rt    s    ::;;r3   rt  c                       \ rS rSr% Sr\" SSS0S9r\\S'   \" SSS	0S9r	\\S
'   \" SSS0S9r
\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   Srg)DataLoaderConfigurationi  a
  
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 reproducible using a different sampling technique. While seed-to-seed results
        may differ, on average the differences are negligible when using multiple different seeds to compare.
        Should also be ran with [`~utils.set_seed`] for the best results.
    data_seed (`int`, defaults to `None`):
        The seed to use for the underlying generator when using `use_seedable_sampler`. If `None`, the generator
        will use the current default seed from torch.
    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_batchesar  Whether or not use a fully seedable random sampler ([`data_loader.SeedableRandomSampler`]).Ensures training results are fully reproducible using a different sampling technique. While seed-to-seed results may differ, on average the differences are negligible when usingmultiple different seeds to compare. Should also be ran with [`~utils.set_seed`] for the best results.use_seedable_samplerzThe seed to use for the underlying generator when using `use_seedable_sampler`. If `None`, the generator will use the current default seed from torch.	data_seeda  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_dataloaderr?   )r@   rA   rB   rC   rD   r   r~  rb   rc   r  r  r  r  r   r  r  rE   r?   r3   r0   ry  ry    s   !F   E
M4  # N
d   
L$  "' u
"$   =
Is   T
L$  %* [
%T r3   ry  c                       \ rS rSr% Sr\" SSS0S9r\\S'   \" SSS0S9r	\\S	'   \" S
SS0S9r
\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" S
SS0S9r\\S'   SS\\   4S jjrS rSrg)ProjectConfigurationiq  aD  
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.
Nrz  z'A path to a directory for storing data.r{  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                 8    Xl         U R                  c  Xl        gg)zISets `self.project_dir` and `self.logging_dir` to the appropriate values.N)r  r  )r/   r  s     r0   set_directories$ProjectConfiguration.set_directories  s    &#* $r3   c                 :    U R                  U R                  5        g r*   )r  r  r.   s    r0   r   "ProjectConfiguration.__post_init__  s    T--.r3   )r  r  r*   )r@   rA   rB   rC   rD   r   r  rY   rc   r  r  rb   r  r   r  r  r   r  r   rE   r?   r3   r0   r  r  q  s    & TV=f4ghKh
K  ).[\) 
 MNK 
 78Is 
 $(
t +8C= +/r3   r  c                       \ rS rSr% Sr\" SSS0S9r\\S'   \" SSS	0S9r	\
\S
'   \" SSS0S9r\
\S'   \" SSS0S9r\
\S'   Srg)GradientAccumulationPlugini  a  
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. Setting 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)
```
Nrz  z0The number of steps to accumulate gradients for.r{  	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_batchr?   )r@   rA   rB   rC   rD   r   r  r   rc   r  rb   r  r  rE   r?   r3   r0   r  r    s    4 LMIs  #  E
d  "'  c
"$  "  Y
OT r3   r  c                   d  ^ \ rS rSr% Sr\" SSS\ V Vs/ s H  oR                  R                  5       PM     snn  30S9r	\\
S'   \" SSS0S9r\\
S	'   \" SSS
0S9r\\
S'   \" SSS0S9r\\
S'   \" SSS0S9r\\
S'   \" SSS0S9r\\
S'   \" SSS0S9r\\
S'   S rS rU4S jrSrU=r$ s  snn f )TorchDynamoPlugini  a  
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
    use_regional_compilation (`bool`, defaults to `None`):
        Use it to reduce the cold start compilation time of torch.compile() by targeting repeated blocks of the
        same class and compiling them sequentially to hit the compiler's cache. For example, in `GPT2LMHeadModel`,
        the repeated block/class is `GPT2Block`, and can be accessed as `model.transformer.h[0]`. The rest of the
        model (e.g model.lm_head) is compiled separately.
Nrz  zPossible options are r{  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disablean  Use it to reduce the cold start compilation time of torch.compile() by targeting repeated blocks of the same class and compiling them sequentially to hit the compiler's cache. For example, in `GPT2LMHeadModel`, the repeated block/class is `GPT2Block`, and can be accessed as `model.transformer.h[0]`. The rest of the model (e.g model.lm_head) is compiled separately.use_regional_compilationc                    SnU R                   c(  [        R                  R                  US-   S5      U l         [	        U R                   R                  5       5      U l         U R                  c(  [        R                  R                  US-   S5      U l        U R                  c4  [        [        R                  R                  US-   S5      5      S:H  U l        U R                  c4  [        [        R                  R                  US	-   S5      5      S:H  U l	        U R                  cZ  [        R                  R                  US
-   S 5      b5  [        [        R                  R                  US
-   S5      5      S:H  U l
        g g g )NACCELERATE_DYNAMO_r   rg   MODEr|  USE_FULLGRAPHFalser   USE_REGIONAL_COMPILATIONUSE_DYNAMIC)r   r   r   r   r5  r   r  r  r   r  r  r/   prefixs     r0   r   TorchDynamoPlugin.__post_init__   s&   %<<::>>&9*<dCDL$T\\%7%7%9:99

v	BDI>>!(8PRY)Z[_``DN((0BJJNN64N+NPWXY]^^ ) <<BJJNN6M3I4$P$\&rzz~~f}6Lg'VW[\\DL %]r3   c                     [         R                  " U R                  5      nUS   R                  R	                  5       US'   U$ )Nr   )r+   r,   r-   rS   r   )r/   dynamo_configs     r0   r1   TorchDynamoPlugin.to_dict2  s8    dmm4#0#;#A#A#G#G#Ii r3   c                 H   > [         TU ]  5       nUR                  SS 5        U$ )Nr  )r   r=   pop)r/   kwargsr7   s     r0   r=   TorchDynamoPlugin.to_kwargs7  s$    "$

-t4r3   )r   r  r  r  r  )r@   rA   rB   rC   rD   r   r5  rS   r   r   rc   r  rY   r  rb   r  r  r	   r  r  r   r1   r=   rE   r   ).0br7   s   00@r0   r  r    s   . #1M2ZMq77==?M2Z1[\]G]  _`D#  RSIt  $&:d1efGTfKLGS  IJGT 
 &+q
&d ]$
 q 3[s   #B,r  c                   d   \ rS rSr% Sr\" SSS0S9r\\S'   \" SSS0S9r	\
\S	'   \" SSS
0S9r\\S'   \" SSS0S9r\
\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS 0S9r\\S!      \S"'   S# rS6S$ jrS% rS7S& jrS8S' jr S( r!S) r"S* r#\$S9S+ j5       r%S, r&S- r'S9S.\4S/ jjr(S0 r)S1\4S2 jr*\+S3 5       r,\,RZ                  S4 5       r,S5r.g):DeepSpeedPlugini=  a  
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'].
Nrz  zkpath to DeepSpeed config file or dict or an object of class `accelerate.utils.deepspeed.HfDeepSpeedConfig`.r{  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           	         SSK Jn  U R                  cG  [        R                  R                  SS5      nUR                  5       (       a  [        U5      OUU l        U R                  c8  [        R                  R                  SS5      nUS:X  a  UO
[        U5      U l        U R                  c.  [        [        R                  R                  SS5      5      U l
        U R                  c%  [        R                  R                  SS	5      U l        U R                  c%  [        R                  R                  S
S	5      U l        U R                  c%  [        R                  R                  SS	5      U l        U R                  c%  [        R                  R                  SS	5      U l        U R                  c6  [        R                  R                  SS5      R!                  5       S:H  U l        U R"                  c(  [        R                  R                  SS 5      S:H  U l        U R$                  c%  [        R                  R                  SS5      U l        U R&                  c%  [        R                  R                  SS	5      U l        [)        U R&                  [*        5      (       dK  [)        U R&                  [,        5      (       a  U R&                  S	:w  d  [)        U R&                  U5      (       Gaw  [)        U R&                  U5      (       d  U" U R&                  5      U l        SU R&                  R.                  ;  a  SU R&                  R.                  S'   SU R&                  R.                  ;  a  [1        S5      eU R3                  5         SSSSSSSSS.nUR5                  5        VVs0 s H  u  pV[7        X5      c  M  U[7        X5      _M!     nnnUR9                  5        H  nU R:                  " U40 UDS S!0D6  M     U R&                  R=                  5         UR5                  5        H9  u  pU R&                  R?                  U	5      n
U
c  M%  U
S:w  d  M-  [A        XU
5        M;     OSSU R                  U R                  U R                  U R                  S":X  a  U R                  OS S#.U R                  U R                  S":X  a  U R                  OS S#.U R                  S$.S%.nU R                  (       a  U R                  US'   U" U5      U l        U R&                  R.                  U l!        [        S&5      U RB                  S''   U RD                  cR  [G        [        R                  R                  S([-        U R&                  RI                  5       5      5      5      S:H  U l"        U RD                  (       a<  U R&                  RI                  5       (       d  [J        RL                  " S)5        S!U l"        U RO                  S!5        U R"                  (       ad  S*U RB                  ;  aS  U R                  S+:X  a  [Q        S,5      eU R$                  S-;  a  [1        S.5      eS/U R$                  S0.U RB                  S*'   g g g s  snnf )1Nr   )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_FILEr  zero_optimizationzDPlease specify the ZeRO optimization config in the DeepSpeed config.r  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)r  r  r  r  r  r  r  r  
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_gpur  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r`   r   ))	deepspeedr  r  r   r   r   isdigitr   r  r   r  r  r  r  r  r  r   r  r  r  
isinstancer   rY   r   rJ   _deepspeed_config_checksr8   getattrkeys
fill_matchset_stage_and_offload	get_valuesetattrdeepspeed_configr  r   is_zero3r   r   _set_selectedNotImplementedError)r/   r  gasr  plugin_to_config_mappingr;   r<   r  keyrS   config_valuer   s               r0   r   DeepSpeedPlugin.__post_init__  sd   0++3**..!I6RC;>;;==s3xcD,!!) "

/Mv V:Kv:U%6[`ar[sD"??"!"**..1RTU"VWDO((0,.JJNN;jlr,sD)$$,(*

7bdj(kD%++3/1zz~~BF0D, ''/+-::>>:hjp+qD(&&.

LgV\\^bhh ' $ "

/G NRY YD'#%::>>2Ld#SD $ "

/QSY ZDt(($//4,,c22t7H7HF7R$++->??d//1BCC$5d6G6G$H!,D4E4E4L4LLJK!!(()FG"$*;*;*B*BB !ghh))+/L%87,X(P+V/^*g	($ 7O6T6T6Vw6VdaZabfZj)a))6VFw{{}@v@%@ %335 7<<>
#00::5A+0FD|4 ? %+28/3/O/O!__"&"?"?@D@]@]ag@gD<<mq* #'";";FJF_F_ciFid&B&Bos& BFA\A\&	F& %%.2.D.D*+ 1& 9D $ 1 1 8 838</0'JJNN9D--6689    (9(9(B(B(D(DMMop#(D  	5! 0E0E!E!#)i  ##<7 !jkk!11.D!!'* "Fo xs   !Y/7Y/c                 P   Uc  / OUnU R                   R                  U5      u  pVUc  g UR                  U5      S:X  a  X;   a  XA   XV'   g [        SU SU S35      eU(       d  g UR                  U5      nUb/  X;   a)  XtU   :w  a   UR	                  SU SU SU SXA    35        g g g g )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 )r  find_config_noder   rJ   append)r/   ds_key_long
mismatchesr  r  r   ds_keyds_vals           r0   r  DeepSpeedPlugin.fill_match(  s    %-R:
**;;KH>::f'$!'!4 } %''2m 4))  F#+"7,,!!E+axx}TUV\ViUj"kl - #8r3   c                 J    U R                   R                  U5      nUc  gUS:H  $ )NFr  r  r  )r/   r  vals      r0   is_autoDeepSpeedPlugin.is_autoA  s*    ))+6;&= r3   c                 8    U R                   R                  X5      $ r*   r  )r/   r  r|  s      r0   r  DeepSpeedPlugin.get_valueH  s      **;@@r3   c           	      d   Uc  / OUnUc  U R                   nUR                  5        HP  u  pg[        U[        5      (       a  U R                  " S
X-   S-   UUUS.UD6  M8  U R
                  " X-   U4SU0UD6  MR     [        U5      S:  a'  US:X  a   SR                  U5      n[        SU S	35      egg)z=Process the DeepSpeed config with the values from the kwargs.Nr   )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'.r?   )	r  r8   r  r   deepspeed_config_processr  lenr   rJ   )	r/   r  r  r   r  r  r  rS   mismatches_msgs	            r0   r  (DeepSpeedPlugin.deepspeed_config_processK  s    %-R:
>**F ,,.JC%&&-- !<#-) )	
  jZZZSYZ ) z?Q6R<!YYz2N+,,su  $0r3   c                    U R                   nUS:H  US;   S.nUS:X  a  SU;  a  SSS.US'   OUS;   a  SU;  a  SS0US'   US:X  a)  U R                  (       a  S	U;  a  SU R                  S
.US	'   US:w  aY  US:X  a  SOSn[        UR	                  U0 5      R	                  SS5      5      R                  5       S:X  a  [        SU SU S35      eS H  nXR;  d  M
  SS0X%'   M     U R                  " SSS0UD6  U R                  " SSS0UD6  g )Nrh   )ri   r]  )fp16.enabledbf16.enabledT)r`   	auto_castri   r`   r]  r   r  rg   r  r  z*`--mixed_precision` arg cannot be set to `z` when `z&` is set in the DeepSpeed config file.)rh   ri   Fr  )r  )r  )r  r  r  rY   r   r   rJ   r  )r/   mixed_precision	ds_configr  
diff_dtyperv  s         r0   set_mixed_precision#DeepSpeedPlugin.set_mixed_precisionb  sP   ))	+v5+>

 f$Y&044$H	&!/Y&%.$5	&!e#(9(9i'#!%!5!5&	'"
 d"#2f#<&J9==R044YHIOOQU[[ @@QQYZdYe  fL  M  &E%$-u#5	  & 	C5CFCC5CFCr3   c                    SSK Jn  [        R                  " U R                  5      nU R
                  (       a  U" 5       (       d  [        S5      eSU;  d	  US   S:X  a  SUS'   SU;  d	  US   S:X  a  SUS'   UR                  SS 5      S:X  a  US	 [        SS	S
5      (       a	  SSK	J
nJn  OSSKJ
nJn  U" 5         U" U5      U l        g )Nr   )is_transformers_availablezoWhen `zero3_init_flag` is set, it requires Transformers to be installed. Please run `pip install transformers`.r  r  r  r  transformers<z4.46r   )r  unset_hf_deepspeed_config)importsr  r+   r,   r  r  	Exceptionr   r#   transformers.deepspeedr  r  transformers.integrationsdschf)r/   r  r  r  r  s        r0   set_deepspeed_weakref%DeepSpeedPlugin.set_deepspeed_weakref  s    6MM$"7"78	,..=  )	9YGd=eio=o78I34+9<	Jj@kou@u:;I67==+T2f<,-NC88 

 	"#&y1
r3   c                     U R                   $ r*   )r  r.   s    r0   is_zero3_init_enabled%DeepSpeedPlugin.is_zero3_init_enabled  s    ###r3   c              #      #    U R                   nX!:X  a  S v   g Xl         S U l        U R                  5         S v   X l         S U l        U R                  5         g 7fr*   )r  r"  r#  )r/   enableolds      r0   zero3_init_context_manager*DeepSpeedPlugin.zero3_init_context_manager  sM     ""=#) DJ&&(#& DJ&&(s   AAc                 H  ^ / SQmT Vs/ s H2  oR                  SS5      R                  SS5      R                  5       PM4     snm[        R                  R	                  SS5      R                  S5      n[        U4S jU 5       5      (       a  [        ST S	35      eg s  snf )
N)	r  r  r  r  r  r  r  r  ACCELERATE_MIXED_PRECISIONACCELERATE_r
  
DEEPSPEED_ACCELERATE_CONFIG_DS_FIELDS,c              3   ,   >#    U  H	  oT;   v   M     g 7fr*   r?   )r  nameenv_variable_names_to_ignores     r0   	<genexpr>;DeepSpeedPlugin._deepspeed_config_checks.<locals>.<genexpr>  s     h@g33@gs   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`.)replacer   r   r   r   splitanyrJ   )r/   r4  'deepspeed_fields_from_accelerate_configr5  s      @r0   r  (DeepSpeedPlugin._deepspeed_config_checks  s    
(
$ [w(
ZvRVLL+33L"EKKMZv(
$ 35**..A^`b2c2i2ijm2n/h@ghhhq  sO  rP Pj j  i(
s   9Bc                    U R                   c%  [        R                  R                  SS 5      U l         U R                   b  [	        SSS5      (       a  [        S5      eSSKJn  U R                   R                  S5      n/ nU H1  n[        X5      nUc  [        S	U S
35      eUR                  U5        M3     U" X5        g g )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_modulesr2  z1Could not find a transformer layer class called 'z' to wrap in the model.)r  r   r   r   r#   r   deepspeed.utilsr?  r9  get_module_class_from_namer  r  )r/   r   r?  class_namestransformer_moe_clslayer_classtransformer_clss          r0   set_moe_leaf_modules$DeepSpeedPlugin.set_moe_leaf_modules  s    ))1-/ZZ^^<fhl-mD*))5S(;;!"tuu;88>>sCK"$*"<U"P"*#KK=Xop  (..?  +  ; 6r3   _from_accelerator_statec                 j    U(       d  [        S5      eU R                  5         U R                  S5        g)zO
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)rJ   r#  r  )r/   rH  s     r0   selectDeepSpeedPlugin.select  s6     ' K  	""$4 r3   c                 &    U R                  S5        g )NF)r  r.   s    r0   	_unselectDeepSpeedPlugin._unselect  s    5!r3   rS   c                     Xl         g)z-
Private setter for the 'enabled' attribute.
N	_selectedr/   rS   s     r0   r  DeepSpeedPlugin._set_selected  s	     r3   c                     U R                   $ r*   rP  r.   s    r0   selectedDeepSpeedPlugin.selected  s    ~~r3   c                     [        S5      e)Nz\'enabled' can only be set through calling 'AcceleratorState().enable_deepspeed_plugin(key)'.)r  rR  s     r0   rU  rV    s    !j
 	
r3   )rQ  r  r"  r  r  r  r  r  r  r  r  r  r  r  r  r  )NTr*   )r
  NNT)F)/r@   rA   rB   rC   rD   r   r  r	   rc   r  r   r  r   r  r  rb   r  rY   r  r  r  r  r  r  r  r  r   r   r   r  r  r  r  r  r#  r&  r   r+  r  rF  rJ  rM  r  propertyrU  setterrE   r?   r3   r0   r  r  =  sr   #J   B
L#  (-  `
(   %TVEj<klulijJ   %qr   %*ij%c  !&bc!#  (-fg(  $)fg$S  " 1
OT  $)mn$D  &+ d
&s  _`L$  6;  T
6OXgj12 @Dm2!A.DB2>$ ) )6<(	!d 	!"4    __
 
r3   r  c                      \ rS rSr% Sr\" SSS0S9r\\S'   \" SSS0S9r	\
\S	4   \S
'   \" SSS0S9r\
\S	\4   \S'   \" SSS0S9r\\
\S4      \S'   \" SSS0S9r\\
\\SS4      \S'   \" SSS0S9r\\
\\S   4      \S'   \" SSS0S9r\
\SS4   \S'   \" SSS0S9r\\
\\R2                  R4                     \4      \S'   \" SSS0S9r\
\S4   \S'   \" SSS 0S9r\\
S!      \S"'   \" SSS#0S9r\\
S$      \S%'   \" S&SS'0S9r\\S('   \" SSS)0S9r\\   \S*'   \" SSS+0S9r \\\R2                  R4                  /S4      \S,'   \" SSS-0S9r!\\   \S.'   \" SSS/0S9r"\\S0'   \" SSS10S9r#\\S2'   \" SSS30S9r$\\S4'   \" SSS50S9r%\\&\      \S6'   \" SSS70S9r'\\   \S8'   S9 r(SAS: jr)S; r*SBS< jr+S= r,S> r-S? r.S@r/g)CFullyShardedDataParallelPlugini  a  
This plugin is used to enable fully sharded data parallelism.

Args:
    fsdp_version (`int`, defaults to `1`):
        The version of FSDP to use. Defaults to 1. If set to 2, launcher expects the config to be converted to
        FSDP2 format.
    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`. Is deprecated in favor of
        `reshard_after_forward`.
    reshard_after_forward (`Union[str, torch.distributed.fsdp.ShardingStrategy, bool]`, defaults to `'FULL_SHARD'` for `fsdp_version=1` and `True` for `fsdp_version=2`):
        Sharding strategy to use. Should be a bool if `fsdp_version` is set to 2 else 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, str, torch.distributed.fsdp.MixedPrecision, torch.distributed.fsdp.MixedPrecisionPolicy]]`, 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`, can be an instance of
        `torch.distributed.fsdp.MixedPrecisionPolicy` if `fsdp_version` is set to 2. If passing in a `str`, it
        should be one of the following values: fp8, fp16, bf16, fp32, and used to set `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, torch.distributed.fsdp.CPUOffloadPolicy]`, 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` or
        `torch.distributed.fsdp.fully_sharded_data_parallel.CPUOffloadPolicy` if `fsdp_version` is set to 2.
    ignored_modules (`Optional[Union[Iterable[torch.nn.Module], str]]`, defaults to `None`):
        A list of modules to ignore when wrapping with FSDP. When passing a string, will match the modules by name
        using regex fullmatch. If `fsdp_version` is set to 2, the modules are converted to parameters and used.
    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`.
Nrz  ztThe version of FSDP to use. Defaults to 1. If set to 2, launcher expects the config to be converted to FSDP2 format.r{  fsdp_versionzSharding strategy to use. Should be either a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`. Defaults to 'FULL_SHARD'. Is deprecated in favor of `reshard_after_forward` z'torch.distributed.fsdp.ShardingStrategysharding_strategyzSharding strategy to use. Should be a bool if `fsdp_version` is set to 2 else a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`. Defaults to 'FULL_SHARD'reshard_after_forwardzBackward 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'. This becomes obsolete in FSDP2.z'torch.distributed.fsdp.BackwardPrefetchbackward_prefetcha  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`.Can also be an instance of `torch.distributed.fsdp.MixedPrecisionPolicy` if `fsdp_version` is set to 2.z%torch.distributed.fsdp.MixedPrecisionz+torch.distributed.fsdp.MixedPrecisionPolicy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_policya  Whether to offload parameters to CPU. Should be either a `bool` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.CPUOffload` or `torch.distributed.fsdp.fully_sharded_data_parallel.CPUOffloadPolicy` if `fsdp_version` is set to 2. Defaults to `False`z!torch.distributed.fsdp.CPUOffloadz'torch.distributed.fsdp.CPUOffloadPolicy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_gathersznWhether to use the original parameters for the optimizer. Defaults to `False`. This becomes obsolete in FSDP2.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_fna  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. This becomes obsolete in FSDP2.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           	        ^	 SSK JnJn  [        5       nSnU R                  c1  [        [        R                  R                  US-   S5      5      U l        U R                  S:X  a'  [        S[        5      (       d  [        S[         35      eU R                  b  UR                  S	5        U R                  S
:X  Ga,  U R                  c(  [        R                  R                  US-   S5      U l        [        U R                  [        5      (       a  U R                  R!                  5       ["        ;   a6  ["        R$                  " U R                  R!                  5       5      S
-   U l        [        U R                  [
        5      (       d  U R                  R'                  5       (       a!  U" [        U R                  5      5      U l        O!X R                  R!                  5          U l        U R(                  cv  U R                  ci  [        R                  R                  US-   U R                  S:X  a  SOS5      nU R                  S:X  a  [+        UR-                  5       SS9U l        OXPl        [        U R(                  [        5      (       Ga  U R                  S:X  a(  [+        U R(                  R-                  5       SS9U l        OU R(                  R!                  5       ["        ;   a6  ["        R$                  " U R(                  R!                  5       5      S
-   U l        [        U R(                  [
        5      (       d  U R(                  R'                  5       (       a!  U" [        U R(                  5      5      U l        O!X R(                  R!                  5          U l        U R                  S:X  a8  [        U R(                  [.        5      (       d  [1        SU R(                   S35      eU R                  S
:X  a8  [        U R(                  [.        5      (       a  [1        SU R(                   S35      eU R2                  c4  [+        [        R                  R                  US-   S5      5      S
:H  U l        U R5                  5         U R7                  5         U R8                  c(  [        R                  R                  US-   S 5      U l        [        U R8                  [        5      (       a%  U R8                  R!                  5       S:X  a  S U l        U R8                  Gb  [        U R8                  U5      (       d  [        U R8                  [        5      (       aX  U R8                  R!                  5       [:        ;   a6  [:        R$                  " U R8                  R!                  5       5      S
-   U l        [        U R8                  [
        5      (       d  U R8                  R'                  5       (       a!  U" [        U R8                  5      5      U l        O!XR8                  R!                  5          U l        U R                  S:X  a%  U R8                  b  UR                  S5        S U l        U R=                  5         U R>                  c(  [        R                  R                  US-   S5      U l        [        U R>                  [        5      (       Ga  U R>                  R!                  5       [@        ;  a  [1        SU R>                   S[@         35      eSSK!J"nJ#n  U R>                  R!                  5       S:X  a{  Xpl        U RH                  c(  [        R                  R                  US-   S 5      U l$        [        U RH                  [        5      (       a   U RH                  RK                  S 5      U l$        OU R>                  R!                  5       S!:X  a  X`l        U RL                  c2  [        [        R                  R                  US"-   S5      5      U l&        Os[        U RL                  [
        5      (       d.  [1        S#U RL                   S$[O        U RL                  5       35      eO%U R>                  R!                  5       S:X  a  S U l        U RP                  cD  U R                  S
:X  a4  [+        [        R                  R                  US%-   S5      5      S
:H  U l(        U R                  S:X  a%  U RP                  b  UR                  S&5        S U l(        U RR                  cD  U R                  S
:X  a4  [+        [        R                  R                  US'-   S5      5      S
:H  U l)        U R                  S:X  a%  U RR                  b  UR                  S(5        S U l)        U RT                  cD  U R                  S
:X  a4  [+        [        R                  R                  US)-   S5      5      S
:H  U l*        U R                  S:X  a  U RT                  b  [1        S*5      eU RV                  c4  [+        [        R                  R                  US+-   S5      5      S
:H  U l+        U RX                  c(  [        R                  R                  US,-   S 5      U l,        U RZ                  c4  [+        [        R                  R                  US--   S5      5      S
:H  U l-        U R                  S
:X  a?  U RZ                  (       a.  U RR                  (       d  [\        R^                  " S.5        SU l)        U RZ                  [/        [+        [        R                  R                  US--   S5      5      5      :w  aE  US--   n[\        R^                  " S/U S035        [        U RZ                  5      [        R                  U'   [        U R`                  [        5      (       a  U Rc                  U R`                  SS19  O:[        U R`                  [d        5      (       a  U Rc                  U R`                  5        U R`                  b  U Rg                  5         U RR                  (       Ga*  [i        5       (       a  [j        Rl                  Ro                  5       m	O[q        5       (       a  [j        Rr                  Ro                  5       m	O[u        5       (       a  [j        Rv                  Ro                  5       m	O[y        5       (       a  [j        Rz                  Ro                  5       m	Og[}        5       (       a  [j        R~                  Ro                  5       m	O9[        5       (       a  [j        R                  Ro                  5       m	O[        S25      eU	4S3 jU lC        [        S4S55      (       a5  U R                  S:X  a%  U RX                  b  UR                  S65        S U l,        U(       a%  [        R                  S7R                  U5      5        g g )8Nr   )BackwardPrefetchShardingStrategyFSDP_VERSION1r  r  zFSDP2 requires PyTorch >= zzsharding_strategy is deprecated in favor of reshard_after_forward. This will be removed in a future version of Accelerate.r   SHARDING_STRATEGY
FULL_SHARDRESHARD_AFTER_FORWARDr  T)to_boolzreshard_after_forward set to z:. This is not supported with FSDP2, please set to a `bool`z. This is not supported with FSDP1, please set to a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`OFFLOAD_PARAMSr  BACKWARD_PREFETCHNO_PREFETCHzObackward_prefetch is not supported in FSDP2. Setting backward prefetch to None.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_WRAPr2  SIZE_BASED_WRAPMIN_NUM_PARAMSz)`min_num_params` must be an integer. Got z	 of type USE_ORIG_PARAMSzSuse_orig_params is obsolete in FSDP2, as FSDP2 always uses the original parameters.SYNC_MODULE_STATESzhsync_module_states is obsolete in FSDP2, as it is not needed anymore.Setting sync_module_states to None.FORWARD_PREFETCHzUforward_prefetch is not yet implemented in FSDP2, set to None or use `fsdp_version=1`ACTIVATION_CHECKPOINTINGIGNORED_MODULESCPU_RAM_EFFICIENT_LOADINGzosync_module_states cannot be False since efficient cpu ram loading enabled. Setting sync_module_states to True.zrThe `cpu_ram_efficient_loading` flag for `FullyShardedDataParallelPlugin` does not match the environment variable zD. Setting environment variable to match `cpu_ram_efficient_loading`.)overridezmThere are currently no available devices found, must be one of 'XPU', 'CUDA', 'MLU', 'NPU', 'MUSA', or 'HPU'.c                 $   > U R                  TSS9$ )NF)r  recurse)to_empty)xr  s    r0   <lambda>>FullyShardedDataParallelPlugin.__post_init__.<locals>.<lambda>  s    1::VU:+Sr3   r  z2.7.0zoFSDP2 ignored_params/ignored_modules is not available for torch version < 2.7.0Setting ignored_modules to None.z7Multiple deprecation warnings due to FSDP2 conversion:
)Gtorch.distributed.fsdprt  ru  setr\  r   r   r   r   r$   r   r   r]  addr  rY   r   r   indexr  r^  r   r   rb   rJ   re  set_cpu_offloadvalidate_cpu_offloadr_  r   set_state_dict_typerd  r   torch.distributed.fsdp.wrapr  r  rq  r9  rr  typerk  rm  rn  ro  rf  rp  r   r   r`  r  r   validate_mixed_precision_policyr    r
  rd  current_devicer   ra  r   rc  r   r   r"   r   r   r   RuntimeErrorrl  loggerwarningr   )
r/   rt  ru  _fsdp2_warningsr   r^  r  r  env_varr  s
            @r0   r   ,FullyShardedDataParallelPlugin.__post_init__  s   M%
$ #BJJNN:	3I3$O PD!#D*?@@!$>?T>U"VWW!!- J !%%-)+
EX8XZf)g&$00#66))//15KK-C-I-I$J`J`JfJfJh-ilm-mD*d44c::d>T>T>\>\>^>^-=c$BXBX>Y-ZD*-=>T>T>Z>Z>\-]D* %%-$2H2H2P$&JJNN44++q0l%!   A%-89N9T9T9V`d-e*-B*d00#66  A%-89S9S9Y9Y9[ei-j* --3359OO1G1M1MdNhNhNnNnNp1qtu1uD.d88#>>$B\B\BdBdBfBf1A#dF`F`Ba1bD.1AB\B\BbBbBd1eD.!*T5O5OQU*V*V/0J0J/K  LF  G  !j1K1KT&R&R/0J0J/K  L]  ^  #*2::>>*GW:WY`+abfggD!!#!!)%'ZZ^^JAT4TVZ%[D"d,,c22t7M7M7S7S7UYf7f%)D"!!-jAWAWYi6j6j$00#664;Q;Q;W;W;Y]s;s)?)E)EdF\F\FbFbFd)ehi)i&$00#66$:P:P:X:X:Z:Z)9#d>T>T:U)V&)9:P:P:V:V:X)Y&!d&<&<&H qr%)D"  "  ($&JJNN:@R3RT]$^D!d++S11$$**,4II 01F1F0GGXYnXop 
 $$**,0HH(D%55=9;
UnHnpt9uD6d@@#FF9=9[9[9a9abe9fD6&&,,.2CC(C%&&.*-bjjnnZJZ=Z\].^*_D'#D$7$7==$CDDWDWCXXabfgkgzgzb{a|}  > &&,,.);(,%'D,=,=,B#.rzz~~jK\>\^e/f#gkl#lD !d&:&:&F uv#'D ""*t/@/@A/E&1"**..NbAbdk2l&mqr&rD#!d&=&=&I6 '+D#  (T->->!-C$/

zL^?^`g0h$imn$nD!!d&;&;&Gtuu((0BJJNN:8R+RT[\]abb ) '#%::>>*?P2PRV#WD ))1BJJNN:8S+SU\]^bcc * !d&D&DTMdMdMM6 '+D#))T

z4O'OQXYZ.
 
 !#>>GMM E  FM  EN NU U #&d&D&D"EBJJwd11377 $$T%@%@4$P33T::$$T%@%@A&&2002"""!!113!##113"$$224"$$224!##113!##113" D 
 "TDC))d.?.?1.DI]I]Ii3 $(D NNUZZ[jkl r3   c                 T   SSK JnJnJnJnJn  Ub  Xl        U R                  c7  [        R                  R                  SU R                  S:X  a  SOS5      U l        [        U R                  [        5      (       aa  U R                  R                  5       (       a!  U" [        U R                  5      5      U l        O!X`R                  R                  5          U l        U R                  UR                   :X  a3  U R"                  c  U" SSS	9U l        U R$                  c  U" SSS	9U l        OJU R                  UR&                  :X  a0  U R"                  c  U" SS
9U l        U R$                  c  U" SS
9U l        U R                  S:X  a&  U R                  UR(                  :X  a  [+        S5      egg)z9
Set the state dict config based on the `StateDictType`.
r   )FullOptimStateDictConfigFullStateDictConfigShardedOptimStateDictConfigShardedStateDictConfigStateDictTypeNFSDP_STATE_DICT_TYPEr   FULL_STATE_DICTSHARDED_STATE_DICTT)offload_to_cpu
rank0_only)r  r  zxFSDP2 does not support LOCAL_STATE_DICT. Please set `fsdp_state_dict_type` to `SHARDED_STATE_DICT` or `FULL_STATE_DICT`.)2torch.distributed.fsdp.fully_sharded_data_parallelr  r  r  r  r  rg  r   r   r   r\  r  rY   r  r   r   r  rh  ri  r  LOCAL_STATE_DICTrJ   )r/   rg  r  r  r  r  r  s          r0   r  2FullyShardedDataParallelPlugin.set_state_dict_type  s   	
 	
 &#2 '#%::>>&%)%6%6!%;!AU$D  d**C00##++--'4S9M9M5N'O$'45I5I5O5O5Q'R$=#@#@@%%-)<D]a)b&++3/GW[hl/m,!!]%E%EE%%-)?t)T&++3/JZ^/_,!d&:&:m>\>\&\b  ']!r3   c                 "   SSK JnJn  [        USS5      nUb  [	        U5      O/ nU R
                  U:X  a  U R                  c  XPl        [        5       nU R                   H1  n[        X5      nUc  [        SU S35      eUR                  U5        M3     [        R                  " U R
                  US9U l        gU R
                  U:X  aG  U R                  S:  a/  [        R                  " U R
                  U R                  S9U l        gSU l        gg)	z|
Given `model`, creates an `auto_wrap_policy` based on the passed in policy and if we can use the
`transformer_cls_to_wrap`
r   r  _no_split_modulesNz+Could not find the transformer layer class z in the model.)transformer_layer_cls)rr  )r  r  r  r  rW   rd  rq  r  rA  rJ   r  	functoolspartialrr  )	r/   r   r  r  no_split_modules%default_transformer_cls_names_to_wraptransformer_cls_to_wraprD  rE  s	            r0   set_auto_wrap_policy3FullyShardedDataParallelPlugin.set_auto_wrap_policy  s   
	
 #5*=tDJZJf5E0Fln-  $@@1195Z2&)e##AA"<U"P"*$'RS^R__m%noo'++O<	  B %.$5$5%%=T%D! ""&AA""Q&(1(9(9$:O:O`d`s`s(t%(,% Br3   c                    [         R                  [         R                  [         R                  [         R                  S.nUn[	        U[
        5      (       a>  UR                  US5      nUc(  [        SU S[        UR                  5       5       35      eOZ[	        U[         R                  5      (       a;  XR                  5       ;  a(  [        SU S[        UR                  5       5       35      eU(       a  [         R                  OUnU R                  S:X  a  SSKJn  OU R                  S:X  a  SS	KJn  U(       d  U R                   c+  XUS
.nU R                  S:X  a  XhS'   OXXS'   W" S0 UD6U l        g[	        U R                   ["        5      (       a  SS/U R                  S:X  a  S/OS/-   n	U	 V
s/ s H  oU R                   ;  d  M  U
PM     nn
U R                   R%                  5        V
Vs/ s H  u  pXR                  5       ;  d  M  U
PM     nn
nU(       d  U(       a5  [        SU R                    SU	 S[        UR                  5       5       35      eW" S0 U R                   D6U l        ggs  sn
f s  snn
f )z(Sets the mixed precision policy for FSDP)r]  rh   ri   fp32NzInvalid mixed precision: r	  r   r   MixedPrecisionr  MixedPrecisionPolicy)param_dtypereduce_dtypebuffer_dtypeoutput_dtyper  r  z Invalid mixed precision policy: z. Must be a `dict` with keys z.Values must be one of r?   )r
  bfloat16float16float32r  rY   r   rJ   rW   r  rv  valuesr\  r  r  r  r`  r   r8   )r/   r  buffer_autocastr  mixed_precision_mappingrv  buffer_typer  
dtype_args
valid_keysr;   missing_keysr<   invalid_valuess                 r0   r  2FullyShardedDataParallelPlugin.set_mixed_precision  sY    >>MMNNMM	#
  os+++//FE} //@@QRVWnWsWsWuRvQwx   55/QoQoQq:q+O+<<MdSjSqSqSsNtMuv  (7emmE!=!#Ut22:).FJ  A%-8>*-2>**8*F:*FD'33T::'8$($5$5$: @PJ (2Zz!d>Y>Y5YAzLZ"99??AAdaQNlNlNnEnA   ~ 6t7R7R6S T22< >--12I2P2P2R-S,TV 
 +9*W4;V;V*WD' ;
 [s   2I0	I0.I5I5c                     U R                   S:X  a  SSKJn  OSSKJn  [	        U R
                  U5      (       d#  U R                   S:X  a  SOSn[        SU S35      eg	)
zb
Validates the mixed precision policy, abstracted away to not bring in the imports if not needed.
r  r   r  r  z-`torch.distributed.fsdp.MixedPrecisionPolicy`z'`torch.distributed.fsdp.MixedPrecision`z.mixed_precision_policy must be an instance of r   N)r\  r  r  r  r  r`  rJ   )r/   r  required_types      r0   r  >FullyShardedDataParallelPlugin.validate_mixed_precision_policy6  sg     !U=$55~FF $$) @> 
 Mm_\]^__ Gr3   c                 "   U R                   S:X  a	  SSKJnJn  OSSKJn  [        U R                  [        5      (       aQ  U R                   S:X  a+  U R                  (       d  W" 5       U l        g W" 5       U l        g W" U R                  S9U l        g g )Nr  r   )CPUOffloadPolicyOffloadPolicy
CPUOffload)offload_params)r\  r  r  r  r  r  re  rb   )r/   r  r  r  s       r0   r  .FullyShardedDataParallelPlugin.set_cpu_offloadG  sp    !NN9d&&--  A%'''4D$'7'9D$#-T=M=M#N  .r3   c                 L   U R                   S:X  a  SSKJn  OSSKJn  U R                   S:X  a3  [	        U R
                  W5      (       d  [        SU R
                   35      eU R                   S:X  a4  [	        U R
                  W5      (       d  [        SU R
                   35      eg g )Nr  r   )r  r  zZ`cpu_offload` must be an instance of `torch.distributed.fsdp.OffloadPolicy` in FSDP2, got r   zW`cpu_offload` must be an instance of `torch.distributed.fsdp.CPUOffload` in FSDP1, got )r\  r  r  r  r  re  rJ   )r/   r  r  s      r0   r  3FullyShardedDataParallelPlugin.validate_cpu_offloadV  s    !<9!*T5E5E}*U*Ulmqm}m}l~  !*T5E5Ez*R*Rijnjzjzi{|  +S!r3   )ro  rd  r_  re  rp  rn  r\  rf  rr  r`  ri  rl  r^  r]  rh  rg  rm  rq  rk  r*   )FF)0r@   rA   rB   rC   rD   r   r\  r   rc   r]  r   rY   r^  rb   r_  r   r`  r   rd  r
   r   re  rf  r   r
  nnModulerg  rh  ri  rj  rk  rl  rm  rn  ro  rp  rq  rW   rr  r   r  r  r  r  r  r  rE   r?   r3   r0   r[  r[    s   FP   K
L#  PU  o
PuS"KKL  Z_  ^
Z5&OQU!UV  Z_  f
Zxc+T&T UV  	 v
	 H39;	
   	 N	
 huXw7m/n%nop  	  d
		 +1	3 	 HMPQHOXeHUXX__$=s$BCD 
 KP  k
KOU3 FFG  	tu	 x=	
  	t
	 XB	
 
 $ N
t  ',  E
'OXd^  BG B
BM8Hehhoo%6%<=>  */ t
*  # o
d  &+ <
&d  ', D
't  :?  L
:!8DI#6  %*  W
%NHSM JmX+Z -D2Xh`"Or3   r[  c                   R    \ rS rSr% Sr\" SSS0S9r\\S'   \" SS	9r	\
S
   \S'   Srg)TorchTensorParallelPluginif  zH
This plugin is used to enable tensor parallelism using PyTorch >= 2.0.
r   rz  z@tensor parallel size will be used in the device mesh preparationr{  tp_sizeN)r|  ztorch.distributed.DeviceMeshtorch_device_meshr?   )r@   rA   rB   rC   rD   r   r  r   rc   r  r   rE   r?   r3   r0   r  r  f  sA     \]GS  CHPTBUx >?Ur3   r  c                   B    \ rS rSr% Sr\" SSS0S9r\\   \	S'   S r
S	rg)
TorchContextParallelConfigiu  zH
This class holds the configuration for context parallelism in PyTorch.
Nrz  zqCommunication strategy for context parallelism. Can be one of 'allgather' or 'alltoall'. Defaults to 'allgather'.r{  cp_comm_strategyc                 
   [        S[        5      (       d  [        S[         S35      eU R                  c%  [        R
                  R                  SS5      U l        U R                  S;  a  [        SU R                   S35      eg )	Nr  z1Context parallelism is only available in PyTorch 9 and later versions. Please upgrade your PyTorch version.#PARALLELISM_CONFIG_CP_COMM_STRATEGY	allgather)r  alltoallzInvalid cp_comm_strategy: z+. Must be one of 'allgather' or 'alltoall'.)r$   r   rJ   r  r   r   r   r.   s    r0   r   (TorchContextParallelConfig.__post_init__  s    &GHHCDeCf g7 7    ($&JJNN3XZe$fD!  (AA,T-B-B,CCno  Br3   )r  )r@   rA   rB   rC   rD   r   r  r   rY   rc   r   rE   r?   r3   r0   r  r  u  s5     ',  H
'hsm r3   r  c                   .    \ rS rSr% SrSr\\S'   S rSr	g)TorchTensorParallelConfigi  zU
Use this object in your [`Accelerator`] to customize your torch tensor parallelism.
Fenable_async_tpc                     [        S[        5      (       d  [        S[         S35      e[        SS[        5      (       d  [        S[         35      eU R
                  (       a  [        R                  " S5        g g )Nr  z6Torch tensor parallelism is only available in PyTorch r  r  zTP requires transformers >= zJAsync tensor parallelism is currently not supported, ignoring this option.)r$   r   rJ   r#   r   r  r   r   r.   s    r0   r   'TorchTensorParallelConfig.__post_init__  ss    &GHHHIjHk l7 7 
  6\]];<b;cdeeMMfg  r3   r?   N)
r@   rA   rB   rC   rD   r  rb   rc   r   rE   r?   r3   r0   r  r    s     "OT!hr3   r  c                   R   \ rS rSr% Sr\" SSS0S9r\\S'   \" SSS0S9r	\\S	'   \" SSS
0S9r
\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS 0S9r\\S!'   \" SSS"0S9r\\S#'   \" SSS$0S9r\\S%'   \" S&SS'0S9r\\S('   \" SSS)0S9r\\S*'   \" SSS+0S9r\\S,'   \" SSS-0S9r\\S.'   \" SSS/0S9r\\S0'   \" SSS10S9r\\S2'   \" S3SS40S9r \\S5'   \" SSS60S9r!\"\   \S7'   \" SSS80S9r#\$\%   \S9'   \" SSS:0S9r&\$\%   \S;'   \" S<SS=0S9r'\\S>'   \" S?SS@0S9r(\\SA'   \" SSSB0S9r)\\SC'   \" SSSD0S9r*\\SE'   \" SSSF0S9r+\\SG'   \" SSSH0S9r,\\SI'   \" S?SSJ0S9r-\\SK'   \" SLSSM0S9r.\\SN'   \" SOSSP0S9r/\\SQ'   \" S?SSR0S9r0\\SS'   \" SSST0S9r1\$\2   \SU'   \" SSSV0S9r3\$\4\\24      \SW'   \" SSSX0S9r5\$\%   \SY'   \" SSSZ0S9r6\$\%   \S['   \" SSS\0S9r7\$\%   \S]'   \" SSS^0S9r8\$\%   \S_'   \" SSS`0S9r9\$\%   \Sa'   \" SSSb0S9r:\$\4\\24      \Sc'   Sd r;SlSe jr<Sf r=Sg r>Sh r?Si r@Sj rASkrBg)mMegatronLMPlugini  an  
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`):
        Minimum 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.
Nrz  ztensor parallelism degree.r{  	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)r  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_sizer  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   zPMinimum 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                    SnU R                   c1  [        [        R                  R	                  US-   S5      5      U l         U R
                  c1  [        [        R                  R	                  US-   S5      5      U l        U R                  c1  [        [        R                  R	                  US-   S5      5      U l        U R                  c1  [        [        R                  R	                  US-   S5      5      U l        U R                  c4  [        [        R                  R	                  US-   S	5      5      S:H  U l	        U R                  c4  [        [        R                  R	                  US
-   S	5      5      S:H  U l        U R                  c4  [        [        R                  R	                  US-   S	5      5      S:H  U l        U R
                  S:  d  U R                  (       a  SU l        OSU l        U R                  bk  [        U R                  5      S:X  a  U R                  R!                  SS/5        O4[        U R                  5      S:X  a  U R                  R#                  S5        0 SU R                   _SU R
                  _SU R$                  _SU R&                  _SU R                  _SU R                  _SU R                  _SU R                  _SU R                  _SU R                  _SU R(                  _SU R*                  _SU R,                  _SU R.                  _SU R0                  _SU R2                  _U l        U R                  (       a  S U R4                  S!'   U R6                  b:  U R6                  U R4                  S"'   U R8                  (       a  U R;                  5         U R<                  b&  U R4                  R?                  U R<                  5        g g )#NMEGATRON_LM_	TP_DEGREEr   	PP_DEGREENUM_MICRO_BATCHESGRADIENT_CLIPPINGr  RECOMPUTE_ACTIVATIONSr  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  ) r  r   r   r   r   r  r  r  r   r  r   r  r  r0  r  r  extendr  r  r  r  r  r  r  r  r  megatron_lm_default_argsr  r  set_tensorboard_logging_optionsr#  updater  s     r0   r   MegatronLMPlugin.__post_init__	  sx   >>! 0Da!HIDN>>! 0Da!HIDN!!)%(AT8TVW)X%YD"!!)%*2::>>&CV:VX[+\%]D"%%-)4RZZ^^FMdDdfm5n)ost)tD&))1BJJNN64O+OQXYZ^__ * $$,(3BJJNN6LbCbdk4l(mqr(rD%>>A!?!?#DM#DM  ,4(()Q.%%,,aV4T**+q0%%,,Q/)
($..)
*DNN)
 1$2Y2Y)
 4T5_5_	)

 )
 ()G)G)
  !:!:)
 //)
  !7!7)
  5 5)
  5 5)
 T//)
 t||)
 $T%?%?)
 $//)
  T//!)
%$ %%EPD))*AB+?C?S?SD))*;<++446##/))001I1IJ 0r3   c                     UR                   R                  R                  5       n[        R	                  5        H  nXC;   d  M
  [        U   " XU5          g    [        SU S35      e)Nz0Accelerate Megatron-LM integration not supports z1 model. You can add your own model config parser.)r   
model_typer   !MODEL_CONFIGS_TO_MEGATRON_PARSERSr  rJ   )r/   r   
batch_datamodel_config_typer;  s        r0   set_network_size_args&MegatronLMPlugin.set_network_size_args	  sj    !LL3399;;@@BJ.1*=d:V C >?P>Q R8 8
 	
r3   c                     US:X  a  SU R                   S'   g US:X  a0  SU R                   S'   SU l        U R                  U R                   S'   g g )Nrh   Tri   r-  r0  )r6  r0  )r/   r  s     r0   r  $MegatronLMPlugin.set_mixed_precision	  sR    f$48D))&1&48D))&1#DM8<D))*5 'r3   c                     X l         Xl        X!-  U R                  -  U l        U R                   U R                  S'   U R                  U R                  S'   U R                  U R                  S'   g )Ndata_parallel_sizemicro_batch_sizeglobal_batch_size)rD  rE  r  rF  r6  )r/   rE  	dp_degrees      r0   set_training_args"MegatronLMPlugin.set_training_args	  si    "+ 0!*!=@V@V!V>B>U>U%%&:;<@<Q<Q%%&89=A=S=S%%&9:r3   c                    UR                   R                  R                  5       nSU;   aj  SU R                  S'   UR                  S   S   U R                  S'   UR                  S   S   U R                  S'   UR                  S   U R                  S	'   OAS
U;   a,  S
U R                  S'   UR                  S   U R                  S'   O[        SU S35      eUR                  S   U R                  S'   UR                  S   U R                  S'   g )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   r6  defaultsrJ   )r/   rL  optimizer_names      r0   set_optimizer_type#MegatronLMPlugin.set_optimizer_type
  s   ",,55;;=^#9?D))+6:C:L:LW:UVW:XD)),7:C:L:LW:UVW:XD)),78A8J8J58QD))*5n$9>D))+6<E<N<Nz<ZD)).9z.)99YZ[[.7.@.@.F%%d+8A8J8J>8Z%%n5r3   c                    U R                   cK  UR                  U R                  S   -  U l         U R                  b  S U l        [        R
                  " S5        U R                  cK  UR                  U R                  S   -  U l        U R                  b  [        R
                  " S5        SU l        U R                   U R                  S'   U R                  U R                  S'   U R                  U R                  S'   U R                  U R                  S'   U R                  U R                  S	'   U R                  U R                  S
'   U R                  U R                  S'   U R                  U R                  S'   U R                  U R                  S'   U R                  U R                  S'   U R                  U R                  S'   U R                   U R                  S'   g )NrD  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_stepsr6  r   r   r   r	  warmup_num_stepsr
  r  r  r  r  r  r  r  r  )r/   	schedulers     r0   set_scheduler_args#MegatronLMPlugin.set_scheduler_args
  s   #(88D<Y<YZn<ooD!!-%)"n '#,#=#=A^A^_sAt#tD %%1v &'D"7;7G7G%%m4;?;O;O%%&789=9K9K%%o6=A=S=S%%&9::>:M:M%%&67<@<Q<Q%%&89>B>U>U%%&:;:>:M:M%%&67CGC_C_%%&?@>B>U>U%%&:;<@<Q<Q%%&8926++%%h/r3   c                    SSK Jn  [        R                  " 5       nU" U5      nUR	                  5       n[        US   5      U l        U R                  R                  5        Hc  u  pEUR                  S5      (       a  SU R                  U'   M,  UR                  S5      (       d  MD  SU R                  UR                  SS5      '   Me     g )Nr   )_add_logging_argslog_Tno_log_no_r
  )megatron.training.argumentsrb  argparseArgumentParserparse_known_argsvarsdataset_argsr8   
startswithr6  r8  )r/   rb  parserlogging_argsr  rS   s         r0   r7  0MegatronLMPlugin.set_tensorboard_logging_options1
  s    A((*"6*..0 a1++113JC~~f%%59--c2	**HL--ckk%.DE	 4r3   )r0  rD  rk  rF  r  r	  r
  r6  rE  r  r  r  r  r  r  r   r  r*   )Cr@   rA   rB   rC   rD   r   r  r   rc   r  r  r  r   r  rb   r  r  r  r  r  rY   r  r   r  r  r  r  r  r  r	  r
  r  r  r  rW   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  rH  rY  r_  r7  rE   r?   r3   r0   r  r    s   ]~ 46;W2XYIsY46;Y2Z[Is["46C]:^_s_$Z[ u  "'78"$  #(EF#4  ',89't  /4KL/&  27(VW2)3  $qr   u
K   u
M3  $)gh$S  !&ST!  $VWe   cdNC   lmNC  "klc  !WXOS  #TUs  !&hi!  lmFE  #(t
#d3i  ,1QuHv+whx(w(-dfNqEr(sM8H%s3&:U1VWGUW"'qr#4  ?@J  $OP  $OP  !:;OS  %*?@%T  [\J  RSM3   DEM4  .345.Xc]  :?56:htCH~6  :?;<:"HX$6  9>:;9!8H#5  FKXYF.0B  5:675x1  05120(8,  5:QR5$sCx.1 
7Kr	
FT[ >:Mr3   r  r;  c                    ^  U 4S jnU$ )Nc                 Z   >^  [         R                  " T 5      U 4S j5       nT [        T'   U$ )Nc                     > T" U 0 UD6$ r*   r?   )argsr  funcs     r0   r   \add_model_config_to_megatron_parser.<locals>.add_model_config_parser_helper.<locals>.wrapperD
  s    (((r3   )r  wrapsr<  )rt  r   r;  s   ` r0   add_model_config_parser_helperKadd_model_config_to_megatron_parser.<locals>.add_model_config_parser_helperC
  s0    			) 
	) 9=)*5r3   r?   )r;  rw  s   ` r0   #add_model_config_to_megatron_parserry  B
  s     *)r3   zmegatron-bertc                    SnUR                   R                  nUR                   R                  nUR                   R                  nUR                   R                  nUR                   R
                  nUR                   R                  n	Sn
SUR                  R                  R                  5       ;   a  Sn
U R                  b5  U R                  b  [        R                  " S5        U R                  U l
        O@U R                  b  U R                  U l
        O!Ub  US   R                  S   U l
        OXpl
        U R                  U R                  S'   X0R                  S	'   X@R                  S
'   XPR                  S'   X`R                  S'   XpR                  S'   XR                  S'   XR                  S'   UR                   R                   U R                  S'   XR                  S'   g )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   ru  r6  return_dict)megatron_lm_pluginr   r=  r~  r  r  r  r  r  r  r  s              r0   parse_bert_configr  N
  s   O//J,,**K,,::#llBB((Jll--OU__--3355$$000<MMkl(:(M(M%		.	.	:(:(M(M%		(2;(?(E(Ea(H%(?%@R@]@]//=ET//0AB@J//=AL//>I\//0EFMd//0IJFV//0BCET//0ABGL||G_G_//0CD@J//=r3   gpt2c                 x   SnUR                   R                  nUR                   R                  nUR                   R                  nUR                   R                  nUR                   R
                  nSn	U R                  b5  U R                  b  [        R                  " S5        U R                  U l        O@U R                  b  U R                  U l        O!Ub  US   R                  S   U l        OXpl        U R                  U R                  S'   U R                  U R                  S'   SU R                  S	'   X0R                  S
'   X@R                  S'   XPR                  S'   X`R                  S'   XpR                  S'   XR                  S'   XR                  S'   UR                   R                  U R                  S'   g )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   ru  r6  r  r  
r  r   r=  r~  r  r  r  r  r  r  s
             r0   parse_gpt2_configr  p
  s   O%%J,,%%K,,--#ll66ll--O$$000<MMkl(:(M(M%		.	.	:(:(M(M%		(2;(?(E(Ea(H%(?%@R@]@]//=CUCcCc//@DV//0@AET//0AB@J//=AL//>I\//0EFMd//0IJFV//0BCET//0ABGL||G_G_//0CDr3   t5c                 H   SnUR                   R                  nUR                   R                  nUR                   R                  n[	        UR                   S5      (       a  UR                   R
                  OSnUR                   R                  nSn	U R                  c!  Ub  US   R                  S   U l        OXpl        U R                  c!  Ub  US   R                  S   U l	        OXpl	        U R                  U R                  S'   U R                  U R                  S	'   X0R                  S
'   X@R                  S'   XPR                  S'   X`R                  S'   XpR                  S'   XR                  S'   XR                  S'   UR                   R                  U R                  S'   g )Nr  r  r   Tr}  r   labelsr  r  r~  r  r  r  r  r  r  r  )r   r  d_model	num_headshasattrr  r  r  ru  r  r6  r  r  s
             r0   parse_t5_configr  
  s   O((J,,&&K,,00:A%,,P]:^:^ell66dhll--O,,4!4>{4K4Q4QRS4T14K1,,4!4>x4H4N4Nq4Q14K1HZHmHm//0DEHZHmHm//0DEET//0AB@J//=AL//>I\//0EFMd//0IJFV//0BCET//0ABGL||G_G_//0CDr3   llamac                 P   SnUR                   R                  nSnUR                   R                  nUR                   R                  nUR                   R                  nUR                   R
                  n	[        UR                   SS 5      n
U R                  cJ  U
b  Xl        O@U R                  b  U R                  U l        O!Ub  US   R                  S   U l        OXl        U R                  U R                  S'   SU R                  S'   X0R                  S	'   X@R                  S
'   XPR                  S'   X`R                  S'   XpR                  S'   XR                  S'   XR                  S'   U R                  U R                  S'   UR                   R                  U R                  S'   g )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  ru  r  r6  r  )r  r   r=  r~  r  r  r  r  r  r  r  s              r0   parse_llama_configr  
  s   O//J,,**K,,::ll--O#llBB'<dCJ$$,!,6)22>,>,Q,Q)#,6{,C,I,I!,L),C)CUCcCc//@DU//0@AET//0AB@J//=FV//0BCAL//>I\//0EFET//0ABMd//0IJ@R@]@]//=GL||G_G_//0CDr3   c                   <   \ rS rSr% Sr\" SSS0S9r\\S'   \" SSS	0S9r	\
\S
'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS0S9r\\S'   \" SSS0S9r\R$                  \S'   \" SSS0S9r\\   \S'   \" SSS0S9r\\   \S'   S rSrg)BnbQuantizationConfigi
  a   
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`.
Frz  zenable 8bit quantization.r{  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','nf4'}.bnb_4bit_quant_typezlenable nested quantization where the quantization constants from the first quantization are quantized again.bnb_4bit_use_double_quantrh   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                    [        U R                  [        5      (       d  [        S5      e[        U R                  [        5      (       d  [        S5      eU R                  (       a  U R                  (       a  [        S5      eU R                  (       d  U R                  (       d  [        S5      e[        U R
                  [        [        45      (       d  [        S5      e[        U R                  [        5      (       d  [        S5      eU R                  S;  a  [        SU R                   35      e[        U R                  [        5      (       d  [        S	5      e[        U R                  [        5      (       a  U R                  S
:X  a  [        R                  U l        OU R                  S:X  a  [        R                  U l        OrU R                  S:X  a  [        R                  U l        OL[        SU R                   35      e[        U R                  [        R                   5      (       d  [        S5      eU R"                  b*  [        U R"                  [$        5      (       d  [        S5      eU R&                  b*  [        U R&                  [$        5      (       d  [        S5      eU R                  (       a  [(        R*                  U l        U R                  (       a  [        R.                  U l        U R                  (       a&  U R
                  S:w  a  [0        R2                  " S5        [        U R4                  [        5      (       a  U R4                  S
:X  a  [        R                  U l        OdU R4                  S:X  a  [        R                  U l        O>U R4                  S:X  a  [        R                  U l        O[        SU R4                   35      eU R                  (       a"  U R4                  c  [        R                  U l        U R                  (       a  U R4                  c  U R                  U l        [        U R4                  [        R                   5      (       d  [        S5      eg)zn
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 booleanz0load_in_4bit and load_in_8bit can't be both Truez1load_in_4bit and load_in_8bit 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 booleanr  rh   ri   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  rb   rJ   r  r  r   r   r  rY   r  r  r
  r  r  r  rv  r  rW   r  rn  rq  target_dtypeint8r   r   r  r.   s    r0   r   #BnbQuantizationConfig.__post_init__!  s5    $++T22=>>$++T22=>>!2!2OPP  ):):PQQ$11C<@@KLL$22C88CDD%%^;VW[WoWoVpqrr$88$??JKKd11377**f4.3mm+,,6.3mm+,,6.3nn+ YZ^ZuZuYvw  D77EEWXX(D<M<Mt1T1TEFF$$0DD]D]_c9d9dNOO + 0 0D %

D!8!8C!?MMXYd&&,,6)#(== !!V+#(== !!V+#(>>  #[\`\l\l[m!noo!1!1!9$}}D!1!1!9#::D$**EKK88@AA 9r3   )r  r  r  )r@   rA   rB   rC   rD   r   r  rb   rc   r  r   r  r  rY   r  r  r  r
  rv  r  rW   r  r   rE   r?   r3   r0   r  r  
  s9   6 u@[7\]L$] %ab! 
 u@[7\]L$]$r
   ',  C
't  #( i
#C   % n
 K  $
L$s)  ',tu'$s) 
HBr3   r  c                     [        U R                  5       5      nU R                  R                  U:X  a  U R                  $ [	        U5      S:X  a  gU H  n[        X15      nUc  M  Us  $    g)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)rW   childrenr7   r@   r  rA  )moduler4  modules_childrenchild_modulemodule_classs        r0   rA  rA  l  sg     FOO-.  D(		!	#,L5lIL'## -r3   )irD   rg  r+   enumr  loggingr   r   collections.abcr   
contextlibr   dataclassesr   r   datetimer   typingr   r	   r
   r   r   r   r   r
  	constantsr   r   r   r   r   r   r   r   r   r6   r   r   r  r   r   r   r   r   r    r!   r"   versionsr#   r$   torchao.float8r%   	getLoggerr@   r  r'   EnumMetarG   EnumrP   r^   re   rr   r   r   r   r   r   r   r   r   r   r   r  r   rY   r  r*  r.  r1  r5  rF  r\  r`  rn  rt  ry  r  r  r  r  r[  r  r  r  r  r<  ry  r  r  r  r  r  rA  r?   r3   r0   <module>r     sd        	  $ % (  S S S 
 
 
 :	 	 	 9 1 
		8	$L L*t}} 	#tyy$4 	# )] ) )*,x ,( RM R Rj }  > 6] 6 6< -
 :,-	34  2] 2 2$ Kg] Kg Kg\ ^ ^ ^   n&7    2 >?  q
M q
 q
h c499  F&sDII &"S$)) "*dii *5 C 5 p 8C  
h 
$))    
 [ [ [| ;/ ;/ ;/| 0 0 0f U U Up @
 @
 @
F a	 a	 a	H V V V   4 h h h* UM UM UMp %' !	*C 	* %_5K 6KB %V,` -`> %T*` +`< %W-` .`B WB WB WBt$r3   