U
    0-e8(                    @  sJ  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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  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)m*Z*m+Z+ ddl,m-Z-m.Z.m/Z/ ddlm0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m: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`maZambZbmcZcmdZdmeZe ddlfmgZg ddlhmiZi eQ rNddlmjZjmkZkmlZlmmZmmnZn eR rtd dlomp  mqZr d dlsmtZt eT rddlmuZumvZvmwZwmxZxmyZymzZzm{Z{m|Z|m}Z}m~Z~ d dlmZ eXddrd dlm  mZ d dlm  mZ eUddrd dlZzd dlmZ W n" ek
r.   d dlmZ Y nX e#eZG dd dZdS )    )annotationsN)OrderedDict)contextmanager)partial)
MethodType)AnyCallableUnion   )load_accelerator_stateload_custom_statesave_accelerator_statesave_custom_state)DataLoaderDispatcherprepare_data_loaderskip_first_batches)
get_logger)AcceleratedOptimizer)AcceleratedScheduler)AcceleratorStateGradientStatePartialState)LOGGER_TYPE_TO_CLASSGeneralTrackerfilter_trackers)6
MODEL_NAMESAFE_WEIGHTS_INDEX_NAMESAFE_WEIGHTS_NAMEWEIGHTS_INDEX_NAMEWEIGHTS_NAMEAutocastKwargsDeepSpeedPluginDistributedDataParallelKwargsDistributedTypeDynamoBackendFP8RecipeKwargsFullyShardedDataParallelPluginGradientAccumulationPluginGradScalerKwargsInitProcessGroupKwargsKwargsHandler
LoggerTypeMegatronLMPluginPrecisionTypeProjectConfigurationRNGTypeTorchDynamoPlugincompare_versionsconvert_modelconvert_outputs_to_fp32extract_model_from_parallelgathergather_object#get_mixed_precision_context_managerget_pretty_namehas_transformer_engine_layersid_tensor_storageis_bf16_availableis_deepspeed_availableis_fp8_availableis_ipex_availableis_megatron_lm_availableis_npu_availableis_safetensors_availableis_torch_versionis_tpu_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shard_checkpointwait_for_everyone)FSDP_PYTORCH_VERSION)is_compiled_module)DeepSpeedEngineWrapperDeepSpeedOptimizerWrapperDeepSpeedSchedulerWrapper
DummyOptimDummyScheduler)fp8_autocast)
MegatronEngineMegatronLMDummyDataLoaderMegatronLMDummySchedulerMegatronLMOptimizerWrapperMegatronLMSchedulerWrappermegatron_lm_initializemegatron_lm_prepare_data_loadermegatron_lm_prepare_modelmegatron_lm_prepare_optimizermegatron_lm_prepare_scheduler)JoinF)Zcheck_device)LRScheduler)_LRSchedulerc                   @  s   e Zd ZdZddddddd	d
ddddddddddddddZedd Zedd Zedd Zedd Z	edd  Z
ed!d" Zed#d$ Zed%d& Zed'd( Zed)d* Zed+d, Zed-d. Zed/d0 Zed1d2 Zedd3dd4d5d6Zdd7d8d9d:Zdd7d8d;d<Zd7d8d=d>Zdd7dd?d@dAZdd7ddBdCdDZedEdF ZedGdH ZedIdJ ZeedKdL ZdMdN Z edOdP Z!e!j"dQdP Z!edRdS Z#e#j"dTdS Z#edUdV Z$eddWdXZ%dYdZ Z&dd[d\Z'd]d^ Z(dd_d`daZ)ddbdddcdddeZ*dfdg Z+dhdi Z,djdk Z-ddldmdndoZ.ddpdqdrdsZ/dtdudvdwZ0dxdy Z1dzd{ Z2d|d} Z3dd~dZ4dddZ5dd Z6dd Z7dd Z8dddZ9dddZ:dddddZ;dd Z<edi fddddddZ=ddddddZ>edi fddddddZ?edd Z@dddZAddbddddddZBdddddZCdddddZDdddddZEdddddZFdd ZGdd ZHdd ZIdd ZJdddZKddĄ ZLeddddƜddȄZMeddʄ ZNddd˜dd̈́ZOddτ ZPdbddМdd҄ZQdS )Acceleratora  
    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...).
        split_batches (`bool`, *optional*, defaults to `False`):
            Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. If
            `True` the actual batch size used will be the same on any kind of distributed processes, but it must be a
            round multiple of the `num_processes` you are using. If `False`, actual batch size used will be the one set
            in your script multiplied by the number of processes.
        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.
        deepspeed_plugin (`DeepSpeedPlugin`, *optional*):
            Tweak your DeepSpeed related args using this argument. This argument is optional and can be configured
            directly using *accelerate config*
        fsdp_plugin (`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 (`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 (`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.
        dispatch_batches (`bool`, *optional*):
            If set to `True`, the dataloader prepared by the Accelerator is only iterated through on the main process
            and then the batches are split and broadcast to each process. Will default to `True` for `DataLoader` whose
            underlying dataset is an `IterableDataset`, `False` otherwise.
        even_batches (`bool`, *optional*, defaults to `True`):
            If set to `True`, in cases where the total batch size across all processes does not exactly divide the
            dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among
            all workers.
        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[KwargHandler]`, *optional*)
            A list of `KwargHandler` to customize how the objects related to distributed training or mixed precision
            are created. See [kwargs](kwargs) for more information.
        dynamo_backend (`str` or `DynamoBackend`, *optional*, defaults to `"no"`):
            Set to one of the possible dynamo backends to optimize your training with torch dynamo.
        gradient_accumulation_plugin (`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.
    TFNr
   boolzPrecisionType | str | NoneintzDeepSpeedPlugin | Nonez%FullyShardedDataParallelPlugin | NonezMegatronLMPlugin | Nonezlist[str | RNGType] | NonezRstr | LoggerType | GeneralTracker | list[str | LoggerType | GeneralTracker] | Nonezstr | os.PathLike | NonezProjectConfiguration | Nonez!GradientAccumulationPlugin | Nonezbool | Nonezlist[KwargsHandler] | NonezDynamoBackend | str | None)device_placementsplit_batchesmixed_precisiongradient_accumulation_stepscpudeepspeed_pluginfsdp_pluginmegatron_lm_plugin	rng_typeslog_withproject_dirproject_configgradient_accumulation_plugindispatch_batcheseven_batchesstep_scheduler_with_optimizerkwargs_handlersdynamo_backendc              
   C  s  |d k	r|| _ nt|d| _ |d k	r:| jd kr:| j | |d k	rjt|}|tkrjtd| dt  |d krxt nt|d}|d krt	j
dddkrt nd }nt|tstddt	j
d< |rt std	td
ddrtd|d krt	j
ddn|}|| |  t	j
dddks:t|trTtdtrTtdt |d kr~t	j
dddkrxt nd }nt|tstddt	j
d< |d krt	j
dddkrt nd }nt|tstddt	j
d< |rt stdd | _d | _d | _d | _d | _|d k	r|D ]}t|tsFtd| dt|t rp| jd k	rhtdn|| _nt|t!r| jd k	rtdn|| _n|t|t"r| jd k	rtdn|| _nRt|t#r| jd k	rtdn|| _n(t|t$r&| jd k	rtdn|| _q&| jd k	r0| j% ni }t&f ||||||dd|| _'t(|
| j)}t*|dk r|
d k	rt+,d |
 d! || _-|d"krt.| j'd#d$r| j'j/t0j1krtd%|d k	r|dkrtd&nt2t3d'|}t4|d(}t5|d)| _6| j'j7t0j1kr*| j6j8dkr*td*|| _9|| _:|| _;|| _<|| _=d | _>d$| _?d+}| j'j@d,kr | jAjBd-kr | j7t0jCt0jDfkr d| _?| jAjBd.krt|jEd,d/d0| jd k	r| j% ni }| j7t0jFkrd1d2lGmH} |f || _>n.tI rtJjKjLjMf || _>ntJjNjLjMf || _>nn| j'j@d"kr| j7t0jCt0jDfkr| jAjBd3krXd| _?n
tOd| _?|d"kr| j?stP st|jEd"d4d0d1| _Qg | _Rg | _Sg | _Tg | _Ug | _VtW | _XtW | _Y|	| _Z| jZd krd5g| _Zd | _[d S )6N)rs   zUnknown mixed_precision mode: z. Choose between )backendZACCELERATE_USE_DEEPSPEEDfalsetruezH`deepspeed_plugin` must be an `accelerate.utils.DeepSpeedPlugin` object.zRDeepSpeed is not installed => run `pip install deepspeed` or build it from source.	deepspeed<z0.9.3z<DeepSpeed version must be >= 0.9.3. Please update DeepSpeed.ZACCELERATE_MIXED_PRECISIONnoZACCELERATE_USE_FSDPzFSDP requires PyTorch >= z>`fsdp_plugin` must be a FullyShardedDataParallelPlugin object.ZACCELERATE_USE_MEGATRON_LMz7`megatron_lm_plugin` must be a MegatronLMPlugin object.z7Megatron is not installed. please build it from source.z#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`.T)rk   rm   dynamo_pluginrn   ro   rp   Z_from_acceleratorr
   z
`log_with=z?` was passed but no supported trackers are currently installed.bf16Zdowncast_bfloatFzMCan 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.Z&ACCELERATE_GRADIENT_ACCUMULATION_STEPS)	num_steps)ru   zGradient accumulation is not supported on TPU. Please set `gradient_accumulation_steps` to 1 and don't pass in a `GradientAccumulationPlugin` object.z-{mode} mixed precision requires {requirement}fp16rm   )xpucudaZmpsnpuza GPU)moderequirementr   )ShardedGradScaler)rm   r   z'PyTorch >= 1.10 and a supported device.	generator)\project_configurationr.   rs   Zset_directoriesstrr-   
ValueErrorlistr0   osenvirongetr!   
isinstanceAssertionErrorr<   ImportErrorr1   Zset_mixed_precisionZset_deepspeed_weakrefr&   rB   rQ   	TypeErrorr,   r?   ddp_handlerZscaler_handlerZinit_handlerfp8_recipe_handlerautocast_handlerr*   r"   r(   r)   r%   r    	to_kwargsr   stater   logging_dirlenwarningswarnrr   getattrZdistributedTyper#   TPUrh   rH   r'   r   gradient_statedistributed_typer   ri   rj   rv   rw   rx   scaler
native_amprk   devicetype	DEEPSPEEDMEGATRON_LMformatFSDPZ*torch.distributed.fsdp.sharded_grad_scalerr   r@   torchr   ampZ
GradScalerr   r;   rC   step_optimizers_models_schedulers_dataloaders_custom_objectsr   _load_model_state_pre_hook_save_model_state_pre_hookrq   flag_tensor)selfri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r   handlerkwargstrackerserrr    r   W/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/accelerate/accelerator.py__init__   sT    

 




 












