
    g`v                   
   d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlmZ d dlmZ d dlmZ d dlmZ d dlmZmZmZ d dlZd dlmc mZ d dlmZ d d	lmZ d
dlmZmZm Z m!Z! d
dl"m#Z#m$Z$m%Z% d
dlm&Z& d
dl'm(Z( d
dl)m*Z* d
dl+m,Z, d
dl-m.Z.m/Z/m0Z0 d
dl1m2Z2m3Z3m4Z4 d
dlm5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZkmlZlmmZmmnZnmoZompZpmqZqmrZr d
dlsmtZtmuZu d
dlvmwZw d
dlxmyZy  e\            rd
dlmzZzm{Z{m|Z|m}Z}m~Z~  e_            rd
dlmZmZmZmZmZmZmZmZ d dlmZ  ee            rd dlmZ d dlmc mZ d dlmc mZ  ecd          rd dlZ	 d dlmZ n# e$ r	 d dlmZ Y nw xY w e(e          Z e            Z e            Z e            Z e            Z G d d          ZdS )     )annotationsN)OrderedDict)contextmanager)partial)
MethodType)AnyCallableUnion)"split_torch_state_dict_into_shards)version   )load_accelerator_stateload_custom_statesave_accelerator_statesave_custom_state)DataLoaderDispatcherprepare_data_loaderskip_first_batches)AlignDevicesHook)
get_logger)AcceleratedOptimizer)AcceleratedScheduler)AcceleratorStateGradientStatePartialState)LOGGER_TYPE_TO_CLASSGeneralTrackerfilter_trackers)>
MODEL_NAMESAFE_WEIGHTS_INDEX_NAMESAFE_WEIGHTS_NAMESAFE_WEIGHTS_PATTERN_NAMEWEIGHTS_INDEX_NAMEWEIGHTS_NAMEWEIGHTS_PATTERN_NAMEAutocastKwargsDataLoaderConfigurationDeepSpeedPluginDistributedDataParallelKwargsDistributedTypeDynamoBackendFP8RecipeKwargsFullyShardedDataParallelPluginGradientAccumulationPluginGradScalerKwargsInitProcessGroupKwargsKwargsHandler
LoggerTypeMegatronLMPluginPrecisionTypeProfileKwargsProjectConfigurationRNGTypeTorchDynamoPluginapply_fp8_autowrapcheck_os_kernel clean_state_dict_for_safetensorscompare_versionsconvert_modelconvert_outputs_to_fp32extract_model_from_parallelgathergather_object#get_mixed_precision_context_managerget_pretty_nameis_bf16_available'is_bitsandbytes_multi_backend_availableis_deepspeed_availableis_ipex_availableis_lomo_availableis_megatron_lm_availableis_mlu_availableis_msamp_availableis_musa_availableis_npu_availableis_torch_versionis_torch_xla_availableis_transformer_engine_availableis_xpu_availableload_fsdp_modelload_fsdp_optimizerpad_across_processesparse_choice_from_envrecursively_applyreducerelease_memorysavesave_fsdp_modelsave_fsdp_optimizerwait_for_everyone)FSDP_PYTORCH_VERSIONPROFILE_PATTERN_NAME)get_state_dict_offloaded_model)is_compiled_module)DeepSpeedEngineWrapperDeepSpeedOptimizerWrapperDeepSpeedSchedulerWrapper
DummyOptimDummyScheduler)MegatronEngineMegatronLMDummyDataLoaderMegatronLMDummySchedulerMegatronLMOptimizerWrapperMegatronLMSchedulerWrappermegatron_lm_initializemegatron_lm_prepare_data_loader-megatron_lm_prepare_model_optimizer_scheduler)JoinF)check_device)LRScheduler)_LRSchedulerc                  N   e Zd ZdZdeddddddddddddddddfdd&Zed'             Zed(             Zed)             Z	ed*             Z
ed+             Zed,             Zed-             Zed.             Zed/             Zed0             Zej        dd2            Zed3             Zed4             Zed5             Zed6             Zed7             Zed8             Zed9             Zed:             Zed;             Zed<             Zeddd@            ZdddCZdddDZddEZ dddGZ!dddIZ"edJ             Z#edK             Z$edL             Z%e&edM                         Z'dN Z(edO             Z)e)j        dP             Z)edQ             Z*e*j        dR             Z*edS             Z+eddT            Z,dU Z-ddVZ.ddWdXZ/ddd\Z0d] Z1d^ Z2d_ Z3d` Z4da Z5	 ddddZ6dddgZ7ddjZ8dk Z9dl Z:dm Z;ddnZ<ddpZ=dq Z>dr Z?ddsZ@ddvZAddxZBdddzZCd{ ZDedi fdd            ZEdddZFedi fdd            ZGd ZHddZI	 	 dddZJddZKdddZLddZMdddZNd ZOd ZPd ZQd ZRddZSd ZTeddd            ZUeddd            ZVed             ZWdddZXd ZYddZZddZ[ed             Z\dS )AcceleratoraG  
    Creates an instance of an accelerator for distributed training (on multi-GPU, TPU) or mixed precision training.

    Args:
        device_placement (`bool`, *optional*, defaults to `True`):
            Whether or not the accelerator should put objects on device (tensors yielded by the dataloader, model,
            etc...).
        mixed_precision (`str`, *optional*):
            Whether or not to use mixed precision training. Choose from 'no','fp16','bf16' or 'fp8'. Will default to
            the value in the environment variable `ACCELERATE_MIXED_PRECISION`, which will use the default value in the
            accelerate config of the current system or the flag passed with the `accelerate.launch` command. 'fp8'
            requires the installation of transformers-engine.
        gradient_accumulation_steps (`int`, *optional*, default to 1):
            The number of steps that should pass before gradients are accumulated. A number > 1 should be combined with
            `Accelerator.accumulate`. If not passed, will default to the value in the environment variable
            `ACCELERATE_GRADIENT_ACCUMULATION_STEPS`. Can also be configured through a `GradientAccumulationPlugin`.
        cpu (`bool`, *optional*):
            Whether or not to force the script to execute on CPU. Will ignore GPU available if set to `True` and force
            the execution on one process only.
        dataloader_config (`DataLoaderConfiguration`, *optional*):
            A configuration for how the dataloaders should be handled in distributed scenarios.
        deepspeed_plugin ([`~utils.DeepSpeedPlugin`] or dict of `str`: [`~utils.DeepSpeedPlugin`], *optional*):
            Tweak your DeepSpeed related args using this argument. This argument is optional and can be configured
            directly using *accelerate config*. If using multiple plugins, use the configured `key` property of each
            plugin to access them from `accelerator.state.get_deepspeed_plugin(key)`. Alias for `deepspeed_plugins`.
        fsdp_plugin ([`~utils.FullyShardedDataParallelPlugin`], *optional*):
            Tweak your FSDP related args using this argument. This argument is optional and can be configured directly
            using *accelerate config*
        megatron_lm_plugin ([`~utils.MegatronLMPlugin`], *optional*):
            Tweak your MegatronLM related args using this argument. This argument is optional and can be configured
            directly using *accelerate config*
        rng_types (list of `str` or [`~utils.RNGType`]):
            The list of random number generators to synchronize at the beginning of each iteration in your prepared
            dataloaders. Should be one or several of:

            - `"torch"`: the base torch random number generator
            - `"cuda"`: the CUDA random number generator (GPU only)
            - `"xla"`: the XLA random number generator (TPU only)
            - `"generator"`: the `torch.Generator` of the sampler (or batch sampler if there is no sampler in your
              dataloader) or of the iterable dataset (if it exists) if the underlying dataset is of that type.

            Will default to `["torch"]` for PyTorch versions <=1.5.1 and `["generator"]` for PyTorch versions >= 1.6.
        log_with (list of `str`, [`~utils.LoggerType`] or [`~tracking.GeneralTracker`], *optional*):
            A list of loggers to be setup for experiment tracking. Should be one or several of:

            - `"all"`
            - `"tensorboard"`
            - `"wandb"`
            - `"comet_ml"`
            If `"all"` is selected, will pick up all available trackers in the environment and initialize them. Can
            also accept implementations of `GeneralTracker` for custom trackers, and can be combined with `"all"`.
        project_config ([`~utils.ProjectConfiguration`], *optional*):
            A configuration for how saving the state can be handled.
        project_dir (`str`, `os.PathLike`, *optional*):
            A path to a directory for storing data such as logs of locally-compatible loggers and potentially saved
            checkpoints.
        step_scheduler_with_optimizer (`bool`, *optional*, defaults to `True`):
            Set `True` if the learning rate scheduler is stepped at the same time as the optimizer, `False` if only
            done under certain circumstances (at the end of each epoch, for instance).
        kwargs_handlers (list of [`~utils.KwargsHandler`], *optional*)
            A list of [`~utils.KwargsHandler`] to customize how the objects related to distributed training, profiling
            or mixed precision are created. See [kwargs](kwargs) for more information.
        dynamo_backend (`str` or [`~utils.DynamoBackend`], *optional*, defaults to `"no"`):
            Set to one of the possible dynamo backends to optimize your training with torch dynamo.
        gradient_accumulation_plugin ([`~utils.GradientAccumulationPlugin`], *optional*):
            A configuration for how gradient accumulation should be handled, if more tweaking than just the
            `gradient_accumulation_steps` is needed.

    **Available attributes:**

        - **device** (`torch.device`) -- The device to use.
        - **distributed_type** ([`~utils.DistributedType`]) -- The distributed training configuration.
        - **local_process_index** (`int`) -- The process index on the current machine.
        - **mixed_precision** (`str`) -- The configured mixed precision mode.
        - **num_processes** (`int`) -- The total number of processes used for training.
        - **optimizer_step_was_skipped** (`bool`) -- Whether or not the optimizer update was skipped (because of
          gradient overflow in mixed precision), in which
        case the learning rate should not be changed.
        - **process_index** (`int`) -- The overall index of the current process among all processes.
        - **state** ([`~state.AcceleratorState`]) -- The distributed setup state.
        - **sync_gradients** (`bool`) -- Whether the gradients are currently being synced across all processes.
        - **use_distributed** (`bool`) -- Whether the current configuration is for distributed training.
    TNr   Fdevice_placementboolsplit_batchesmixed_precisionPrecisionType | str | Nonegradient_accumulation_stepsintcpudataloader_configDataLoaderConfiguration | Nonedeepspeed_plugin3DeepSpeedPlugin | dict[str, DeepSpeedPlugin] | Nonefsdp_plugin%FullyShardedDataParallelPlugin | Nonemegatron_lm_pluginMegatronLMPlugin | None	rng_typeslist[str | RNGType] | Nonelog_withRstr | LoggerType | GeneralTracker | list[str | LoggerType | GeneralTracker] | Noneproject_dirstr | os.PathLike | Noneproject_configProjectConfiguration | Nonegradient_accumulation_plugin!GradientAccumulationPlugin | Nonestep_scheduler_with_optimizerkwargs_handlerslist[KwargsHandler] | Nonedynamo_backendDynamoBackend | str | Nonedeepspeed_pluginsc                   g | _         ||| _        nt          |          | _        |!| j        | j                            |           |>t          |          }|t          vr&t          d| dt          j                               |t                      nt          |          }||t          d          ||}|zt          j        i k    r5t                      j        t          j        k    rt                      j        }nt"          j                            dd          dk    rt)                      nd }nt                      j        t          j        k    r2t          j        i k    r"t                      j        t+          d	          t-          |t.                    r;|                                D ]&}t-          |t(                    st3          d
          '|dt"          j        d<   t5                      st7          d          t9                      r!t;          ddd          rt7          d          nOt=                      r!t;          ddd          rt7          d          n t;          ddd          rt7          d          | t"          j                            dd          n|}t-          |t.                    s,|                    |           |                     d           np|                                D ]}|                    |           tC          tE          |                                                    }|                     d           d | _#        t"          j                            dd          dk    st-          |tH                    r,tK          dtL                    st          dtL                     |5t"          j                            dd          dk    rtI                      nd }n3t-          |tH                    st3          d          dt"          j        d<   |	5t"          j                            dd          dk    rtO                      nd }	n3t-          |	tN                    st3          d          dt"          j        d<   |	rtQ                      st7          d           d | _)        d | _*        d | _+        d | _,        d | _-        d | _.        d!| _/        |\|D ]X}t-          |t`                    sJ d"| d#            t-          |tb                    r| j)        t          d$          || _)        Yt-          |td                    r| j*        t          d%          || _*        t-          |tf                    r| j+        t          d&          || _+        t-          |th                    r| j,        t          d'          || _,        t-          |tj                    r| j-        t          d(          || _-        &t-          |tl                    r| j.        t          d)          || _.        Z| j+        | j+        7                                ni }t          dI||||||	dd*|| _8        | j8        j9        d+k    r| j,        ti                      | _,        d!| _:        | j,        r| j8        j9        d+k    r.| j        t          j;        t          j        fvrt          d,          | j,        j<        d-k    o| j        t          j=        t          j;        fv | _:        t}          || j?                  }t          |          d.k     r|t          jB        d/| d0           || _C        |d1k    r?t          | j8        d2d!          r)| j8        jE        t          jF        k    rt          d3          ||d.k    rt          d4          n-t          t          d5|                    }t          |6          }t          |7          | _K        || _L        |t                      }|| _N        || _O        d | _P        d!| _Q        | j8        j9        d8k    r| jR        jS        d9k    r| j        t          j        t          jT        fvrd| _Q        | jR        jS        d:vst          d;          rt          d<| jR        jS        d=          | j*        | j*        7                                ni }| j        t          j;        k    rd>d?lVmW}  |dIi || _P        nt          d@          rt          jY        dIi || _P        nt9                      r"t          j[        j\        jY        dIi || _P        n^t=                      r"t          j]        j\        jY        dIi || _P        n.t                      r"t          j_        j\        jY        dIi || _P        nt                      rt          j\        jY        dJi || _P        nt          jb        t          jc                  t          jb        dB          k    rt          j\        jY        dKi || _P        nt          jd        j\        jY        dIi || _P        n`| j8        j9        d1k    rt| j        t          j        t          jT        fvrU| jR        jS        dDv rd| _Q        nt          d          | _Q        |d1k    r$| jQ        st                      st          dE          n| j8        j9        d+k    rd| _Q        | jf        dFk    r| j        t          j;        k    rt+          dG          | j        t          j        k    rt          jb        t          jc                  t          jb        dB          k    r%t          j\        Y                    dC          | _P        n(t          jd        j\        Y                                | _P        d>| _g        g | _h        g | _i        g | _j        g | _k        g | _l        t                      | _n        t                      | _o        |
