� %�gw���.�ddlmZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddlm Z ddlmZddlmZddlmZmZmZddlZddlmcmZddlmZdd lmZd d lmZmZm Z m!Z!d d l"m#Z#m$Z$m%Z%d d l&m'Z'd dl(m)Z)d dl*m+Z+d dl,m-Z-m.Z.m/Z/d dl0m1Z1m2Z2m3Z3d dlm4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m: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`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZkmlZlmmZmmnZnmoZompZpmqZqmrZrmsZsmtZtmuZumvZvmwZwmxZxmyZymzZzm{Z{m|Z|d dl}m~Z~mZm�Z�m�Z�m�Z�d dl�m�Z�d dl�m�Z�ef��rd dlm�Z�m�Z�m�Z�m�Z�m�Z�m�Z�ei��rd dlm�Z�m�Z�m�Z�m�Z�m�Z�m�Z�m�Z�m�Z�ddl�m�Z�eo��rddl�m�cm�Z�ddl�m�cm�Z�emd���rddl�Z� ddl�m�Z�n#e�$r ddl�m�Z�YnwxYwe'e���Z�e���Z�e���Z�e���Z�e���Z�Gd�d��Z�dS)�)� annotationsN)� OrderedDict)�contextmanager)�partial)� MethodType)�Any�Callable�Union)�"split_torch_state_dict_into_shards)�is_torchao_available�)�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)I� MODEL_NAME�SAFE_WEIGHTS_INDEX_NAME�SAFE_WEIGHTS_NAME�SAFE_WEIGHTS_PATTERN_NAME�WEIGHTS_INDEX_NAME� WEIGHTS_NAME�WEIGHTS_PATTERN_NAME�AORecipeKwargs�AutocastKwargs�DataLoaderConfiguration�DeepSpeedPlugin�DistributedDataParallelKwargs�DistributedType� DynamoBackend�FP8RecipeKwargs�FullyShardedDataParallelPlugin�GradientAccumulationPlugin�GradScalerKwargs�InitProcessGroupKwargs� KwargsHandler� LoggerType�MegatronLMPlugin�MSAMPRecipeKwargs� PrecisionType� ProfileKwargs�ProjectConfiguration�RNGType�TERecipeKwargs�TorchDynamoPlugin�TorchTensorParallelPlugin�apply_fp8_autowrap�check_os_kernel� clean_state_dict_for_safetensors�compare_versions� convert_model�convert_model_to_fp8_ao�convert_outputs_to_fp32�ensure_weights_retied�extract_model_from_parallel�fsdp2_prepare_model�!fsdp2_switch_optimizer_parameters�gather� gather_object�get_fsdp2_grad_scaler�get_grad_scaler�#get_mixed_precision_context_manager�get_pretty_name�has_offloaded_params�is_bf16_available�'is_bitsandbytes_multi_backend_available�is_deepspeed_available�is_ipex_available�is_lomo_available�is_megatron_lm_available�is_mlu_available�is_msamp_available�is_musa_available�is_npu_available�is_torch_version�is_torch_xla_available�is_transformer_engine_available�is_xpu_available�load_fsdp_model�load_fsdp_optimizer�pad_across_processes�parse_choice_from_env�recursively_apply�reduce�release_memory�save�save_fsdp_model�save_fsdp_optimizer�wait_for_everyone)�!BETA_TP_AVAILABLE_PYTORCH_VERSION�&BETA_TP_AVAILABLE_TRANSFORMERS_VERSION�FSDP2_PYTORCH_VERSION�FSDP_PYTORCH_VERSION�PROFILE_PATTERN_NAME)�get_state_dict_offloaded_model)�is_compiled_module)�DeepSpeedEngineWrapper�DeepSpeedOptimizerWrapper�DeepSpeedSchedulerWrapper� DummyOptim�DummyScheduler�map_pytorch_optim_to_deepspeed)�MegatronEngine�MegatronLMDummyDataLoader�MegatronLMDummyScheduler�MegatronLMOptimizerWrapper�MegatronLMSchedulerWrapper�megatron_lm_initialize�megatron_lm_prepare_data_loader�-megatron_lm_prepare_model_optimizer_scheduler)�JoinF)� check_device)� LRScheduler)� _LRSchedulerc�z�eZdZdZdeddddddddddddddddddfd�d*�Zed+���Zed,���Zed-���Z ed.���Z ed/���Z ed0���Z ed1���Z ed2���Zed3���Zed4���Zejd�d6���Zed7���Zed8���Zed9���Zed:���Zed;���Zed<���Zed=���Zed>���Zed?���Zed@���ZedA���Zed�d�dE���Zd�d�dH�Zd�d�dI�Z d�dJ�Z!d�d�dL�Z"d�d�dN�Z#edO���Z$edP���Z%edQ���Z&e'edR�����Z(dS�Z)edT���Z*e*jdU���Z*edV���Z+e+jdW���Z+edX���Z,ed�dY���Z-dZ�Z.d�d[�Z/dd\�d]�Z0d�d�da�Z1db�Z2dc�Z3dd�Z4de�Z5df�Z6dg�Z7dh�Z8 d�d�dk�Z9d�d�dn�Z:d�dq�Z;dr�Z<ds�Z=dt�Z>d�du�Z?d�dw�Z@dx�ZAdy�ZBd�dz�ZCd�d}�ZDd�d�ZEd�d�d��ZFd��ZGedifd�d����ZHd�d�d��ZIedifd�d����ZJd��ZKd�d��ZL d�d�d��ZMd�d��ZNd�d�d��ZOd�d��ZPd�d�d��ZQd��ZRd��ZSdd��d��ZTd��ZUd�d��ZVd��ZWed�d�d����ZXed�d�d����ZYed����ZZd�d�d��Z[d��Z\d�d��Z]d�d��Z^ed����Z_dS)�� Acceleratora� Creates an instance of an accelerator for distributed training or mixed precision training. Args: device_placement (`bool`, *optional*, defaults to `True`): Whether or not the accelerator should put objects on device (tensors yielded by the dataloader, model, etc...). mixed_precision (`str`, *optional*): Whether or not to use mixed precision training. Choose from 'no','fp16','bf16' or 'fp8'. Will default to the value in the environment variable `ACCELERATE_MIXED_PRECISION`, which will use the default value in the accelerate config of the current system or the flag passed with the `accelerate.launch` command. 'fp8' requires the installation of transformers-engine. gradient_accumulation_steps (`int`, *optional*, default to 1): The number of steps that should pass before gradients are accumulated. A number > 1 should be combined with `Accelerator.accumulate`. If not passed, will default to the value in the environment variable `ACCELERATE_GRADIENT_ACCUMULATION_STEPS`. Can also be configured through a `GradientAccumulationPlugin`. cpu (`bool`, *optional*): Whether or not to force the script to execute on CPU. Will ignore GPU available if set to `True` and force the execution on one process only. dataloader_config (`DataLoaderConfiguration`, *optional*): A configuration for how the dataloaders should be handled in distributed scenarios. deepspeed_plugin ([`~utils.DeepSpeedPlugin`] or dict of `str`: [`~utils.DeepSpeedPlugin`], *optional*): Tweak your DeepSpeed related args using this argument. This argument is optional and can be configured directly using *accelerate config*. If using multiple plugins, use the configured `key` property of each plugin to access them from `accelerator.state.get_deepspeed_plugin(key)`. Alias for `deepspeed_plugins`. fsdp_plugin ([`~utils.FullyShardedDataParallelPlugin`], *optional*): Tweak your FSDP related args using this argument. This argument is optional and can be configured directly using *accelerate config* torch_tp_plugin ([`~utils.TorchTensorParallelPlugin`], *optional*): Tweak your torch tensor parallel. This argument is optional and can be configured directly using *accelerate config* megatron_lm_plugin ([`~utils.MegatronLMPlugin`], *optional*): Tweak your MegatronLM related args using this argument. This argument is optional and can be configured directly using *accelerate config* rng_types (list of `str` or [`~utils.RNGType`]): The list of random number generators to synchronize at the beginning of each iteration in your prepared dataloaders. Should be one or several of: - `"torch"`: the base torch random number generator - `"cuda"`: the CUDA random number generator (GPU only) - `"xla"`: the XLA random number generator (TPU only) - `"generator"`: the `torch.Generator` of the sampler (or batch sampler if there is no sampler in your dataloader) or of the iterable dataset (if it exists) if the underlying dataset is of that type. Will default to `["torch"]` for PyTorch versions <=1.5.1 and `["generator"]` for PyTorch versions >= 1.6. log_with (list of `str`, [`~utils.LoggerType`] or [`~tracking.GeneralTracker`], *optional*): A list of loggers to be setup for experiment tracking. Should be one or several of: - `"all"` - `"tensorboard"` - `"wandb"` - `"comet_ml"` If `"all"` is selected, will pick up all available trackers in the environment and initialize them. Can also accept implementations of `GeneralTracker` for custom trackers, and can be combined with `"all"`. project_config ([`~utils.ProjectConfiguration`], *optional*): A configuration for how saving the state can be handled. project_dir (`str`, `os.PathLike`, *optional*): A path to a directory for storing data such as logs of locally-compatible loggers and potentially saved checkpoints. step_scheduler_with_optimizer (`bool`, *optional*, defaults to `True`): Set `True` if the learning rate scheduler is stepped at the same time as the optimizer, `False` if only done under certain circumstances (at the end of each epoch, for instance). kwargs_handlers (list of [`~utils.KwargsHandler`], *optional*) A list of [`~utils.KwargsHandler`] to customize how the objects related to distributed training, profiling or mixed precision are created. See [kwargs](kwargs) for more information. dynamo_backend (`str` or [`~utils.DynamoBackend`], *optional*, defaults to `"no"`): Set to one of the possible dynamo backends to optimize your training with torch dynamo. dynamo_plugin ([`~utils.TorchDynamoPlugin`], *optional*): A configuration for how torch dynamo should be handled, if more tweaking than just the `backend` or `mode` is needed. gradient_accumulation_plugin ([`~utils.GradientAccumulationPlugin`], *optional*): A configuration for how gradient accumulation should be handled, if more tweaking than just the `gradient_accumulation_steps` is needed. **Available attributes:** - **device** (`torch.device`) -- The device to use. - **distributed_type** ([`~utils.DistributedType`]) -- The distributed training configuration. - **local_process_index** (`int`) -- The process index on the current machine. - **mixed_precision** (`str`) -- The configured mixed precision mode. - **num_processes** (`int`) -- The total number of processes used for training. - **optimizer_step_was_skipped** (`bool`) -- Whether or not the optimizer update was skipped (because of gradient overflow in mixed precision), in which case the learning rate should not be changed. - **process_index** (`int`) -- The overall index of the current process among all processes. - **state** ([`~state.AcceleratorState`]) -- The distributed setup state. - **sync_gradients** (`bool`) -- Whether the gradients are currently being synced across all processes. - **use_distributed** (`bool`) -- Whether the current configuration is for distributed training. TNr F�device_placement�bool� split_batches�mixed_precision�PrecisionType | str | None�gradient_accumulation_steps�int�cpu�dataloader_config�DataLoaderConfiguration | None�deepspeed_plugin�3DeepSpeedPlugin | dict[str, DeepSpeedPlugin] | None� fsdp_plugin�%FullyShardedDataParallelPlugin | None�torch_tp_plugin� TorchTensorParallelPlugin | None�megatron_lm_plugin�MegatronLMPlugin | None� rng_types�list[str | RNGType] | None�log_with�Rstr | LoggerType | GeneralTracker | list[str | LoggerType | GeneralTracker] | None� project_dir�str | os.PathLike | None�project_config�ProjectConfiguration | None�gradient_accumulation_plugin�!GradientAccumulationPlugin | None�step_scheduler_with_optimizer�kwargs_handlers�list[KwargsHandler] | None�dynamo_backend�DynamoBackend | str | None� dynamo_plugin�TorchDynamoPlugin | None�deepspeed_pluginsc�R�g|_|�||_nt| ���|_| �!|j�|j�| ��|�>t |��}|t vr&td|�dt j�������|�|�td���|�t|���}n|�t��}|�|�td���|�|}|�ztj ikr5t��j tjkrt��j}n�t"j�dd��d krt)��nd}n�t��j tjkr2tj ikr"t��j�t+d ���t-|t.��r;|���D]&}t-|t(��st3d ����'|���d t"jd<t5��st7d ���t9��r!t;d dd��rt7d���nOt=��r!t;d dd��rt7d���n t;d dd��rt7d���|� t"j�dd��n|}t-|t.��s,|�|��|� d���np|���D]}|�|���tCtE|�������}|� d���d|_#t"j�dd��d kst-|tH��r,tKdtL��stdtL�����t"j�dd��d kst-| tN��rYtKdtP��stdtP�����t;ddtR��stdtR�����|�5t"j�dd��d krtI��nd}n3t-|tH��st3d ���d t"jd<|�7|j*d!kr,tKdtV��st7d"tV�����| �5t"j�dd��d krtO��nd} n3t-| tN��st3d#���d t"jd<| �5t"j�d$d��d krtY��nd} n3t-| tX��st3d%���d t"jd$<| rt[��st7d&���d|_.d|_/d|_0d|_1d|_2d|_3d|_4d|_5d|_6d'|_7tq��}trd(ttd)tvd*txd+tzd,t|d-t~d.t�d/t�d0i }d'|_B|��|D]�}t-|t���sJd1|�d2����|jD|vrtd3|jD�d4����|�E|jD��||jD}t�|||��d5|vr|jBsd|_B��|j0�|j0�G��ni}tdT|||||| | dd6�|��|_H||_I|jId7kr�|jBs�t���r.t��Ld8��t��|_2n�t���r.t��Ld9��t���|_3nKt���r.t��Ld:��t���|_4nt7d;���d'|_O|jBrc|d7kr.|j tjPtjfvrtd<���|jQd=ko|j tjRtjPfv|_Ot�| |jT��}t�|��d>kr| �t�jWd?| �d@���||_X|dAkr?t�|jHdBd'��r)|jHjZtj[krtdC���|�|d>krtdD���n-t�t�dE|����}t�|�F��}t�|�G��|_`||_a|�t���}||_c||_dd|_ed'|_f|jHjgdHkr�|jhjidIkr�|j tjtjjfvr�d|_f|jhjidJvst�d�K��rtdL|jhji�dM����|j/�|j/�G��ni}|jlrt�dTi|��|_e�nt�|j fi|��|_en�|jHjgdAkrt|j tjtjjfvrU|jhjidNvrd|_fnt�d��|_f|dAkr$|jfst���stdO���nr|d7ks|jHjgd7kr\d|_f|jQdPkrJ|j tjPkrt+dQ���|j tjkrt�dTi|��|_edR|_pg|_qg|_rg|_sg|_tg|_ut���|_wt���|_x| |_y|jy�dSg|_yd|_zt���dS)UN)r�zUnknown mixed_precision mode: z. Choose between zVYou cannot pass in both `dynamo_plugin` and `dynamo_backend`, please only pass in one.)�backendzCYou cannot pass in both `deepspeed_plugins` and `deepspeed_plugin`.�ACCELERATE_USE_DEEPSPEED�false�truez�You cannot pass in a `deepspeed_plugin` when creating a second `Accelerator`. Please make sure the first `Accelerator` is initialized with all the plugins you want to use.z4`deepspeed_plugin` must be a DeepSpeedPlugin object.zRDeepSpeed is not installed => run `pip install deepspeed` or build it from source.� deepspeed�<z0.15.2zADeepSpeed MLU version must be >= 0.15.2. Please update DeepSpeed.z0.14.3zBDeepSpeed MUSA version must be >= 0.14.3. Please update DeepSpeed.z0.9.3z<DeepSpeed version must be >= 0.9.3. Please update DeepSpeed.�ACCELERATE_MIXED_PRECISION�noT)�_from_accelerator_state�ACCELERATE_USE_FSDP�>=zFSDP requires PyTorch >= �ACCELERATE_USE_TPzTP requires PyTorch >= � transformers�TP requires transformers >= z>`fsdp_plugin` must be a FullyShardedDataParallelPlugin object.�zFSDP2 requires PyTorch >= z=`torch_tp_plugin` must be a TorchTensorParallelPlugin object.�ACCELERATE_USE_MEGATRON_LMz7`megatron_lm_plugin` must be a MegatronLMPlugin object.z7Megatron is not installed. please build it from source.F� ddp_handler�scaler_handler� init_handler�fp8_recipe_handler�autocast_handler�profile_handler�ao_recipe_handler�te_recipe_handler�msamp_recipe_handlerz#Unsupported kwargs handler passed: z=, must be one that inherits `accelerate.utils.KwargsHandler`.zYou can only pass one z in `kwargs_handlers`.�recipe_handler)r�r�r�r�r�r�r��_from_accelerator�fp8z5Found `torchao` installed, using it for FP8 training.z@Found `transformer-engine` installed, using it for FP8 training.z3Found `msamp` installed, using it for FP8 training.z�Tried to train with `fp8` and auto-detect backend, but no FP8-compatible backend was installed. Valid backends are: `torchao`, `transformer-engine`, and `msamp`.zIPassing in an FP8 configuration requires setting `mixed_precision='fp8'`.�TEr z `log_with=z?` was passed but no supported trackers are currently installed.�bf16�downcast_bfloatzMCan only use `downcast_bf16` when using `mixed_precision='bf16'` and on a TPUz�You can only pass one of `gradient_accumulation_steps` and `gradient_accumulation_plugin`. Please only pass in the created `GradientAccumulationPlugin` object.�&ACCELERATE_GRADIENT_ACCUMULATION_STEPS)� num_steps)r��fp16r�)�xpu�cuda�npu�xla�mlu�musa�hpu�sdaa)� check_is_tpuz)fp16 mixed precision requires a GPU (not �).)r�r�r�zEbf16 mixed precision requires PyTorch >= 1.10 and a supported device.�MSAMPzt`accelerate` + `MS-AMP` + `FSDP` is not supported at this time. Please consider using deepspeed, which is supported.r� generator�)|�trackers�project_configurationr7r��set_directories�strr5� ValueError�listr:r� _shared_state�distributed_typer*� DEEPSPEEDrr��os�environ�getr(�NotImplementedError� isinstance�dict�values� TypeErrorrP� ImportErrorrTr?rV�set_mixed_precision�select�next�iter�deepspeed_engine_wrappedr-rXrjr;rgrh� fsdp_versionrir3rSr�r�r�r�r�r�r�r�r��has_lomo_optimizer�setr)r/r0r,r&r6r%r9r4�has_fp8_handlerr1� __class__�add�setattr� to_kwargs�state�_mixed_precisionr �logger�inforZrU�delayed_fp8_autocast�FSDP� fp8_backend� MULTI_GPUr� logging_dir�len�warnings�warnr��getattr�distributedType�XLAr�r_r.r�gradient_stater�r'r�r��scaler� native_ampr��device�type� MEGATRON_LMrY�is_fsdp2rIrJrN�step� _optimizers�_models� _schedulers� _dataloaders�_custom_objectsr�_load_model_state_pre_hook�_save_model_state_pre_hookr�� flag_tensorr=)�selfr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r��plugin� first_plugin�found_handlers�handler_class_to_attr�handler� handler_attr�kwargsr�s �f/home/asafur/pinokio/api/open-webui.git/app/env/lib/python3.11/site-packages/accelerate/accelerator.py�__init__zAccelerator.__init__sO ��.�� � � %�)7�D� &� &�)=�+�)V�)V�)V�D� &� � "�t�'7�'?� � &� 6� 6�{� C� C� C� � &�!�/�2�2�O��m�3�3� �m�_�m�m�Wd�Wi�Wk�Wk�m�m���� � $��)C��u�v�v� v� � %�-�n�E�E�E�M�M� � "�-�/�/�M� � (�-=�-I��b�c�c� c� � )� 0� � � $��)�R�/�/�L�N�N�4S�Wf�Wp�4p�4p�$4�$6�$6�$H�!�!�*,����8R�T[�)\�)\�`f�)f�)f�O�%�%�%�lp�"�!� ���/�?�3L�L�L�$�2�b�8�8�$�&�&�8�D�)�t�����+�T�2�2� `�/�6�6�8�8�`�`�F�%�f�o�>�>�`�'�(^�_�_�_�`� � (�5;�B�J�1� 2�)�+�+� x�!�"v�w�w�w��!�!� b�#�K��h�?�?�k�%�&i�j�j�j�k�"�$�$� b�#�K��h�?�?�l�%�&j�k�k�k�l�!�+�s�G�<�<� b�!�"`�a�a�a�GV�F]�� ���;�T�B�B�B�cr� ��/��6�6� B�!�5�5�o�F�F�F�!�(�(��(�F�F�F�F�/�6�6�8�8�@�@�F��.�.��?�?�?�?�#�D�):�)A�)A�)C�)C�$D�$D�E�E� ��#�#�D�#�A�A�A�,0�D� )� �:�>�>�/�� 9� 9�V� C� C�z� �7�H �H � C�$�D�*>�?�?� U� �!S�=Q�!S�!S�T�T�T� �:�>�>�-�w� 7� 7�6� A� A�Z� �6�F �F � A�$�D�*K�L�L� `� �!^�;\�!^�!^�_�_�_�#�N�D�:`�a�a� j� �!h�@f�!h�!h�i�i�i� � �46�J�N�N�CX�Za�4b�4b�fl�4l�4l�.�0�0�0�rv� �K��k�+I�J�J� b�� `�a�a�a�06�B�J�,� -� � "�{�'?�1�'D�'D�#�D�*?�@�@� X�!�"V�?T�"V�"V�W�W�W� � "�/1�z�~�~�>Q�SZ�/[�/[�_e�/e�/e�)�+�+�+�ko� �O��o�/H�I�I� a�� _�`�`�`�.4�B�J�*� +� � %�&(�j�n�n�5Q�SZ�&[�&[�_e�&e�&e� �"�"�"�ko� � ��0�2B�C�C� [�� Y�Z�Z�Z�7=�B�J�3� 4� � ]�+�-�-� ]�!�"[�\�\�\� ���"��� ���"&���!%���!%���$(��!� $���#���"'������� )�=� �.� "�N� �1� �.� �,� �/� �/� �5� ! �� %��� � &�*� 0� 0��!�'�=�9�9���A�'�A�A�A���9��$��6�6�$�%g�g�>O�%g�%g�%g�h�h�h��"�"�7�#4�5�5�5�4�W�5F�G� ���l�G�4�4�4�#�|�3�3�D�<P�3�+/�D�(��26�2C�2O��"�,�,�.�.�.�UW��%�  �+��'�.�#�+�1�"�  �  ��  �  �� �!0��� � �E� )� )�$�2F� )�#�%�%� �� � �S�T�T�T�)7�)9�)9��&�&�0�2�2� �� � �^�_�_�_�)7�)9�)9��&�&�#�%�%� �� � �Q�R�R�R�,=�,?�,?��)�)�!�X���� %*��!� � � ��%�'�'��%�o�.B�O�D]�-^�^�^� �!l�m�m�m�(,�(8�D�(@�)�T�EZ��)��$�_�F�D� %� #�8�T�-=�>�>�� �x�=�=�1� � ��!5� �M�p�x�p�p�p� q� q� q� �� ��� &� &��� �$5�u�=�=�'���+��/B�B�B��l�m�m� m� '� 3�*�a�/�/� �v����0� +.�%�&N�Pk�l�l�+�+� '�,F�Pk�+l�+l�+l� (�+�)E� � � ���!1��� � $� 7� 9� 9� �!2���-J��*��� ���� �J� &�&� 0� 0�� � �E�)�)��%�o�.G��Id�-e�e�e�"�D�O��{�� (� � �(�T�:�:�:� �!�!c�T�[�M]�!c�!c�!c�d�d�d�8<�8K�8W�T�(�2�2�4�4�4�]_�F��}� O�3�=�=�f�=�=�� � �-�d�.C�N�N�v�N�N�� � � �Z� '�6� 1� 1�d�6K� � %� � '�T �7 �7 ��{��#8�8�8�"&����"3�D�"9�"9����&�(�(���(�I_�Ia�Ia�(� �!h�i�i�i�� �� %� %���)C�u�)L�)L�"�D�O���7�*�*��(�O�,@�@�@�-�O�����*�o�.G�G�G�"1�";�";�F�";�";�D�K��� ������ �������!���+6�-�-��'�*5�-�-��'�#��� �>� !�)�]�D�N� ���������c��|jjS)a: Returns the currently active DeepSpeedPlugin. If using multiple plugins, the first one will be the active one by default. Manually call `accelerator.state.select_deepspeed_plugin(key)` to activate a different plugin. If deepspeed is not enabled, this will return `None`. )r�r��rs rr�zAccelerator.deepspeed_plugings���z�*�*rc��|jjS)zP Whether the Accelerator is configured for distributed training )r��use_distributedr s rr"zAccelerator.use_distributedss�� �z�)�)rc��|jjS�N)r�r�r s rr�zAccelerator.distributed_typezs ���z�*�*rc��|jjSr$)r�� num_processesr s rr&zAccelerator.num_processes~� ���z�'�'rc��|jjSr$)r�� process_indexr s rr)zAccelerator.process_index�r'rc��|jjSr$)r��local_process_indexr s rr+zAccelerator.local_process_index�s ���z�-�-rc��|jjSr$)r�rr s rrzAccelerator.device�s ���z� � rc��|jjSr$)r�r�r s rr�zAccelerator.split_batches�s���%�3�3rc��|jjSr$)r��dispatch_batchesr s rr/zAccelerator.dispatch_batches�s���%�6�6rc��|jjSr$�r�� even_batchesr s rr2zAccelerator.even_batches�����%�2�2r�valuec��||j_dSr$r1)rr4s rr2zAccelerator.even_batches�s��.3���+�+�+rc��|jjSr$)r��use_seedable_samplerr s rr7z Accelerator.use_seedable_sampler�s���%�:�:rc��|jjSr$)r�� non_blockingr s rr9zAccelerator.non_blocking�r3rc�H�t|jd��r |jjSdS)N�use_stateful_dataloaderF)�hasattrr�r;r s rr;z#Accelerator.use_stateful_dataloader�s*�� �4�)�+D� E� E� B��)�A� A��urc��|jjSr$)r�r�r s rr�zAccelerator.project_dir�����)�5�5rc��|jjSr$)r�r�r s rr�zAccelerator.logging_dir�r>rc��|jjSr$)r�� iterationr s r�save_iterationzAccelerator.save_iteration�s���)�3�3rc��|jjS)zTrue for one process only.)r��is_main_processr s rrDzAccelerator.is_main_process�s���z�)�)rc��|jjS)z True for one process per server.)r��is_local_main_processr s rrFz!Accelerator.is_local_main_process�s���z�/�/rc�(�|j|jdz kS)Nr )r)r&r s r�is_last_processzAccelerator.is_last_process�s���!�T�%7�!�%;�;�;rc��|jjSr$)r�r�r s rr�zAccelerator.mixed_precision�s ���z�)�)rc��|jjSr$)r�r r s rr zAccelerator.is_fsdp2�s ���z�"�"r�inputs�"list | tuple | dict | torch.Tensor� apply_paddingc#�K�t���||���5}|V�ddd��dS#1swxYwYdS)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"] ``` )rMN)r�split_between_processes)rrKrMs rrOz#Accelerator.split_between_processes�s�����N�^�^� 3� 3�F�-� 3� X� X� �\b��L�L�L� � � � � � � � � � � � ���� � � � � � s �8�<�<�function�Callable[..., Any]c�L����d|jvr|�ntd����fd�}|S)aL A decorator that will run the decorated function on the main process only. Can also be called using the `PartialState` class. Args: function (`Callable`): The function to decorate. Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> @accelerator.on_main_process ... def print_something(): ... print("This will be printed by process 0 only.") >>> print_something() "This will be printed by process 0 only" ``` N� Accelerator.�gThe `on_main_process` decorator must be called with a function on an instantiated `Accelerator` object.c�R��t������|i|��Sr$)r�on_main_process��argsrrPs �r�_innerz+Accelerator.on_main_process.<locals>._inner�*���;�<�>�>�1�1�(�;�;�T�L�V�L�L� Lr�� __qualname__r��rrPrYs ` rrVzAccelerator.on_main_process��Z���4 � ���!2�2�2���� �}���� M� M� M� M� M�� rc�L����d|jvr|�ntd����fd�}|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" ``` NrSzmThe `on_local_main_process` decorator must be called with a function on an instantiated `Accelerator` object.c�R��t������|i|��Sr$)r�on_local_main_processrWs �rrYz1Accelerator.on_local_main_process.<locals>._innerDs*���A�<�>�>�7�7��A�A�4�R�6�R�R� Rrr[r]s ` rraz!Accelerator.on_local_main_processs]���: � ���!2�2�2���� �D���� S� S� S� S� S�� rc�L����d|jvr|�ntd����fd�}|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" ``` NrSzgThe `on_last_process` decorator must be called with a function on an instantiated `Accelerator` object.c�R��t������|i|��Sr$)r�on_last_processrWs �rrYz+Accelerator.on_last_process.<locals>._innerkrZrr[r]s ` rrdzAccelerator.on_last_processIr^rr)c����|�����t|j����S��d|jvr|�ntd�����fd�}|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)rSrTc�T��t�������|i|��Sr$)r� on_process)rXrrPr)s ��rrYz&Accelerator.on_process.<locals>._inner�s,���E�<�>�>�,�,�X�}�E�E�t�V�v�V�V� Vr)rrgr\r�)rrPr)rYs `` rrgzAccelerator.on_processps�����: � �=�#<�8�CS��4�?�-�H�H�H� H� � ���!2�2�2���� �}���� W� W� W� W� W� W�� rr+c����|�����t|j����S��d|jvr|�ntd�����fd�}|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+rSrTc�T��t�������|i|��Sr$)r�on_local_process)rXrrPr+s ��rrYz,Accelerator.on_local_process.<locals>._inner�s/���Q�<�>�>�2�2�8�=P�Q�Q�SW�b�[a�b�b� br)rrjr\r�)rrPr+rYs `` rrjzAccelerator.on_local_process�s�����@ � �#6�#B��IY��4�0�FY�Z�Z�Z� Z� � ���!2�2�2���� �}���� c� c� c� c� c� c�� rc#�vK�|j���5dV�ddd��dS#1swxYwYdS)a1 Lets the main process go first inside a with block. The other processes will enter the with block after the main process exits. Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> with accelerator.main_process_first(): ... # This will be printed first by process 0 then in a seemingly ... # random order by the other processes. ... print(f"This will be printed by process {accelerator.process_index}") ``` N)r��main_process_firstr s rrlzAccelerator.main_process_first�s�����&�Z� *� *� ,� ,� � � �E�E�E� � � � � � � � � � � � ���� � � � � � � �.�2�2c#�vK�|j���5dV�ddd��dS#1swxYwYdS)aC Lets the local main process go inside a with block. The other processes will enter the with block after the main process exits. Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> with accelerator.local_main_process_first(): ... # This will be printed first by local process 0 then in a seemingly ... # random order by the other processes. ... print(f"This will be printed by process {accelerator.local_process_index}") ``` N)r��local_main_process_firstr s rroz$Accelerator.local_main_process_first�s�����&�Z� 0� 0� 2� 2� � � �E�E�E� � � � � � � � � � � � ���� � � � � � rmc#�K�tj}|jrt|d|��}|��5dV�ddd��dS#1swxYwYdS)ab A context manager to disable gradient synchronizations across DDP processes by calling `torch.nn.parallel.DistributedDataParallel.no_sync`. If `model` is not in DDP, this context manager does nothing Args: model (`torch.nn.Module`): PyTorch Module that was prepared with `Accelerator.prepare` Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> dataloader, model, optimizer = accelerator.prepare(dataloader, model, optimizer) >>> input_a = next(iter(dataloader)) >>> input_b = next(iter(dataloader)) >>> with accelerator.no_sync(): ... outputs = model(input_a) ... loss = loss_func(outputs) ... accelerator.backward(loss) ... # No synchronization across processes, only accumulate gradients >>> outputs = model(input_b) >>> accelerator.backward(loss) >>> # Synchronization across all processes >>> optimizer.step() >>> optimizer.zero_grad() ``` �no_syncN)� contextlib� nullcontextr"r)r�model�contexts rrqzAccelerator.no_sync�s�����D�(�� � � 9��e�Y��8�8�G� �W�Y�Y� � � �E�E�E� � � � � � � � � � � � ���� � � � � � s�A�A� Ac#�K�t|tjjj��sdV�dS|j}|j}d|_d|_|j�g�� dV�||_||_dS#||_||_wxYw)aTrigger 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��torch�nn�parallel�DistributedDataParallel�require_backward_grad_sync�require_forward_param_sync�reducer�prepare_for_backward)rt�old_require_backward_grad_sync�old_require_forward_param_syncs r�trigger_sync_in_backwardz$Accelerator.trigger_sync_in_backward"s�����<�%���!2�!J�K�K� � �E�E�E� �F�).�)I�&�).�)I�&�,0��(�+/��(� � �*�*�2�.�.�.� N� �E�E�E�/M�E� ,�/M�E� ,� ,� ,��0N�E� ,�/M�E� ,� M� M� M� Ms �$A8�8Bc���|jjr/|jjr#d|_|j�d��dS|xjdz c_|j�|j|jjzdk��dS)zRSets the right `sync_gradients` context and either resets or increases `self.step`rTr N)r�sync_with_dataloader�end_of_dataloaderr �_set_sync_gradientsr�r s r�_do_synczAccelerator._do_syncSs��� � � 3� f��8K�8]� f��D�I� � � 3� 3�D� 9� 9� 9� 9� 9� �I�I��N�I�I� � � 3� 3�T�Y��AT�A^�5^�cd�4d� e� e� e� e� erc��|jjSr$�r�sync_gradientsr s rr�zAccelerator.sync_gradients\s���"�1�1rc��||j_dSr$r�)rr�s rr�zAccelerator.sync_gradients`s��-;���*�*�*rc��|jjSr$)rr�r s rr�z'Accelerator.gradient_accumulation_stepsds���"�,�,rc�H�|jj�d|i��dS)Nr�)r� plugin_kwargs�update)rr�s rr�z'Accelerator.gradient_accumulation_stepshs(�� ��)�0�0�+�?Z�1[�\�\�\�\�\rc'�rK�|���|jp&|jo|jj�dd��}t j��5}|D]?}|�|rt j ��n|� |�����@dV�ddd��dS#1swxYwYdS)a� A context manager that will lightly wrap around and perform gradient accumulation automatically Args: *models (list of `torch.nn.Module`): PyTorch Modules that were prepared with `Accelerator.prepare`. Models passed to `accumulate()` will skip gradient syncing during backward pass in distributed training Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator(gradient_accumulation_steps=1) >>> dataloader, model, optimizer, scheduler = accelerator.prepare(dataloader, model, optimizer, scheduler) >>> for input, output in dataloader: ... with accelerator.accumulate(model): ... outputs = model(input) ... loss = loss_func(outputs) ... loss.backward() ... optimizer.step() ... scheduler.step() ... optimizer.zero_grad() ``` �sync_each_batchFN) r�r�r"rr�r�rr� ExitStack� enter_contextrsrq)r�models�allow_gradient_sync�cm_stack�ms r� accumulatezAccelerator.accumulatels����8 � � ���� � � � �$�T��'�5�9�9�:K�U�S�S� �� !� #� #� �x�� m� m���&�&�CV�'k�z�'=�'?�'?�'?�\`�\h�\h�ij�\k�\k�l�l�l�l� �E�E�E� � � � � � � � � � � � ���� � � � � � s�AB,�,B0�3B0c#�dK�|jtjtjtjtjtjtjtjfvr�g}|�xd}t|j ��D]J\}}t|t��rd}�|� ||jjf��||j_�K|rt!jd��n|j}|rdnd} t%||d���5dV�ddd��n #1swxYwY|D]\}}||j |j_�dS#|D]\}}||j |j_�wxYw|jtjkrt!jd��t)j|��5dV�ddd��dS#1swxYwYdS)a� A context manager that facilitates distributed training or evaluation on uneven inputs, which acts as a wrapper around `torch.distributed.algorithms.join`. This is useful when the total batch size does not evenly divide the length of the dataset. Args: joinables (`list[torch.distributed.algorithms.Joinable]`): A list of models or optimizers that subclass `torch.distributed.algorithms.Joinable`. Most commonly, a PyTorch Module that was prepared with `Accelerator.prepare` for DistributedDataParallel training. even_batches (`bool`, *optional*) If set, this will override the value of `even_batches` set in the `Accelerator`. If it is not provided, the default `Accelerator` value wil be used. <Tip warning={true}> `join_uneven_inputs` is only supported for Distributed Data Parallel training on multiple GPUs. For any other configuration, this method will have no effect. </Tip> <Tip warning={true}> Overidding `even_batches` will not affect iterable-style data loaders. </Tip> Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator(even_batches=True) >>> ddp_model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader) >>> with accelerator.join_uneven_inputs([ddp_model], even_batches=False): ... for input, output in dataloader: ... outputs = model(input) ... loss = loss_func(outputs) ... loss.backward() ... optimizer.step() ... optimizer.zero_grad() ``` NFTzkOverridding even_batches is only supported for map-style datasets, yet some dataloaders given were iterable)�enable�throw_on_early_terminationzuJoining uneven inputs is only supported for multi-GPU training, as a result `join_uneven_inputs` will have no effect.)r�r*r�� MULTI_NPU� MULTI_MLU� MULTI_SDAA� MULTI_MUSA� MULTI_XPU� MULTI_HPU� enumeraterr�r�append� batch_samplerr2r�rr|�NOrrrs) r� joinablesr2�dl_even_batches_values�iterable_dl_seen�dl_idx�dl� enable_join�even_batches_values r�join_uneven_inputszAccelerator.join_uneven_inputs�s�����Z � � � %� � %� � %� � &� � &� � %� � %�% � � �&(� "��'�#(� �"+�D�,=�">�">�A�A�J�F�B�!�"�&:�;�;�!�+/�(� �*�1�1�6�2�;K�;X�2Y�Z�Z�Z�4@�B�$�1�1�#���M�F����� $�0� �#/�9�%�%�T�K� ^��)�K�TY�Z�Z�Z����E�E�E�������������������3I�^�^�.�F�.�K]�D�%�f�-�;�H�H�^�^��2H�^�^�.�F�.�K]�D�%�f�-�;�H�H�^�����$��(:�:�:�� �L�����'� �2�2� � ����� � � � � � � � � � � � ���� � � � � � sB�#D2�5D�: D2�D � D2� D �D2�2!E�F%�%F)�,F)c�*�|jj|i|��dS)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)rrXrs rr�zAccelerator.print�s$�� �� ��$�)�&�)�)�)�)�)rc��|r�t|tjjj��r|�||���St|tjj��r|�||���St|tj j ��r|� ||���}|Sn,t|t��r|� |��}|S|S)N�r�)r�rw�utils�data� DataLoaderrrx�Module� prepare_model�optim� Optimizer�prepare_optimizerr~�prepare_scheduler)r�obj� first_passr�� optimizer� schedulers r� _prepare_onezAccelerator._prepare_ones��� � ��#�u�{�/�:�;�;� !��/�/��FV�/�W�W�W��C����1�1� !��)�)�#�@P�)�Q�Q�Q��C���!6�7�7� !� �2�2�3�IY�2�Z�Z� � � � !���[� )� )� ��.�.�s�3�3�I�� �� rr�c�8 ����|� d�|D��}nn�jtjtjfvrt d���t |��t |��kr t dt |���d����|D]~}t |tjj ��r]�� |��rH�jtj kr3tj �dd��dkrt d �����jtjkr@d }|D]&}t |tjj ��r|d z }�'|d krtd ����jtjkr0����\}}|�|�||krt d ����jryd }d }|D]K}t |tjj ��r|d z }�'t |tjj��r|d z }�L|d kr|d ks |d kr|d krt d����jo�jtjk}�j} |p| } | r �j|d| i�} | r�|D]�}t |tjj��rg|jD]_} t1| d��D]G\} }tj|��| d| <|���| d| _�H�`���jtjtjtj fvr6�jjdks�jjdkr�jj r �j!|�}�j"dkr �j#|�}n�j"dkr �j$|�}�jtjkr �j%|�}n��jtjkr �j&|�}nm�j"dkr�j'|d|i�\}}tQ�fd�tS||��D����}tQ�fd�tS||��D����}| r��j|��| r/�jj*j+rd���,��D����fd�| �,��D��}|D]I}t |tjj��r(| s|�-|���9t]||���J|D]<�t_�fd��j0�j1�j2�j3fD����rd�_4�=t |��d kr|n|d S)a Prepare all objects passed in `args` for distributed training and mixed precision, then return them in the same order. Args: *args (list of objects): Any of the following type of objects: - `torch.utils.data.DataLoader`: PyTorch Dataloader - `torch.nn.Module`: PyTorch Module - `torch.optim.Optimizer`: PyTorch Optimizer - `torch.optim.lr_scheduler.LRScheduler`: PyTorch LR Scheduler device_placement (`list[bool]`, *optional*): Used to customize whether automatic device placement should be performed for each object passed. Needs to be a list of the same length as `args`. Not compatible with DeepSpeed or FSDP. <Tip> You don't need to prepare a model if you only use it for inference without any kind of mixed precision </Tip> Examples: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> # Assume a model, optimizer, data_loader and scheduler are defined >>> model, optimizer, data_loader, scheduler = accelerator.prepare(model, optimizer, data_loader, scheduler) ``` ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> # Assume a model, optimizer, data_loader and scheduler are defined >>> device_placement = [True, True, False, False] >>> # Will place the first two items passed in automatically to the right device but not the last two. >>> model, optimizer, data_loader, scheduler = accelerator.prepare( ... model, optimizer, data_loader, scheduler, device_placement=device_placement ... ) ``` Nc��g|]}d��Sr$r�)�.0�_s r� <listcomp>z'Accelerator.prepare.<locals>.<listcomp>Cs��3�3�3���3�3�3rzDYou 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}}`.rr zUYou can't use same `Accelerator()` instance with multiple models when using DeepSpeeda~The model and the optimizer parameters are not on the same device, which probably means you created an optimizer around your model **before** putting on the device. Make sure the line model.to(device) is before the optimizer creation in your script or remove it entirely and use the flag default value for `device_placement` in your `Accelerator` to let it handle that part for you.z�When using FSDP2, a model and optimizer must be passed together to `Accelerator.prepare()` as the optimizer needs to have its parameters modified after the model is converted.� drop_refs�paramsr�r�r��AOr�r�c3�N�K�|]\}}��|d|���V�� dS)T)r�r�N�r��r�r��drs �r� <genexpr>z&Accelerator.prepare.<locals>.<genexpr>�sO�������PV�PS�UV��!�!�#�$��!�K�K������rc3�L�K�|]\}}��||���V��dS)r�Nr�r�s �rr�z&Accelerator.prepare.<locals>.<genexpr>�s:�����r�r�&�#�q�4�,�,�S�1�,�E�E�r�r�r�r�r�rrc�B�i|]\}}|�dd��|��S)z._checkpoint_wrapped_module�)�replace�r��k�vs r� <dictcomp>z'Accelerator.prepare.<locals>.<dictcomp>�s:��$�$�$�HL��1�A�I�I�;�R�@�@�!�$�$�$rc�(��i|]\}}|�|��Sr�r��r��n�p�new_named_paramss �rr�z'Accelerator.prepare.<locals>.<dictcomp>�s%���S�S�S�$�!�Q�q�*�1�-�S�S�Src3� �K�|]}�|vV�� dSr$r�)r�� container�items �rr�z&Accelerator.prepare.<locals>.<genexpr>�s<��������� �!������rT)5r�r*r�r r�r�r�rwrxr��verify_device_mapr�r�r�r��AssertionErrorr� _get_devicesr r�r�r��_get_named_parameters� param_groupsr�� empty_like�data_ptr� MULTI_CPUr�rrr��use_ipex� _prepare_ipexr�� _prepare_te� _prepare_ao�_prepare_deepspeed�_prepare_megatron_lm�_prepare_msamp�tuple�zipr��activation_checkpointing�items�_switch_parametersrF�anyrr r r�_is_accelerate_prepared)rr�rXr�� model_count� model_device�optimizer_device�optimizer_count�tpu_should_fix_optimizer�fsdp2_should_fix_optimizer�should_fix_optimizer�old_named_params� param_group�ir��result�mappingr�r�s` @@r�preparezAccelerator.preparesV�����\ � #�3�3�d�3�3�3� � � � "��'@�/�B]�&^� ^� ^��c�d�d� d� �!� "� "�c�$�i�i� /� /��p�C��I�I�p�p�p��� �� � �C��3����0�0� ��*�*�3�/�/� ��)�_�-?�?�?��J�N�N�#A�7�K�K�v�U�U� �~����� � �O�$=� =� =��K�� %� %���c�5�8�?�3�3�%��1�$�K���Q���$�k���� � �O�$7� 7� 7�-1�->�->�-@�-@� *�L�*��'�,<�,H�\�]m�Mm�Mm� �$���� �=� ��K��O�� )� )���c�5�8�?�3�3�)��1�$�K�K���U�[�%:�;�;�)�#�q�(�O���a���O�a�$7�$7�[�1�_�_�Q`�cd�Qd�Qd� �l���� $(�#8�#i�T�=R�Ve�Vi�=i� �%)�]�"�7�U�;U�� � �9�t�9�� �!;� � � � &� M�� M� M���c�5�;�#8�9�9�M�'*�'7�M�M� �$-�k�(�.C�$D�$D�M�M�D�A�q�8=�7G��7J�7J�K��1�!�4�@A� � � � �K��1�!�4�=�=� M�� � �_�%>��@Y�[j�[m�$n� n� n�� � �E�)�)�T�[�-=��-F�-F�D�J�L_�-F�)�t�)�4�0�� � �t� #� #�#�4�#�T�*�D�D� � �� %� %�#�4�#�T�*�D� � �O�$=� =� =�,�T�,�d�3�F�F� � "�o�&A� A� A�.�T�.��5�F�F���7�*�*�)<��)<�d�)f�Ue�)f�)f�&��&������Z]�^b�dt�Zu�Zu������F��r�r�r�r�TW�X^�`p�Tq�Tq�r�r�r�r�r�F� � H�9�t�9�6�B� �)� �d�j�.D�.]� �$�$�P`�Pf�Pf�Ph�Ph�$�$�$� �T�S�S�S�:J�:P�:P�:R�:R�S�S�S�G�� H� H���c�5�;�#8�9�9�H�5�H��.�.�w�7�7�7�7�9�#�w�G�G�G��� 4� 4�D������"&�"3�T�\�4�CS�UY�Ue�!f������ 4�04��,���V���q���v�v�f�Q�i�7rrt�torch.nn.Module�evaluation_modec �B�|�|jo|jtjk}|j�|��|�|��rH|jtjkr3tj � dd��dkrtd���|j r�|j |_t|j |j��}|jdkst%|j d��s%|j }t'||����|_ nX|j j}||��}t+||��|_ t+t'|j j��|��|_ |jdkr#|jst/||jp|j��}t5|d d ��st5|d d ���rt5|d d ���rmt7|j�����}t=|��d kr$|jtjkrtd���t=|��d kr�t?|��d}tA|tBj"��r|j#} n1tA|tH��rtCj"|��j#} n|} |j"j%dkrtM��rn>tCj"| ��|j"kr!|j"j#�| dkrtd���d|vrtM��rd|vrtO��sd|vrtd���n1|r/|�|��s|�(|j"��}|�s�|jtj)tj*tj+tj,tj-tj.tj/fvr�tad�|�1��D����r�|j2�|j2�3��ni} tj � dd��dkr:|j"j%dkr|j"j#g|j"j#} } n|j4g|j4} } nd\} } tCj5j6j7|f| | d�| ��}|j2�|j2�8|���nt|jtj9krt%|d��rC|j:s<twddtx��stdtx�����t{d���|�>|j?j@jAd���n�|jBrVt�||��}t=|j��d kr"|jd|jdur|jd=||jd<�n�|jtjk�r�dd lDmE} tA|| ��p#t�|��otA|jG| ��}|s�|j?jH�I|��|j?jH}t�|jK||j"��|_K|jLp|jM|jN|jO|jP|jQ|jR|jS|jT|jK|jU|jV|j"d!� } | |fi| ��}|jWr6dd"lXmY}mZ}m[}||t�j]||j^�#��|jO�$��|j_d%k�r;g}| �`|��D]�}|jas� |jb}|jctBjdkr�|j"tCj"d&��kr�|jer�|jfjgjhd'�i|jbjj��f}||vr|�|��|jk�(tBjd��|_ktBjd|jl_m��|jnrJ|D] \}}t�jpd(|�d)|�d*����!t=|��dkrt�jpd+��t=|j��d kr"|jd|jdur|jd=||jd<n�|jtjqkr`|j2�|j2�3��ni} tCj5j6j7|fi| ��}|j2�|j2�8|��nM|jtjrkr8|j?jsr,t�ju|���(|j"��}|jrt/||jp|j��}|j?jvjwt�jkr=t�|��s.tCjy|fi|j?jv�3����}|S),a� Prepares a PyTorch model for training in any distributed setup. It is recommended to use [`Accelerator.prepare`] instead. Args: model (`torch.nn.Module`): A PyTorch model to prepare. You don't need to prepare a model if it is used only for inference without any kind of mixed precision device_placement (`bool`, *optional*): Whether or not to place the model on the proper device. Will default to `self.device_placement`. evaluation_mode (`bool`, *optional*, defaults to `False`): Whether or not to set the model for evaluation only, by just applying mixed precision and `torch.compile` (if configured in the `Accelerator` object). Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> # Assume a model is defined >>> model = accelerator.prepare_model(model) ``` Nr�r�r�r�r��__func__r��is_loaded_in_8bitF�is_loaded_in_4bit� hf_device_mapr a_You can't train a model that has been loaded in 8-bit or 4-bit precision on multiple devices in any distributed mode. In order to use 8-bit or 4-bit models that have been loaded across multiple GPUs the solution is to use Naive Pipeline Parallelism. Therefore you should not specify that you are under any distributed regime in your accelerate config.rr�a$You can't train a model that has been loaded in 8-bit or 4-bit precision on a different device than the one you're training on. Make sure you loaded the model on the correct device using for example `device_map={'':torch.cuda.current_device()}` or `device_map={'':torch.xpu.current_device()}`�diskaYou can't train a model that has been loaded in 8-bit or 4-bit precision with CPU or disk offload. If you want train the 8-bit or 4-bit model in CPU, please install bitsandbytes with multi-backend, see https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backendc3�$K�|] }|jV�� dSr$)� requires_grad�r�r�s rr�z,Accelerator.prepare_model.<locals>.<genexpr>0s$����C�C�1�q��C�C�C�C�C�Crr��NN)� device_ids� output_device�supports_tp_planr�r�r�z�Provided model does not support tensor parallelism. Tensor parallelism plan can be added as base_model_tp_plan to model config class and _tp_plan attribute to model class.�tp������������FullyShardedDataParallel) �sharding_strategy� cpu_offload�auto_wrap_policyr��sync_module_states�backward_prefetch�forward_prefetch�use_orig_params� param_init_fn�ignored_modules�limit_all_gathers� device_id)�CheckpointImpl�apply_activation_checkpointing�checkpoint_wrapper)�checkpoint_impl)�checkpoint_wrapper_fnrr��metaz, z%Upcasted low precision parameters in z5 because mixed precision turned on in FSDP. Affects: �.zVFSDP upcast of low precision parameters may affect the precision of model checkpoints.)zr�r�r*r�r r�r�r�r�r�r�r�r�forward�_original_forwardrKr�r�r<rBrrr�r<r�r�rr�rr�r�r�r�rwr�indexr�rrOr[�tor�r�r�r�r�r�r�r�� parametersr�r�r+rxryrz�register_comm_hook�TPrr?rhr��tensor_parallelr�r��torch_device_meshr rE�2torch.distributed.fsdp.fully_sharded_data_parallelrrm� _orig_modr��set_auto_wrap_policyrCrr�reshard_after_forwardrr�mixed_precision_policyrrrrrrr��;torch.distributed.algorithms._checkpoint.checkpoint_wrapperr r!r"� functoolsr� NO_REENTRANTr�� fsdp_modules� _has_params� _flat_param�dtype�float32r �moduler��__name__�join�_fqnsr��_handle�_orig_param_dtyperDr�rr�r� fork_launched�xmp�MpModelWrapperr�r�r+�compile)rrtr�r�autocast_context�model_forward_func� new_forward� model_devices�current_device�current_device_indexrr rr�� is_type_fsdpr�r r!r"� upcasted_logr=�param�name_param_log�name_log� param_logs rr�zAccelerator.prepare_model�sZ ��2 � #�#�4�f��9N�Ra�Rf�9f� � � ���E�"�"�"� � "� "�5� )� )� ��%��);�;�;�� ���=�w�G�G�6�Q�Q��z��� � �?� c�&+�m�E� #�B�4�?�TX�Ti�j�j� ���7�*�*�'�%�-��2T�2T�*�%*�]�"� 7�8H�8H�I[�8\�8\� ]� ]�� � �%*�]�%;�"�.�.�/A�B�B� � *�;�� >� >�� � *�+B�5�=�CY�+Z�+Z�\a� b� b�� � � �t� #� #�D�,E� #�&�u�d�.D�._��H_�`�`�E� �E�.�� 6� 6�' *�'�%�I\�^c�:d�:d�' *�jq� �?�E�k �k �' *� �� 3� :� :� <� <�=�=�M��=�!�!�A�%�%�$�*?�?�CU�*U�*U� �}���� �]�#�#�q�(�(�!%�m�!4�!4�Q�!7���n�e�l�;�;�:�+9�+?�(�(����4�4�:�+0�<��+G�+G�+M�(�(�+9�(��;�#�u�,�,�1X�1Z�1Z�,���\�"6�7�7�4�;�F�F�� �)�5�;O�ST�;T�;T�(�W���� �-�'�'�0W�0Y�0Y�'��]�*�*�/?�/A�/A�*��]�*�*� �I����+� � *�d�&<�&<�U�&C�&C� *��H�H�T�[�)�)�E��q B��$��)��)��*��*��)��)��)�)����C�C��0@�0@�0B�0B�C�C�C�C�C�C�=A�=M�=Y�T�-�7�7�9�9�9�_a�F��z�~�~�&D�g�N�N�RX�X�X��;�+�u�4�4�9=��9J�8K�T�[�M^� �J�J�9=�9Q�8R�TX�Tl� �J�J�4>�1� �M�!�H�-�E���*4�M���U[���E��'�3��(�;�;�E�B�B�B���&�/�*<�<�<��5�"4�5�5��e�>T��+�N�D�Bh�i�i�r�(�)p�Hn�)p�)p�q�q�q�-�@���� �%�%�d�j�&@�&R�SW�&X�Y�Y�Y�Y���M B�+�D�%�8�8���t�|�$�$�q�(�(�d�l�2�.>�$�,�r�BR�.R�.R�� �R�(�#(�� �R� � ��&�/�*>�>�>�o�o�o�o�o�o� *�%��6�6� �&�u�-�-�S�*�U�_�d�2S�2S��$�,��J�*�?�?��F�F�F�"&�*�"8�K�1F�#�1��� �1�1�K�-�.9�-J�-o�k�No�'2�'>�,7�,H�+6�+M�.9�.L�-8�-J�,7�,H�+6�+F�)4�)B�+6�+F�-8�-J�%)�[���F�"!�D��1�1�&�1�1�E�"�;������������ 7�6�!�2;�2C� 2�0>�0K�3�3�3�.9�-I� ����&�'�4�/�/�#%�L�"&�"3�"3�E�":�":�&M�&M��( &�1�%�$� &� 2��!�K�5�=�8�8� %� �� �V�0D�0D� D� D� %� 3�!E� /5�m�.E�.N�PT�PY�PY�Z`�Zl�Zr�Ps�Ps�-t�N�-�\�A�A� ,� 3� 3�N� C� C� C� */����u�}�)E�)E�E�J�?D�}�F�N�<���+� �3?���/�H�i�$�M�!9��!9�!9�,5�!9�!9�!9����� �|�,�,�q�0�0�$�M� x���� �t�|�$�$�q�(�(�d�l�2�.>�$�,�r�BR�.R�.R�� �R�(�#(�� �R� � ��&�/�*C�C�C�9=�9I�9U��)�3�3�5�5�5�[]����)�A�%�R�R�6�R�R���#�/��$�7�7��>�>�>���&�/�*=�=�=�$�*�BZ�=��*�5�1�1�4�4�T�[�A�A�� � $� a�&�u�d�.D�._��H_�`�`�E� �:� #� +�}�/?� ?� ?�HZ�[`�Ha�Ha� ?��M�%�P�P�4�:�+C�+M�+M�+O�+O�P�P�E�� rc���t��std���|D]G}t|tjj��r&t ||jj|jj ����H|S)Nzu`torchao` was not found on your system or is too old of a version. Please ensure that `torchao >= 0.6.1` is installed)�config�module_filter_func) r r�r�rwrxr�rAr�rTrU)rrX�args rr�zAccelerator._prepare_ao�s���#�%�%� ��H��� �� � �C��#�u�x��/�/� �'���1�8�'+�'=�'P������ � rc��� � �t��std���d\}}d\}}d�|D��}|D]O}t|tjj��r|}|dz }�)t|tjj��r|}|dz }�P|�|�|S|�|�td���|dks|dkrtd|�d|�d ����|� |��}tj ��5t|��ddd��n #1swxYwY|� |��� � fd �|� ��D��� |j D]} � fd �| d D��| d <�|S) Nzg`transformer_engine` was not found on your system. Please ensure that `transformer_engine` is installedr �rrc��g|]}|��Sr�r��r�r�s rr�z+Accelerator._prepare_te.<locals>.<listcomp>����&�&�&�#�#�&�&�&rr zgYou must pass a model and an optimizer together to `accelerate.prepare()` when using TransformerEngine.�You can't use multiple models (�) or optimizers z with TransformerEngine.c�(��i|]\}}|�|��Sr�r�r�s �rr�z+Accelerator._prepare_te.<locals>.<dictcomp> s%���O�O�O�d�a��1�&�q�)�O�O�Orc� ��g|] }�|�� Sr�r�)r�r�r�s �rr�z+Accelerator._prepare_te.<locals>.<listcomp>s���$O�$O�$O�A�W�Q�Z�$O�$O�$Orr�)rZr�r�rwrxr�r�r�r�r��no_gradr@r�r�) rrXrtr�� num_models�num_optimizersr�r�r�r�r�r�s @@rr�zAccelerator._prepare_te�s����.�0�0� ��y��� �&���y�%)�"� �N�&�&��&�&�&��� $� $�C��#�u�x��/�/� $����a�� � ��C�%�+�"7�9�9� $�� ��!�#��� � ����M� � �%�-��y��� ��!�^�^�~��1�1��v�*�v�v�n�v�v�v��� � �5�5�e�<�<�� �]�_�_� !� !� �%� � � � !� !� !� !� !� !� !� !� !� !� !���� !� !� !� !��5�5�e�<�<��O�O�O�O�6F�6L�6L�6N�6N�O�O�O��$�1� P� P�K�$O�$O�$O�$O��X�9N�$O�$O�$O�K�� !� !�� s�+D�D �D c� ���ddl}|j}�jdkr ddlm}|j}�j�t d�|D����}�j�di���dd��}|dkrktdd d ��std ���td d ��std ���ddl m }d}|�j j|f|f����j_�fd�|D��} ��d��r�|r�d�|D��} t d�| D����rt%d����jr�fd�| D��} �jrt+| ��nt-| ��} t/| ��dkr&t0�d�j�d| �d���n$t%d�����d��} ��dd�j���ddd�} | �(| | d<| ��d��z�jz| d <d} d}d}| D]�}t=|t>j j!��r|} �$t=|t>j"j#tHf��r|}�Mt=|tJtLf��s%t|��j'|j(j)j*vr|}��|��d!�jvr$t=|tH��st%d"���d!�jvr$t=|tH��rt%d#���t=|t>j"j#��r d$�jd%<|�ad&�jvr$t=|tL��st%d'���d&�jvr+t=|tL��r|j+�t%d(���|�;|�9t=|tH��r$t=|tL��st%d)���| ����jd*krtY| �j-��} ��.| ��gd+�}�fd,�|D��}t/|��dkr�d-d.|�d/�zd0z}t_| d1��st%d2|z���t_| j0d3��r | j0j1}nAt_| j0d4��rt-| j0j2��}nt%d5|z���| �3||ztid6|z|z��d7|zd+���t=|tH��r"| �3|j5|j6d8���t=|tL��r�|j+��to|j8d9d���to|j8d:d��n|j8j9d:}| �3d||j:d;���|j;�2�js!tyj=|j;�jz ��n|j;| d<<�j>dQd=di| ���j�_t| �j�>��}|��t=|tH��r1|j@|d?<t=|tL��r|j+� |j+|d@<n׉jdA�dBi���dCdD��dDkrm�j�dEd$��rR�j jdFkr3t�jB�dGdH��dHkrt%dI���t�|��}||d!<|�*t|��j'|j(j)j*vr||d@<�j jdFkrdJt�jBdK<|dQi|��\}}}}tdd dL��rg�jjDjEt�jGkrH�jjD�H��}|�I|�JdM��|�N��|�t�|��}|�0|�t�||�jM�j�O��}nt�||��}t�t/| ����D]�}t=| |t>j j!��r|| |<�-t=| |t>j"j#tHf��r|| |<�_t=| |tJtLf��s+t| |��j'|j(j)j*vr|| |<���jP�t�|���_Pnt0�RdP���jS�T|��|��jU�T|��|��jV�T|��t�| ��S)RNrr�)r�c3�^K�|](}t|tjjj��V��)dSr$)r�rwr�r�r�rZs rr�z1Accelerator._prepare_deepspeed.<locals>.<genexpr>s5����#a�#a�UX�J�s�E�K�4D�4O�$P�$P�#a�#a�#a�#a�#a�#arr.� autotp_sizer r�r��0.16.4�bDeepspeed TP requires deepspeed >= 0.16.4, Please update DeepSpeed via `pip install deepspeed -U`.z2.2.0zsTried to use TP, but `torch.distributed.device_mesh` requires PyTorch >= 2.2.0. Please upgrade your PyTorch version)�init_device_meshr)�mesh_dim_namesc���g|]?}t|tjjj��r��|d���n|��@S)T)r�)r�rwr�r�r�r�)r�r�rs �rr�z2Accelerator._prepare_deepspeed.<locals>.<listcomp>.sZ��� � � ��8B�#�u�{�GW�Gb�7c�7c� l�D� � �c�d� � 3� 3� 3�il� � � r�train_micro_batch_size_per_gpuc�<�g|]}t|d���|j��S�� batch_size�r<rnrZs rr�z2Accelerator._prepare_deepspeed.<locals>.<listcomp>5s)��\�\�\�#���l�A[�A[�\�s�~�\�\�\rc3�K�|]}|duV�� dSr$r�)r��bss rr�z1Accelerator._prepare_deepspeed.<locals>.<genexpr>6s&����8�8�b�r�T�z�8�8�8�8�8�8ra,At least one of the dataloaders passed to `accelerate.prepare()` has `None` as batch size. Please set an integer value in `train_micro_batch_size_per_gpu` in the deepspeed config file or assign integer value to `AcceleratorState().deepspeed_plugin.deepspeed_config['train_micro_batch_size_per_gpu']`.c�$��g|] }|�jz�� Sr�)r&)r�rnrs �rr�z2Accelerator._prepare_deepspeed.<locals>.<listcomp>=s!���"b�"b�"b� �:��1C�#C�"b�"b�"br�RSince you passed both train and evaluation dataloader, `is_train_batch_min` (here �% will decide the `train_batch_size` (r�a�When using DeepSpeed, `accelerate.prepare()` requires you to pass at least one of training or evaluation dataloaders with `batch_size` attribute returning an integer value or alternatively set an integer value in `train_micro_batch_size_per_gpu` in the deepspeed config file or assign integer value to `AcceleratorState().deepspeed_plugin.deepspeed_config['train_micro_batch_size_per_gpu']`.r�F)� must_matchr���?)�gradient_clippingz;zero_optimization.stage3_gather_16bit_weights_on_model_save�train_batch_sizer�z�You cannot specify an optimizer in the config file and in the code at the same time. Please remove the optimizer from the config file or create `accelerate.utils.DummyOptim` in the code.zTYou cannot create a `DummyOptim` without specifying an optimizer in the config file.T�zero_allow_untested_optimizerr�z�You 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.z�Either specify a scheduler in the config file or pass in the `lr_scheduler_callable` parameter when using `accelerate.utils.DummyScheduler`.zlYou can only specify `accelerate.utils.DummyScheduler` in the code when using `accelerate.utils.DummyOptim`.r�)z$zero_optimization.reduce_bucket_sizez-zero_optimization.stage3_prefetch_bucket_sizez4zero_optimization.stage3_param_persistence_thresholdc�>��g|]}��|���|��Sr�)�is_auto)r��xr�s �rr�z2Accelerator._prepare_deepspeed.<locals>.<listcomp>�s.���$f�$f�$f�1�JZ�Jb�Jb�cd�Je�Je�$f�Q�$f�$f�$frzStherefore it's not possible to automatically fill out the following `auto` entries zin the DeepSpeed config file: z . You can fix that by replacing zB`auto` values for these keys with an integer value of your choice.rTz!Can't find `model.config` entry, � hidden_size� hidden_sizeszMCan find neither `model.config.hidden_size` nor `model.config.hidden_sizes`, g�������?� )zoptimizer.params.lrzoptimizer.params.weight_decay�defaults�lr)zscheduler.params.warmup_min_lrzscheduler.params.warmup_max_lrz!scheduler.params.warmup_num_stepsz scheduler.params.total_num_stepsru)rt� config_params�model_parameters� lr_scheduler�zero_optimization�offload_optimizerr�none�zero_force_ds_cpu_optimizerr��PT_HPU_LAZY_MODE�1zxYou can't use an Offload Optimizer with HPU in Lazy Mode. Please set the environment variable `PT_HPU_LAZY_MODE` to `0`.r��DEEPSPEED_USE_HPUz0.14.4r�)r��compile_kwargs��step_with_optimizerr�aA wrapped DeepSpeed engine reference is currently tied for this `Accelerator()` instance. If you want to call `accelerator.backward()` referencing a new model/engine, please create a separate `Accelerator()` instance and call `accelerator.prepare()` on it.r�)Xr�� initializer��msampr�r��deepspeed_configr�r?r�rX�torch.distributed.device_meshrhrrr��ds_device_meshr{r�r��is_train_batch_min�min�maxr�r�r�� get_value� fill_matchr�r&r�rwrxr�r�r�rqr~rrr>�runtime� lr_schedules�VALID_LR_SCHEDULES�lr_scheduler_callabler<r��set_moe_leaf_modulesr<rTr}r~r�r�r�� weight_decayrr�r��warmup_num_steps�total_num_steps�math�ceil�deepspeed_config_processr�r�r�r�rsr�r�r+r�r�rF�poprorr�rp�ranger�rn�warningr r�r rr�)rrXr�� ds_initialize�msamp_deepspeed�is_dataloader_present�tp_sizerh� mesh_dim_namer�� batch_sizes�batch_size_per_device� config_kwargsrtr�r�r��hidden_size_based_keys�hidden_size_auto_keys� reasoningr}�max_lrr�enginer�r�r�r�r�s` @rr�zAccelerator._prepare_deepspeedse ��������!�,� � � �w� &� &� :� :� :� :� :� :�+�6�M��0�� #�#a�#a�\`�#a�#a�#a� a� a��"�3�7�7�8I�2�N�N�R�R�S`�bc�d�d�� �Q�;�;�#�K��x�@�@� �!�x����$�D�'�2�2� �!�J���� G� F� F� F� F� F� �M�(8�(8���9I�G�:�gt�fv�(w�(w�(w�D�J� %� � � � �� � � �� � #� #�$D� E� E� a�$� �\�\��\�\�\� ��8�8�K�8�8�8�8�8��$�O���� �%�c�"b�"b�"b�"b�Va�"b�"b�"b�K�<L�<_�(u��K�(8�(8�(8�eh�it�eu�eu�%��{�#�#�a�'�'��K�K��+�>���ez�������� !�K����%5�$>�$>�?_�$`�$`� !� �#�#� )��(,�(H� $� � � �"%�KP� � � � !� ,�>S�M�:� ;�%�(8�(B�(B�C`�(a�(a�a�dh�dv�v� �,� -���� �� �� � �C��#�u�x��/�/� �����C�%�+�"7��!D�E�E� �� � ��S�;��"?�@�@� ��S� � �"�i�&7�&D�&W�W�W�� �� � ��.�?�?�?� �S\�_i�Hk�Hk�?� �H���� �$4�$E�E�E�*�U^�ak�Jm�Jm�E� �j�����)�e�k�&;�=�=� Z�UY� �1�2Q�R� � ��.�?�?�?� �S\�_m�Ho�Ho�?� �L���� �#3�#D�D�D��y�>�;�;�E��3�;� �r���� � �Y�%:��)�j�2�2� �:�i�R`�;b�;b� � �5���� � ���4�'�'�*�5�$�2I�J�J�� � 1� 1�%� 8� 8� 8�&�&�&� "� %g�$f�$f�$f�0F�$f�$f�$f� !��(�)�)�A�-�-�i�n�7L�n�n�n�o�Z�[�� �u�h�/�/�V�$�%H�9�%T�U�U�U��5�<��7�7��"'�,�":�K�K��U�\�>�:�:��"%�e�l�&?�"@�"@�K�K�$�g�js�s�����$�$�@K�k�@Y�IL�S�S^�M^�al�Ml�Im�Im�PR�U`�P`�������)�j�2�2� ��$�$�,5�L�[d�[q�r�r�����)�n�6�6� �9�;Z�;b��y�2�J��E�E�M��I�/��t�<�<�<�"�,�5�d�;�� �$�$�:;�:@�=F�=W�������,�8� $�1�7�� �)�";�d�>P�"P�Q�Q�Q�&�6�"�"D�E� 6� � 5� X� X�� X�-� X� X� X�$4�$E�D� !���T�5J�K�K�K�F��$��i�*�6�6�?�1:�1A�F�-�.�!�)�n�>�>�Q�9�Cb�Cn�1:�1P��~�.���,�-@�A�E�E�FY�[]�^�^�b�b� �&���� � �$(�$9�$=�$=�>[�]a�$b�$b� � �;�+�u�4�4�����HZ�\_�9`�9`�dg�9g�9g�",�!a�#�#�� %C�9�$M�$M� �*3�F�;�'� �,�� �?�?�3�y�7H�7U�7h�h�h�5>�F�>�2��{��5�(�(�39�� �.�/�1>��1H�1H��1H�1H� .�F�I�q�,�� �T�8�<�<� e���AY�Aa�er�eu�Au�Au�!%��!9�!C�!C�!E�!E�����~�'9�'9�)�'D�'D�Uc��d�d�d��$�5�i�@�@� ��$��'� 4�!�!�,0�,N�&*�&8� !�!�!�I�I�!:�,� � R� R�I��3�v�;�;�'�'� *� *���f�Q�i����9�9�*� &�F�1�I�I���q� �E�K�,A�:�+N�O�O�*� )�F�1�I�I� ����[�.�,I�J�J�*�����O�O�,� �0A�0N�0a�a�a� )�F�1�I���,�4�0F�v�0N�0N��-�-����p���� �L� � �� '� '� '��$�� �'�'� �2�2�2��$�� �'�'� �2�2�2��V�}�}�rc� �|jj}d}|js�d�|D��}t|��dkrt d���|jrt |��nt|��}t|��dkr&t� d|j�d|�d���n)|D]&}t|t��r|j d}n�'|�.|j |j|jzz}|�||��nt d ���d}d}d} d} |D]�}t|t"jjj��r| �t+t-|����} �Et|t"jj��r|}�gt|t"jj��r|}��t|t6t8f��r|} ��|�|�|| ��|�|�|��| �9t| t8��st d ���|�| ��tA||j!� ��tE|��\}}} |�#��d} g} |D]�}t|t"jjj��r)| �$tK||����| dz } �Ot|t��rK| dkr$|�&��tK||��} | �$| | ��| dz } ��| �$|����|�tO|||| ��}|�tQ|��}| �tS| |��} tUt| ����D]x}t| |t"jj��r|| |<�-t| |t"jj��r|| |<�Xt| |t8��r| | |<�y|�A|j+�$|��t|j+��dkrtYd ���|�|j-�$|��| �|j.�$| ��t_| ��S) Nc�<�g|]}t|d���|j��SrmrorZs rr�z4Accelerator._prepare_megatron_lm.<locals>.<listcomp> s)��X�X�X�c�W�S�,�=W�=W�X�3�>�X�X�XrrzfYou must specify a training or evaluation dataloader in `accelerate.prepare()` when using Megatron-LM.r rsrtr��micro_batch_sizez�When you do not pass the dataloader parameter, the `data_parallel_size`, `micro_batch_size`, and `global_batch_size` megatron parameters will not be updated.zvYou can't use a custom scheduler with Megatron-LM. Please use the `accelerate.utils.MegatronLMDummyScheduler` instead.)� args_defaultszWYou can't use same `Accelerator()` instance with multiple models when using Megatron-LM)0r�r��megatron_dataset_flagr�r�r�r�r�r�r�r�ru� dataset_argsr&� tp_degree� pp_degree�set_training_argsrwr�r�r�r�r�rxr�r�r�r~rv�set_network_size_args�set_optimizer_type�set_scheduler_argsry�megatron_lm_default_argsr{rfr�rz�set_megatron_data_argsrtrwrxr�r r�r rr�)rrXr�r�r�r�� dp_degreertr�r�� batch_data�counterr�� dataloadersr�s rr�z Accelerator._prepare_megatron_lms���!�Z�:����!�7� �X�X�T�X�X�X�K��;���1�$�$� �|����4F�3X�n�s�;�/�/�/�^a�bm�^n�^n� ��;���!�#�#�� � �x�)�<�x�x�cs�x�x�x����� � � ���c�#<�=�=��'*�'7�8J�'K�$��E�� � '��*�/A�/K�N`�Nj�/j�k�I� � 0� 0�1A�9� M� M� M� M��g��� ���� �� �� �� � �C��#�u�{�/�:�;�;� � �@R�!�$�s�)�)�_�_� � ��C����1�1� �����C�%�+�"7�9�9� �� � ��C�+�/G�!H�I�I� �� �� � � � 4� 4�U�J� G� G� G� � � � 1� 1�)� <� <� <� � ��i�)A�B�B� � �M���� � 1� 1�)� <� <� <� �t�3E�3^�_�_�_�_�(U�VZ�([�([�%�� �9� ��� � � ������ #� #�C��#�u�{�/�:�;�;� #�� � �=�d�C�H�H�I�I�I��1� ����C�!:�;�;� #��a�<�<��.�.�0�0�0�"A�$��"L�"L�K�� � �k�'�2�3�3�3��1� ���� � �c�"�"�"�"� � �"�4�� �9�E�E�E� � �2�9�=�=�I� � �2�9�i�H�H�I��s�6�{�{�#�#� &� &�A��&��)�U�X�_�5�5� &�!��q� � ��F�1�I�u�{�'<�=�=� &�%��q� � ��F�1�I�'?�@�@� &�%��q� �� � � �L� � �� &� &� &��4�<� � �1�$�$�$�m���� � � � � #� #�I� .� .� .� � � � � #� #�I� .� .� .��V�}�}�rc��|jjrt��std���d}d}d�|D��}|D]Y}t |t jj��r|}|����8t |t j j ��r|}�Z|��|��|jj dkr t j nd}|j jdkrIt|�����j jdkr|�|j ��}t��r!ddl}|�|||dd � ��\}}t)t+|����D]W}t ||t jj��r|||<�-t ||t j j ��r|||<�Xt-|��S) a Prepares model and optimizer for training with IPEX on CPU/XPU. This covers 3 cases, IPEX compiled with CPU only support, IPEX compiled with XPU support and training with XPU pytorch backend available in stock pytorch starting from version 2.4. z�IPEX is not installed or IPEX's version does not match current PyTorch version. Please refer to https://github.com/intel/intel-extension-for-pytorch.Nc��g|]}|��Sr�r�rZs rr�z-Accelerator._prepare_ipex.<locals>.<listcomp>�r[rr�r�r�rT�O1)r�r;�inplace�level)r�r�rQr�r�rwrxr��trainr�r�r��bfloat16rrr�r+r*�intel_extension_for_pytorch�optimizer�r�r�) rrXrtr�r�r�r;�ipexr�s rr�zAccelerator._prepare_ipex�s��� �:� � �$�&�&� �!�P���� ��� �&�&��&�&�&��� � �C��#�u�x��/�/� ���� � � � � � ��C�%�+�"7�9�9� �� �� � �U�%6�&*�j�&@�F�&J�&J�E�N�N�PT�E��{��5�(�(�T�%�2B�2B�2D�2D�-E�-E�-L�-Q�UZ�-Z�-Z������-�-�� �"�"� t�:�:�:�:�#'�=�=��)�SX�bf�nr�=�#s�#s� ��y��s�6�{�{�#�#� &� &�A��&��)�U�X�_�5�5� &�!��q� � ��F�1�I�� �(=�?�?� &�%��q� ���V�}�}�rc��|jjr|jjjS|jtjkr!t |jd��r |jjSdS)z� Prepare the device mesh for distributed training. The dataloader will determine how to load data based on the device mesh. r�N)r�r�r/r�r*r�r<r�r s r�_prepare_device_meshz Accelerator._prepare_device_mesh�sR�� �:� %� ��:�-�?� ?� � "�o�&?� ?� ?�G�D�J�Xh�Di�Di� ?��:�,� ,��4rc�D�t��std���ddl}d\}}d}d\}}d�|D��} t| ��D]T\} } t | t jj��r| }|dz }�,t | t jj ��r | }| }|dz }�U|�|�| |fS|�|�td���|dks|dkrtd|�d |�d ����|j � |j j } n |j j } |�||| � ��\}}tt!| ����D]W} t | | t jj��r|| | <�-t | | t jj ��r|| | <�X|�d ||<t#| ��|fS) Nz�MS-AMP was not found on your system. Please ensure that MS-AMP is available or choose `'te'` as the backend for FP8 mixed precision training.rr rXc��g|]}|��Sr�r�rZs rr�z.Accelerator._prepare_msamp.<locals>.<listcomp>�r[rr z\You must pass a model and an optimizer together to `accelerate.prepare()` when using MS-AMP.r\r]z with MS-AMP.)� opt_levelF)rUr�r�r�r�rwrxr�r�r�r�r�r�r�r�r�r�r�) rr�rXr�rtr��optimizer_indexrarbr�r�r�r�s rr�zAccelerator._prepare_msamp�s ��!�#�#� ��U��� � � � � �%���y���%)�"� �N�&�&��&�&�&����'�'� $� $�F�A�s��#�u�x��/�/� $����a�� � ��C�%�+�"7�9�9� $�� �"#���!�#��� � ����+�+� +� � �%�-��n��� ��!�^�^�~��1�1��k�*�k�k�n�k�k�k��� � �&�2� �3�=� � � �5�?� �$�/�/��y�I�/�V�V� �E�9��s�6�{�{�#�#� &� &�A��&��)�U�X�_�5�5� &�!��q� � ��F�1�I�� �(=�?�?� &�%��q� �� � &�05� �_� -��V�}�}�.�.�.r� data_loader�torch.utils.data.DataLoaderc���t|dd��r%||jvr|j�|��|S|�|jtjkr|jnd}|���}t||j |j |j |j ||j ���|j|j||j|jj|j|j|���}|j�|��|S)am Prepares a PyTorch DataLoader for training in any distributed setup. It is recommended to use [`Accelerator.prepare`] instead. Args: data_loader (`torch.utils.data.DataLoader`): A vanilla PyTorch DataLoader to prepare device_placement (`bool`, *optional*): Whether or not to place the batches on the proper device in the prepared dataloader. Will default to `self.device_placement`. slice_fn_for_dispatch (`Callable`, *optional*`): If passed, this function will be used to slice tensors across `num_processes`. Will default to [`~utils.slice_tensors`]. This argument is used only when `dispatch_batches` is set to `True` and will be ignored otherwise. Example: ```python >>> import torch >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> data_loader = torch.utils.data.DataLoader(...) >>> data_loader = accelerator.prepare_data_loader(data_loader, device_placement=True) ``` r�FN) r&r)r�� put_on_devicer�r/r2�slice_fn_for_dispatchr7� data_seedr9r;r/)rrr�r�r*rr�r�rrr&r)r�r��copyr/r2r7r�r�r9r;)rr�r�r�� device_mesh�prepared_data_loaders rrzAccelerator.prepare_data_loader�s ��< �;� 9�5� A� A� ��$�"3�3�3��!�(�(��5�5�5�� � � #�8<�8M�Q`�Qd�8d�8d�t�4�4�jo� ��/�/�1�1� �2� � �K��,��,��,�*��n�)�)�+�+�!�2��*�"7�!%�!:��,�6��*�$(�$@�)� � � ��" �� � �!5�6�6�6�#�#rr��torch.optim.Optimizerc�p�t��r(ddlm}m}|xjt |||f��zc_t |dd��r%||jvr|j�|��|S|�|j }|j dkrdn|j }t|||���}|j�|��|S)a� Prepares a PyTorch Optimizer for training in any distributed setup. It is recommended to use [`Accelerator.prepare`] instead. Args: optimizer (`torch.optim.Optimizer`): A vanilla PyTorch optimizer to prepare device_placement (`bool`, *optional*): Whether or not to place the optimizer on the proper device. Will default to `self.device_placement`. Example: ```python >>> import torch >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> optimizer = torch.optim.Adam(...) >>> optimizer = accelerator.prepare_optimizer(optimizer, device_placement=True) ``` r��AdaLomo�Lomor�FNr�)r�r) rR� lomo_optimr�r�r�r�rr r�r�r�rr)rr�r�r�r�rs rr�zAccelerator.prepare_optimizer! s���, � � � N� 1� 0� 0� 0� 0� 0� 0� 0� � #� #�z�)�d�G�_�'M�'M� M� #� #� �9�7�� ?� ?� ��� 0�0�0�� �'�'� �2�2�2�� � � #�#�4� ��)�W�4�4���$�+��(��EU�^d�e�e�e� � ���� �*�*�*��rr�r~c�>�t|dd��r%||jvr|j�|��|S|j}|jD] }t|dd��|jkr|}n�!t |||j|j���}|j�|��|S)ax Prepares a PyTorch Scheduler for training in any distributed setup. It is recommended to use [`Accelerator.prepare`] instead. Args: scheduler (`torch.optim.lr_scheduler.LRScheduler`): A vanilla PyTorch scheduler to prepare Example: ```python >>> import torch >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> optimizer = torch.optim.Adam(...) >>> scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, ...) >>> scheduler = accelerator.prepare_scheduler(scheduler) ``` r�Fr�Nr�)rrr�r r�rr�r�)rr�r��opts rr�zAccelerator.prepare_schedulerM s���, �9�7�� ?� ?� ��� 0�0�0�� �'�'� �2�2�2�� ��$� ��#� � �C��y�+�t�4�4�� �E�E�� ���F�)� � � $� B��,�  � � � � ���� �*�*�*��rc ��|�d��}|jtjkr ||jz }|jtjkr|jj|fi|��dS|jtjkrdS|j�'|j� |��jdi|��dS|�|j r|� ||��dS|jdi|��dS)a� Scales the gradients in accordance to the `GradientAccumulationPlugin` and calls the correct `backward()` based on the configuration. Should be used in lieu of `loss.backward()`. Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator(gradient_accumulation_steps=2) >>> outputs = model(inputs) >>> loss = loss_fn(outputs, labels) >>> accelerator.backward(loss) ``` � learning_rateNr�) r�r�r*r�r�r��backwardr r�scaler�� lomo_backward)r�lossrr�s rr�zAccelerator.backwardv s���$� � �?�3�3� � � �O�$=� =� =��$�:�:�D� � �O�$=� =� =� 2�D� )� 2�4� B� B�6� B� B� B� B� B� � "�o�&A� A� A� �F� �[� $� ,�D�K� � �d� #� #� ,� 6� 6�v� 6� 6� 6� 6� 6� � &�4�+B� &� � � �t�]� 3� 3� 3� 3� 3� �D�M� #� #�F� #� #� #� #� #rc�F�tjd|j���|_dS)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 �rN)rw�tensorrrr s r� set_triggerzAccelerator.set_trigger� s#��0!�<��$�+�>�>�>����rc���|j� tjd|j���|_|�|j��}|���dkr"tjd|j���|_dSdS)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 ``` Nrr�r TF)rrwr�rrar�)rrs r� check_triggerzAccelerator.check_trigger� st��2 � � #�$�|�A�d�k�B�B�B�D� ��k�k�$�"2�3�3� � � � � � �� "� "�$�|�A�d�k�B�B�B�D� ��4��urc�$�|jr�|jdkr{|�|j}nt|tt f��s|g}|D]Q}t|t ��r|j}t|t ���|j� |���NdSdSdS)a� Unscale the gradients in mixed precision training with AMP. This is a noop in all other settings. Likely should be called through [`Accelerator.clip_grad_norm_`] or [`Accelerator.clip_grad_value_`] Args: optimizer (`torch.optim.Optimizer` or `list[torch.optim.Optimizer]`, *optional*): The optimizer(s) for which to unscale gradients. If not set, will unscale gradients on all optimizers that were passed to [`~Accelerator.prepare`]. Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> model, optimizer = accelerator.prepare(model, optimizer) >>> outputs = model(inputs) >>> loss = loss_fn(outputs, labels) >>> accelerator.backward(loss) >>> accelerator.unscale_gradients(optimizer=optimizer) ``` r�N) rr�r r�r�r�rr�r�unscale_)rr�r�s r�unscale_gradientszAccelerator.unscale_gradients� s���0 �?� *�t�3�v�=�=�� � �,� � �� �E�4�=�9�9� (�&�K� � � *� *�� ��&:�;�;�(��-�C�!��&:�;�;�(�� �$�$�S�)�)�)�)� *� *�=�=�  *� *rr�c�H�|jtjkr�|���d�|D��}|jD]l}|d�|���D��krH|js|�||��cStj j �|||���cS�m�n=|jtj krdS|jtj k�r|j D]�}|jjsr|}t!|t"��r|j}t!|t"���t'j|��}t'jd|d|jz ���d|j_��t.j�d d ��d krd|���d �|D��}|jD]<}|d �|���D��kr|�||��cS�=|���tj j �|||���S)aQ Should be used in place of `torch.nn.utils.clip_grad_norm_`. Returns: `torch.Tensor`: Total norm of the parameter gradients (viewed as a single vector). Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator(gradient_accumulation_steps=2) >>> dataloader, model, optimizer, scheduler = accelerator.prepare(dataloader, model, optimizer, scheduler) >>> for input, target in dataloader: ... optimizer.zero_grad() ... output = model(input) ... loss = loss_func(output, target) ... accelerator.backward(loss) ... if accelerator.sync_gradients: ... accelerator.clip_grad_norm_(model.parameters(), max_grad_norm) ... optimizer.step() ``` c��g|]}|��Sr�r�r s rr�z/Accelerator.clip_grad_norm_.<locals>.<listcomp> s��0�0�0��!�0�0�0rc��g|]}|��Sr�r�r s rr�z/Accelerator.clip_grad_norm_.<locals>.<listcomp> s��!@�!@�!@��!�!@�!@�!@r)� norm_typeN�sumrv)r�Tr�r�r�c��g|]}|��Sr�r�r s rr�z/Accelerator.clip_grad_norm_.<locals>.<listcomp>- s��4�4�4�A�a�4�4�4rc��g|]}|��Sr�r�r s rr�z/Accelerator.clip_grad_norm_.<locals>.<listcomp>/ s��%D�%D�%D�A�a�%D�%D�%Dr)r�r*r�r�r r+r �clip_grad_norm_rwrxr�r�rr r�is_xla_gradients_syncedr�rr��xm�_fetch_gradients� all_reducer&r�r�r�)rr+�max_normr�rt�acc_optr�� gradientss rr�zAccelerator.clip_grad_norm_� s`��2 � �O�$8� 8� 8� � "� "� $� $� $�0�0�Z�0�0�0�J��� � ���!@�!@�U�-=�-=�-?�-?�!@�!@�!@�@�@��=��$�4�4�X�y�I�I�I�I�I�$�x�~�=�=�&��I� >� � ���� A� �� "�o�&?� ?� ?��4� � "�o�&9� 9� 9��+� J� J���-�E� J�!�C�$�S�*>�?�?�,�!�m��%�S�*>�?�?�,� "� 3�C� 8� 8�I��M�%��#��@R�:R�S�S�S�S�EI�G�*�B���z�~�~�3�W�=�=��G�G��&�&�(�(�(�4�4��4�4�4� �!�\�J�J�E�!�%D�%D��1A�1A�1C�1C�%D�%D�%D�D�D�$�4�4�X�y�I�I�I�I�I�E� ��� � � ��x�~�-�-�j�(�i�-�X�X�Xrc���|jtjtjfvrt d���|���t jj� ||��dS)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�rwrxr��clip_grad_value_)rr+� clip_values rrzAccelerator.clip_grad_value_4 s^��, � �_�%>��@T�$U� U� U��s�t�t� t� ��� � � � ���'�'� �J�?�?�?�?�?rc� �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]) ``` )rG)rr�s rrGzAccelerator.gatherO s��<�f�~�~�rc��� td�|d���d}n#t$rd}YnwxYw|p| }|rt|��}n��|��} �jjr`�jjdkrt�d��|S�jjdkr"�fd�}|r ||��St||��S|S|S#t$r|cYSwxYw) a� Gathers `input_data` and potentially drops duplicates in the last batch if on a distributed system. Should be used for gathering the inputs and targets for metric calculation. Args: input (`torch.Tensor`, `object`, a nested tuple/list/dictionary of `torch.Tensor`, or a nested tuple/list/dictionary of `object`): The tensors or objects for calculating metrics across all processes use_gather_object(`bool`): Whether to forcibly use gather_object instead of gather (which is already done if all objects passed do not contain tensors). This flag can be useful for gathering tensors with different sizes that we don't want to pad and concatenate along the first dimension. Using it with GPU tensors is not well supported and inefficient as it incurs GPU -> CPU transfer since tensors would be pickled. Example: ```python >>> # Assuming two processes, with a batch size of 5 on a dataset with 9 samples >>> import torch >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> dataloader = torch.utils.data.DataLoader(range(9), batch_size=5) >>> dataloader = accelerator.prepare(dataloader) >>> batch = next(iter(dataloader)) >>> gathered_items = accelerator.gather_for_metrics(batch) >>> len(gathered_items) 9 ``` c��|Sr$r�)r|s r�<lambda>z0Accelerator.gather_for_metrics.<locals>.<lambda>� s���rT)�error_on_other_typeFrzcThe used dataset had no length, returning gathered tensors. You should drop the remainder yourself.rc�,��|d�jj�Sr$)r� remainder)r�rs �r�_adjust_samplesz7Accelerator.gather_for_metrics.<locals>._adjust_samples� s���%�&E��(;�(E�&E�F�Fr) r`r�rHrGrr�rr�r�r)r� input_data�use_gather_object� all_tensorsr�rs` r�gather_for_metricszAccelerator.gather_for_metricso sS���> � �k�k�:�4� P� P� P� P��K�K��� � � ��K�K�K� ����.�@�[��� � +� ��,�,�D�D��;�;�z�*�*�D� ��"�4� ��&�0�B�6�6��K�K�}���� �K��(�2�Q�6�6�G�G�G�G�G�)�H�.��t�4�4�4�0��$�G�G�G� �K�� ��� � � ��K�K�K� ���s6�� (�(�7C�!C�2C�C�C� C�Cr�rvc�$�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]) ``` )ra)rr�� reductionr�s rrazAccelerator.reduce� s��D�f�i��/�/�/rrc�(�t||||���S)a� Recursively pad the tensors in a nested list/tuple/dictionary of tensors from all devices to the same size so they can safely be gathered. Args: tensor (nested list/tuple/dictionary of `torch.Tensor`): The data to gather. dim (`int`, *optional*, defaults to 0): The dimension on which to pad. pad_index (`int`, *optional*, defaults to 0): The value with which to pad. pad_first (`bool`, *optional*, defaults to `False`): Whether to pad at the beginning or the end. Returns: `torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`: The padded tensor(s). Example: ```python >>> # Assuming two processes, with the first processes having a tensor of size 1 and the second of size 2 >>> import torch >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> process_tensor = torch.arange(accelerator.process_index + 1).to(accelerator.device) >>> padded_tensor = accelerator.pad_across_processes(process_tensor) >>> padded_tensor.shape torch.Size([2]) ``` )�dim� pad_index� pad_first)r^)rr�rrrs rr^z Accelerator.pad_across_processes� s��B$�F��y�T]�^�^�^�^r�keep_fp32_wrapper�keep_torch_compilec�$�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. keep_torch_compile (`bool`, *optional*, defaults to `True`): Whether to not unwrap compiled model if compiled. 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 ``` )rD)rrtrrs r� unwrap_modelzAccelerator.unwrap_model� s��@+�5�2C�EW�X�X�Xrc�"�t��dS)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)rfr s rrfzAccelerator.wait_for_everyone! s��, �����r� project_namer�rT� dict | None� init_kwargsc �2�|jD]�}tt|��t��r|j�|���?t t|��}|jrI|j�|||j fi|� t|��i��������|j�||fi|� t|��i��������|�|jD]}|� |���dSdS)a Initializes a run for all trackers stored in `self.log_with`, potentially with starting configurations Args: project_name (`str`): The name of the project. All trackers will save their data based on this config (`dict`, *optional*): Optional starting configuration to be logged. init_kwargs (`dict`, *optional*): A nested dictionary of kwargs to be passed to a specific tracker's `__init__` function. Should be formatted like so: ```python {"wandb": {"tags": ["tag_a", "tag_b"]}} ``` Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator(log_with="tensorboard") >>> accelerator.init_trackers( ... project_name="my_project", ... config={"learning_rate": 0.001, "batch_size": 32}, ... init_kwargs={"tensorboard": {"flush_secs": 60}}, ... ) ``` N) r�� issubclassrrr�r�rr��requires_logging_directoryr�r��store_init_configuration)rr rTr"�tracker� tracker_inits r� init_trackerszAccelerator.init_trackers9 s=��<�}� j� j�G��$�w�-�-��8�8� j�� �$�$�W�-�-�-�-�3�C��L�L�A� ��:�j��M�(�(�$� �\�4�3C�i�i�{���WZ�[b�Wc�Wc�eg�Gh�Gh�i�i������M�(�(���l�)h�)h�k�o�o�VY�Za�Vb�Vb�df�Fg�Fg�)h�)h�i�i�i�i� � ��=� 9� 9���0�0��8�8�8�8� � � 9� 9r�name�unwrapc��t|j��dkr4|jD]}|j|kr |r|jn|cS�t |�d����t d���S)a Returns a `tracker` from `self.trackers` based on `name` on the main process only. Args: name (`str`): The name of a tracker, corresponding to the `.name` property. unwrap (`bool`): Whether to return the internal tracking mechanism or to return the wrapped tracker instead (recommended). Returns: `GeneralTracker`: The tracker corresponding to `name` if it exists. Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator(log_with="tensorboard") >>> accelerator.init_trackers("my_project") >>> tensorboard_tracker = accelerator.get_tracker("tensorboard") ``` rz= is not an available tracker stored inside the `Accelerator`.T)�_blank)r�r�r*r'r�r)rr*r+r's r� get_trackerzAccelerator.get_trackerh s}��0 �t�}� � �� !� !��=� B� B���<�4�'�'�.4�A�7�?�?�'�A�A�A�(���c�c�c�d�d� d��T�*�*�*�*rr�r�r � int | None� log_kwargsc �l�|jD]+}|j|fd|i|�|ji�����,dS)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*)rr�r r0r's rr2zAccelerator.log� sU��6�}� O� O�G� �G�K�� N� N�T� N�Z�^�^�G�L�"�-M�-M� N� N� N� N� O� Orc�t�|jD]}|����|j���dS)a� Runs any special end training behaviors, such as stopping trackers on the main process only or destoying process group. Should always be called at the end of your script if using experiment tracking. Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator(log_with="tensorboard") >>> accelerator.init_trackers("my_project") >>> # Do training >>> accelerator.end_training() ``` N)r��finishr��destroy_process_group)rr's r� end_trainingzAccelerator.end_training� sB�� �}� � �G� �N�N� � � � � � �(�(�*�*�*�*�*rc�@�t|||jj|���dS)a� Save the object passed to disk once per machine. Use in place of `torch.save`. Args: obj (`object`): The object to save. f (`str` or `os.PathLike`): Where to save the content of `obj`. safe_serialization (`bool`, *optional*, defaults to `False`): Whether to save `obj` using `safetensors` Note: If `save_on_each_node` was passed in as a `ProjectConfiguration`, will save the object once per node, rather than only once on the main node. Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> arr = [0, 1, 2, 3] >>> accelerator.save(arr, "array.pkl") ``` ��save_on_each_node�safe_serializationN)rcr�r9)rr��fr:s rrczAccelerator.save� s7��. � � �"�8�J�1�  � � � � � r�10GB�save_directory�Union[str, os.PathLike]�max_shard_size�Union[int, str]r:c �P��tj�|��r t�d|�d���dSt d�|���D����rt|���nOt d�|���D����rtd���|� |�����dStj |d���|rt����|rtnt}|rtnt }t#�||� ��}tj|��D]�}tj�||��} |�d d ��} |�d d ��} t+jd ��} |�| ��rvtj�| ��rW||j���vr<| �| ���'t7��jrtj| ����|j���D]I\}} �fd �| D��}|�|tj�||��|����J|j r�|j!|j"d�}|rtFntH}tj�||��}tK|dd���5}tMj'|dd���dz}|�(|��ddd��n #1swxYwYt�)d|�dtU|j���d|�d���dStj�|t��}t�)d|����dS)a( Save a model so that it can be re-loaded using load_checkpoint_in_model Arguments: model: (`torch.nn.Module`): Model to be saved. The model can be wrapped or unwraped. save_directory (`str` or `os.PathLike`): Directory to which to save. Will be created if it doesn't exist. max_shard_size (`int` or `str`, *optional*, defaults to `"10GB"`): The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`). <Tip warning={true}> If a single weight of the model is bigger than `max_shard_size`, it will be in its own checkpoint shard which will be bigger than `max_shard_size`. </Tip> safe_serialization (`bool`, *optional*, defaults to `True`): Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`). Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> model = ... >>> accelerator.save_model(model, save_directory) ``` zProvided path (z#) should be a directory, not a fileNc3�4K�|]}t|��V��dSr$)rM)r�r=s rr�z)Accelerator.save_model.<locals>.<genexpr> s+����J�J��#�F�+�+�J�J�J�J�J�Jrc3�PK�|]!}|jtjd��kV��"dS)r%N)rrw)r�rOs rr�z)Accelerator.save_model.<locals>.<genexpr> s3����X�X�E�5�<�5�<��#7�#7�7�X�X�X�X�X�XrzFYou can't save the model since some parameters are on the meta device.T��exist_ok)�filename_patternr?z.binr�z(.*?)-\d{5}-of-\d{5}c�"��i|] }|�|�� Sr�r�)r�r�� state_dicts �rr�z*Accelerator.save_model.<locals>.<dictcomp>1 s ���F�F�F�F�V�Z��/�F�F�Fr)r:)�metadata� weight_map�wzutf-8)�encodingr�)�indent� sort_keys� z:The model is bigger than the maximum size per checkpoint (z) and is going to be split in z^ checkpoint shards. You can find where each parameters has been saved in the index located at r&zModel weights saved in )+r��path�isfiler��errorr��modulesrlr+� RuntimeError�get_state_dict�makedirsr>r r#r!r$r �listdirr?r��rerF� startswith�filename_to_tensors�keys� fullmatchrrD�remover�rc� is_shardedrI�tensor_to_filenamerr"�open�json�dumps�writer�r�)rrtr=r?r:� weights_namerF�state_dict_split�filename� full_filename�weights_no_suffix�filename_no_suffix�reg�tensors�shardr)�save_index_filer;�content�path_to_weightsrHs @r� save_modelzAccelerator.save_model� s���P �7�>�>�.� )� )� � �L�L�^�>�^�^�^� _� _� _� �F� �J�J�%�-�-�/�/�J�J�J� J� J� 4�7��>�>�J�J��X�X�U�EU�EU�EW�EW�X�X�X�X�X� m�"�#k�l�l�l��,�,�U�3�3�J� � � �F� � �N�T�2�2�2�2� � F�9�*�E�E�J�,>�P�(�(�L� �8J�d�4�4�Pd��=� �)9�.� � � �� � �>�2�2� )� )�H��G�L�L���B�B�M�!-� 4� 4�V�R� @� @� �"*�!1�!1�&�"�!=�!=� ��*�4�5�5�C��#�#�$5�6�6� )��G�N�N�=�1�1� )��$4�$H�$M�$M�$O�$O�O�O��M�M�"4�5�5�A� �N�N�2�B�� �-�(�(�(��"2�!E�!K�!K�!M�!M� l� l� �H�g�F�F�F�F�g�F�F�F�E� �I�I�e�R�W�\�\�.�(�C�C�Xj�I� k� k� k� k� � &� E�,�5�.�A���E�:L�c�5�5�Qc�O� �g�l�l�>�?�K�K�O��o�s�W�=�=�=� !���*�U�1��E�E�E��L������ � � � !� !� !� !� !� !� !� !� !� !� !���� !� !� !� !� �K�K�7�^�7�7�� 0� D�E�E�7�7�$3�7�7�7� � � � � � !�g�l�l�>�<�H�H�O� �K�K�C�/�C�C� D� D� D� D� Ds�%0L!�!L%�(L%�hook�Callable[..., None]�return�hooks.RemovableHandlec�V�tj|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�rrq�handles r�register_save_state_pre_hookz(Accelerator.register_save_state_pre_hookH s+��8�&�t�'F�G�G��59��'�� �2�� r� output_dirc �@ ��|jjr%tj�|jd���tj�d���|jj�r[�fd�tj���D��}|jj��t|��dz|jjkr�|j r�d�}|� |���t� d t|��dz|jjz �d ���|dt|��dz|jjz �D]}tj|���tj��d |j�����tj����rt%d ��d |j�d����|���tj�d���t�d�����|jt,jkrt1j��g}t5|j��D�]�\}} |jt,jkrUt�d��t;|jj|| �|��t�d������p|jt,j kr�t�d��|dkrtB�n tB�d|��} | j"�| fi|��t�dtj��| ��������|jt,j#krNt�d��| �"���t�d�������h|�$|�%| d��������g} |jt,jkr{t5|j&��D]e\}} t�d��tO|jj|| |j|�|��t�d������fn&|jt,j t,j#fvr|j&} g} |jt,j krFt5|j(��D]0\}}tS|tT��r�| �$|���1n|jt,j#fvr|j(} |j+}|j,�-��D]}||j|����t]�|| | ||jj/|j0|j1|jj2|�� � }t5|j3��D]"\}}ti|�||jj2����#|jxj5dz c_5|S)a� Saves the current states of the model, optimizer, scaler, RNG generators, and registered objects to a folder. If a `ProjectConfiguration` was passed to the `Accelerator` object with `automatic_checkpoint_naming` enabled then checkpoints will be saved to `self.project_dir/checkpoints`. If the number of current saves is greater than `total_limit` then the oldest save is deleted. Each checkpoint is saved in seperate folders named `checkpoint_<iteration>`. Otherwise they are just saved to `output_dir`. <Tip> Should only be used when wanting to save a checkpoint during training and restoring the state in the same environment. </Tip> Args: output_dir (`str` or `os.PathLike`): The name of the folder to save all relevant weights and states. safe_serialization (`bool`, *optional*, defaults to `True`): Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`). save_model_func_kwargs (`dict`, *optional*): Additional keyword arguments for saving model which can be passed to the underlying save function, such as optional arguments for DeepSpeed's `save_checkpoint` function. Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> model, optimizer, lr_scheduler = ... >>> model, optimizer, lr_scheduler = accelerator.prepare(model, optimizer, lr_scheduler) >>> accelerator.save_state(output_dir="my_checkpoint") ``` � checkpointsTrDc�P��g|]"}tj��|����#Sr��r�rPr?)r��folderr|s �rr�z*Accelerator.save_state.<locals>.<listcomp>� s)���]�]�]�F�r�w�|�|�J��7�7�]�]�]rNr c �x�ttttjd|������dS�Nz[\/]?([0-9]+)(?=[^\/]*$)r�r��mapr�rX�findall�r�s rrYz&Accelerator.save_state.<locals>._inner� s.����C���4O�QW�)X�)X� Y� Y�Z�Z�[\�]�]r��keyz Deleting z- checkpoints to make room for new checkpoint.� checkpoint_zCheckpoint directory z (zc) already exists. Please manually override `self.save_iteration` with what iteration to start with.zSaving current state to zSaving FSDP modelzFSDP Model saved to output dir z$Saving DeepSpeed Model and Optimizerrr�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+zSaving FSDP Optimizerz#FSDP Optimizer saved to output dir r8)r9)6r��automatic_checkpoint_namingr�rPr?r�rVrW� total_limitr�rD�sortr�r��shutil�rmtreerB�existsr�rfr�r�r*rr�� mark_stepr�r r�rdr�r�r�r�save_checkpointr r�rUr rerr�rprrr�rr)r rr9rrrA)rr|r:�save_model_func_kwargs�foldersrYr��weightsr�rt�ckpt_id� optimizersr�� schedulersr�r�rq� save_locationr�s ` r� save_statezAccelerator.save_stateh s����L � %� A� G�����d�&6� �F�F�J� � �J��.�.�.�.� � %� A� %�]�]�]�]�b�j�Q[�F\�F\�]�]�]�G��*�6�B���\�\�A�%��(B�(N�N�N��(�O�^�^�^�� � �� �(�(�(����I��G� � �q� 0�4�3M�3Y� Y�I�I�I����&�&a��G� � �q�(8�4�;U�;a�(a�&a�b�*�*�F��M�&�)�)�)�)�����j�2U��@S�2U�2U�V�V�J��w�~�~�j�)�)� � �s�J�s�s�$�:M�s�s�s���� � "� "� $� $� $� � �J��.�.�.�.�� � �;�z�;�;�<�<�<� � �O�$7� 7� 7� �L�N�N�N���!�$�,�/�/� I� I�H�A�u��$��(<�<�<�� � �/�0�0�0��� � 6��e�Z�QR�S�S�S�� � �J�j�J�J�K�K�K�K��&�/�*C�C�C�� � �B�C�C�C�-.�!�V�V�Z�/�/�J�9L�9L��9L�9L��%��%�j�'�T�T�=S�T�T�T�� � �t�QS�QX�Q]�Q]�^h�jq�Qr�Qr�t�t�u�u�u�u��&�/�*E�E�E�� � �O�P�P�P��%�%�j�1�1�1�� � �k�_i�k�k�l�l�l�l����t�2�2�5��2�G�G�H�H�H�H�� � � �O�$8� 8� 8�#�D�$4�5�5� P� P���3�� � �3�4�4�4�#�D�J�$:�D�#�t�|�TU��Xb�de�f�f�f�� � �N�*�N�N�O�O�O�O� P�� "�?�+D�o�Fa�*b� b� b��)�J�� � � �O�$=� =� =� )�$�*:� ;� ;� -� -� ��9��i�)B�C�C����!�!�)�,�,�,�,� -�� "�?�+F�*G� G� G��)�J��'� ��3�:�:�<�<� 4� 4�D� �D���w� � 3� 3� 3� 3�.� � � � � � �J� $� �I� �K�"�8�J�1�  �  �  � � �� 4�5�5� r� r�F�A�s� �c�:�q�D�D^�Dp� q� q� q� q� q� �"�,�,��1�,�,��rc�V�tj|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()` )rvrwrrxrys r�register_load_state_pre_hookz(Accelerator.register_load_state_pre_hook� s+��6�&�t�'F�G�G��59��'�� �2�� r� input_dirc �� ����Rtj�����tj����st d��d����n�|jjrgtj�|jd����fd�tj ���D��}d�}|� |���|d�nt d ���t� d �����g}t|j��D�]}\}}|jt jkrUt� d ��t%|jj||�|��t� d ������p|jt jkr�t� d ��|dkrt,�n t,�d|��}|j�|fi|��t� dtj��|��������|jt jkrNt� d��|����t� d�������h|�|����g} |jt jkr{t|j��D]e\}} t� d��t7|jj|| |j|�|��t� d������fn&|jt jt jfvr|j} g} |jt jkrFt|j��D]0\}} t;| t<��r�| �| ���1n|jt jfvr|j} |j} |j �!��D]}||����|�"dd��}|�[|j#dkrN|jt j$t j%t j&t j't j(t j)fvrd}nd}tU�|| | | |jj+|j,|fi|��}d|vr |d|_-d�tj ���D��}t]|��t]|j/��krOd��d�}|dt]|����z }|dt]|j/���d�z }|d z }|d!z }ta|���t� d"t]|���d#���t|j/��D]\}}tc|�|���dS)$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") ``` NzTried to find z but folder does not existr~c�P��g|]"}tj��|����#Sr�r�)r�r�r�s �rr�z*Accelerator.load_state.<locals>.<listcomp>5 s)���[�[�[�6�r�w�|�|�I�v�6�6�[�[�[rc �x�ttttjd|������dSr�r�r�s rrYz&Accelerator.load_state.<locals>._inner7 s-���C��R�Z�0K�V�%T�%T�U�U�V�V�WX�Y�Yrr�rzBNo input_dir provided and automatic checkpoint naming is disabled.zLoading states from zLoading FSDP modelz!FSDP Model loaded from input dir z%Loading DeepSpeed Model and Optimizerrr�z4DeepSpeed Model and Optimizer loaded from input dir z2Loading Megatron-LM Model, Optimizer and SchedulerzBMegatron-LM Model , Optimizer and Scheduler loaded from input dir zLoading FSDP Optimizerz%FSDP Optimizer loaded from input dir � map_locationr � on_devicer�r c�<�g|]}tjd|���|��S)z^custom_checkpoint_\d+\.pkl$)rX�search)r�r;s rr�z*Accelerator.load_state.<locals>.<listcomp>� s2�� � � ��� �:Y�[\�0]�0]�0i�A�0i�0i�0irz'Number of custom checkpoints in folder z1 does not match the number of registered objects:z Found checkpoints: z Registered objects: rOzqPlease 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)2r�rP� expanduser�isdirr�r�r�r?r�rWr�r�r�r�r r�r*r�r\r�r�r�r�load_checkpointr r�r r]rr�rprrr�r�r&r�r�r�r�r�r�rr)rr r�rrTr)rr��load_model_func_kwargsr�rYr�r�rtr�r�r�r�r�r�rqr��override_attributes�custom_checkpoints�errr)r�s ` r� load_statezAccelerator.load_state s����> � ���*�*�9�5�5�I��7�=�=��+�+� Y� �!W�)�!W�!W�!W�X�X�X� Y� � '� C� c��� � �T�%5�}�E�E�I�[�[�[�[�R�Z�PY�EZ�EZ�[�[�[�G� Z� Z� Z� �L�L�V�L� $� $� $��� �I�I��a�b�b� b�� � �6�9�6�6�7�7�7���!�$�,�/�/� %� %�H�A�u��$��(<�<�<�� � �0�1�1�1��� � 6��e�Y�PQ�R�R�R�� � �K� �K�K�L�L�L�L��&�/�*C�C�C�� � �C�D�D�D�-.�!�V�V�Z�/�/�J�9L�9L��9L�9L��%��%�i��S�S�<R�S�S�S�� � �u�SU�SZ�S_�S_�`i�kr�Ss�Ss�u�u�v�v�v�v��&�/�*E�E�E�� � �P�Q�Q�Q��%�%�i�0�0�0�� � �l�aj�l�l�m�m�m�m�� � �e�$�$�$�$�� � � �O�$8� 8� 8�#�D�$4�5�5� Q� Q���3�� � �4�5�5�5�#�D�J�$:�D�#�t�|�TU��Xa�cd�e�e�e�� � �O�I�O�O�P�P�P�P� Q�� "�?�+D�o�Fa�*b� b� b��)�J�� � � �O�$=� =� =� )�$�*:� ;� ;� -� -� ��9��i�)B�C�C����!�!�)�,�,�,�,� -�� "�?�+F�*G� G� G��)�J��'� ��3�:�:�<�<� $� $�D� �D��� #� #� #� #�-�1�1�.�$�G�G� � � ��!�A�%�%�$�*?��)��)��*��*��)��)� D�+�+� +� � �$� �4� � � � � � �J� $� �K� �  �  �%�  �  �� �(� (� (�+�F�3�D�I� � ��z�)�,�,� � � �� �!� "� "�c�$�*>�&?�&?� ?� ?�v�)�v�v�v� � �F�S�1C�-D�-D�F�F� F�C� �K�c�$�2F�.G�.G�K�K�K� K�C� �G� G�C� �D� D�C��s�#�#� #� �K�K�M�c�*<�&=�&=�M�M�M� N� N� N�'��(<�=�=� 9� 9� ��s�!�#�y�%�8�8�8�8� 9� 9rc���t|d��r,|j�|jj���d|_t |�}g|_g|_g|_g|_d|_ |S)ab Will release all references to the internal objects stored and call the garbage collector. You should call this method between two trainings with different models/optimizers. Also will reset `Accelerator.step` to 0. Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> model, optimizer, scheduler = ... >>> model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler) >>> model, optimizer, scheduler = accelerator.free_memory(model, optimizer, scheduler) ``` r�Nr) r<r�r��destroyrbrr r rr �r�objectss r� free_memoryzAccelerator.free_memory� su��" �4�3� 4� 4� 1��,�8��-�4�<�<�>�>�>�,0�D� )� �'�*���������� ������ ��rc��|j|�S)aU Alias for [`Accelerate.free_memory`], releases all references to the internal objects stored and call the garbage collector. You should call this method between two trainings with different models/optimizers. Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> model, optimizer, scheduler = ... >>> model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler) >>> model, optimizer, scheduler = accelerator.clear(model, optimizer, scheduler) ``` )r�r�s r�clearzAccelerator.clear� s��  �t���)�)r)r�c����i}|D]c}t|tjj��rBt |��}|��fd�|���D�����d|S)Nc�H��i|]\}}|�r|���n|��Sr�)r�)r�r�r�r�s �rr�z5Accelerator._get_named_parameters.<locals>.<dictcomp>� s3���(p�(p�(p�QU�QR�TU��I�,L�A�J�J�L�L�L�1�(p�(p�(pr)r�rwrxr�rDr��named_parameters)rr�rXr�r�s ` rr�z!Accelerator._get_named_parameters� s{������ r� r�C��#�u�x��/�/� r�1�#�6�6�� �'�'�(p�(p�(p�(p�Y\�Ym�Ym�Yo�Yo�(p�(p�(p�q�q�q���rc�D�d}d}|D]�}t|tjj��r|���D] }|j}t|tjj��r8|jD]0}t|d��dkr|ddj}n�1��||fS)Nr�r) r�rwrxr�r+rr�r�r�r�)rrXr�r�r�rOr�s rr�zAccelerator._get_devices� s���� ���� � �C��#�u�x��/�/� � �^�^�-�-���E�#(�<�L���#�u�{�4�5�5� �#&�#3���K��;�x�0�1�1�A�5�5�+6�x�+@��+C�+J�(���6���.�/�/rc�,�|jtjkr�|jdddk}|j�di���dd��dk}|s|rq|���rN|r t dd d ��std ���|r|���n|� ��}�nNtd ���dd l m }||� |�������}�n|jr\t!j��5d�|������D��}ddd��n #1swxYwYn�|jtjkrdddlm}m}ddlm} |dd���} | �||j| ��5|���}ddd��n #1swxYwYn+|r|� |��}|���}|S)aP Returns the state dictionary of a model sent through [`Accelerator.prepare`] potentially without full precision. Args: model (`torch.nn.Module`): A PyTorch model sent through [`Accelerator.prepare`] unwrap (`bool`, *optional*, defaults to `True`): Whether to return the original underlying state_dict of `model` or to return the wrapped state_dict Returns: `dict`: The state dictionary of the model potentially without full precision. Example: ```python >>> import torch >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> net = torch.nn.Linear(2, 2) >>> net = accelerator.prepare(net) >>> state_dict = accelerator.get_state_dict(net) ``` r��stage�r.rerr r�r�rfrga�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.)�clone_tensors_for_torch_savec�>�i|]\}}||�����Sr�)� full_tensorr�s rr�z.Accelerator.get_state_dict.<locals>.<dictcomp>s&��X�X�X�T�Q��a������X�X�XrN)�FullStateDictConfig� StateDictTyperT)�offload_to_cpu� rank0_only)r�r*r�r�r��'zero_gather_16bit_weights_on_model_saver?r��_consolidated_16bit_state_dict�$_zero3_consolidated_16bit_state_dictr��deepspeed.checkpoint.utilsr�rrHr rwr`r�r��torch.distributed.fsdpr�r�r�state_dict_type�FULL_STATE_DICT) rrtr+�zero3_sharding� tp_shardingrHr�r�r�r��full_state_dict_configs rrUzAccelerator.get_state_dict� s���6 � �O�$=� =� =�!�2�3F�G��P�TU�U�N��/�3�3�4E�r�J�J�N�N�}�^_�`�`�cd�d�K�� a�� a��@�@�B�B��"��+;�K��x�+X�+X��)�A���� '�J��<�<�>�>�>�"�G�G�I�I��J� %�K����T�S�S�S�S�S�9�9�$�:K�:K�E�:R�:R�:]�:]�:_�:_�`�`� � � �]� ,����� Y� Y�X�X�U�=M�=M�=O�=O�=U�=U�=W�=W�X�X�X� � Y� Y� Y� Y� Y� Y� Y� Y� Y� Y� Y���� Y� Y� Y� Y�� � "�o�&:� :� :� Q� Q� Q� Q� Q� Q� Q� Q� O� O� O� O� O� O�%8�%8��Y]�%^�%^�%^� "��%�%�e�]�-J�Lb�c�c� 0� 0�"�-�-�/�/� � 0� 0� 0� 0� 0� 0� 0� 0� 0� 0� 0���� 0� 0� 0� 0��� 1��)�)�%�0�0���)�)�+�+�J��s$�'1E$�$E(�+E(�<G�G!�$G!c�V�g}|D]7}t|d��rt|d��s|�|���8t|��dkr?d}t|��D]\}}|d|�dt |���d�z }�t |���|j�|��dS) 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") ``` rH�load_state_dictrzxAll `objects` must include a `state_dict` and `load_state_dict` function to be stored. The following inputs are invalid:z - Item at index z, `�`N)r<r�r�r�rLr�r�extend)rr��invalid_objectsr�r�r)s r�register_for_checkpointingz&Accelerator.register_for_checkpointing's���2��� ,� ,�C��3� �-�-� ,�W�S�BS�5T�5T� ,��&�&�s�+�+�+�� �� � �!� #� #�M�C�'��8�8� P� P� ��s��O�e�O�O���8L�8L�O�O�O�O����S�/�/� !� ��#�#�G�,�,�,�,�,rr�r&c#�K�|�|j}t|j|��}|���dV�|jt j���dS)aI Will apply automatic mixed-precision inside the block inside this context manager, if it is enabled. Nothing different will happen otherwise. A different `autocast_handler` can be passed in to override the one set in the `Accelerator` object. This is useful in blocks under `autocast` where you want to revert to fp32. Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator(mixed_precision="fp16") >>> with accelerator.autocast(): ... train() ``` N)r�rKr� __enter__�__exit__�sys�exc_info)rr�rGs r�autocastzAccelerator.autocastKsb����& � #�#�4� �>�t��P`�a�a���"�"�$�$�$� ����!��!�3�<�>�>�2�2�2�2rr��ProfileKwargs | Nonec#�K�|p|jp t��}|���5}|V�ddd��n #1swxYwY|j�dSt j|jd���|�tj�|jtj |j �������|� ��dS)a  Will profile the code inside the context manager. The profile will be saved to a Chrome Trace file if `profile_handler.output_trace_dir` is set. A different `profile_handler` can be passed in to override the one set in the `Accelerator` object. Args: profile_handler (`ProfileKwargs`, *optional*): The profile handler to use for this context manager. If not passed, will use the one set in the `Accelerator` object. Example: ```python # Profile with default settings from accelerate import Accelerator from accelerate.utils import ProfileKwargs accelerator = Accelerator() with accelerator.profile() as prof: train() accelerator.print(prof.key_averages().table()) # Profile with the custom handler def custom_handler(prof): print(prof.key_averages().table(sort_by="self_cpu_time_total", row_limit=10)) kwargs = ProfileKwargs(schedule_option=dict(wait=1, warmup=1, active=1), on_trace_ready=custom_handler) accelerator = Accelerator(kwarg_handler=[kwargs]) with accelerator.profile() as prof: for _ in range(10): train_iteration() prof.step() # Profile and export to Chrome Trace kwargs = ProfileKwargs(output_trace_dir="output_trace") accelerator = Accelerator(kwarg_handler=[kwargs]) with accelerator.profile(): train() ``` NTrD)�suffix) r�r6�build�output_trace_dirr�rV�export_chrome_tracerPr?rk�formatr)rf)rr��profilers r�profilezAccelerator.profilefs����\*�T�T�-A�T�]�_�_�� � "� "� $� $� ���N�N�N� � � � � � � � � � � ���� � � � � � +� 3� �F� � �O�4�t�D�D�D�D��$�$� �G�L�L��9�;O�;V�^b�^p�;q�;q�;q� r� r� � � � ��� � � � � s�?�A�Ac�.�|jD] }|jrdS� dS)z� Whether or not the optimizer update was skipped (because of gradient overflow in mixed precision), in which case the learning rate should not be changed. TF)r �step_was_skipped)rr�s r�optimizer_step_was_skippedz&Accelerator.optimizer_step_was_skipped�s2�� �)� � �I��)� ��t�t� ��ur� num_batchesc�$�t||���S)a@ Creates a new `torch.utils.data.DataLoader` that will efficiently skip the first `num_batches`. Args: dataloader (`torch.utils.data.DataLoader`): The data loader in which to skip batches. num_batches (`int`, *optional*, defaults to 0): The number of batches to skip Example: ```python >>> from accelerate import Accelerator >>> accelerator = Accelerator() >>> dataloader, model, optimizer, scheduler = accelerator.prepare(dataloader, model, optimizer, scheduler) >>> skipped_dataloader = accelerator.skip_first_batches(dataloader, num_batches=2) >>> # for the first epoch only >>> for input, target in skipped_dataloader: ... optimizer.zero_grad() ... output = model(input) ... loss = loss_func(output, target) ... accelerator.backward(loss) ... optimizer.step() >>> # subsequent epochs >>> for input, target in dataloader: ... optimizer.zero_grad() ... ... ``` )r�)r)r� dataloaderr�s rrzAccelerator.skip_first_batches�s��<"�*�+�F�F�F�Frc�:�t�d��|S)Nz]Deep copying the `Accelerator` object, note that this will point to the same original object.)r�r�)r�memos r� __deepcopy__zAccelerator.__deepcopy__�s��� � �s�t�t�t�� rc��|���D]-}t|d��rt|j��dkrdS�.dS)z{ Verifies that `model` has not been prepared with big model inference with a device-map resembling `auto`. rr TF)rSr<r�r)rrtr�s rr�zAccelerator.verify_device_map�sN�� ����� � �A��q�/�*�*� �s�1�?�/C�/C�a�/G�/G��t�t���urr�� torch.Tensorr��float�Nonec���t��rddlm}m}|�t d���d}|jD]6}t |j||f��r|j�||��d}�7|st d���dS)z8 Runs backward pass on LOMO optimizers. rr�NzSA learning rate must be passed in order to call backward pass with LOMO optimizers.FTzxBackward pass not properly called on LOMO optimizers. Are you sure you passed a LOMO optimizer in accelerator.prepare()?) rRr�r�r�r�r r�r��fused_backward)rr�r�r�r��_backward_calledr�s rr�zAccelerator.lomo_backward�s��� � � � 1� 1� 0� 0� 0� 0� 0� 0� 0� � ��r�s�s� s� ���)� (� (�I��)�-��g��?�?� (��#�2�2�4��G�G�G�#'� ��� ��K��� � � rc��|jr/|j� |jjS|j�dS|j�dS|j�dSn|jj�|jjjrdSdS)z2Returns the configured backend for training in FP8Nr�r�r�) r�r�r�r�r�r�r�r�� enable_msampr s rr�zAccelerator.fp8_backend�su�� � � ��&�2��.�6�6��'�3��t��'�3��t��*�6��w�7� �Z� (� 4���9T�9a� 4��7��tr)(r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�)r4r�)F)rKrLrMr�r$)rPrQr )rPrQr)r�)rPrQr+r�)FN)NF)rtrr�r�rr�)r�r�)r�r�)r�r~)r�)r�rv)rrF)TT)rr�rr�)r r�rTr!r"r!)r*r�r+r�)r�r�r r/r0r!)r<T)rtrr=r>r?r@r:r�)rqrrrsrt)NT)r|r�r:r�)r�r�)T)r�r&)r�r�)r)r�r�)rtrrsr�)r�r�r�r�rsr�)`r>� __module__r\�__doc__�_split_batchesr�propertyr�r"r�r&r)r+rr�r/r2�setterr7r9r;r�r�rBrDrFrHr�r rrOrVrardrgrjrlrorq� staticmethodr�r�r�r�r�r�r�r�rr�r�r�r�r�r�r�r�rr�r�r�r�r�r�r�rrGrrar^rrfr)r.r2r6rcrpr{r�r�r�r�r�r�r�rUr�r�r�r�rr�r�r�r�r�rrr�r��sW ������X�X�x"&�,�6:�+,��<@�PT�=A�<@�6:�04�gk�04�6:�JN�.2�6:�59�26�QU�+W�W�W�W�W�r � +� +��X� +��*�*��X�*� �+�+��X�+��(�(��X�(��(�(��X�(��.�.��X�.��!�!��X�!��4�4��X�4��7�7��X�7��3�3��X�3���4�4�4���4��;�;��X�;��3�3��X�3�����X�� �6�6��X�6��6�6��X�6��4�4��X�4��*�*��X�*��0�0��X�0��<�<��X�<��*�*��X�*��#�#��X�#��'�'�'�'��^�'�R%�%�%�%�%�N(�(�(�(�(�T%�%�%�%�N+�+�+�+�+�Z.�.�.�.�.�`����^��*����^��*�&�&��^�&�P��-N�-N��^��\�-N�^f�f�f��2�2��X�2���<�<���<��-�-��X�-�!�'�]�]�(�'�]��*�*��^�*�X�X�X�X��^�X�t *� *� *�����"/3�n8�n8�n8�n8�n8�`Z�Z�Z�Z�Z�x � � �"�"�"�HH�H�H�Te�e�e�N$�$�$�L � � �//�//�//�dfj�9$�9$�9$�9$�9$�v*�*�*�*�*�X'�'�'�'�R $� $� $�D?�?�?�4���B!*�!*�!*�!*�F<Y�<Y�<Y�<Y�|@�@�@�6���@G�G�G�G�R"0�"0�"0�"0�H!_�!_�!_�!_�F Y� Y� Y� Y� Y�D���0�EI�fh�,9�,9�,9�,9��_�,9�\+�+�+�+�+�@�37�SU�O�O�O�O��_�O�:+�+�+�* � � � �D+1�#'� mE�mE�mE�mE�mE�^����@E�E�E�E�E�N����>J9�J9�J9�J9�J9�X���:*�*�*�$6;� � � � � �0�0�0�"C�C�C�C�J"-�"-�"-�H�3�3�3�3��^�3�4�9!�9!�9!�9!��^�9!�v����X��G�G�G�G�G�@��� � � � �����0� � ��X� � � rr�)�� __future__rrrr6rar�r�rXr�r�r�� collectionsrrr�typesr�typingrr r rw�torch.utils.hooksr�rv�huggingface_hubr �accelerate.utils.importsr � checkpointingrrrrr�rrr�loggingrr�rr�rr�rrr�trackingrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/r0r1r2r3r4r5r6r7r8r9r:r;r<r=r>r?r@rArBrCrDrErFrGrHrIrJrKrLrMrNrOrPrQrRrSrTrUrVrWrXrYrZr[r\r]r^r_r`rarbrcrdrerf�utils.constantsrgrhrirjrk�utils.modelingrl� utils.otherrmrnrorprqrrrsrtrurvrwrxryrzr{�!torch.distributed.algorithms.joinr|�torch_xla.core.xla_model�core� xla_modelr��)torch_xla.distributed.xla_multiprocessing� distributed�xla_multiprocessingrD� torch_npu�torch.optim.lr_schedulerr~r�rr>r��objectr��_dispatch_batches� _even_batches�_use_seedable_samplerr�r�rr�<module>rs���#�"�"�"�"�"��������� � � � � � � � � � � � � � � � � � � � � � � � �����#�#�#�#�#�#�%�%�%�%�%�%�������������'�'�'�'�'�'�'�'�'�'� � � � �!�!�!�!�!�!�!�!�!�>�>�>�>�>�>�9�9�9�9�9�9�o�o�o�o�o�o�o�o�o�o�o�o�V�V�V�V�V�V�V�V�V�V�������+�+�+�+�+�+�+�+�+�+�+�+�@�@�@�@�@�@�@�@�@�@�K�K�K�K�K�K�K�K�K�K�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�J�V��������������;�:�:�:�:�:�+�+�+�+�+�+�������������������������� � � � � � � � � � � � � � � � � � � � � �3�2�2�2�2�2�����<�)�)�)�)�)�)�)�)�)�;�;�;�;�;�;�;�;�;����'�'�'������E�4�4�4�4�4�4�4���E�E�E�D�D�D�D�D�D�D�D�E���� ��H� � ��������F�H�H������ ������O9�O9�O9�O9�O9�O9�O9�O9�O9�O9s�=G� G�G
Memory