zAccelerator.__init__c                 C  s   | j jS )zP
        Whether the Accelerator is configured for distributed training
        )r   use_distributedr   r   r   r   r     s    zAccelerator.use_distributedc                 C  s   | j jS N)r   r   r   r   r   r   r     s    zAccelerator.distributed_typec                 C  s   | j jS r   )r   num_processesr   r   r   r   r     s    zAccelerator.num_processesc                 C  s   | j jS r   )r   process_indexr   r   r   r   r     s    zAccelerator.process_indexc                 C  s   | j jS r   )r   local_process_indexr   r   r   r   r     s    zAccelerator.local_process_indexc                 C  s   | j jS r   )r   r   r   r   r   r   r     s    zAccelerator.devicec                 C  s   | j jS r   )r   rs   r   r   r   r   rs     s    zAccelerator.project_dirc                 C  s   | j jS r   )r   r   r   r   r   r   r     s    zAccelerator.logging_dirc                 C  s   | j jS r   )r   	iterationr   r   r   r   save_iteration  s    zAccelerator.save_iterationc                 C  s   | j jS )zTrue for one process only.)r   is_main_processr   r   r   r   r     s    zAccelerator.is_main_processc                 C  s   | j jS )z True for one process per server.)r   is_local_main_processr   r   r   r   r     s    z!Accelerator.is_local_main_processc                 C  s   t dt | jdkS )NzThe `use_fp16` property is deprecated and will be removed in version 1.0 of Accelerate use `Accelerator.mixed_precision == 'fp16'` instead.r   )r   r   FutureWarningrk   r   r   r   r   use_fp16	  s
    zAccelerator.use_fp16c                 C  s   | j | jd kS )Nr
   )r   r   r   r   r   r   is_last_process  s    zAccelerator.is_last_processc                 C  s   | j jS r   )r   rk   r   r   r   r   rk     s    zAccelerator.mixed_precisionz"list | tuple | dict | torch.Tensor)inputsapply_paddingc              	   c  s&   t  j||d}|V  W 5 Q R X dS )a  
        Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing
        distributed inference, such as with different prompts.

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

        Args:
            inputs (`list`, `tuple`, `torch.Tensor`, or `dict` of `list`/`tuple`/`torch.Tensor`):
                The input to split between processes.
            apply_padding (`bool`, `optional`, defaults to `False`):
                Whether to apply padding by repeating the last element of the input so that all processes have the same
                number of elements. Useful when trying to perform actions such as `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   r   r   r   r     s    'z#Accelerator.split_between_processeszCallable[..., Any]functionc                   s0    dkr d| j kr|  ntd fd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                    s   t   | |S r   )r   on_main_processargsr   r   r   r   _innerf  s    z+Accelerator.on_main_process.<locals>._inner__qualname__r   r   r   r   r   r   r   r   D  s    
zAccelerator.on_main_processc                   s0    dkr d| j kr|  ntd fd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"
        ```
        Nr   zmThe `on_local_main_process` decorator must be called with a function on an instantiated `Accelerator` object.c                    s   t   | |S r   )r   on_local_main_processr   r   r   r   r     s    z1Accelerator.on_local_main_process.<locals>._innerr   r   r   r   r   r   k  s    