| _p        | jp        dHg| _p        d | _q        t                       d S )LN)r   zUnknown mixed_precision mode: z. Choose between )backendzCYou cannot pass in both `deepspeed_plugins` and `deepspeed_plugin`.ACCELERATE_USE_DEEPSPEEDfalsetruezYou cannot pass in a `deepspeed_plugin` when creating a second `Accelerator`. Please make sure the first `Accelerator` is initialized with all the plugins you want to use.z4`deepspeed_plugin` must be a DeepSpeedPlugin object.zRDeepSpeed is not installed => run `pip install deepspeed` or build it from source.zdeepspeed-mlu<z0.10.1zEDeepSpeed MLU version must be >= 0.10.1. Please update DeepSpeed MLU.	deepspeed>z0.14.3zEDeepSpeed MUSA version must be <= 0.14.3. Please downgrade DeepSpeed.z0.9.3z<DeepSpeed version must be >= 0.9.3. Please update DeepSpeed.ACCELERATE_MIXED_PRECISIONnoT)_from_accelerator_stateACCELERATE_USE_FSDP>=zFSDP requires PyTorch >= z>`fsdp_plugin` must be a FullyShardedDataParallelPlugin object.ACCELERATE_USE_MEGATRON_LMz7`megatron_lm_plugin` must be a MegatronLMPlugin object.z7Megatron is not installed. please build it from source.Fz#Unsupported kwargs handler passed: z=, must be one that inherits `accelerate.utils.KwargsHandler`.zJYou can only pass one `DistributedDataParallelKwargs` in `kwargs_handler`.z=You can only pass one `GradScalerKwargs` in `kwargs_handler`.zCYou can only pass one `InitProcessGroupKwargs` in `kwargs_handler`.z<You can only pass one `FP8RecipeKwargs` in `kwargs_handler`.z;You can only pass one `AutocastKwargs` in `kwargs_handler`.z:You can only pass one `ProfileKwargs` in `kwargs_handler`.)rw   r{   dynamo_pluginr~   r   r   _from_acceleratorfp8zOPassing in a `FP8RecipeKwargs` object requires setting `mixed_precision='fp8'`.TEr   z
`log_with=z?` was passed but no supported trackers are currently installed.bf16downcast_bfloatzMCan only use `downcast_bf16` when using `mixed_precision='bf16'` and on a TPUzYou can only pass one of `gradient_accumulation_steps` and `gradient_accumulation_plugin`. Please only pass in the created `GradientAccumulationPlugin` object.&ACCELERATE_GRADIENT_ACCUMULATION_STEPS)	num_steps)r   fp16r{   )xpucudanpuxlamlumusa)check_is_tpuz)fp16 mixed precision requires a GPU (not ).r   )ShardedGradScaler)check_is_gpur   z2.3r   )r{   r   zEbf16 mixed precision requires PyTorch >= 1.10 and a supported device.MSAMPzt`accelerate` + `MS-AMP` + `FSDP` is not supported at this time. Please consider using deepspeed, which is supported.	generator )r   )r   )strackersproject_configurationr6   r   set_directoriesstrr4   
ValueErrorlistr8   r   _shared_statedistributed_typer*   	DEEPSPEEDr   r   osenvirongetr(   NotImplementedError
isinstancedictvalues	TypeErrorrF   ImportErrorrJ   r<   rL   set_mixed_precisionselectnextiterdeepspeed_engine_wrappedr-   rN   r]   r3   rI   ddp_handlerscaler_handlerinit_handlerfp8_recipe_handlerautocast_handlerprofile_handlerhas_lomo_optimizerr1   r)   r/   r0   r,   r&   r5   	to_kwargsstaterw   delayed_fp8_autocastFSDPr   	MULTI_GPUr   logging_dirlenwarningswarnr   getattrdistributedTypeXLArz   rU   r.   r   gradient_statert   r'   r|   r   scaler
native_ampdevicetypeMEGATRON_LMrO   *torch.distributed.fsdp.sharded_grad_scalerr   xamp
GradScalertorchr   ampr   rM   r   rQ   r   parse__version__r   rD   fp8_backendstep_optimizers_models_schedulers_dataloaders_custom_objectsr   _load_model_state_pre_hook_save_model_state_pre_hookr   flag_tensorr:   )selfrt   rv   rw   ry   r{   r|   r~   r   r   r   r   r   r   r   r   r   r   r   r   pluginfirst_pluginhandlerkwargsr   r   s                             R/var/www/html/ai-engine/env/lib/python3.11/site-packages/accelerate/accelerator.py__init__zAccelerator.__init__   s   * %)7D&&)=+)V)V)VD&"t'7'?&66{CCC&!/22Om33 m_mmWdWiWkWkmm   0>/E)+++K\esKtKtKt(-=-Ibccc) 0$)R//LNN4SWfWp4p4p$4$6$6$H!! *,8RT[)\)\`f)f)fO%%%lp "! /?3LLL$2b88$&&8D)t   +T22 `/6688 ` `F%fo>> `'(^___` (5;BJ12)++ x!"vwww!! b#OS(CC o%&mnnno"$$ b#Kh?? o%&mnnno!+sG<< b!"`aaa GVF]
;TBBBcr  /66 B!55oFFF!(((FFFF/6688 @ @F..????#D):)A)A)C)C$D$DEE##D#AAA,0D):>>/99VCCz7H
 H
C $D*>?? U !S=Q!S!STTT46JNNCXZa4b4bfl4l4l.000rv K k+IJJ b `aaa06BJ,-%&(jnn5QSZ&[&[_e&e&e """ko  02BCC [ YZZZ7=BJ34 	]+-- ]!"[\\\  " "& $#"'&* !7 !7!]  @ @@ @ @ g'DEE 7'3()uvvv+2(()9:: 7*6()hiii.5++)?@@ 7(4()nooo,3))99 7.:()ghhh29//88 	7,8()fggg07--77 7+7()efff/6,262C2O",,...UW% 	
+'.#1"	
 	
 	
 	

 :%..43J3R&5&7&7D#$)!".z)U22%o.BOD]-^^^ !rsss(,(?(G4(O )TXTi)$n UD%
 #8T-=>>x==1!5Mpxpppqqq  &&
$5u== '+/BBBlmmm'3*a//  v   0
 +.%&NPkll+ +' ,FPk+l+l+l(+)E
 
 
 !1$ 7 9 9!2-J* J&&00 E))%o.GId-eee"DO{'SSSWm!X X XS !!cT[M]!c!c!cddd8<8K8WT(22444]_F$(<<<XXXXXX//99&99'T::: F"o7777!## F#im6@@@@"$$ 
F#jn7AA&AA!## F#im6@@@@!## F#i2CCFCC=!233gmE6J6JJJ"')"6"H"H"H"HDKK"'*.";"E"Ef"E"EDKKZ'611d6K%'T
 7
 7
 {>11"&"3D"9"9&(((I_IaIa( !hiiiZ'500"DO7**(O,@@@-O   *o.GGG}U%677'-:N:NNN&+i&:&:6&B&B&+jn&?&?&A&A 	 ! +6--'*5--' #>!)]DN      c                    | j         j        S )a:  
        Returns the currently active DeepSpeedPlugin.

        If using multiple plugins, the first one will be the active one by default. Manually call
        `accelerator.state.select_deepspeed_plugin(key)` to activate a different plugin.

        If deepspeed is not enabled, this will return `None`.
        )r   r~   r   s    r   r~   zAccelerator.deepspeed_plugin.  s     z**r   c                    | j         j        S )zP
        Whether the Accelerator is configured for distributed training
        )r   use_distributedr  s    r   r  zAccelerator.use_distributed:  s    
 z))r   c                    | j         j        S N)r   r   r  s    r   r   zAccelerator.distributed_typeA  s    z**r   c                    | j         j        S r  )r   num_processesr  s    r   r  zAccelerator.num_processesE      z''r   c                    | j         j        S r  )r   process_indexr  s    r   r  zAccelerator.process_indexI  r	  r   c                    | j         j        S r  )r   local_process_indexr  s    r   r  zAccelerator.local_process_indexM  s    z--r   c                    | j         j        S r  )r   r   r  s    r   r   zAccelerator.deviceQ  s    z  r   c                    | j         j        S r  )r|   rv   r  s    r   rv   zAccelerator.split_batchesU  s    %33r   c                    | j         j        S r  )r|   dispatch_batchesr  s    r   r  zAccelerator.dispatch_batchesY  s    %66r   c                    | j         j        S r  r|   even_batchesr  s    r   r  zAccelerator.even_batches]      %22r   valuec                    || j         _        d S r  r  )r   r  s     r   r  zAccelerator.even_batchesa  s    .3+++r   c                    | j         j        S r  )r|   use_seedable_samplerr  s    r   r  z Accelerator.use_seedable_samplere  s    %::r   c                    | j         j        S r  )r|   non_blockingr  s    r   r  zAccelerator.non_blockingi  r  r   c                H    t          | j        d          r| j        j        S dS )Nuse_stateful_dataloaderF)hasattrr|   r  r  s    r   r  z#Accelerator.use_stateful_dataloaderm  s*    4)+DEE 	B)AAur   c                    | j         j        S r  )r   r   r  s    r   r   zAccelerator.project_dirs      )55r   c                    | j         j        S r  )r   r   r  s    r   r   zAccelerator.logging_dirw  r   r   c                    | j         j        S r  )r   	iterationr  s    r   save_iterationzAccelerator.save_iteration{  s    )33r   c                    | j         j        S )zTrue for one process only.)r   is_main_processr  s    r   r&  zAccelerator.is_main_process  s     z))r   c                    | j         j        S )z True for one process per server.)r   is_local_main_processr  s    r   r(  z!Accelerator.is_local_main_process  s     z//r   c                (    | j         | j        dz
  k    S )Nr   )r  r  r  s    r   is_last_processzAccelerator.is_last_process  s    !T%7!%;;;r   c                    | j         j        S r  )r   rw   r  s    r   rw   zAccelerator.mixed_precision  s    z))r   inputs"list | tuple | dict | torch.Tensorapply_paddingc              #     K   t                                          ||          5 }|V  ddd           dS # 1 swxY w Y   dS )a  
        Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing
        distributed inference, such as with different prompts.

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

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

        Example:

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

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

        with accelerator.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs:
            print(inputs)
        # Process 0
        ["A", "B"]
        # Process 1
        ["C", "C"]
        ```
        )r.  N)r   split_between_processes)r   r,  r.  s      r   r0  z#Accelerator.split_between_processes  s      N ^^33F-3XX 	\bLLL	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   8<<functionCallable[..., Any]c                L    d| j         v r| nt          d          fd}|S )aL  
        A decorator that will run the decorated function on the main process only. Can also be called using the
        `PartialState` class.

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

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()


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


        >>> print_something()
        "This will be printed by process 0 only"
        ```
        NAccelerator.gThe `on_main_process` decorator must be called with a function on an instantiated `Accelerator` object.c                 R     t                                                    | i |S r  )r   on_main_processargsr   r1  s     r   _innerz+Accelerator.on_main_process.<locals>._inner  *    ;<>>11(;;TLVLLLr   __qualname__r   r   r1  r:  s    ` r   r7  zAccelerator.on_main_process  Z    4 !222 }  	M 	M 	M 	M 	M r   c                L    d| j         v r| nt          d          fd}|S )a  
        A decorator that will run the decorated function on the local main process only. Can also be called using the
        `PartialState` class.

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

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

        accelerator = Accelerator()


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


        print_something()
        # On server 1:
        "This will be printed by process 0 only"
        # On server 2:
        "This will be printed by process 0 only"
        ```
        Nr4  zmThe `on_local_main_process` decorator must be called with a function on an instantiated `Accelerator` object.c                 R     t                                                    | i |S r  )r   on_local_main_processr8  s     r   r:  z1Accelerator.on_local_main_process.<locals>._inner  s*    A<>>77AA4R6RRRr   r<  r>  s    ` r   rB  z!Accelerator.on_local_main_process  s]    : !222  D  	S 	S 	S 	S 	S r   c                L    d| j         v r| nt          d          fd}|S )aO  
        A decorator that will run the decorated function on the last process only. Can also be called using the
        `PartialState` class.

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

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

        accelerator = Accelerator()


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


        print_something()
        "Printed on process 3"
        ```
        Nr4  zgThe `on_last_process` decorator must be called with a function on an instantiated `Accelerator` object.c                 R     t                                                    | i |S r  )r   on_last_processr8  s     r   r:  z+Accelerator.on_last_process.<locals>._inner.  r;  r   r<  r>  s    ` r   rE  zAccelerator.on_last_process  r?  r   r  c                    | t          | j                  S d| j        v r| nt          d          fd}|S )a  
        A decorator that will run the decorated function on a given process index only. Can also be called using the
        `PartialState` class.

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

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

        accelerator = Accelerator()


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


        print_something()
        "Printed on process 2"
        ```
        N)r  r4  r5  c                 T     t                                                    | i |S r  )r   
on_process)r9  r   r1  r  s     r   r:  z&Accelerator.on_process.<locals>._inner[  s,    E<>>,,X}EEtVvVVVr   )r   rH  r=  r   )r   r1  r  r:  s    `` r   rH  zAccelerator.on_process3  s    : =#<8CS4?-HHHH!222 }  	W 	W 	W 	W 	W 	W r   r  c                    | t          | j                  S d| j        v r| nt          d          fd}|S )aw  
        A decorator that will run the decorated function on a given local process index only. Can also be called using
        the `PartialState` class.

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

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

        accelerator = Accelerator()


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


        print_something()
        # On server 1:
        "Printed on process 2"
        # On server 2:
        "Printed on process 2"
        ```
        N)r  r4  r5  c                 T     t                                                    | i |S r  )r   on_local_process)r9  r   r1  r  s     r   r:  z,Accelerator.on_local_process.<locals>._inner  s/    Q<>>228=PQQSWb[abbbr   )r   rK  r=  r   )r   r1  r  r:  s    `` r   rK  zAccelerator.on_local_process`  s    @ #6#BIY40FYZZZZ!222 }  	c 	c 	c 	c 	c 	c r   c              #  v   K   | j                                         5  dV  ddd           dS # 1 swxY w Y   dS )a1  
        Lets the main process go first inside a with block.

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

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> with accelerator.main_process_first():
        ...     # This will be printed first by process 0 then in a seemingly
        ...     # random order by the other processes.
        ...     print(f"This will be printed by process {accelerator.process_index}")
        ```
        N)r   main_process_firstr  s    r   rM  zAccelerator.main_process_first  s      & Z**,, 	 	EEE	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	   .22c              #  v   K   | j                                         5  dV  ddd           dS # 1 swxY w Y   dS )aC  
        Lets the local main process go inside a with block.

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

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> with accelerator.local_main_process_first():
        ...     # This will be printed first by local process 0 then in a seemingly
        ...     # random order by the other processes.
        ...     print(f"This will be printed by process {accelerator.local_process_index}")
        ```
        N)r   local_main_process_firstr  s    r   rP  z$Accelerator.local_main_process_first  s      & Z0022 	 	EEE	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	rN  c              #     K   t           j        }| j        rt          |d|          } |            5  dV  ddd           dS # 1 swxY w Y   dS )ab  
        A context manager to disable gradient synchronizations across DDP processes by calling
        `torch.nn.parallel.DistributedDataParallel.no_sync`.

        If `model` is not in DDP, this context manager does nothing

        Args:
            model (`torch.nn.Module`):
                PyTorch Module that was prepared with `Accelerator.prepare`

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> dataloader, model, optimizer = accelerator.prepare(dataloader, model, optimizer)
        >>> input_a = next(iter(dataloader))
        >>> input_b = next(iter(dataloader))

        >>> with accelerator.no_sync():
        ...     outputs = model(input_a)
        ...     loss = loss_func(outputs)
        ...     accelerator.backward(loss)
        ...     # No synchronization across processes, only accumulate gradients
        >>> outputs = model(input_b)
        >>> accelerator.backward(loss)
        >>> # Synchronization across all processes
        >>> optimizer.step()
        >>> optimizer.zero_grad()
        ```
        no_syncN)