z!Accelerator.on_local_main_processc                   s0    dkr d| j kr|  ntd fd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"
        ```
        Nr   zgThe `on_last_process` decorator must be called with a function on an instantiated `Accelerator` object.c                    s   t   | |S r   )r   on_last_processr   r   r   r   r     s    z+Accelerator.on_last_process.<locals>._innerr   r   r   r   r   r     s    
zAccelerator.on_last_processr   r   c                   sX   | dk	r&dk	r& dkr&t | jdS  dkrFd| jkr>|  ntd fd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   r   r   c                    s   t   | |S r   )r   
on_processr   r   r   r   r     s    z&Accelerator.on_process.<locals>._inner)r   r   r   r   )r   r   r   r   r   r   r   r     s    
zAccelerator.on_processr   r   c                   sX   | dk	r&dk	r& dkr&t | jdS  dkrFd| jkr>|  ntd fd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   r   r   c                    s   t   | |S r   )r   on_local_processr   r   r   r   r     s    z,Accelerator.on_local_process.<locals>._inner)r   r   r   r   )r   r   r   r   r   r   r   r     s     
zAccelerator.on_local_processc              	   c  s    | j   dV  W 5 Q R X 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   r   r   r   r     s    zAccelerator.main_process_firstc              	   c  s    | j   dV  W 5 Q R X 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   r   r   r   r   /  s    z$Accelerator.local_main_process_firstc              	   c  s4   t j}| jrt|d|}|  dV  W 5 Q R X 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contextr   r   r   r   E  s
    "zAccelerator.no_syncc                 c  s\   t | tjjjsdV  dS | j}| j}d| _d| _| jg  z
dV  W 5 || _|| _X dS )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DistributedDataParallelZrequire_backward_grad_syncZrequire_forward_param_syncZreducerZprepare_for_backward)r   Zold_require_backward_grad_syncZold_require_forward_param_syncr   r   r   trigger_sync_in_backwardn  s    
z$Accelerator.trigger_sync_in_backwardc                 C  sP   | j jr$| j jr$d| _| j d n(|  jd7  _| j | j| j j dk dS )zRSets the right `sync_gradients` context and either resets or increases `self.step`r   Tr
   N)r   Zsync_with_dataloaderend_of_dataloaderr   Z_set_sync_gradientsr   r   r   r   r   _do_sync  s
    zAccelerator._do_syncc                 C  s   | j jS r   r   sync_gradientsr   r   r   r   r     s    zAccelerator.sync_gradientsc                 C  s   || j _d S r   r   )r   r   r   r   r   r     s    c                 C  s   | j jS r   )r   r   r   r   r   r   rl     s    z'Accelerator.gradient_accumulation_stepsc                 C  s   | j jd|i d S )Nr   )r   Zplugin_kwargsupdate)r   rl   r   r   r   rl     s    c              	   g  sN   |    t 4}|D ]"}|| jr,t n| | qdV  W 5 Q R X 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 was 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()
        ```
        N)r   r   	ExitStackenter_contextr   r   r   )r   modelsZcm_stackmr   r   r   
accumulate  s
    
 zAccelerator.accumulatec           	   
   c  s  | j tjtjtjfkrg }|dk	rtd}t| jD ]2\}}t|trHd}q0|	||j
jf ||j
_q0|rztd n| j}|rdnd}z$t||dd dV  W 5 Q R X W 5 |D ]\}}|| j| j
_qX n2| j tjkrtd t| dV  W 5 Q R X 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)enableZ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#   	MULTI_GPU	MULTI_NPU	MULTI_XPU	enumerater   r   r   appendZbatch_samplerrw   r   r   rc   NOr   r   )	r   Z	joinablesrw   Zdl_even_batches_valuesZiterable_dl_seenZdl_idxdlZenable_joinZeven_batches_valuer   r   r   join_uneven_inputs  s6    -

zAccelerator.join_uneven_inputsc                 O  s   | j j|| 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   r   r   r   r   r   r   -  s    zAccelerator.printc                 C  s|   |r`t |tjjjr"| j||dS t |tjjr>| j||dS t |tj	j
rx| j||d}|S nt |trx| |}|S |S )Nri   )r   r   utilsdata
DataLoaderr   r   Moduleprepare_modeloptim	Optimizerprepare_optimizerrd   prepare_scheduler)r   obj
first_passri   	optimizer	schedulerr   r   r   _prepare_one<  s    

zAccelerator._prepare_onec              	   G  s  g }|D ]}t |tjjr|} q$qg }g | _g | _g }|D ]}t |tjjrt|j	dkrft
d z|jj| f|jj}W nN tk
r   d|jjkrdd |jj D }|jj| f|}n Y nX | |}|| nt |tjjr| j| || q<|D ]x}t |tr||_t| jD ]>\}	}
t|jdd |
jkr4||	 |j_||	 g|_ qtq4| j| || q|| _t|S )Nr
   zFSDP Warning: When using FSDP, several parameter groups will be conflated into a single one due to nested module wrapping and parameter flattening.differentiablec                 S  s   i | ]\}}|d kr||qS )r  r   .0kvr   r   r   
<dictcomp>d  s       z-Accelerator._prepare_fsdp.<locals>.<dictcomp>r  )r   r   r   r  r   r   r  r  r   param_groupsloggerwarningr  	__class__
parametersdefaultsr   itemsr  r   r   r   r   r   r  
optimizerstuple)r   r   resultr	  r   r  Zintermediate_resultr  r  ioptr   r   r   _prepare_fsdpM  sN    

zAccelerator._prepare_fsdpr   c                  s  |dkrdd |D }n@j tjtjfkr4tdn$t|t|krXtdt| d|D ]B}t|tjj	r\
|r\j tjkr\tjddd	kr\td
q\j tjkrVddlm} d}d}d}|D ]P}t|tjj	r|d7 }t||pt|ot|j|}t|tjjrd}q|dkr6|r6tdn |dkrV|sV|rVtd j tjkrd}|D ]}t|tjj	rl|d7 }ql|dkrtdj tjkrވ \}}	|dk	r|	dk	r||	krtdjoj tjk}
|
sjdkrj| }j tjtjtjfkrjj j!dkrJj"j#rJj$| }n j j!dkrjt% rjj$| }j tjkrj&| }nRj tjkrj'| }n8t(fddt)||D }t(fddt)||D }|
sjdkr.j| fdd|* D }|D ] }t|tjjr|+| qj tjkr\|dkr\|s\|r\j,| }|D ]: t- fddj.j/j0j1fD r`t2 dd q`t|dkr|S |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                 S  s   g | ]}d qS r   r   )r  _r   r   r   
<listcomp>  s     z'Accelerator.prepare.<locals>.<listcomp>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   FullyShardedDataParallelFr
   TzFor FSDP to work with multiple models (>1), prepare must be called for all the models before optimizers are created. Then pass the optimizers to the prepare call in the same order as corresponding models.zzFSDP Warning: When using FSDP, it is efficient and recommended to call prepare for the model before creating the optimizerUYou 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.fp8rm   r   c                 3  s"   | ]\}} j |d |dV  qdS )T)r
  ri   Nr  r  r	  dr   r   r   	<genexpr>  s    z&Accelerator.prepare.<locals>.<genexpr>c                 3  s    | ]\}} j ||d V  qdS )r   Nr)  r*  r   r   r   r,    s     c                   s   i | ]\}}| | qS r   r   r  np)new_named_paramsr   r   r    s      z'Accelerator.prepare.<locals>.<dictcomp>c                 3  s   | ]} |kV  qd S r   r   )r  	container)itemr   r   r,    s   _is_accelerate_prepared)3r   r#   r   r   r   r   r   r   r   r  verify_device_mapr   r   r   r   r   2torch.distributed.fsdp.fully_sharded_data_parallelr&  rR   	_orig_modr  r  r  r  r   r   _get_devicesri   rk   _get_named_parameters	MULTI_CPUr   r   r   r   Zuse_ipex_prepare_ipexrD   _prepare_deepspeed_prepare_megatron_lmr  zipr  Z_switch_parametersr   anyr   r   r   r   setattr)r   ri   r   r	  r   Zmodel_countZoptimizer_presentis_type_fsdpmodel_deviceoptimizer_deviceZtpu_should_fix_optimizerZold_named_paramsr  mappingr   )r2  r0  r   r   prepare{  s    .


	





zAccelerator.prepareztorch.nn.Module)r   ri   evaluation_modec                 C  s  |dkr| j o| jtjk}| j| | |rV| jtjkrVtj	
dddkrVtdt|ddspt|ddrt|d	drt|j }t|d
kr| jtjkrtdt|d }t|tjr|jn|}t|| jkr| jjdk	s|dkrtdd|ksd|kr6tdn|r6| |s6|| j}| jr|j|_t|jdr\|jjn|j}t| j| j}||}	t|jdrt|	||_tt|jj||_n
t|	|_n| j dkrvt!|st"  t#| W 5 Q R X d|_$|j|_| j%dk	r
| j%& ni }
d|
kr,tt'j(|
d |
d< t'j)f |
}tj*+ }|dk}|sbt,-d| d t.||d|j|_|s| jtj/tj0tj1fkrt2dd |3 D r| j4dk	r| j4& ni }
tj	
dddkr| j5g| j5 }}nd\}}tj6j7j8|f||d|
}nr| jtjkr ddl9m:} t||pNt;|oNt|j<|}|s| j=j>?| | j=j>}|j@|jA|jB|jC|jD|jE|jF|jG|jH|jI|jJ| jd}
||f|
}|jKrddlLmM}mN}mO} ||tPjQ||jRd |jBd! t| jd
kr| jd" | jd# kr| jd"= || jd#< nf| jtjSkr\| j4dk	rD| j4& ni }
tj6j7j8|f|
}n*| jtjTkr| j=jUrtVW|| j}| j=jXjYtZjkrt;|st[d$d%std&tj\|f| j=jX& }|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$  Zis_loaded_in_8bitFZis_loaded_in_4bithf_device_mapr
   aM  You can't train a model that has been loaded in 8-bit precision on multiple devices in any distributed mode. In order to use 8-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 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()}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()}rm   ZdiskzYYou can't train a model that has been loaded in 8-bit precision with CPU or disk offload.__func__r(  TZ
fp8_format)   	   z-The current device has compute capability of z which is insufficient for FP8 mixed precision training (requires a GPU Hopper/Ada Lovelace or higher, compute capability of 8.9 or higher). Will use FP16 instead.)enabled
fp8_recipec                 s  s   | ]}|j V  qd S r   )Zrequires_gradr  r/  r   r   r   r,    s     z,Accelerator.prepare_model.<locals>.<genexpr>)NN)
device_idsoutput_devicer%  )sharding_strategycpu_offloadauto_wrap_policyrk   sync_module_statesbackward_prefetchforward_prefetchuse_orig_paramsparam_init_fnignored_moduleslimit_all_gathersZ	device_id)CheckpointImplapply_activation_checkpointingcheckpoint_wrapper)Zcheckpoint_impl)Zcheckpoint_wrapper_fnrQ  z>=z2.0z5Using `torch.compile` requires PyTorch 2.0 or higher.)]ri   r   r#   r   r   r   r4  r   r   r   r   r   r   setrF  valuesr   r   r   r   r   indextor   forwardZ_original_forwardhasattrrG  r7   r   r   r3   rk   r9   Zno_gradr2   Z _converted_to_transformer_enginer   r   	te_recipeZFormatZDelayedScalingr   Zget_device_capabilityr  r   rX   r   r   r   r>  r  r   r   r   r   r   r5  r&  rR   r6  r   ro   Zset_auto_wrap_policyrO  rP  rQ  Zmixed_precision_policyrR  rS  rT  rU  rV  rW  rX  Zactivation_checkpointingZ;torch.distributed.algorithms._checkpoint.checkpoint_wrapperrY  rZ  r[  	functoolsr   ZNO_REENTRANTr9  r   Zfork_launchedxmpZMpModelWrapperr   r{   r$   rB   compile)r   r   ri   rE  Zmodel_devicesZcurrent_deviceZcurrent_device_indexZmodel_forward_funcautocast_contextZnew_forwardr   rK  Zcuda_device_capacityZfp8_enabledrM  rN  r   r@  ro   rY  rZ  r[  r   r   r   r  $  s    
  




 
	&zAccelerator.prepare_modelc                   s  dd l } jj}tdd |D }|jd dks4|r؇ fdd|D }dd |D } jrl fd	d|D }td
d |D rtdt|dkrtd|jrt	|nt
|}t|dkrtd|j d| d n|jd }dd |D }|jdd jd |||jd   j ddd}d }	d }
d }|D ]`}t|tjjrJ|}	nDt|tjjtfrd|}
n*t|ttfst|j|jjjkr0|}q0|
d k	rd|jkrt|
tstdn d|jkrt|
trtdt|
tjjrd|jd< |d k	rPd|jkr$t|ts$tdn,d|jkrPt|trP|jd krPtd|
d k	r|d k	rt|
trt|tstd|	d k	rt|	d rt |	j!d!d rt
|	j!j"nt |	j!d"d }|d k	r|#|| d#| | d$| d% t|
tr|#|
j$|
j%d& t|tr|jd krt |j&d'd d krJt |j&d(d n
|j&j'd( }|#d||j(d) |j)d k	r jst*+|j) j n|j)|d*< |j,f d+di| |j _t-|	 jd,}|
d k	rt|
tr|
j.|d-< t|tr|jd k	r|j|d.< n jd/ /d0i /d1d2d2krf j/d3drfdd4l0m1} d5d6 |
j'2 D }||
j3f|}
|
|d< |d k	rt|tst|j|jjjkr||d.< |j4f |\}}
}}|
d k	rt5|
}
|d k	r|d krt6||
 j7 jd7}n