contextlibnullcontextr  r   )r   modelcontexts      r   rR  zAccelerator.no_sync  s      D ( 	9eY88GWYY 	 	EEE	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   AA
Ac              #    K   t          | t          j        j        j                  sdV  dS | j        }| j        }d| _        d| _        | j                            g            	 dV  || _        || _        dS # || _        || _        w xY w)a  Trigger the sync of the gradients in the next backward pass of the model after multiple forward passes under
        `Accelerator.no_sync` (only applicable in multi-GPU scenarios).

                If the script is not launched in distributed mode, this context manager does nothing.

                Args:
                    model (`torch.nn.Module`):
                        The model for which to trigger the gradient synchronization.

                Example:

                ```python
                >>> from accelerate import Accelerator

                >>> accelerator = Accelerator()
                >>> dataloader, model, optimizer = accelerator.prepare(dataloader, model, optimizer)

                >>> with accelerator.no_sync():
                ...     loss_a = loss_func(model(input_a))  # first forward pass
                ...     loss_b = loss_func(model(input_b))  # second forward pass
                >>> accelerator.backward(loss_a)  # No synchronization across processes, only accumulate gradients
                >>> with accelerator.trigger_sync_in_backward(model):
                ...     accelerator.backward(loss_b)  # Synchronization across all processes
                >>> optimizer.step()
                >>> optimizer.zero_grad()
                ```
        NT)	r   r   nnparallelDistributedDataParallelrequire_backward_grad_syncrequire_forward_param_syncreducerprepare_for_backward)rU  old_require_backward_grad_syncold_require_forward_param_syncs      r   trigger_sync_in_backwardz$Accelerator.trigger_sync_in_backward  s      < %!2!JKK 	EEEF).)I&).)I& ,0(+/(**2...	NEEE/ME,/ME,,, 0NE,/ME,MMMMs   $A8 8Bc                    | j         j        r/| j         j        r#d| _        | j                             d           dS | xj        dz  c_        | j                             | j        | j         j        z  dk               dS )zRSets the right `sync_gradients` context and either resets or increases `self.step`r   Tr   N)r   sync_with_dataloaderend_of_dataloaderr   _set_sync_gradientsr   r  s    r   _do_synczAccelerator._do_sync  s    3 	f8K8] 	fDI33D99999IINII33TYATA^5^cd4deeeeer   c                    | j         j        S r  r   sync_gradientsr  s    r   ri  zAccelerator.sync_gradients  s    "11r   c                    || j         _        d S r  rh  )r   ri  s     r   ri  zAccelerator.sync_gradients#  s    -;***r   c                    | j         j        S r  )r   r   r  s    r   ry   z'Accelerator.gradient_accumulation_steps'  s    ",,r   c                H    | j         j                            d|i           d S )Nr   )r   plugin_kwargsupdate)r   ry   s     r   ry   z'Accelerator.gradient_accumulation_steps+  s(    )00+?Z1[\\\\\r   c              '  r  K   |                                   | j        p&| j        o| j        j                            dd          }t          j                    5 }|D ]?}|                    |rt          j	                    n| 
                    |                     @dV  ddd           dS # 1 swxY w Y   dS )a  
        A context manager that will lightly wrap around and perform gradient accumulation automatically

        Args:
            *models (list of `torch.nn.Module`):
                PyTorch Modules that were prepared with `Accelerator.prepare`. Models passed to `accumulate()` will
                skip gradient syncing during backward pass in distributed training

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator(gradient_accumulation_steps=1)
        >>> dataloader, model, optimizer, scheduler = accelerator.prepare(dataloader, model, optimizer, scheduler)

        >>> for input, output in dataloader:
        ...     with accelerator.accumulate(model):
        ...         outputs = model(input)
        ...         loss = loss_func(outputs)
        ...         loss.backward()
        ...         optimizer.step()
        ...         scheduler.step()
        ...         optimizer.zero_grad()
        ```
        sync_each_batchFN)rf  ri  r  r   rm  r   rS  	ExitStackenter_contextrT  rR  )r   modelsallow_gradient_synccm_stackms        r   
accumulatezAccelerator.accumulate/  s     8 	  
 $ T'599:KUSS 	 !## 	x m m&&CV'kz'='?'?'?\`\h\hij\k\kllllEEE	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   AB,,B03B0c              #  8  K   | j         t          j        t          j        t          j        t          j        t          j        fv rg }|xd}t          | j                  D ]J\  }}t          |t                    rd}|                    ||j        j        f           ||j        _        K|rt          j        d           n| j        }|rdnd}	 t!          ||d          5  dV  ddd           n# 1 swxY w Y   |D ]\  }}|| j        |         j        _        dS # |D ]\  }}|| j        |         j        _        w xY w| j         t          j        k    rt          j        d           t%          j        |          5  dV  ddd           dS # 1 swxY w Y   dS )a  
        A context manager that facilitates distributed training or evaluation on uneven inputs, which acts as a wrapper
        around `torch.distributed.algorithms.join`. This is useful when the total batch size does not evenly divide the
        length of the dataset.

        Args:
            joinables (`list[torch.distributed.algorithms.Joinable]`):
                A list of models or optimizers that subclass `torch.distributed.algorithms.Joinable`. Most commonly, a
                PyTorch Module that was prepared with `Accelerator.prepare` for DistributedDataParallel training.
            even_batches (`bool`, *optional*)
                If set, this will override the value of `even_batches` set in the `Accelerator`. If it is not provided,
                the default `Accelerator` value wil be used.

        <Tip warning={true}>

        `join_uneven_inputs` is only supported for Distributed Data Parallel training on multiple GPUs. For any other
        configuration, this method will have no effect.

        </Tip>

        <Tip warning={true}>

        Overidding `even_batches` will not affect iterable-style data loaders.

        </Tip>

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator(even_batches=True)
        >>> ddp_model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader)

        >>> with accelerator.join_uneven_inputs([ddp_model], even_batches=False):
        ...     for input, output in dataloader:
        ...         outputs = model(input)
        ...         loss = loss_func(outputs)
        ...         loss.backward()
        ...         optimizer.step()
        ...         optimizer.zero_grad()
        ```
        NFTzkOverridding even_batches is only supported for map-style datasets, yet some dataloaders given were iterable)enablethrow_on_early_terminationzuJoining uneven inputs is only supported for multi-GPU training, as a result `join_uneven_inputs` will have no effect.)r   r*   r   	MULTI_NPU	MULTI_MLU
MULTI_MUSA	MULTI_XPU	enumerater   r   r   appendbatch_samplerr  r   r   rn   NOrS  rT  )	r   	joinablesr  dl_even_batches_valuesiterable_dl_seendl_idxdlenable_joineven_batches_values	            r   join_uneven_inputszAccelerator.join_uneven_inputs\  s     Z  %%%&%%
 
 
 &("'#( "+D,=">"> A AJFB!"&:;; !+/( *1162;K;X2YZZZ4@B$11# M F    $0#/9%%TK^)KTYZZZ  EEE               3I ^ ^.F.K]D%f-;HH^ ^2H ^ ^.F.K]D%f-;HH^ $(::: L   '	22                   sB   D C0$D 0C44D 7C48D !D==FFFc                *     | j         j        |i | dS )a  
        Drop in replacement of `print()` to only print once per server.

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> accelerator.print("Hello world!")
        ```
        N)r   print)r   r9  r   s      r   r  zAccelerator.print  s$     	
$)&)))))r   c                   |rt          |t          j        j        j                  r|                     ||          S t          |t          j        j                  r|                     ||          S t          |t          j	        j
                  r|                     ||          }|S n,t          |t                    r|                     |          }|S |S )Nrt   )r   r   utilsdata
DataLoaderr   rX  Moduleprepare_modeloptim	Optimizerprepare_optimizerrp   prepare_scheduler)r   obj
first_passrt   	optimizer	schedulers         r   _prepare_onezAccelerator._prepare_one  s     	#u{/:;; !//FV/WWWC11 !))#@P)QQQC!677 ! 223IY2ZZ	  ! [)) 	..s33I
r   r  c                   |d |D             }nn j         t          j        t          j        fv rt	          d          t          |          t          |          k    r t	          dt          |           d          |D ]~}t          |t          j        j	                  r] 
                    |          rH j         t          j        k    r3t          j                            dd          dk    rt	          d	           j         t          j        k    r@d
}|D ]&}t          |t          j        j	                  r|dz  }'|dk    rt          d           j         t          j        k    r0                                 \  }}||||k    rt	          d           j        o j         t          j        k    }|r
  j        | } j         t          j        t          j        t          j        fv rO j        j        dk    r j        j        r  j        | }n( j        j        dk    rt7                      r
  j        | } j        dk    r
  j        | } j         t          j        k    r  j        | }	n j         t          j        k    r  j        | }	nm j        dk    r  j         |d|i\  }}tC           fdtE          ||          D                       }	tC           fdtE          |	|          D                       }	|rc  j        |	 fd|#                                D             }
|	D ]6}t          |t          j$        j%                  r|&                    |
           7|	D ]<tO          fd j(         j)         j*         j+        fD                       rd_,        =t          |	          dk    r|	n|	d
         S )a  
        Prepare all objects passed in `args` for distributed training and mixed precision, then return them in the same
        order.

        Args:
            *args (list of objects):
                Any of the following type of objects:

                - `torch.utils.data.DataLoader`: PyTorch Dataloader
                - `torch.nn.Module`: PyTorch Module
                - `torch.optim.Optimizer`: PyTorch Optimizer
                - `torch.optim.lr_scheduler.LRScheduler`: PyTorch LR Scheduler

            device_placement (`list[bool]`, *optional*):
                Used to customize whether automatic device placement should be performed for each object passed. Needs
                to be a list of the same length as `args`. Not compatible with DeepSpeed or FSDP.

        <Tip>

          You don't need to prepare a model if you only use it for inference without any kind of mixed precision

        </Tip>

        Examples:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> # Assume a model, optimizer, data_loader and scheduler are defined
        >>> model, optimizer, data_loader, scheduler = accelerator.prepare(model, optimizer, data_loader, scheduler)
        ```

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> # Assume a model, optimizer, data_loader and scheduler are defined
        >>> device_placement = [True, True, False, False]
        >>> # Will place the first to items passed in automatically to the right device but not the last two.
        >>> model, optimizer, data_loader, scheduler = accelerator.prepare(
        ...     model, optimizer, data_loader, scheduler, device_placement=device_placement
        ... )
        ```
        Nc                    g | ]}d S r  r   ).0_s     r   
<listcomp>z'Accelerator.prepare.<locals>.<listcomp>  s    333333r   zDYou can't customize device placements with DeepSpeed or Megatron-LM.z)`device_placement` should be a list with z) elements (the number of objects passed).ACCELERATE_BYPASS_DEVICE_MAPr   r   You can't train a model that has been loaded with `device_map='auto'` in any distributed mode. Please rerun your script specifying `--num_processes=1` or by launching with `python {{myscript.py}}`.r   r   zUYou can't use same `Accelerator()` instance with multiple models when using DeepSpeeda~  The model and the optimizer parameters are not on the same device, which probably means you created an optimizer around your model **before** putting on the device. Make sure the line model.to(device) is before the optimizer creation in your script or remove it entirely and use the flag default value for `device_placement` in your `Accelerator` to let it handle that part for you.r{   r   r   r   rt   c              3  N   K   | ]\  }}                     |d |          V   dS )T)r  rt   Nr  r  r  dr   s      r   	<genexpr>z&Accelerator.prepare.<locals>.<genexpr>F  sO        PVPSUV!!#$!KK     r   c              3  L   K   | ]\  }}                     ||           V  dS )r  Nr  r  s      r   r  z&Accelerator.prepare.<locals>.<genexpr>I  s:      rr&#q4,,S1,EErrrrrrr   c                (    i | ]\  }}||         S r   r   r  npnew_named_paramss      r   
<dictcomp>z'Accelerator.prepare.<locals>.<dictcomp>N  s%    SSS$!Qq*1-SSSr   c              3      K   | ]}|v V  	d S r  r   )r  	containeritems     r   r  z&Accelerator.prepare.<locals>.<genexpr>U  s<         	!     r   T)-r   r*   r   r   r   r   r   r   rX  r  verify_device_mapr  r   r   r   AssertionErrorr   _get_devicesrt   _get_named_parameters	MULTI_CPUr~  r   r   r   use_ipex_prepare_ipex_or_xpurQ   r   _prepare_te_prepare_deepspeed_prepare_megatron_lm_prepare_msamptuplezipitemsr  r  _switch_parametersanyr   r   r   r   _is_accelerate_prepared)r   rt   r9  r  model_countmodel_deviceoptimizer_devicetpu_should_fix_optimizerold_named_paramsresultmappingr  r  s   `          @@r   preparezAccelerator.prepare  sw   \ #33d333"'@/B]&^^^cddd!""c$ii//pCIIppp    	 	C 300	**3//	 )_-???JNN#A7KKvUU ~  
  O$===K % %c58?33 %1$KQ$k    O$777-1->->-@-@*L*',<,H\]mMmMm $   $(#8#iT=RVeVi=i # 	A9t94@ _%>@Y[j[m$nnn{5((TZ-@(0t0$7!U**/?/A/A*0t0$7t###4#T*D O$===,T,d3FF"o&AAA.T.5FF7**)<)<d)fUe)f)f&&    Z]^bdtZuZu    F rrrrTWX^`pTqTqrrrrrF# 	49t96BSSSS:J:P:P:R:RSSSG 4 4c5;#899 4**7333 	4 	4D    "&"3T\4CSUYUe!f     4 04,VqvvfQi7r   rU  torch.nn.Moduleevaluation_modec                   || j         o| j        t          j        k    }| j                            |           |                     |          rH| j        t          j        k    r3t          j	        
                    dd          dk    rt          d          | j        r|j        |_        t          | j        | j                  }| j        dk    st%          |j        d          s%|j        }t'           ||                    |_        nX|j        j        } ||          }t+          ||          |_        t+          t'          |j        j                  |          |_        | j        dk    r| j        st/          || j                  }t3          |d	d
          st3          |dd
          rt3          |dd
          rt5          |j                                                  }t;          |          dk    r$| j        t          j        k    rt          d          t;          |          dk    rvt=          |          d         }t?          |t@          j!                  r|j"        n|}	tA          j!        |	          | j!        k    r!| j!        j"        |	dk    rt          d          d|v rtG                      rd|v rt          d          n1|r/|                     |          s|$                    | j!                  }|sd| j        t          j%        t          j&        t          j'        t          j(        t          j)        fv rtU          d |+                                D                       r| j,        | j,        -                                ni }
t          j	        
                    dd          dk    r| j.        g| j.        }}nd\  }}tA          j/        j0        j1        |f||d|
}| j,        | j,        2                    |           n\| j        t          j        k    rddl3m4} t?          ||          p#tk          |          ot?          |j6        |          }|s| j7        j8        9                    |           | j7        j8        }|j:        |j;        |j<        |j=        |j>        |j?        |j@        |jA        |jB        |jC        |jD        | j!        d}
 ||fi |
}|jE        r6ddlFmG}mH}mI}  ||t          jK        ||jL                  |j<                   | jM        dk    r;g }|N                    |          D ]}|jO        s
|jP        }|jQ        t@          jR        k    r|j!        tA          j!        d          k    r|jS        r|jT        jU        jV        dW                    |jP        jX                  f}||vr|                    |           |jY        $                    t@          jR                  |_Y        t@          jR        |jZ        _[        | j\        rJ|D ] \  }}t          j^        d| d | d!           !t;          |          dk    rt          j^        d"           t;          | j                  dk    r"| j        d#         | j        d$         u r| j        d#= || j        d$<   n| j        t          j_        k    r`| j,        | j,        -                                ni }
tA          j/        j0        j1        |fi |
}| j,        | j,        2                    |           nM| j        t          j`        k    r8| j7        ja        r,t          jc        |          $                    | j!                  }| j        rt/          || j                  }| j7        jd        je        t          j        k    r\tk          |          sMt          d%d&          st          d'          tA          jh        |fi | j7        jd        -                                }|S )(a  
        Prepares a PyTorch model for training in any distributed setup. It is recommended to use
        [`Accelerator.prepare`] instead.

        Args:
            model (`torch.nn.Module`):
                A PyTorch model to prepare. You don't need to prepare a model if it is used only for inference without
                any kind of mixed precision
            device_placement (`bool`, *optional*):
                Whether or not to place the model on the proper device. Will default to `self.device_placement`.
            evaluation_mode (`bool`, *optional*, defaults to `False`):
                Whether or not to set the model for evaluation only, by just applying mixed precision and
                `torch.compile` (if configured in the `Accelerator` object).

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> # Assume a model is defined
        >>> model = accelerator.prepare_model(model)
        ```
        Nr  r   r   r  r   __func__r   is_loaded_in_8bitFis_loaded_in_4bithf_device_mapr   a_  You can't train a model that has been loaded in 8-bit or 4-bit precision on multiple devices in any distributed mode. In order to use 8-bit or 4-bit models that have been loaded across multiple GPUs the solution is to use Naive Pipeline Parallelism. Therefore you should not specify that you are under any distributed regime in your accelerate config.r   a$  You can't train a model that has been loaded in 8-bit or 4-bit precision on a different device than the one you're training on. Make sure you loaded the model on the correct device using for example `device_map={'':torch.cuda.current_device()}` or `device_map={'':torch.xpu.current_device()}`r{   diska  You can't train a model that has been loaded in 8-bit or 4-bit precision with CPU or disk offload. If you want train the 8-bit or 4-bit model in CPU, please install bitsandbytes with multi-backend, see https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backendc              3  $   K   | ]}|j         V  d S r  )requires_gradr  r  s     r   r  z,Accelerator.prepare_model.<locals>.<genexpr>  s$      CC1qCCCCCCr   NN)