t8||
}t9t|D ]|}t|| tjjr*|||< nXt|| tjjtfrL|
||< n6t|| ttfszt|| j|jjjkr|||< qt:| _; j<=| |
d k	r j>=|
 |d k	rȈ j?=| t j<dkrt@d8tA|S )9Nr   c                 s  s   | ]}t |tjjjV  qd S r   )r   r   r   r  r  r  r	  r   r   r   r,    s     z1Accelerator._prepare_deepspeed.<locals>.<genexpr>train_micro_batch_size_per_gpuautoc                   s.   g | ]&}t |tjjjr& j|d dn|qS )T)r
  )r   r   r   r  r  r  ri  r   r   r   r"    s   z2Accelerator._prepare_deepspeed.<locals>.<listcomp>c                 S  s   g | ]}t |d r|jqS 
batch_sizerc  rm  ri  r   r   r   r"    s     
 c                   s   g | ]}| j  qS r   )r   )r  rm  r   r   r   r"    s     c                 s  s   | ]}|d kV  qd S r   r   )r  bsr   r   r   r,    s     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 fileor assign integer value to `AcceleratorState().deepspeed_plugin.deepspeed_config['train_micro_batch_size_per_gpu']`.aN  When using DeepSpeed `accelerate.prepare()` requires you to pass at least one of training or evaluation dataloaders or alternatively set an integer value in `train_micro_batch_size_per_gpu` in the deepspeed config fileor assign integer value to `AcceleratorState().deepspeed_plugin.deepspeed_config['train_micro_batch_size_per_gpu']`.r
   RSince you passed both train and evaluation dataloader, `is_train_batch_min` (here % will decide the `train_batch_size` ().c                 S  s   g | ]}|qS r   r   ri  r   r   r   r"    s     rl   F)
must_matchrl         ?)rj  Ztrain_batch_sizeZgradient_clippingz;zero_optimization.stage3_gather_16bit_weights_on_model_saver  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.TZ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`.confighidden_sizeshidden_sizeg?
   )z$zero_optimization.reduce_bucket_sizez-zero_optimization.stage3_prefetch_bucket_sizez4zero_optimization.stage3_param_persistence_threshold)zoptimizer.params.lrzoptimizer.params.weight_decayr  lr)zscheduler.params.warmup_min_lrzscheduler.params.warmup_max_lrz!scheduler.params.warmup_num_stepsz scheduler.params.total_num_stepsrs  )r   Zconfig_paramsZmodel_parameterslr_schedulerzero_optimizationZoffload_optimizerr   noneZzero_force_ds_cpu_optimizer)DeepSpeedCPUAdamc                 S  s   i | ]\}}|d kr||qS ))ry  weight_decayr   r  r   r   r   r  t  s       z2Accelerator._prepare_deepspeed.<locals>.<dictcomp>Zstep_with_optimizerrj   r'  )Br~   r   rn   r>  deepspeed_configrj   r   r   is_train_batch_minminmaxr  infoZ
fill_matchrl   r   r   r   r   r  r  r  rV   rd   rW   r   __name__ZruntimeZlr_schedulesZVALID_LR_SCHEDULESZlr_scheduler_callablerc  r   ru  rv  r   ry  r~  r  r  Zwarmup_num_stepsZtotal_num_stepsmathceilZdeepspeed_config_processdictparamsr   Zdeepspeed.ops.adamr}  r  r  Z
initializerT   r   rx   rU   rangerS   deepspeed_engine_wrappedr   r   r   r   r   r  )r   r   r~   rn   Zis_dataloader_presentr  batch_sizesZbatch_size_per_deviceZconfig_kwargsr   r  r  r	  rw  Zmax_lrr   r}  r  Zenginer!  rz  r  r   r   r   r;    sX   

	








 









zAccelerator._prepare_deepspeedc                 G  s`  | j j}|jsndd |D }t|dkr0td|jr>t|nt|}t|dkrt	d|j d| d n"|D ]}t
|trr|jd	 } qqr| j|j|j  }||| d }d }d }	d
}
d }|D ]f}t
|tjjjr|d krtt|}t
|tjjr|}qt
|tjjr|}qt
|ttfr|}	q|d k	rD||| |d k	rX|| |	d k	rt
|	t}
|
sztd||	 t | |j!d d}g }|D ]|}t
|tjjjr|"t#| | |d7 }nJt
|tr|dkr|$  t#| |}|"||  |d7 }n
|"| q|d k	r.t%| }|d k	rBt&| |}|	d k	rXt'| ||	}	|d k	rpt(| |||	}|d k	rt)|}|	d k	rt*|	|}	t+t|D ]Z}t
|| tjjr|||< n6t
|| tjjr|||< nt
|| tr|	||< q|d k	r| j,"| |d k	r*| j-"| |	d k	r@| j."|	 t| j,dkrXt/dt0|S )Nc                 S  s   g | ]}t |d r|jqS rl  rn  ri  r   r   r   r"    s     
 z4Accelerator._prepare_megatron_lm.<locals>.<listcomp>r   zfYou must specify a training or evaluation dataloader in `accelerate.prepare()` when using Megatron-LM.r
   rp  rq  rr  micro_batch_sizeFzvYou can't use a custom scheduler with Megatron-LM. Please use the `accelerate.utils.MegatronLMDummyScheduler` instead.)Zargs_defaultszWYou can't use same `Accelerator()` instance with multiple models when using Megatron-LM)1r   rp   Zmegatron_dataset_flagr   r   r  r  r  r  r  r   rZ   Zdataset_argsr   Z	tp_degreeZ	pp_degreeZset_training_argsr   r   r  r  nextiterr   r  r  r  rd   r[   Zset_network_size_argsZset_optimizer_typeZset_scheduler_argsr^   Zmegatron_lm_default_argsr   r_   Zset_megatron_data_argsr`   ra   rb   rY   r\   r]   r  r   r   r   r   r  )r   r   rp   r  r  r	  Z	dp_degreer   r  r  Zis_dummy_schedulerZ
batch_datacounterr  Zdataloadersr  r   r   r   r<    s    
























z Accelerator._prepare_megatron_lmc           	      G  s*  t  stdndd l}d }d }dd |D }|D ]*}t|tjjrJ|}q2t|tjjr2|}q2|d k	r|d k	r| j	j
dkrtjntj}| jjdkrt r|| j}tjj|||ddd	\}}n|j|||ddd	\}}tt|D ]<}t|| tjjr|||< qt|| tjjr|||< qt|S )
NzIPEX is not installed or IPEX's version does not match current PyTorch version. Please refer to https://github.com/intel/intel-extension-for-pytorch.r   c                 S  s   g | ]}|qS r   r   ri  r   r   r   r"    s     z-Accelerator._prepare_ipex.<locals>.<listcomp>r   r   TZO1)r  dtypeZinplacelevel)r>   r   Zintel_extension_for_pytorchr   r   r   r  r  r  r   rk   Zbfloat16Zfloat32r   r   rD   ra  r   optimizer  r   r  )	r   r   Zipexr   r  r  r	  r  r  r   r   r   r:    s>        

zAccelerator._prepare_ipexztorch.utils.data.DataLoader)data_loaderc                 C  s   t |ddr&|| jkr"| j| |S |dkrD| jtjkr@| jnd}t|| j| j	| j
| j|| j | j| j|d
}| 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)
        ```
        r3  FN)r   r   rj   Zput_on_devicerq   rv   rw   slice_fn_for_dispatch)r   r   r   r   r#   r   ri   r   r   r   r   rj   rq   copyrv   rw   )r   r  ri   r  Zprepared_data_loaderr   r   r   r   (  s(    