device_idsoutput_deviceFullyShardedDataParallel)sharding_strategycpu_offloadauto_wrap_policyrw   sync_module_statesbackward_prefetchforward_prefetchuse_orig_paramsparam_init_fnignored_moduleslimit_all_gathers	device_id)CheckpointImplapply_activation_checkpointingcheckpoint_wrapper)checkpoint_impl)checkpoint_wrapper_fnr  r   metaz, z%Upcasted low precision parameters in z5 because mixed precision turned on in FSDP. Affects: .zVFSDP upcast of low precision parameters may affect the precision of model checkpoints.r   z2.0z5Using `torch.compile` requires PyTorch 2.0 or higher.)irt   r   r*   r   r   r  r  r  r   r   r   r   r   forward_original_forwardrB   r   r   r  r>   r  r   r   r9   r   r   setr  r   r   r   r   r   r   indexrE   tor   r|  r}  r{  r~  r  
parametersr   r   r  rX  rY  rZ  register_comm_hook2torch.distributed.fsdp.fully_sharded_data_parallelr  r`   	_orig_modr   r   set_auto_wrap_policyr  r  r  mixed_precision_policyr  r  r  r  r  r  r  activation_checkpointing;torch.distributed.algorithms._checkpoint.checkpoint_wrapperr  r  r  	functoolsr   NO_REENTRANTrw   fsdp_modules_has_params_flat_paramdtypefloat32r  module	__class____name__join_fqnsr  _handle_orig_param_dtyper&  r   r   r  r   fork_launchedxmpMpModelWrapperr   r   r+   rN   compile)r   rU  rt   r  autocast_contextmodel_forward_funcnew_forwardmodel_devicescurrent_devicecurrent_device_indexr   r  r  r   is_type_fsdpr   r  r  r  upcasted_logr  paramname_param_logname_log	param_logs                            r   r  zAccelerator.prepare_model]  s   2 ##4f9NRaRf9fE""" ""5))	%);;;
=wGG6QQz  
 ? 	c&+mE#B4?TXTijj7**'%-2T2T*%*]" 78H8HI[8\8\ ] ]%*]%;"../ABB *; > > *+B5=CY+Z+Z\a b b t##D,E#&ud.EFFEE.66 	*'%I\^c:d:d 	*jq?Ek
 k
 	*   3 : : < <==M=!!A%%$*??CU*U*U }  
 ]##q((!%m!4!4Q!7,6~u|,T,ThN((Zh % < 455DD)5;OST;T;T(W  
 &&/V/X/X&]cgt]t]t I   ^u
  	*d&<&<U&C&C 	*HHT[))E O	B$))*)))   CC0@0@0B0BCCCCC C=A=M=YT-77999_aFz~~&DgNNRXXX595M4NPTPhM

4>1
M!H-E*4M U[ E '3(;;EBBB&/*>>>oooooo  *%66  &u--S*U_d2S2S  $  J*??FFF"&*"8K-8-J'2'>,7,H+6+M.9.L-8-J,7,H+6+F)4)B+6+F-8-J%)[ F !D11&11E";           76!2;2C 20>0K3 3 3 .9-I   & '4//#%L"&"3"3E":": &M &M(  &1 %$ & 2!K5=88 %V0D0D D D % 3 !E
 /5m.E.NPTPYPYZ`ZlZrPsPs-tN-\AA , 3 3N C C C
 */u})E)EEJ?D}FN< + 
3?  /Hi$M!9 !9 !9,5!9 !9 !9   
 |,,q00$M x  
 t|$$q((dl2.>$,rBR.R.RR(#(R  &/*CCC9=9I9U)33555[])A%RR6RR#/$77>>>&/*===$*BZ=*51144T[AA$ 	G&ud.EFFE:#+}/???HZ[`HaHa?#D%00 Z !XYYYM%PP4:+C+M+M+O+OPPEr   c                  
 t                      st          d          d\  }}d\  }}d |D             }|D ]O}t          |t          j        j                  r|}|dz  })t          |t          j        j                  r|}|dz  }P|||S ||t          d          |dk    s|dk    rt          d| d| d	          | 	                    |          }t          j
                    5  t          |           d d d            n# 1 swxY w Y   | 	                    |          fd
|                                D             
|j        D ]}	
fd|	d         D             |	d<   |S )Nzg`transformer_engine` was not found on your system. Please ensure that `transformer_engine` is installedr  r   r   c                    g | ]}|S r   r   r  r  s     r   r  z+Accelerator._prepare_te.<locals>.<listcomp>V      &&&##&&&r   r   zgYou must pass a model and an optimizer together to `accelerate.prepare()` when using TransformerEngine.You can't use multiple models () or optimizers z with TransformerEngine.c                (    i | ]\  }}||         S r   r   r  s      r   r  z+Accelerator._prepare_te.<locals>.<dictcomp>l  s%    OOOda1&q)OOOr   c                     g | ]
}|         S r   r   )r  r  r  s     r   r  z+Accelerator._prepare_te.<locals>.<listcomp>o  s    $O$O$OAWQZ$O$O$Or   params)rP   r   r   r   rX  r  r  r  r   r  no_gradr=   r  param_groups)r   r9  rU  r  
num_modelsnum_optimizersr  r  r  param_groupr  r  s             @@r   r  zAccelerator._prepare_teO  s   .00 	y   &y%)"
N&&&&& 	$ 	$C#ux// $a

C%+"799 $	!#M%-y   !^^~11v*vvnvvv    55e<<]__ 	! 	!%   	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	!55e<<OOOO6F6L6L6N6NOOO$1 	P 	PK$O$O$O$OX9N$O$O$OK!!s   +DDDc                    dd l }|j        } j        dk    rddlm } |j        } j        t          d |D                       } fd|D             }                    d          r|rd |D             }t          d |D                       rt          d	           j        r fd
|D             }j	        rt          |          nt          |          }t          |          dk    r&t                              dj	         d| d           n$t          d                              d          }                    dd j                   ddd}	|(||	d<   |                    d          z   j        z  |	d<   d }
d }d }|D ]}t'          |t(          j        j                  r|}
$t'          |t(          j        j        t2          f          r|}Mt'          |t4          t6          f          s%t9          |          j        |j        j        j         v r|}|dj!        v r$t'          |t2                    st          d          dj!        vr$t'          |t2                    rt          d          t'          |t(          j        j                  r
dj!        d<   |adj!        v r$t'          |t6                    st          d          dj!        vr+t'          |t6                    r|j"        t          d          |;|9t'          |t2                    r$t'          |t6                    st          d          |
tG           j$        dd           d k    rtK          |
 j$                  }
&                    |
           g d!}fd"|D             }t          |          dk    rd#d$| d%z   d&z   }tO          |
d'          st          d(|z             tO          |
j(        d)          r|
j(        j)        }nAtO          |
j(        d*          rt          |
j(        j*                  }nt          d+|z             |	+                    ||z  tY          d,|z  |z            d-|z  d!           t'          |t2                    r"|	+                    |j-        |j.        d.           t'          |t6                    r|j"        tG          |j/        d/d           tG          |j/        d0d           n|j/        j0        d0         }|	+                    d||j1        d1           |j2        2 j        s!tg          j4        |j2         j        z            n|j2        |	d2<    j5        d@d3di|	 j!         _!        tm          |
 j!        4          }|t'          |t2                    r1|j7        |d5<   t'          |t6                    r|j"        
|j"        |d6<   n j!        d7         8                    d8i           8                    d9d:          d:k    rR j!        8                    d;d          r7dd<l9m:} d= |j0        ;                                D             } ||j<        fi |}||d<   |*t9          |          j        |j        j        j         v r||d6<    |d@i |\  }}}}|t{          |          }|0|t}          || j?         j        >          }nt          ||          }t          t          |                    D ]}t'          ||         t(          j        j                  r|||<   -t'          ||         t(          j        j        t2          f          r|||<   _t'          ||         t4          t6          f          s+t9          ||                   j        |j        j        j         v r|||<    jB        t          |           _B        nt          D                    d?            jE        F                    |           | jG        F                    |           | jH        F                    |           t          |          S )ANr   r   )r   c              3  ^   K   | ](}t          |t          j        j        j                  V  )d S r  )r   r   r  r  r  r  s     r   r  z1Accelerator._prepare_deepspeed.<locals>.<genexpr>  s5      #a#aUXJsEK4D4O$P$P#a#a#a#a#a#ar   c                    g | ]?}t          |t          j        j        j                  r                    |d           n|@S )T)r  )r   r   r  r  r  r  )r  r  r   s     r   r  z2Accelerator._prepare_deepspeed.<locals>.<listcomp>  sZ     
 
 
 8B#u{GWGb7c7clDcd333il
 
 
r   train_micro_batch_size_per_gpuc                <    g | ]}t          |d           |j        S 
batch_sizer  r0  r  s     r   r  z2Accelerator._prepare_deepspeed.<locals>.<listcomp>  s)    \\\#lA[A[\s~\\\r   c              3     K   | ]}|d u V  	d S r  r   )r  bss     r   r  z1Accelerator._prepare_deepspeed.<locals>.<genexpr>  s&      88brTz888888r   a,  At least one of the dataloaders passed to `accelerate.prepare()` has `None` as batch size. Please set an integer value in `train_micro_batch_size_per_gpu` in the deepspeed config file or assign integer value to `AcceleratorState().deepspeed_plugin.deepspeed_config['train_micro_batch_size_per_gpu']`.c                $    g | ]}|j         z  S r   )r  )r  r0  r   s     r   r  z2Accelerator._prepare_deepspeed.<locals>.<listcomp>  s!    "b"b"b
:1C#C"b"b"br   r   RSince you passed both train and evaluation dataloader, `is_train_batch_min` (here % will decide the `train_batch_size` (r   a  When using DeepSpeed, `accelerate.prepare()` requires you to pass at least one of training or evaluation dataloaders with `batch_size` attribute returning an integer value or alternatively set an integer value in `train_micro_batch_size_per_gpu` in the deepspeed config file or assign integer value to `AcceleratorState().deepspeed_plugin.deepspeed_config['train_micro_batch_size_per_gpu']`.ry   F)
must_matchry         ?)gradient_clippingz;zero_optimization.stage3_gather_16bit_weights_on_model_savetrain_batch_sizer  zYou cannot specify an optimizer in the config file and in the code at the same time. Please remove the optimizer from the config file or create `accelerate.utils.DummyOptim` in the code.zTYou cannot create a `DummyOptim` without specifying an optimizer in the config file.Tzero_allow_untested_optimizerr  zYou cannot specify a scheduler in the config file and in the code at the same time. Please remove the scheduler from the config file or create `accelerate.utils.DummyScheduler` in the code.zEither specify a scheduler in the config file or pass in the `lr_scheduler_callable` parameter when using `accelerate.utils.DummyScheduler`.zlYou can only specify `accelerate.utils.DummyScheduler` in the code when using `accelerate.utils.DummyOptim`.r   r   )z$zero_optimization.reduce_bucket_sizez-zero_optimization.stage3_prefetch_bucket_sizez4zero_optimization.stage3_param_persistence_thresholdc                >    g | ]}                     |          |S r   )is_auto)r  xr~   s     r   r  z2Accelerator._prepare_deepspeed.<locals>.<listcomp>  s.    $f$f$f1JZJbJbcdJeJe$fQ$f$f$fr   zStherefore it's not possible to automatically fill out the following `auto` entries zin the DeepSpeed config file: z . You can fix that by replacing zB`auto` values for these keys with an integer value of your choice.configz!Can't find `model.config` entry, hidden_sizehidden_sizeszMCan find neither `model.config.hidden_size` nor `model.config.hidden_sizes`, g?
   )zoptimizer.params.lrzoptimizer.params.weight_decaydefaultslr)zscheduler.params.warmup_min_lrzscheduler.params.warmup_max_lrz!scheduler.params.warmup_num_stepsz scheduler.params.total_num_stepsr7  )rU  config_paramsmodel_parameterslr_schedulerzero_optimizationoffload_optimizerr   nonezero_force_ds_cpu_optimizer)DeepSpeedCPUAdamc                "    i | ]\  }}|d v 	||S ))rD  weight_decayr   )r  kvs      r   r  z2Accelerator._prepare_deepspeed.<locals>.<dictcomp>4  s*    #o#o#oTQSTXnSnSnAqSnSnSnr   step_with_optimizerrv   a   A wrapped DeepSpeed engine reference is currently tied for this `Accelerator()` instance. If you want to call `accelerator.backward()` referencing a new model/engine, please create a separate `Accelerator()` instance and call `accelerator.prepare()` on it.r   )Jr   