zAccelerator.prepare_data_loaderztorch.optim.Optimizer)r  c                 C  sT   t |ddr&|| jkr"| j| |S |dkr4| j}t||| jd}| 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)
        ```
        r3  FN)ri   r   )r   r   r   ri   r   r   )r   r  ri   r   r   r   r  [  s    
zAccelerator.prepare_optimizerrd   )r  c                 C  sv   t |ddr&|| jkr"| j| |S | j}| jD ]}t |dd|jkr2|} qRq2t||| j| jd}| 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)
        ```
        r3  Fr  Nr  )r   r   r   r   r  r   rx   rj   )r   r  r  r  r   r   r   r  |  s"    

zAccelerator.prepare_schedulerc                 K  st   | j tjkr|| j }| j tjkr4| jj|f| n<| j tjkrDdS | jdk	rd| j|jf | n|jf | 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)
        ```
        N)	r   r#   r   rl   r  backwardr   r   scale)r   Zlossr   r   r   r   r    s    

zAccelerator.backwardc                 C  s   t jd| jd| _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   r   r   r   set_trigger  s    zAccelerator.set_triggerc                 C  sN   | j dkrtjd| jd| _ | | j }| dkrJtjd| jd| _ 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   rJ   r2  )r   r   r   r   r   check_trigger  s    
zAccelerator.check_triggerc                 C  s   | j r| jdkr|dkr | j}nt|ttfs4|g}|D ]L}t|trN|j}q<| jt	j
krxt|}| j|d| j d | j| q8d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   Nrt  )r  )r   rk   r   r   r  r   r   r  r   r#   r   xmZ_fetch_gradientsrJ   r   r   Zunscale_)r   r  r  Z	gradientsr   r   r   unscale_gradients  s    

zAccelerator.unscale_gradients   c                 C  s   | j tjkrV|   dd |D }| jD ]*}|dd | D kr(|||  S q(n| j tjkrfdS |   tj	j
j|||d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                 S  s   g | ]}|qS r   r   rL  r   r   r   r"  @  s     z/Accelerator.clip_grad_norm_.<locals>.<listcomp>c                 S  s   g | ]}|qS r   r   rL  r   r   r   r"  B  s     N)	norm_type)r   r#   r   r  r   r  clip_grad_norm_r   r   r   r   )r   r  Zmax_normr  r   r   r   r   r  %  s    
zAccelerator.clip_grad_norm_c                 C  s6   | j tjtjfk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   r   r   clip_grad_value_)r   r  Z
clip_valuer   r   r   r  K  s    zAccelerator.clip_grad_value_c                 C  s   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])
        ```
        )r5   )r   r  r   r   r   r5   f  s    zAccelerator.gatherc                   s   zt dd |dd d}W n tk
r2   d}Y nX |sBt|}n
 |}zZ jjr jjdkrrtd |W S  jjdkr fd	d
}t ||W S |W S n|W S W n t	k
r   | Y S X dS )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

        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  s   | S r   r   )xr   r   r   <lambda>      z0Accelerator.gather_for_metrics.<locals>.<lambda>T)Zerror_on_other_typeFr]  zcThe used dataset had no length, returning gathered tensors. You should drop the remainder yourself.r   c                   s   | d  j j S r   )r   	remainder)r  r   r   r   _adjust_samples  s    z7Accelerator.gather_for_metrics.<locals>._adjust_samplesN)
rI   r   r6   r5   r   r   r  r  r  r  )r   Z
input_dataZall_tensorsr  r  r   r   r   gather_for_metrics  s,    



zAccelerator.gather_for_metricssumrt  c                 C  s   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])
        ```
        )rJ   )r   r  Z	reductionr  r   r   r   rJ     s    "zAccelerator.reducer   c                 C  s   t ||||d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)rG   )r   r  r  r  r  r   r   r   rG     s    !z Accelerator.pad_across_processes)keep_fp32_wrapperc                 C  s
   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
        ```
        )r4   )r   r   r  r   r   r   unwrap_model	  s    zAccelerator.unwrap_modelc                 C  s
   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)rP   r   r   r   r   rP   ,	  s    zAccelerator.wait_for_everyoner   zdict | None)project_nameru  init_kwargsc              	   C  s   g | _ | jD ]|}tt|tr,| j | qtt| }t|drh| j ||| j	f|