initializer   msampr~   r  r=  r   rv   is_train_batch_minminmaxr   loggerinfo	get_value
fill_matchry   r  r   r   rX  r  r  r  rd   rp   re   r   r  runtimelr_schedulesVALID_LR_SCHEDULESdeepspeed_configlr_scheduler_callabler   r   r9   set_moe_leaf_modulesr  r?  r@  rA  rn  rz   rD  rN  r  rC  warmup_num_stepstotal_num_stepsmathceildeepspeed_config_processr   r$  r   deepspeed.ops.adamrL  r  r&  rb   r   r   rc   ranger   ra   warningr   r  r   r   r  )r   r9  r   ds_initializemsamp_deepspeedis_dataloader_presentr  batch_sizesbatch_size_per_deviceconfig_kwargsrU  r  r  r  hidden_size_based_keyshidden_size_auto_keys	reasoningr@  max_lrr   rL  rC  enginer  rG  ir~   s   `                         @r   r  zAccelerator._prepare_deepspeeds  s
   !,w&&::::::+6M0 ##a#a\`#a#a#a a a
 
 
 

 
 

 ##$DEE 	a$ \\\\\88K88888 $O  
 % c"b"b"b"bVa"b"b"bK<L<_(uK(8(8(8ehiteueu%{##a''KK+> ez    
 !K   %5$>$>?_$`$`! 	##)(,(H 	$ 	
 	
 	
 "%KP
 

 !,>SM:;%(8(B(BC`(a(aadhdvv ,- 		 	  	 C#ux//  C%+"7!DEE  		S;"?@@  S		"i&7&D&WWW	 .???
S\_iHkHk? H  
 $4$EEE*U^akJmJmE j   )ek&;== ZUY 12QR .???
S\_mHoHo? L   #3#DDDy>;; E3; r  
  Y%:)j22 :iR`;b;b  5  
 t.	4@@DHH*5$2IJJ11%888& & &"
 %g$f$f$f0F$f$f$f!())A--in7LnnnoZ[ 
 uh// V$%H9%TUUU5<77 "',":KKU\>:: "%el&?"@"@KK$gjss   $$@Kk@YILSS^M^alMlImImPRU`P`    )j22 $$,5L[d[qrr   )n66 9;Z;b y2JEEM I/t<<<",5d; 
 $$:;:@=F=W    ,8  $17	)";d>P"PQQQ&6 ""DE
 65XXX-XXX$4$ED!T5JKKKF$i*66 ?1:1AF-.!)n>> Q9CbCn1:1P~.,-@AEEFY[]^^bb &    $($9$=$=>[]a$b$b  HGGGGG#o#oY5G5M5M5O5O#o#o#o$4$4Y5K$X$Xx$X$X	*3F;' ,	??3y7H7U7hhh5>F>21>1H1H1H1H.FIq,$5i@@	$' 4!!,0,N&*&8	! ! !II !:,	 R RI3v;;'' * *fQi99 * &F1IIq	EK,A:+NOO * )F1II [.,IJJ *OO,	0A0N0aaa )F1I,40Fv0N0N--p  
 L'''$ ''	222$ ''	222V}}r   c                
	   | j         j        }d }|j        sd |D             }t          |          dk    rt	          d          |j        rt          |          nt          |          }t          |          dk    r&t          	                    d|j         d| d           n)|D ]&}t          |t                    r|j        d         } n'|.| j        |j        |j        z  z  }|                    ||           nt	          d	          d }d }d }	d }
|D ]}t          |t"          j        j        j                  r|
t+          t-          |                    }
Et          |t"          j        j                  r|}gt          |t"          j        j                  r|}t          |t6          t8          f          r|}	||                    ||
           ||                    |           |	9t          |	t8                    st	          d
          |                    |	           tA          | |j!                   tE          |           \  }}}	| #                                 d}g }|D ]}t          |t"          j        j        j                  r)|$                    tK          | |                     |dz  }Ot          |t                    rK|dk    r$|&                                 tK          | |          }|$                    ||                    |dz  }|$                    |           |tO          | |||	          }|tQ          |          }|	tS          |	|          }	tU          t          |                    D ]x}t          ||         t"          j        j                  r|||<   -t          ||         t"          j        j                  r|||<   Xt          ||         t8                    r|	||<   y|A| j+        $                    |           t          | j+                  dk    rtY          d          || j-        $                    |           |	| j.        $                    |	           t_          |          S )Nc                <    g | ]}t          |d           |j        S r/  r1  r  s     r   r  z4Accelerator._prepare_megatron_lm.<locals>.<listcomp>f  s)    XXXcWS,=W=WX3>XXXr   r   zfYou must specify a training or evaluation dataloader in `accelerate.prepare()` when using Megatron-LM.r   r5  r6  r   micro_batch_sizezWhen you do not pass the dataloader parameter, the `data_parallel_size`, `micro_batch_size`, and `global_batch_size` megatron parameters will not be updated.zvYou can't use a custom scheduler with Megatron-LM. Please use the `accelerate.utils.MegatronLMDummyScheduler` instead.)args_defaultszWYou can't use same `Accelerator()` instance with multiple models when using Megatron-LM)0r   r   megatron_dataset_flagr   r   rU  rV  rW  rX  rY  r   rg   dataset_argsr  	tp_degree	pp_degreeset_training_argsr   r  r  r  r   r   rX  r  r  r  rp   rh   set_network_size_argsset_optimizer_typeset_scheduler_argsrk   megatron_lm_default_argsrm   r\   r  rl   set_megatron_data_argsrf   ri   rj   rh  r   r  r   r   r  )r   r9  r   rx  rm  r  	dp_degreerU  r  r  
batch_datacounterr  dataloadersru  s                  r   r  z Accelerator._prepare_megatron_lmb  s   !Z:!7 	XXTXXXK;1$$ |   4F3Xns;///^abm^n^n;!##x)<x xcsx x x  
   c#<== '*'78J'K$E '*/A/KN`Nj/jkI001A9MMMMg   		
 	  	 C#u{/:;;  
@R!$s))__

C11  C%+"799  		C+/G!HII  	44UJGGG 11)<<< i)ABB   M   11)<<< 	t3E3^____(UVZ([([%	9    	# 	#C#u{/:;; 
#=dCHHIII1C!:;; #a<<..000"A$"L"LKk'23331c"""""4	9EEE 29==I 29iHHIs6{{## 	& 	&A&)UX_55 &!q		F1Iu{'<== &%q		F1I'?@@ &%q	L&&&4<  1$$$m    ##I... ##I...V}}r   c                H   | j         j        rt                      st          d          d}d}d |D             }|D ]Y}t	          |t
          j        j                  r|}|                                 8t	          |t
          j	        j
                  r|}Z||| j         j        dk    rt
          j        nd}| j        j        dk    r*|j        j        dk    r|                    | j                  }t                      r!ddl}|                    |||dd	
          \  }}t%          t'          |                    D ]W}t	          ||         t
          j        j                  r|||<   -t	          ||         t
          j	        j
                  r|||<   Xt)          |          S )a  
        Prepares model and optimizer for training with IPEX or XPU acceleration. This covers 3 cases, IPEX compiled
        with CPU only support, IPEX compiled with XPU support and training with XPU pytorch backend available in stock
        pytorch starting from version 2.4.
        zIPEX is not installed or IPEX's version does not match current PyTorch version. Please refer to https://github.com/intel/intel-extension-for-pytorch.Nc                    g | ]}|S r   r   r  s     r   r  z4Accelerator._prepare_ipex_or_xpu.<locals>.<listcomp>  r  r   r   r   r{   r   TO1)r  r  inplacelevel)r   r  rG   r   r   r   rX  r  trainr  r  rw   bfloat16r   r   r  intel_extension_for_pytorchoptimizerh  r   r  )	r   r9  rU  r  r  r  r  ipexru  s	            r   r  z Accelerator._prepare_ipex_or_xpu  s    : 	$&& !P  
 	&&&&& 	  	 C#ux//  C%+"799  	 U%6&*j&@F&J&JENNPTE{5((U\->%-G-G-- "" t::::#'==)SXbfnr=#s#s ys6{{## 	& 	&A&)UX_55 &!q		F1I(=?? &%q	V}}r   c                  t                      st          d          dd l}d\  }}d }d\  }}d |D             }	t          |	          D ]T\  }
}t	          |t
          j        j                  r|}|dz  },t	          |t
          j        j	                  r	|}|
}|dz  }U|||	|fS ||t          d          |dk    s|dk    rt          d| d	| d
          |                    ||| j        j                  \  }}t          t          |	                    D ]W}
t	          |	|
         t
          j        j                  r||	|
<   -t	          |	|
         t
          j        j	                  r||	|
<   X|d||<   t!          |	          |fS )NzMS-AMP was not found on your system. Please ensure that MS-AMP is available  or choose `'te'` as the backend for FP8 mixed precision training.r   r  r  c                    g | ]}|S r   r   r  s     r   r  z.Accelerator._prepare_msamp.<locals>.<listcomp>  r  r   r   z\You must pass a model and an optimizer together to `accelerate.prepare()` when using MS-AMP.r   r!  z with MS-AMP.)	opt_levelF)rK   r   rT  r  r   r   rX  r  r  r  r   rS  r   r  rh  r   r  )r   rt   r9  rT  rU  r  optimizer_indexr'  r(  r  ru  r  s               r   r  zAccelerator._prepare_msamp  s   !## 	U  
 	%y%)"
N&&&&&'' 	$ 	$FAs#ux// $a

C%+"799 $	"#!#+++%-n   !^^~11k*kknkkk    %//yDLcLm/nnE9s6{{## 	& 	&A&)UX_55 &!q		F1I(=?? &%q	&05_-V}}...r   data_loadertorch.utils.data.DataLoaderc                   t          |dd          r%|| j        vr| j                            |           |S || j        t          j        k    r| j        nd}t          || j        | j	        | j
        | j        || j                                        | j        | j        || j        | j        | j                  }| j                            |           |S )am  
        Prepares a PyTorch DataLoader for training in any distributed setup. It is recommended to use
        [`Accelerator.prepare`] instead.

        Args:
            data_loader (`torch.utils.data.DataLoader`):
                A vanilla PyTorch DataLoader to prepare
            device_placement (`bool`, *optional*):
                Whether or not to place the batches on the proper device in the prepared dataloader. Will default to
                `self.device_placement`.
            slice_fn_for_dispatch (`Callable`, *optional*`):
                If passed, this function will be used to slice tensors across `num_processes`. Will default to
                [`~utils.slice_tensors`]. This argument is used only when `dispatch_batches` is set to `True` and will
                be ignored otherwise.

        Example:

        ```python
        >>> import torch
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> data_loader = torch.utils.data.DataLoader(...)
        >>> data_loader = accelerator.prepare_data_loader(data_loader, device_placement=True)
        ```
        r  FN)r  r  rv   put_on_devicer   r  r  slice_fn_for_dispatchr  r  r  )r   r   r  r   r*   r   rt   r   r   r  r  rv   r   copyr  r  r  r  r  )r   r  rt   r  prepared_data_loaders        r   r   zAccelerator.prepare_data_loader  s    < ; 95AA 	$"333!((555#8<8MQ`Qd8d8dt44jo2K,,,*n))++!2*"7!%!:*$($@ 
  
  
 	  !5666##r   r  torch.optim.Optimizerc                p   t                      r(ddlm}m} | xj        t          |||f          z  c_        t          |dd          r%|| j        vr| j                            |           |S || j	        }| j
        dk    rdn| j        }t          |||          }| j                            |           |S )a  
        Prepares a PyTorch Optimizer for training in any distributed setup. It is recommended to use
        [`Accelerator.prepare`] instead.

        Args:
            optimizer (`torch.optim.Optimizer`):
                A vanilla PyTorch optimizer to prepare
            device_placement (`bool`, *optional*):
                Whether or not to place the optimizer on the proper device. Will default to `self.device_placement`.

        Example:

        ```python
        >>> import torch
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> optimizer = torch.optim.Adam(...)
        >>> optimizer = accelerator.prepare_optimizer(optimizer, device_placement=True)
        ```
        r   AdaLomoLomor  FNr   )rt   r   )rH   
lomo_optimr  r  r   r   r   r   r  rt   r   r   r   )r   r  rt   r  r  r   s         r   r  zAccelerator.prepare_optimizerQ  s    ,  	N 10000000 ##z)dG_'M'MM## 97?? 	 000 ''	222##4 )W44$+(EU^deee		***r   r  rp   c                >   t          |dd          r%|| j        vr| j                            |           |S | j        }| j        D ] }t          |dd          |j        k    r|} n!t          ||| j        | j                  }| j                            |           |S )ax  
        Prepares a PyTorch Scheduler for training in any distributed setup. It is recommended to use
        [`Accelerator.prepare`] instead.

        Args:
            scheduler (`torch.optim.lr_scheduler.LRScheduler`):
                A vanilla PyTorch scheduler to prepare

        Example:

        ```python
        >>> import torch
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> optimizer = torch.optim.Adam(...)
        >>> scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, ...)
        >>> scheduler = accelerator.prepare_scheduler(scheduler)
        ```
        r  Fr  NrQ  )r   r   r  r   r  r   r   rv   )r   r  r  opts       r   r  zAccelerator.prepare_scheduler}  s    , 97?? 	 000 ''	222$	# 	 	Cy+t44EE	 F ) $ B,	
 
 
	 		***r   c                   |                     d          }| j        t          j        k    r
|| j        z  }| j        t          j        k    r | j        j        |fi | dS | j        t          j        k    rdS | j        ' | j        	                    |          j        di | dS || j
        r|                     ||           dS  |j        di | dS )a  
        Scales the gradients in accordance to the `GradientAccumulationPlugin` and calls the correct `backward()` based
        on the configuration.

        Should be used in lieu of `loss.backward()`.

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator(gradient_accumulation_steps=2)
        >>> outputs = model(inputs)
        >>> loss = loss_fn(outputs, labels)
        >>> accelerator.backward(loss)
        ```
        learning_rateNr   )r   r   r*   r   ry   r   backwardr   r   scaler   lomo_backward)r   lossr   r  s       r   r  zAccelerator.backward  s    $ 

?33 O$===$::D O$===2D)24BB6BBBBB"o&AAAF[$,DKd##,66v66666&4+B&t]33333DM##F#####r   c                F    t          j        d| j                  | _        dS )a  
        Sets the internal trigger tensor to 1 on the current process. A latter check should follow using this which
        will check across all processes.

        Note:
            Does not require `wait_for_everyone()`

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> # Assume later in the training script
        >>> # `should_do_breakpoint` is a custom function to monitor when to break,
        >>> # e.g. when the loss is NaN
        >>> if should_do_breakpoint(loss):
        ...     accelerator.set_trigger()
        >>> # Assume later in the training script
        >>> if accelerator.check_breakpoint():
        ...     break
        ```
        r   r   N)r   tensorr   r   r  s    r   set_triggerzAccelerator.set_trigger  s#    0 !<$+>>>r   c                    | j          t          j        d| j                  | _         |                     | j                   }|                                dk    r"t          j        d| j                  | _         dS dS )a  
        Checks if the internal trigger tensor has been set to 1 in any of the processes. If so, will return `True` and
        reset the trigger tensor to 0.

        Note:
            Does not require `wait_for_everyone()`

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> # Assume later in the training script
        >>> # `should_do_breakpoint` is a custom function to monitor when to break,
        >>> # e.g. when the loss is NaN
        >>> if should_do_breakpoint(loss):
        ...     accelerator.set_trigger()
        >>> # Assume later in the training script
        >>> if accelerator.check_trigger():
        ...     break
        ```
        Nr   r  r   TF)r   r   r  r   rW   r  )r   r   s     r   check_triggerzAccelerator.check_trigger  st    2 #$|AdkBBBDkk$"233""$|AdkBBBD4ur   c                $   | j         r| j        dk    r{|| j        }nt          |t          t
          f          s|g}|D ]Q}t          |t                    r|j        }t          |t                    | j        	                    |           NdS dS dS )a  
        Unscale the gradients in mixed precision training with AMP. This is a noop in all other settings.

        Likely should be called through [`Accelerator.clip_grad_norm_`] or [`Accelerator.clip_grad_value_`]

        Args:
            optimizer (`torch.optim.Optimizer` or `list[torch.optim.Optimizer]`, *optional*):
                The optimizer(s) for which to unscale gradients. If not set, will unscale gradients on all optimizers
                that were passed to [`~Accelerator.prepare`].

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> model, optimizer = accelerator.prepare(model, optimizer)
        >>> outputs = model(inputs)
        >>> loss = loss_fn(outputs, labels)
        >>> accelerator.backward(loss)
        >>> accelerator.unscale_gradients(optimizer=optimizer)
        ```
        r   N)
r   rw   r   r   r  r   r   r  r   unscale_)r   r  r  s      r   unscale_gradientszAccelerator.unscale_gradients	  s    0 ? 		*t3v==  ,			E4=99 (&K	  * * &:;; (-C !&:;; ($$S))))		* 		*==* *r      c                   | j         t          j        k    rf|                                  d |D             }| j        D ]<}|d |                                D             k    r|                    ||          c S =n=| j         t          j        k    rdS | j         t          j        k    r| j	        D ]}|j
        j        sr|}t          |t                    r|j        }t          |t                    t          j        |          }t          j        d|d| j        z             d|j
        _        t&          j                            dd	          d