t|i  q| j ||f|
t|i  q|dk	r| j D ]}|| qd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}},
        ... )
        ```
        Zrequires_logging_directoryN)r   rr   
issubclassr   r   r   r   r   r   r   r   Zstore_init_configuration)r   r  ru  r  trackerZtracker_initr   r   r   init_trackersD	  s    

"
zAccelerator.init_trackers)nameunwrapc                 C  sT   t t| dg dkrJ| jD ] }|j|kr|r2|jn|  S qt| dtd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   r   z= is not an available tracker stored inside the `Accelerator`.T)Z_blank)r   r   r   r  r  r   r   )r   r  r  r  r   r   r   get_trackert	  s    

zAccelerator.get_trackerr  z
int | None)r_  r   
log_kwargsc                 C  s0   | j D ]$}|j|fd|i||ji  q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  r   r   r   r  	  s    
zAccelerator.logc                 C  s   | j D ]}|  qdS )a  
        Runs any special end training behaviors, such as stopping trackers on the main process only. 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   finish)r   r  r   r   r   end_training	  s    
zAccelerator.end_trainingc                 C  s   t |||d dS )a6  
        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`

        Example:

        ```python
        >>> from accelerate import Accelerator

        >>> accelerator = Accelerator()
        >>> arr = [0, 1, 2, 3]
        >>> accelerator.save(arr, "array.pkl")
        ```
        safe_serializationN)rL   )r   r	  fr  r   r   r   rL   	  s    zAccelerator.save10GBzUnion[str, os.PathLike]zUnion[int, str])r   save_directorymax_shard_sizer  c              	   C  s  |rt  stdtj|r4td| d dS tj|dd | |}|rt	
t}| D ]$\}}t|tsd|t| | qddd | D }	t }
|	 D ]:}d	}|D ],}||kr|d
7 }|d
kr||= |
| qqt|
d	krtd|
 d |rtnt}t|||d\}}t|D ]}tj||}|dd}|dd}td}||r0tj|r0|| kr0| |dk	r0t! j"r0t#| q0| D ]$\}}| j$|tj|||d q|dkrtj|t}t%d|  nv|rt&nt'}tj||}t(|ddd$}t)j*|dddd }|+| W 5 Q R X t%d| dt| d| 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 `False`):
                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)
        ```
        zR`safe_serialization` requires the `safetensors library: `pip install safetensors`.zProvided path (z#) should be a directory, not a fileNTexist_okc                 S  s"   i | ]\}}t |d kr||qS )r
   )r   )r  Zptrnamesr   r   r   r  
  s       z*Accelerator.save_model.<locals>.<dictcomp>r   r
   zRemoved shared tensor zk while saving. This should be OK, but check by verifying that you don't receive any warning while reloading)r  weights_namez.bin z(.*?)-\d{5}-of-\d{5}r  zModel weights saved in 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 .),rA   r   r   pathisfiler  errormakedirsget_state_dictcollectionsdefaultdictr   r  r   r   r:   r   r^  r_  addr   r  r   r   rO   listdirjoinreplacererg  
startswithkeys	fullmatchr   r   removerL   r  r   r   openjsondumpswrite)r   r   r  r  r  
state_dictZptrsr  r  Zshared_ptrsZ
warn_namesr  foundr  Zshardsr`  filenameZfull_filenameZweights_no_suffixZfilename_no_suffixregZ
shard_fileZshardZpath_to_weightsZsave_index_filer  contentr   r   r   
save_model	  sr    (








zAccelerator.save_modelzCallable[(Ellipsis, None)]zhooks.RemovableHandle)hookreturnc                 C  s   t | 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   r  handler   r   r   register_save_state_pre_hookZ
  s    z(Accelerator.register_save_state_pre_hook
output_dirc                   s  | j jrtj| jd tj dd | j jr fddt D }| j jdk	rt	|d | j jkr| j
rdd	 }|j|d
 tdt	|d | j j  d |dt	|d | j j  D ]}t| qtj d| j  tj rtd  d| j d|   tj dd td   | jtjkrHt  g }t| jD ]\}}| jtjkrtd t| jj| | | td   n| jtj krtd |dkrt! nt! d| }	|j" |	f| tdtj |	  nH| jtj#kr2td |"  td   n|$| j%|dd qVg }
| jtjkr| j&D ]<}td t'| jj| || j|  | td   qbn| jtj tj#fkr| j&}
g }| jtj kr t| j(D ]$\}}t)|t*rq|$| qn| jtj#fkr| j(}| j+, D ]}|| j|  q t- ||
|| jj.| j/}t| j0D ]\}}t1| | qX| j  j2d7  _2|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.
            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                   s   g | ]}t j |qS r   r   r  r  r  folderr  r   r   r"  
  s     z*Accelerator.save_state.<locals>.<listcomp>Nr
   c                 S  s   t tttd| d S Nz[\/]?([0-9]+)(?=[^\/]*$)r   r   maprh   r  findallr  r   r   r   r   
  s    z&Accelerator.save_state.<locals>._innerkeyz	Deleting z- checkpoints to make room for new checkpoint.Z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 )3r   automatic_checkpoint_namingr   r  r  rs   r  r  Ztotal_limitr   r   sortr  r  shutilrmtreer   existsr   rP   r  r   r#   r   r  Z	mark_stepr   r   r   rM   r   ro   r   r   Zsave_checkpointr   r   r  r   rN   r   r   rU   r   r_  r   r   r   r   r   r   )r   r  Zsave_model_func_kwargsfoldersr   r  weightsr  r   ckpt_idr  r  
schedulersr  r  Zsave_locationr	  r   r  r   
save_statez
  s    $

 





     zAccelerator.save_statec                 C  s   t | 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()`
        )r  r  r   r  r  r   r   r   register_load_state_pre_hook
  s    z(Accelerator.register_load_state_pre_hook	input_dirc                   s   dk	r2t j  t j std  dn`| jjrt j| jd  fddt 	 D }dd }|j
|d	 t j |d
  ntdtd   g }t| jD ]\}}| jtjkrtd t| jj| | | td   q| jtjkrVtd |dkrt nt d| }|j |f| tdt j |  q| jtjkrtd |  td   q|| qg }	| jtjkrt| jD ]@\}}
td t| jj| |
| j|  | td   qn| jtjtjfkr| j}	g }| jtjkrTt| jD ]$\}}t|trDq,|| q,n| jtjfkrj| j}| j  D ]}||  qt|!dd}|dkr| j"dkr| jtj#tj$fkrd}nd}t% ||	|| jj&| j'|f| dd t 	 D }t(|t(| j)krRd}|dt(| 7 }|dt(| j) d7 }|d 7 }|d!7 }t*|n8td"t(| d# t| j)D ]\}}t+| | qrd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                   s   g | ]}t j |qS r   r  r  r  r   r   r"  9  s     z*Accelerator.load_state.<locals>.<listcomp>c                 S  s   t tttd| d S r  r  r  r   r   r   r   ;  s    z&Accelerator.load_state.<locals>._innerr  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
   Z	on_devicerm   c                 S  s    g | ]}t d |dk	r|qS )z^custom_checkpoint_\d+\.pkl$N)r  search)r  r  r   r   r   r"    s     zcNumber of custom checkpoints in folder {input_dir} 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),r   r  
expanduserisdirr   r   r  r  rs   r  r  r  r  r   r   r   r#   r   rE   r   ro   r   r   Zload_checkpointr   r   r   rF   r   r   rU   r   r_  popr   r   r   r   r   r   r   r   RuntimeErrorr   )r   r  Zload_model_func_kwargsr  r   r   r  r   r  r  r  r  r  r  r	  Zcustom_checkpointsr   r`  r	  r   r  r   
load_state  s    







zAccelerator.load_statec                 C  s.   g | _ g | _g | _g | _d| _d| _t  dS )aU  
        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)
        >>> accelerator.free_memory()
        >>> del model, optimizer, scheduler
        ```
        Nr   )r   r   r   r   r  r   rK   r   r   r   r   free_memory  s    zAccelerator.free_memoryc                 C  s   |    dS )aN  
        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)
        >>> accelerator.free_memory()
        >>> del model, optimizer, scheduler
        ```
        N)r  r   r   r   r   clear  s    zAccelerator.clearc                 G  s@   i }|D ]2}t |tjjrt|}|dd | D  q|S )Nc                 S  s   i | ]\}}||qS r   r   r-  r   r   r   r    s      z5Accelerator._get_named_parameters.<locals>.<dictcomp>)r   r   r   r  r4   r   named_parameters)r   r   r  r	  r   r   r   r8    s    z!Accelerator._get_named_parametersc                 G  s|   d }d }|D ]f}t |tjjr6| D ]}|j} q6q&t |tjjr|jD ]&}t	|d dkrJ|d d j} qqJq||fS )Nr  r   )
r   r   r   r  r  r   r  r  r  r   )r   r   rA  rB  r	  paramZparam_groupr   r   r   r7    s    
zAccelerator._get_devicesc                 C  st   | j tjkrZ| jd d dkr:| r0| }qXtdqpddlm} || 	|
 }n|rh| 	|}|
 }|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)
        ```
        r{  Z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)r   r#   r   r  Z'zero_gather_16bit_weights_on_model_saveZ$_zero3_consolidated_16bit_state_dictr   Zdeepspeed.checkpoint.utilsr  r  r  )r   r   r  r  r  r   r   r   r    s    

zAccelerator.get_state_dictc                 G  s   g }|D ]"}t |dr t |ds|| qt|dkrpd}t|D ]"\}}|d| dt| d7 }qDt|| 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  Z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)rc  r   r   r   r8   r   r   extend)r   objectsZinvalid_objectsr	  r   r`  r   r   r   register_for_checkpointing	  s    z&Accelerator.register_for_checkpointingr    )cache_enabledr   c                 c  sj   |r0t dt | jdk	r$d| j_ntdd| _|dkr>| j}t| j|}|  dV  |j	t
   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()
        ```
        zPassing `cache_enabled=True` to `accelerator.autocast` is deprecated and will be removed in v0.23.0. Please use the `AutocastKwargs` class instead and pass it to the `Accelerator` as a `kwarg_handler`.NT)r  )r   r   r   r   r  r    r7   r   	__enter____exit__sysexc_info)r   r  r   rh  r   r   r   autocast-  s    

zAccelerator.autocastc                 C  s   | j D ]}|jr dS q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   Zstep_was_skipped)r   r  r   r   r   optimizer_step_was_skippedQ  s    
z&Accelerator.optimizer_step_was_skippednum_batchesc                 C  s   t ||d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   Z
dataloaderr"  r   r   r   r   \  s    zAccelerator.skip_first_batchesc                 C  s   t d | S )Nz]Deep copying the `Accelerator` object, note that this will point to the same original object.)r  r  )r   memor   r   r   __deepcopy__|  s    
zAccelerator.__deepcopy__)r   r  c                 C  s0   |  D ]"}t|drt|jdkr dS qdS )z{
        Verifies that `model` has not been prepared with big model inference with a device-map resembling `auto`.
        rF  r
   TF)modulesrc  r   rF  )r   r   r   r   r   r   r4    s    zAccelerator.verify_device_map)TFNr
   FNNNNNNNNNTTNN)F)N)N)NN)NN)N)FN)NF)NN)N)N)r  )r  rt  )r   r   F)T)F)F)r  F)N)N)T)FN)r   )Rr  
__module__r   __doc__r   propertyr   r   r   r   r   r   rs   r   r   r   r   r   r   rk   r   r   r   r   r   r   r   r   r   r   staticmethodr   r   r   setterrl   r   r   r   r  r   rD  r  r;  r<  r:  r   r  r  r  r  r  r  r  r  r5   r  rJ   rG   r  rP   r  r  r  r  rL   r  r  r  r  r  r  r  r8  r7  r  r  r  r   r   r$  r4  r   r   r   r   rf      s  `                  2 c













)'*'-0


(/	




!R
. * 1 Oe"   3!)!
'
& >
$
#!/ 

   y 
1$#

 rf   )
__future__r   r  r   re  r  r  r   r  r  r  r   r   r   r   typesr   typingr   r   r	   r   Ztorch.utils.hooksr   r  Zcheckpointingr   r   r   r   r  r   r   r   loggingr   r  r   r  r   r   r   r   r   Ztrackingr   r   r   r   r   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   Zutils.constantsrQ   Zutils.otherrR   rS   rT   rU   rV   rW   Z transformer_engine.common.recipecommonZreciperd  Ztransformer_engine.pytorchrX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   Z!torch.distributed.algorithms.joinrc   Ztorch_xla.core.xla_modelcoreZ	xla_modelr  Z)torch_xla.distributed.xla_multiprocessingdistributedZxla_multiprocessingrf  Z	torch_npuZtorch.optim.lr_schedulerrd   r   re   r  r  rf   r   r   r   r   <module>   s\   80