k    rd|                                  d |D             }| j        D ]<}|d |                                D             k    r|                    ||          c S =|                                  t,          j        j                            |||          S )aQ  
        Should be used in place of `torch.nn.utils.clip_grad_norm_`.

        Returns:
            `torch.Tensor`: Total norm of the parameter gradients (viewed as a single vector).

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator(gradient_accumulation_steps=2)
        >>> dataloader, model, optimizer, scheduler = accelerator.prepare(dataloader, model, optimizer, scheduler)

        >>> for input, target in dataloader:
        ...     optimizer.zero_grad()
        ...     output = model(input)
        ...     loss = loss_func(output, target)
        ...     accelerator.backward(loss)
        ...     if accelerator.sync_gradients:
        ...         accelerator.clip_grad_norm_(model.parameters(), max_grad_norm)
        ...     optimizer.step()
        ```
        c                    g | ]}|S r   r   r  s     r   r  z/Accelerator.clip_grad_norm_.<locals>.<listcomp>A	  s    000!000r   c                    g | ]}|S r   r   r  s     r   r  z/Accelerator.clip_grad_norm_.<locals>.<listcomp>C	  s    !@!@!@!!@!@!@r   Nsumr8  )r  Tr   r   r   c                    g | ]}|S r   r   r  s     r   r  z/Accelerator.clip_grad_norm_.<locals>.<listcomp>X	  s    444Aa444r   c                    g | ]}|S r   r   r  s     r   r  z/Accelerator.clip_grad_norm_.<locals>.<listcomp>Z	  s    %D%D%DAa%D%D%Dr   )	norm_type)r   r*   r   r  r   r  clip_grad_norm_r   r   r   r   is_xla_gradients_syncedr   r   r  xm_fetch_gradients
all_reducer  r   r   r   r   rX  r  )r   r  max_normr  rU  acc_optr  	gradientss           r   r  zAccelerator.clip_grad_norm_&	  s'   2  O$888""$$$00Z000J F F!@!@U-=-=-?-?!@!@!@@@ 009EEEEE AF "o&??? 4"o&999+ 
J 
J-E 	J!C$S*>?? ,!m %S*>?? , " 3C 8 8I M%#@R:RSSSSEIG*Bz~~3W==GG&&(((44444
!\ J JE!%D%D1A1A1C1C%D%D%DDD$44XyIIIII E   x~--j(i-XXXr   c                    | j         t          j        t          j        fv rt	          d          |                                  t          j        j        	                    ||           dS )a  
        Should be used in place of `torch.nn.utils.clip_grad_value_`.

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator(gradient_accumulation_steps=2)
        >>> dataloader, model, optimizer, scheduler = accelerator.prepare(dataloader, model, optimizer, scheduler)

        >>> for input, target in dataloader:
        ...     optimizer.zero_grad()
        ...     output = model(input)
        ...     loss = loss_func(output, target)
        ...     accelerator.backward(loss)
        ...     if accelerator.sync_gradients:
        ...         accelerator.clip_grad_value_(model.parameters(), clip_value)
        ...     optimizer.step()
        ```
        zUDeepSpeed and FSDP  do not support `clip_grad_value_`. Use `clip_grad_norm_` instead.N)
r   r*   r   r   	Exceptionr  r   rX  r  clip_grad_value_)r   r  
clip_values      r   r  zAccelerator.clip_grad_value__	  s^    ,  _%>@T$UUUsttt   ''
J?????r   c                     t          |          S )a2  
        Gather the values in *tensor* across all processes and concatenate them on the first dimension. Useful to
        regroup the predictions from all processes when doing evaluation.

        Note:
            This gather happens in all processes.

        Args:
            tensor (`torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`):
                The tensors to gather across all processes.

        Returns:
            `torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`: The gathered tensor(s). Note that the
            first dimension of the result is *num_processes* multiplied by the first dimension of the input tensors.

        Example:

        ```python
        >>> # Assuming four processes
        >>> import torch
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> process_tensor = torch.tensor([accelerator.process_index])
        >>> gathered_tensor = accelerator.gather(process_tensor)
        >>> gathered_tensor
        tensor([0, 1, 2, 3])
        ```
        )r@   )r   r  s     r   r@   zAccelerator.gatherz	  s    < f~~r   c                    	 t          d |d           d}n# t          $ r d}Y nw xY w|p| }|rt          |          }n                     |          }	  j        j        r` j        j        dk    rt                              d           |S  j        j        dk    r" fd}|r ||          S t          ||          S |S |S # t          $ r |cY S w xY w)	a  
        Gathers `input_data` and potentially drops duplicates in the last batch if on a distributed system. Should be
        used for gathering the inputs and targets for metric calculation.

        Args:
            input (`torch.Tensor`, `object`, a nested tuple/list/dictionary of `torch.Tensor`, or a nested tuple/list/dictionary of `object`):
                The tensors or objects for calculating metrics across all processes
            use_gather_object(`bool`):
                Whether to forcibly use gather_object instead of gather (which is already done if all objects passed do
                not contain tensors). This flag can be useful for gathering tensors with different sizes that we don't
                want to pad and concatenate along the first dimension. Using it with GPU tensors is not well supported
                and inefficient as it incurs GPU -> CPU transfer since tensors would be pickled.

        Example:

        ```python
        >>> # Assuming two processes, with a batch size of 5 on a dataset with 9 samples
        >>> import torch
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> dataloader = torch.utils.data.DataLoader(range(9), batch_size=5)
        >>> dataloader = accelerator.prepare(dataloader)
        >>> batch = next(iter(dataloader))
        >>> gathered_items = accelerator.gather_for_metrics(batch)
        >>> len(gathered_items)
        9
        ```
        c                    | S r  r   )r>  s    r   <lambda>z0Accelerator.gather_for_metrics.<locals>.<lambda>	  s     r   T)error_on_other_typeFr  zcThe used dataset had no length, returning gathered tensors. You should drop the remainder yourself.r   c                ,    | d j         j                 S r  )r   	remainder)r  r   s    r   _adjust_samplesz7Accelerator.gather_for_metrics.<locals>._adjust_samples	  s    %&E(;(E&EFFr   )
rV   r   rA   r@   r   rd  r  rX  rY  r  )r   
input_datause_gather_objectall_tensorsr  r  s   `     r   gather_for_metricszAccelerator.gather_for_metrics	  sS   >	 kk:4PPPPKK 	  	  	 KKK	  .@[ 	+ ,,DD;;z**D	"4  &0B66KK}    K(2Q66G G G G G ) H.t4440$GGG  K  	 	 	KKK	s6    ((7C !C 2C C C CCr  r8  c                $    t          |||          S )a
  
        Reduce the values in *tensor* across all processes based on *reduction*.

        Note:
            All processes get the reduced value.

        Args:
            tensor (`torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`):
                The tensors to reduce across all processes.
            reduction (`str`, *optional*, defaults to "sum"):
                A reduction type, can be one of 'sum', 'mean', or 'none'. If 'none', will not perform any operation.
            scale (`float`, *optional*, defaults to 1.0):
                A default scaling value to be applied after the reduce, only valied on XLA.

        Returns:
            `torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`:
                The reduced tensor(s).

        Example:

        ```python
        >>> # Assuming two processes
        >>> import torch
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> process_tensor = torch.arange(accelerator.num_processes) + 1 + (2 * accelerator.process_index)
        >>> process_tensor = process_tensor.to(accelerator.device)
        >>> reduced_tensor = accelerator.reduce(process_tensor, reduction="sum")
        >>> reduced_tensor
        tensor([4, 6])
        ```
        )rW   )r   r  	reductionr  s       r   rW   zAccelerator.reduce	  s    D fi///r   r   c                (    t          ||||          S )a  
        Recursively pad the tensors in a nested list/tuple/dictionary of tensors from all devices to the same size so
        they can safely be gathered.

        Args:
            tensor (nested list/tuple/dictionary of `torch.Tensor`):
                The data to gather.
            dim (`int`, *optional*, defaults to 0):
                The dimension on which to pad.
            pad_index (`int`, *optional*, defaults to 0):
                The value with which to pad.
            pad_first (`bool`, *optional*, defaults to `False`):
                Whether to pad at the beginning or the end.

        Returns:
            `torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`:
                The padded tensor(s).

        Example:

        ```python
        >>> # Assuming two processes, with the first processes having a tensor of size 1 and the second of size 2
        >>> import torch
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> process_tensor = torch.arange(accelerator.process_index + 1).to(accelerator.device)
        >>> padded_tensor = accelerator.pad_across_processes(process_tensor)
        >>> padded_tensor.shape
        torch.Size([2])
        ```
        )dim	pad_index	pad_first)rT   )r   r  r  r  r  s        r   rT   z Accelerator.pad_across_processes
  s    B $FyT]^^^^r   keep_fp32_wrapperc                "    t          ||          S )a  
        Unwraps the `model` from the additional layer possible added by [`~Accelerator.prepare`]. Useful before saving
        the model.

        Args:
            model (`torch.nn.Module`):
                The model to unwrap.
            keep_fp32_wrapper (`bool`, *optional*, defaults to `True`):
                Whether to not remove the mixed precision hook if it was added.

        Returns:
            `torch.nn.Module`: The unwrapped model.

        Example:

        ```python
        >>> # Assuming two GPU processes
        >>> from torch.nn.parallel import DistributedDataParallel
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> model = accelerator.prepare(MyModel())
        >>> print(model.__class__.__name__)
        DistributedDataParallel

        >>> model = accelerator.unwrap_model(model)
        >>> print(model.__class__.__name__)
        MyModel
        ```
        )r?   )r   rU  r  s      r   unwrap_modelzAccelerator.unwrap_model*
  s    > +52CDDDr   c                "    t                       dS )a  
        Will stop the execution of the current process until every other process has reached that point (so this does
        nothing when the script is only run in one process). Useful to do before saving a model.

        Example:

        ```python
        >>> # Assuming two GPU processes
        >>> import time
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> if accelerator.is_main_process:
        ...     time.sleep(2)
        >>> else:
        ...     print("I'm waiting for the main process to finish its sleep...")
        >>> accelerator.wait_for_everyone()
        >>> # Should print on every process at the same time
        >>> print("Everyone is here")
        ```
        N)r\   r  s    r   r\   zAccelerator.wait_for_everyoneK
  s    , 	r   project_namer   r?  dict | Noneinit_kwargsc                2   | j         D ]}t          t          |          t                    r| j                            |           ?t          t          |                   }|j        rI| j                             ||| j	        fi |
                    t          |          i                      | j                             ||fi |
                    t          |          i                      || j        D ]}|                    |           dS dS )a  
        Initializes a run for all trackers stored in `self.log_with`, potentially with starting configurations

        Args:
            project_name (`str`):
                The name of the project. All trackers will save their data based on this
            config (`dict`, *optional*):
                Optional starting configuration to be logged.
            init_kwargs (`dict`, *optional*):
                A nested dictionary of kwargs to be passed to a specific tracker's `__init__` function. Should be
                formatted like so:
                ```python
                {"wandb": {"tags": ["tag_a", "tag_b"]}}
                ```

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator(log_with="tensorboard")
        >>> accelerator.init_trackers(
        ...     project_name="my_project",
        ...     config={"learning_rate": 0.001, "batch_size": 32},
        ...     init_kwargs={"tensorboard": {"flush_secs": 60}},
        ... )
        ```
        N)r   
issubclassr   r   r   r  r   r   requires_logging_directoryr   r   store_init_configuration)r   r  r?  r  trackertracker_inits         r   init_trackerszAccelerator.init_trackersc
  s=   < } 	j 	jG$w--88 j$$W----3CLLA: jM(($\43Cii{WZ[bWcWcegGhGhii    M((l)h)hkooVYZaVbVbdfFgFg)h)hiiii= 9 9008888 9 9r   nameunwrapc                    t          | j                  dk    r4| j        D ]}|j        |k    r|r|j        n|c S t	          | d          t          d          S )a   
        Returns a `tracker` from `self.trackers` based on `name` on the main process only.

        Args:
            name (`str`):
                The name of a tracker, corresponding to the `.name` property.
            unwrap (`bool`):
                Whether to return the internal tracking mechanism or to return the wrapped tracker instead
                (recommended).

        Returns:
            `GeneralTracker`: The tracker corresponding to `name` if it exists.

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator(log_with="tensorboard")
        >>> accelerator.init_trackers("my_project")
        >>> tensorboard_tracker = accelerator.get_tracker("tensorboard")
        ```
        r   z= is not an available tracker stored inside the `Accelerator`.T)_blank)r   r   r  r  r   r   )r   r  r  r  s       r   get_trackerzAccelerator.get_tracker
  s}    0 t}!!= B B<4''.4A7??'AAA (cccdddT****r   r   r   r   
int | None
log_kwargsc           	     l    | j         D ]+} |j        |fd|i|                    |j        i            ,dS )a  
        Logs `values` to all stored trackers in `self.trackers` on the main process only.

        Args:
            values (`dict`):
                Values should be a dictionary-like object containing only types `int`, `float`, or `str`.
            step (`int`, *optional*):
                The run step. If included, the log will be affiliated with this step.
            log_kwargs (`dict`, *optional*):
                A nested dictionary of kwargs to be passed to a specific tracker's `log` function. Should be formatted
                like so:
                ```python
                {"wandb": {"tags": ["tag_a", "tag_b"]}}
                ```

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator(log_with="tensorboard")
        >>> accelerator.init_trackers("my_project")
        >>> accelerator.log({"loss": 0.5, "accuracy": 0.9})
        ```
        r   N)r   logr   r  )r   r   r   r  r  s        r   r  zAccelerator.log
  sU    6 } 	O 	OGGKNNTNZ^^GL"-M-MNNNN	O 	Or   c                t    | j         D ]}|                                 | j                                         dS )a  
        Runs any special end training behaviors, such as stopping trackers on the main process only or destoying
        process group. Should always be called at the end of your script if using experiment tracking.

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator(log_with="tensorboard")
        >>> accelerator.init_trackers("my_project")
        >>> # Do training
        >>> accelerator.end_training()
        ```
        N)r   finishr   destroy_process_group)r   r  s     r   end_trainingzAccelerator.end_training
  sB      } 	 	GNN
((*****r   c                @    t          ||| j        j        |           dS )a  
        Save the object passed to disk once per machine. Use in place of `torch.save`.

        Args:
            obj (`object`): The object to save.
            f (`str` or `os.PathLike`): Where to save the content of `obj`.
            safe_serialization (`bool`, *optional*, defaults to `False`): Whether to save `obj` using `safetensors`

        Note:
            If `save_on_each_node` was passed in as a `ProjectConfiguration`, will save the object once per node,
            rather than only once on the main node.

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> arr = [0, 1, 2, 3]
        >>> accelerator.save(arr, "array.pkl")
        ```
        save_on_each_nodesafe_serializationN)rY   r   r  )r   r  fr  s       r   rY   zAccelerator.save
  s7    . 	"8J1		
 	
 	
 	
 	
 	
r   10GBsave_directoryUnion[str, os.PathLike]max_shard_sizeUnion[int, str]r  c           	     H   t           j                            |          r t                              d| d           dS t          j        |d           t          d |                                D                       rt          |          nOt          d |	                                D                       rt          d          |                     |          |rt                    |rt          nt          }|rt          nt           }t#          ||	          }t          j        |          D ]}t           j                            ||          }	|                    d
d          }
|                    d
d          }t+          j        d          }|                    |
          rvt           j                            |	          rW||j                                        vr<|                    |          't7                      j        rt          j        |	           |j                                        D ]I\  }}fd|D             }|                     |t           j                            ||          |           J|j         r|j!        |j"        d}|rtF          ntH          }t           j                            ||          }tK          |dd          5 }tM          j'        |dd          dz   }|(                    |           ddd           n# 1 swxY w Y   t          )                    d| dtU          |j                   d| d           dS t           j                            |t                    }t          )                    d|            dS )a(  
        Save a model so that it can be re-loaded using load_checkpoint_in_model

        Arguments:
            model: (`torch.nn.Module`):
                Model to be saved. The model can be wrapped or unwraped.
            save_directory (`str` or `os.PathLike`):
                Directory to which to save. Will be created if it doesn't exist.
            max_shard_size (`int` or `str`, *optional*, defaults to `"10GB"`):
                The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size
                lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`).

                <Tip warning={true}>

                If a single weight of the model is bigger than `max_shard_size`, it will be in its own checkpoint shard
                which will be bigger than `max_shard_size`.

                </Tip>

            safe_serialization (`bool`, *optional*, defaults to `True`):
                Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> model = ...
        >>> accelerator.save_model(model, save_directory)
        ```
        zProvided path (z#) should be a directory, not a fileNTexist_okc                z    g | ]8}t          |d           t          |j        t                    ,|j        j        9S )_hf_hook)r  r   r  r   offload)r  r  s     r   r  z*Accelerator.save_model.<locals>.<listcomp>3  sT       6:.. 4>foO_3`3`'  r   c              3  P   K   | ]!}|j         t          j         d           k    V  "dS )r  N)r   r   )r  r  s     r   r  z)Accelerator.save_model.<locals>.<genexpr>;  s3      XXE5<5<#7#77XXXXXXr   zFYou can't save the model since some parameters are on the meta device.)filename_patternr  z.bin z(.*?)-\d{5}-of-\d{5}c                "    i | ]}||         S r   r   )r  r  
state_dicts     r   r  z*Accelerator.save_model.<locals>.<dictcomp>^  s     FFFFVZ/FFFr   )r  )metadata
weight_mapwzutf-8)encodingr  )indent	sort_keys
z:The model is bigger than the maximum size per checkpoint (z) and is going to be split in z^ checkpoint shards. You can find where each parameters has been saved in the index located at r  zModel weights saved in )+r   pathisfilerX  errormakedirsr  modulesr_   r  RuntimeErrorget_state_dictr;   r!   r$   r"   r%   r   listdirr  replacerer  
startswithfilename_to_tensorskeys	fullmatchr   r&  remover  rY   
is_shardedr
  tensor_to_filenamer    r#   openjsondumpswriterY  r   )r   rU  r  r  r  weights_namer  state_dict_splitfilenamefull_filenameweights_no_suffixfilename_no_suffixregtensorsshardr  save_index_filer  contentpath_to_weightsr	  s                       @r   
save_modelzAccelerator.save_model  s   P 7>>.)) 	LL^>^^^___F
NT2222  #mmoo  
 
 	4 8>>JJXXUEUEUEWEWXXXXX m"#klll,,U33J 	F9*EEJ,>P((L8Jd44Pd=)9.
 
 

 
>22 	) 	)HGLLBBM !- 4 4VR @ @ "*!1!1&"!=!=*455C ##$566)GNN=11) $4$H$M$M$O$OOOMM"455A NN2 B 	-((( "2!E!K!K!M!M 	l 	lHgFFFFgFFFEIIeRW\\.(CCXjIkkkk & 	E,5.A E :Lc55QcO gll>?KKOosW=== !*U1EEEL   ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! KK7^ 7 7 0 DEE7 7$37 7 7     !gll><HHOKKC/CCDDDDDs   !0LL!$L!hookCallable[..., None]returnhooks.RemovableHandlec                V    t          j        | j                  }|| j        |j        <   |S )a  
        Registers a pre hook to be run before `save_checkpoint` is called in [`Accelerator.save_state`].

        Args:
            hook (`Callable`):
                A function to be called in [`Accelerator.save_state`] before `save_checkpoint`.

        The hook should have the following signature:

        `hook(models: list[torch.nn.Module], weights: list[dict[str, torch.Tensor]], input_dir: str) -> None`

        The `models` argument are the models as saved in the accelerator state under `accelerator._models`, `weigths`
        argument are the state dicts of the `models`, and the `input_dir` argument is the `input_dir` argument passed
        to [`Accelerator.load_state`].

        <Tip>

        Should only be used in conjunction with [`Accelerator.register_load_state_pre_hook`]. Can be useful to save
        configurations in addition to model weights. Can also be used to overwrite model saving with a customized
        method. In this case, make sure to remove already loaded weights from the weights list.

        </Tip>

        Returns:
            `torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling
            `handle.remove()`
        )hooksRemovableHandler   idr   r3  handles      r   register_save_state_pre_hookz(Accelerator.register_save_state_pre_hooku  s+    8 &t'FGG59'	2r   
output_dirc                @   | j         j        r%t          j                            | j        d          t          j        d           | j         j        r[fdt          j                  D             }| j         j        t          |          dz   | j         j        k    r| j
        rd }|                    |           t                              d	t          |          dz   | j         j        z
   d
           |dt          |          dz   | j         j        z
           D ]}t          j        |           t          j                            d| j                   t          j                                      rt%          d d| j         d          |                                  t          j        d           t                              d            | j        t,          j        k    rt1          j                     g }t5          | j                  D ]\  }}	| j        t,          j        k    rUt                              d           t;          | j        j        | |	|           t                              d            p| j        t,          j         k    rt                              d           |dk    rtB           ntB           d| }
 |	j"        |
fi | t                              dt          j                            |
                      | j        t,          j#        k    rNt                              d           |	"                               t                              d            h|$                    | %                    |	d                     g }| j        t,          j        k    r{t5          | j&                  D ]e\  }}t                              d           tO          | j        j        | || j        |         |           t                              d            fn&| j        t,          j         t,          j#        fvr| j&        }g }| j        t,          j         k    rFt5          | j(                  D ]0\  }}tS          |tT                    r|$                    |           1n| j        t,          j#        fvr| j(        }| j+        }| j,        -                                D ]} || j        |           t]          ||||| j        j/        | j0        | j1        | j         j2        |
  
        }t5          | j3                  D ]"\  }}ti          ||| j         j2                   #| j         xj5        dz  c_5        |S )a  
        Saves the current states of the model, optimizer, scaler, RNG generators, and registered objects to a folder.

        If a `ProjectConfiguration` was passed to the `Accelerator` object with `automatic_checkpoint_naming` enabled
        then checkpoints will be saved to `self.project_dir/checkpoints`. If the number of current saves is greater
        than `total_limit` then the oldest save is deleted. Each checkpoint is saved in seperate folders named
        `checkpoint_<iteration>`.

        Otherwise they are just saved to `output_dir`.

        <Tip>

        Should only be used when wanting to save a checkpoint during training and restoring the state in the same
        environment.

        </Tip>

        Args:
            output_dir (`str` or `os.PathLike`):
                The name of the folder to save all relevant weights and states.
            safe_serialization (`bool`, *optional*, defaults to `True`):
                Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
            save_model_func_kwargs (`dict`, *optional*):
                Additional keyword arguments for saving model which can be passed to the underlying save function, such
                as optional arguments for DeepSpeed's `save_checkpoint` function.

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> model, optimizer, lr_scheduler = ...
        >>> model, optimizer, lr_scheduler = accelerator.prepare(model, optimizer, lr_scheduler)
        >>> accelerator.save_state(output_dir="my_checkpoint")
        ```
        checkpointsTr   c                P    g | ]"}t           j                            |          #S r   r   r  r  )r  folderr>  s     r   r  z*Accelerator.save_state.<locals>.<listcomp>  s)    ]]]Frw||J77]]]r   Nr   c           	     x    t          t          t          t          j        d|                               d         S Nz[\/]?([0-9]+)(?=[^\/]*$)r   r   maprz   r  findallrC  s    r   r:  z&Accelerator.save_state.<locals>._inner  s.    C4OQW)X)X Y YZZ[\]]r   keyz	Deleting z- checkpoints to make room for new checkpoint.checkpoint_zCheckpoint directory z (zc) already exists. Please manually override `self.save_iteration` with what iteration to start with.zSaving current state to zSaving FSDP modelzFSDP Model saved to output dir z$Saving DeepSpeed Model and Optimizerr   r  z2DeepSpeed Model and Optimizer saved to output dir z1Saving Megatron-LM Model, Optimizer and Schedulerz@Megatron-LM Model , Optimizer and Scheduler saved to output dir F)r  zSaving FSDP Optimizerz#FSDP Optimizer saved to output dir r  )r  )6r   automatic_checkpoint_namingr   r  r  r   r  r  total_limitr   r&  sortrX  ri  shutilrmtreer$  existsr   r\   rY  r   r*   r   r  	mark_stepr  r   r   rZ   r   r   r   r   save_checkpointr   r  r  r   r[   r   r   rc   r   r   r   r   r  r   r   r  r   r   r#  )r   r>  r  save_model_func_kwargsfoldersr:  rC  weightsru  rU  ckpt_id
optimizersr  
schedulersr  r  r3  save_locationr  s    `                 r   
save_statezAccelerator.save_state  s   L %A 	Gd&6FFJ
J....%A 	%]]]]bjQ[F\F\]]]G*6B\\A%(B(NNN( O^ ^ ^ ((( IGq 043M3Y Y  I  I  I   &&aGq(84;U;a(a&ab * *FM&))))j2U@S2U2UVVJw~~j))   sJ  s  s$:M  s  s  s   ""$$$
J....;z;;<<< O$777LNNN !$,// 	I 	IHAu$(<<</000
 6eZQRSSSJjJJKKKK&/*CCCBCCC-.!VVZ//J9L9L9L9L%%j'TT=STTTtQSQXQ]Q]^hjqQrQrttuuuu&/*EEEOPPP%%j111k_ikkllllt2252GGHHHH 
 O$888#D$455 P P33444#DJ$:D#t|TUXbdefffN*NNOOOOP "?+DoFa*bbb)J 
 O$=== )$*: ; ; - -9i)BCC !!),,,,- "?+F*GGG)J ' 3::<< 	4 	4DDw
3333.J$IK"8J1
 
 
   455 	r 	rFAsc:qDD^Dpqqqqq",,1,,r   c                V    t          j        | j                  }|| j        |j        <   |S )aX  
        Registers a pre hook to be run before [`load_checkpoint`] is called in [`Accelerator.load_state`].

        Args:
            hook (`Callable`):
                A function to be called in [`Accelerator.load_state`] before `load_checkpoint`.

        The hook should have the following signature:

        `hook(models: list[torch.nn.Module], input_dir: str) -> None`

        The `models` argument are the models as saved in the accelerator state under `accelerator._models`, and the
        `input_dir` argument is the `input_dir` argument passed to [`Accelerator.load_state`].

        <Tip>

        Should only be used in conjunction with [`Accelerator.register_save_state_pre_hook`]. Can be useful to load
        configurations in addition to model weights. Can also be used to overwrite model loading with a customized
        method. In this case, make sure to remove already loaded models from the models list.

        </Tip>

        Returns:
            `torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling
            `handle.remove()`
        )r8  r9  r   r:  r;  s      r   register_load_state_pre_hookz(Accelerator.register_load_state_pre_hook  s+    6 &t'FGG59'	2r   	input_dirc           
     
   Rt           j                                      t           j                                      st	          d d          n| j        j        rgt           j                            | j        d          fdt          j	                  D             }d }|
                    |           |d         nt	          d	          t                              d
            g }t          | j                  D ]}\  }}| j        t           j        k    rUt                              d           t%          | j        j        | ||           t                              d            p| j        t           j        k    rt                              d           |dk    rt,           nt,           d| } |j        |fi | t                              dt           j                            |                      | j        t           j        k    rNt                              d           |                               t                              d            h|                    |           g }	| j        t           j        k    r{t          | j                  D ]e\  }}
t                              d           t7          | j        j        | |
| j        |         |           t                              d            fn&| j        t           j        t           j        fvr| j        }	g }| j        t           j        k    rFt          | j                  D ]0\  }}t;          |t<                    r|                    |           1n| j        t           j        fvr| j        }| j        }| j         !                                D ]} ||           |"                    dd          }|E| j#        dk    r8| j        t           j$        t           j%        t           j&        t           j'        fv rd}nd}tQ          ||	||| j        j)        | j*        |fi |}d|v r|d         | _+        d t          j	                  D             }tY          |          tY          | j-                  k    rOd d}|dtY          |           z  }|dtY          | j-                   dz  }|d z  }|d!z  }t]          |          t                              d"tY          |           d#           t          | j-                  D ]\  }}t_          ||           dS )$a  
        Loads the current states of the model, optimizer, scaler, RNG generators, and registered objects.

        <Tip>

        Should only be used in conjunction with [`Accelerator.save_state`]. If a file is not registered for
        checkpointing, it will not be loaded if stored in the directory.

        </Tip>

        Args:
            input_dir (`str` or `os.PathLike`):
                The name of the folder all relevant weights and states were saved in. Can be `None` if
                `automatic_checkpoint_naming` is used, and will pick up from the latest checkpoint.
            load_model_func_kwargs (`dict`, *optional*):
                Additional keyword arguments for loading model which can be passed to the underlying load function,
                such as optional arguments for DeepSpeed's `load_checkpoint` function or a `map_location` to load the
                model and optimizer on.

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> model, optimizer, lr_scheduler = ...
        >>> model, optimizer, lr_scheduler = accelerator.prepare(model, optimizer, lr_scheduler)
        >>> accelerator.load_state("my_checkpoint")
        ```
        NzTried to find z but folder does not existr@  c                P    g | ]"}t           j                            |          #S r   rB  )r  rC  r_  s     r   r  z*Accelerator.load_state.<locals>.<listcomp>b  s)    [[[6rw||Iv66[[[r   c           	     x    t          t          t          t          j        d|                               d         S rE  rF  rI  s    r   r:  z&Accelerator.load_state.<locals>._innerd  s-    CRZ0KV%T%TUUVVWXYYr   rJ  r  zBNo input_dir provided and automatic checkpoint naming is disabled.zLoading states from zLoading FSDP modelz!FSDP Model loaded from input dir z%Loading DeepSpeed Model and Optimizerr   r  z4DeepSpeed Model and Optimizer loaded from input dir z2Loading Megatron-LM Model, Optimizer and SchedulerzBMegatron-LM Model , Optimizer and Scheduler loaded from input dir zLoading FSDP Optimizerz%FSDP Optimizer loaded from input dir map_locationr   	on_devicer{   r   c                <    g | ]}t          j        d |          |S )z^custom_checkpoint_\d+\.pkl$)r  search)r  r  s     r   r  z*Accelerator.load_state.<locals>.<listcomp>  s2     
 
 
	:Y[\0]0]0iA0i0i0ir   z'Number of custom checkpoints in folder z1 does not match the number of registered objects:z
	Found checkpoints: z
	Registered objects: r  zqPlease make sure to only load checkpoints from folders that were created with the same set of registered objects,znor avoid using `custom_checkpoint` in the filename for files in that same directory and load them in manually.zLoading in z custom states)0r   r  
expanduserisdirr   r   rM  r  r   r  rO  rX  rY  r  r   r   r*   r   rR   r   r   r   r   load_checkpointr   r  r   rS   r   r   rc   r   r   r   popr  r   r|  r}  r{  r   r  r   r   r   r   r  r   )r   r_  load_model_func_kwargsrV  r:  rs  ru  rU  rX  rY  r  rZ  r  r  r3  rc  override_attributescustom_checkpointserrr  r  s    `                   r   
load_statezAccelerator.load_state;  s   >  **955I7==++ Y !W)!W!W!WXXXY'C 	cT%5}EEI[[[[RZPYEZEZ[[[GZ Z Z LLVL$$$IIabbb6966777 !$,// 	% 	%HAu$(<<<0111
 6eYPQRRRK	KKLLLL&/*CCCCDDD-.!VVZ//J9L9L9L9L%%iSS<RSSSuSUSZS_S_`ikrSsSsuuvvvv&/*EEEPQQQ%%i000lajllmmmme$$$$ 
 O$888#D$455 Q Q34555#DJ$:D#t|TUXacdeeeOIOOPPPPQ "?+DoFa*bbb)J 
 O$=== )$*: ; ; - -9i)BCC !!),,,,- "?+F*GGG)J' 3::<< 	$ 	$DD####-11.$GG!A%%$*?))*)	D + +  +$4J$K

 

 %

 

 (((+F3DI
 
z),,
 
 
 !""c$*>&?&???v)vvv  FS1C-D-DFFFCKc$2F.G.GKKKKC  G  GC  D  DCs###KKMc*<&=&=MMMNNN'(<== 9 9
s!#y%88889 9r   c                    t          | d          r,| j        | j        j                                         d| _        t	          | }g | _        g | _        g | _        g | _        d| _	        |S )ab  
        Will release all references to the internal objects stored and call the garbage collector. You should call this
        method between two trainings with different models/optimizers. Also will reset `Accelerator.step` to 0.

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> model, optimizer, scheduler = ...
        >>> model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler)
        >>> model, optimizer, scheduler = accelerator.free_memory(model, optimizer, scheduler)
        ```
        r   Nr   )
r  r   rt  destroyrX   r   r   r   r   r   r   objectss     r   free_memoryzAccelerator.free_memory  su    " 4344 	1,8-4<<>>>,0D) '*	r   c                     | j         | S )aU  
        Alias for [`Accelerate.free_memory`], releases all references to the internal objects stored and call the
        garbage collector. You should call this method between two trainings with different models/optimizers.

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> model, optimizer, scheduler = ...
        >>> model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler)
        >>> model, optimizer, scheduler = accelerator.clear(model, optimizer, scheduler)
        ```
        )rt  rr  s     r   clearzAccelerator.clear  s       t))r   c                    i }|D ]a}t          |t          j        j                  r@t	          |          }|                    d |                                D                        b|S )Nc                    i | ]\  }}||	S r   r   )r  r  r  s      r   r  z5Accelerator._get_named_parameters.<locals>.<dictcomp>  s    (Q(Q(Q$!QA(Q(Q(Qr   )r   r   rX  r  r?   rn  named_parameters)r   r9  ry  r  s       r   r  z!Accelerator._get_named_parameters  ss     	S 	SC#ux// S1#66 ''(Q(Q#:N:N:P:P(Q(Q(QRRRr   c                D   d }d }|D ]}t          |t          j        j                  r|                                D ]	}|j        } t          |t          j        j                  r8|j        D ]0}t          |d                   dk    r|d         d         j        } n1||fS )Nr$  r   )
r   r   rX  r  r  r   r  r  r&  r   )r   r9  r  r  r  r  r)  s          r   r  zAccelerator._get_devices  s     	 	C#ux//  ^^--  E#(<L#u{455 #&#3  K;x011A55+6x+@+C+J( 6 .//r   c                   | j         t          j        k    r| j        d         d         dk    r8|                                r|                                }nt          d          ddlm}  || 	                    |          
                                          }n| j         t          j        k    rdddlm}m} ddlm}  |d	d	
          }|                    ||j        |          5  |
                                }ddd           n# 1 swxY w Y   n+|r| 	                    |          }|
                                }|S )aP  
        Returns the state dictionary of a model sent through [`Accelerator.prepare`] potentially without full
        precision.

        Args:
            model (`torch.nn.Module`):
                A PyTorch model sent through [`Accelerator.prepare`]
            unwrap (`bool`, *optional*, defaults to `True`):
                Whether to return the original underlying state_dict of `model` or to return the wrapped state_dict

        Returns:
            `dict`: The state dictionary of the model potentially without full precision.

        Example:

        ```python
        >>> import torch
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> net = torch.nn.Linear(2, 2)
        >>> net = accelerator.prepare(net)
        >>> state_dict = accelerator.get_state_dict(net)
        ```
        rH  stage   a  Cannot get 16bit model weights because `stage3_gather_16bit_weights_on_model_save` in DeepSpeed config is False. To save the model weights in 16bit, set `stage3_gather_16bit_weights_on_model_save` to True in DeepSpeed config file or set `zero3_save_16bit_model` to True when using `accelerate config`. To save the full checkpoint, run `model.save_checkpoint(save_dir)` and use `zero_to_fp32.py` to recover weights.r   )clone_tensors_for_torch_save)FullStateDictConfigStateDictTyper  T)offload_to_cpu
rank0_onlyN)r   r*   r   r_  'zero_gather_16bit_weights_on_model_save$_zero3_consolidated_16bit_state_dictr   deepspeed.checkpoint.utilsr~  r  r	  r   torch.distributed.fsdpr  r  r  state_dict_typeFULL_STATE_DICT)	r   rU  r  r	  r~  r  r  r   full_state_dict_configs	            r   r  zAccelerator.get_state_dict  s   6  O$===$%89'BaGG@@BB !&!K!K!M!MJJ$K   TSSSSS99$:K:KE:R:R:]:]:_:_``

"o&:::QQQQQQQQOOOOOO%8%8Y]%^%^%^"%%e]-JLbcc 0 0"--//
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0  1))%00))++Js   (D		DDc                V   g }|D ]7}t          |d          rt          |d          s|                    |           8t          |          dk    r?d}t          |          D ]\  }}|d| dt	          |           dz  }t          |          | j                            |           dS )	a  
        Makes note of `objects` and will save or load them in during `save_state` or `load_state`.

        These should be utilized when the state is being loaded or saved in the same script. It is not designed to be
        used in different scripts.

        <Tip>

        Every `object` must have a `load_state_dict` and `state_dict` function to be stored.

        </Tip>

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> # Assume `CustomObject` has a `state_dict` and `load_state_dict` function.
        >>> obj = CustomObject()
        >>> accelerator.register_for_checkpointing(obj)
        >>> accelerator.save_state("checkpoint.pt")
        ```
        r	  load_state_dictr   zxAll `objects` must include a `state_dict` and `load_state_dict` function to be stored. The following inputs are invalid:z
	- Item at index z, ``N)r  r  r   r  rC   r   r   extend)r   rs  invalid_objectsr  rn  r  s         r   register_for_checkpointingz&Accelerator.register_for_checkpointingE  s    2  	, 	,C3-- ,WSBS5T5T ,&&s+++!## MC'88 P P
sOeOO8L8LOOOOS//!##G,,,,,r   r   r&   c              #     K   || j         }t          | j        |          }|                                 dV   |j        t          j                      dS )aI  
        Will apply automatic mixed-precision inside the block inside this context manager, if it is enabled. Nothing
        different will happen otherwise.

        A different `autocast_handler` can be passed in to override the one set in the `Accelerator` object. This is
        useful in blocks under `autocast` where you want to revert to fp32.

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator(mixed_precision="fp16")
        >>> with accelerator.autocast():
        ...     train()
        ```
        N)r   rB   r   	__enter____exit__sysexc_info)r   r   r  s      r   autocastzAccelerator.autocasti  sb      & ##4>tP`aa""$$$!!3<>>2222r   r   ProfileKwargs | Nonec              #    K   |p| j         pt                      }|                                5 }|V  ddd           n# 1 swxY w Y   |j        dS t	          j        |j        d           |                    t          j                            |j        t          j
        | j                                       |                                  dS )a	  
        Will profile the code inside the context manager. The profile will be saved to a Chrome Trace file if
        `profile_handler.output_trace_dir` is set.

        A different `profile_handler` can be passed in to override the one set in the `Accelerator` object.

        Args:
            profile_handler (`ProfileKwargs`, *optional*):
                The profile handler to use for this context manager. If not passed, will use the one set in the
                `Accelerator` object.

        Example:

        ```python
        # Profile with default settings
        from accelerate import Accelerator
        from accelerate.utils import ProfileKwargs

        accelerator = Accelerator()
        with accelerator.profile() as prof:
            train()
        accelerator.print(prof.key_averages().table())


        # Profile with the custom handler
        def custom_handler(prof):
            print(prof.key_averages().table(sort_by="self_cpu_time_total", row_limit=10))


        kwargs = ProfileKwargs(schedule_option=dict(wait=1, warmup=1, active=1), on_trace_ready=custom_handler)
        accelerator = Accelerator(kwarg_handler=[kwargs])
        with accelerator.profile() as prof:
            for _ in range(10):
                train_iteration()
                prof.step()


        # Profile and export to Chrome Trace
        kwargs = ProfileKwargs(output_trace_dir="output_trace")
        accelerator = Accelerator(kwarg_handler=[kwargs])
        with accelerator.profile():
            train()
        ```
        NTr   )suffix)r   r5   buildoutput_trace_dirr   r  export_chrome_tracer  r  r^   formatr  r\   )r   r   profilers      r   profilezAccelerator.profile  s     \ *TT-AT]__""$$ 	NNN	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 +3F
O4tDDDD$$GLL9;O;V^b^p;q;q;qrr	
 	
 	
 	     s   ?AAc                .    | j         D ]}|j        r dS dS )z
        Whether or not the optimizer update was skipped (because of gradient overflow in mixed precision), in which
        case the learning rate should not be changed.
        TF)r   step_was_skipped)r   r  s     r   optimizer_step_was_skippedz&Accelerator.optimizer_step_was_skipped  s2     ) 	 	I) ttur   num_batchesc                $    t          ||          S )a@  
        Creates a new `torch.utils.data.DataLoader` that will efficiently skip the first `num_batches`.

        Args:
            dataloader (`torch.utils.data.DataLoader`): The data loader in which to skip batches.
            num_batches (`int`, *optional*, defaults to 0): The number of batches to skip

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> dataloader, model, optimizer, scheduler = accelerator.prepare(dataloader, model, optimizer, scheduler)
        >>> skipped_dataloader = accelerator.skip_first_batches(dataloader, num_batches=2)
        >>> # for the first epoch only
        >>> for input, target in skipped_dataloader:
        ...     optimizer.zero_grad()
        ...     output = model(input)
        ...     loss = loss_func(output, target)
        ...     accelerator.backward(loss)
        ...     optimizer.step()

        >>> # subsequent epochs
        >>> for input, target in dataloader:
        ...     optimizer.zero_grad()
        ...     ...
        ```
        )r  )r   )r   
dataloaderr  s      r   r   zAccelerator.skip_first_batches  s    < "*+FFFFr   c                :    t                               d           | S )Nz]Deep copying the `Accelerator` object, note that this will point to the same original object.)rX  rY  )r   memos     r   __deepcopy__zAccelerator.__deepcopy__  s    stttr   c                    |                                 D ]-}t          |d          rt          |j                  dk    r dS .dS )z{
        Verifies that `model` has not been prepared with big model inference with a device-map resembling `auto`.
        r  r   TF)r  r  r   r  )r   rU  rv  s      r   r  zAccelerator.verify_device_map  sN    
  	 	Aq/** s1?/C/Ca/G/Gttur   r  torch.Tensorr  floatNonec                    t                      rddlm}m} |t	          d          d}| j        D ]6}t          |j        ||f          r|j                            ||           d}7|st	          d          dS )z8
        Runs backward pass on LOMO optimizers.
        r   r  NzSA learning rate must be passed in order to call backward pass with LOMO optimizers.FTzxBackward pass not properly called on LOMO optimizers. Are you sure you passed a LOMO optimizer in accelerator.prepare()?)	rH   r  r  r  r   r   r   r  fused_backward)r   r  r  r  r  _backward_calledr  s          r   r  zAccelerator.lomo_backward  s      	1 10000000 rsss ) 	( 	(I)-g?? (#224GGG#'  	 K  	 	r   c                    | j         dk    r| j        | j        j        S | j        j        | j        j        j        rdS dS )z2Returns the configured backend for training in FP8r   Nr   )rw   r   r   r   r~   enable_msampr  s    r   r   zAccelerator.fp8_backend  sH     5((T-D-P*22Z(49T9a47tr   )$rt   ru   rv   ru   rw   rx   ry   rz   r{   ru   r|   r}   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ru   r   r   r   r   r   r   )r  ru   )F)r,  r-  r.  ru   r  )r1  r2  r  )r1  r2  r  rz   )r1  r2  r  rz   )FN)NF)rU  r  rt   ru   r  ru   )r  r  )r  r  )r  rp   )r  )r  r8  )r   r   F)T)r  ru   )r  r   r?  r  r  r  )r  r   r  ru   )r   r   r   r  r  r  )r  T)rU  r  r  r  r  r  r  ru   )r3  r4  r5  r6  )NT)r>  r   r  ru   )r_  r   )r   r&   )r   r  )r   )r  rz   )rU  r  r5  ru   )r  r  r  r  r5  r  )]r  
__module__r=  __doc___split_batchesr   propertyr~   r  r   r  r  r  r   rv   r  r  setterr  r  r  r   r   r$  r&  r(  r*  rw   r   r0  r7  rB  rE  rH  rK  rM  rP  rR  staticmethodra  rf  ri  ry   rw  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r@   r  rW   rT   r  r\   r  r  r  r  rY   r2  r=  r\  r^  ro  rt  rv  r  r  r  r  r  r  r  r   r  r  r  r   r   r   r   rs   rs      s	       R Rl "&,6:+,<@PT=A6:04gk046:JN.26:59QU'u u u u un	 	+ 	+ X	+ * * X* + + X+ ( ( X( ( ( X( . . X. ! ! X! 4 4 X4 7 7 X7 3 3 X3 4 4 4 4 ; ; X; 3 3 X3   X
 6 6 X6 6 6 X6 4 4 X4 * * X* 0 0 X0 < < X< * * X* ' ' ' ' ^'R% % % % %N( ( ( ( (T% % % %N+ + + + +Z. . . . .`   ^*   ^* & & ^&P -N -N ^ \-N^f f f 2 2 X2 < < < - - X- !'] ] ('] * * ^*X V V V ^Vp* * *   " /3 F8 F8 F8 F8 F8Pp p p p pd" " "Hm m m^e e eN$ $ $L*/ */ */Z fj4$ 4$ 4$ 4$ 4$l* * * * *X' ' ' 'R $  $  $D? ? ?4  B!* !* !* !*F7Y 7Y 7Y 7Yr@ @ @6  @G G G GR"0 "0 "0 "0H!_ !_ !_ !_FE E E E EB  0 EIfh ,9 ,9 ,9 ,9 _,9\+ + + + +@ 37SU O O O O _O:+ + +*
 
 
 
D +1#'pE pE pE pE pEd   @E E E E EN   >H9 H9 H9 H9 H9T  :* * *$     0 0 0"6 6 6 6p"- "- "-H 3 3 3 3 ^34 9! 9! 9! 9! ^9!v   XG G G G G@  	 	 	 	   0   X  r   rs   )
__future__r   rS  r  r#  rd  r   r  rP  r  r   collectionsr   r   r   typesr   typingr   r	   r
   r   torch.utils.hooksr  r8  huggingface_hubr   	packagingr   checkpointingr   r   r   r   r  r   r   r   r   loggingr   r  r   r  r   r   r   r   r   trackingr   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   utils.constantsr]   r^   utils.modelingr_   utils.otherr`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   !torch.distributed.algorithms.joinrn   torch_xla.ampr   r   torch_xla.core.xla_modelcore	xla_modelr  )torch_xla.distributed.xla_multiprocessingdistributedxla_multiprocessingr  	torch_nputorch.optim.lr_schedulerrp   r   rq   r  rX  objectr  _dispatch_batches_even_batches_use_seedable_samplerrs   r   r   r   <module>r     s   # " " " " "           				 				  



  # # # # # # % % % % % %             ' ' ' ' ' ' ' ' ' '  ! ! ! ! ! ! ! ! ! > > > > > >       o o o o o o o o o o o o V V V V V V V V V V # # # # # #       + + + + + + + + + + + + @ @ @ @ @ @ @ @ @ @ K K K K K K K K K K? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?@ H G G G G G G G : : : : : : + + + + + +                 
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 3 2 2 2 2 2  <      )))))))));;;;;;;;; ''' E4444444 E E EDDDDDDDDE 
H		 FHH  w5 w5 w5 w5 w5 w5 w5 w5 w5 w5s   +F2 2G ?G 