� %�g���6�dZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z mZddlmZddlmZmZmZmZmZmZmZddlZdd lmZmZmZmZmZm Z dd l!m"Z"m#Z#dd l$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,dd l-m.Z.m/Z/erdd l0m1Z1ej2e3��Z4Gd�d��Z5Gd�dej6��Z7Gd�dej8e7���Z9e Gd�de5����Z:Gd�de9��Z;e Gd�de5����Z<e Gd�de5����Z=e Gd�de5����Z>edZ?ed Z@ed!ZAed"ZBe Gd#�d$e5����ZCe Gd%�d&e5����ZDe Gd'�d(e5����ZEe Gd)�d*eDeE����ZFed+ZGe Gd,�d-e5����ZHGd.�d/eIej8��ZJGd0�d1eIej8��ZKGd2�d3eIej8��ZLGd4�d5eIej8��ZMGd6�d7eIe9��ZNGd8�d9e9��ZOGd:�d;eIe9��ZPGd<�d=e9��ZQGd>�d?ej8��ZRe Gd@�dA����ZSe GdB�dC����ZTe GdD�dE����ZUe GdF�dGe5����ZVe GdH�dIe5����ZWe GdJ�dK����ZXe GdL�dM����ZYe GdN�dO����ZZe GdP�dQ����Z[iZ\dReIfdS�Z]e]dT��dU���Z^e]dV��dW���Z_e]dX��dY���Z`e]dZ��d[���Zae Gd\�d]����Zbd^�ZcdS)_z1 General namespace and dataclass related classes �N)�Iterable)�contextmanager)� dataclass�field)� timedelta)� TYPE_CHECKING�Any�Callable�Literal�Optional�Union�get_args�)�!BETA_TP_AVAILABLE_PYTORCH_VERSION�FSDP_AUTO_WRAP_POLICY�FSDP_BACKWARD_PREFETCH�FSDP_SHARDING_STRATEGY�(MITA_PROFILING_AVAILABLE_PYTORCH_VERSION�'XPU_PROFILING_AVAILABLE_PYTORCH_VERSION)�parse_flag_from_env� str_to_bool)�is_cuda_available�is_hpu_available�is_mlu_available�is_msamp_available�is_musa_available�is_npu_available�is_transformer_engine_available�is_xpu_available)�compare_versions�is_torch_version)�Float8LinearConfigc��eZdZdZd�Zd�ZdS)� KwargsHandlerzP Internal mixin that implements a `to_kwargs()` method for a dataclass. c�4�tj|j��S�N)�copy�deepcopy�__dict__��selfs �l/home/asafur/pinokio/api/open-webui.git/app/env/lib/python3.11/site-packages/accelerate/utils/dataclasses.py�to_dictzKwargsHandler.to_dictDs���}�T�]�+�+�+�c���ddlm}|��5|�������ddd��n #1swxYwY|���}�fd�|���D��S)zv Returns a dictionary containing the attributes with values different from the default of this class. r)�clear_environmentNc�4��i|]\}}�||k�||��S�r2)�.0�k�v� default_dicts �r,� <dictcomp>z+KwargsHandler.to_kwargs.<locals>.<dictcomp>Qs-���K�K�K���A�l�1�o��6J�6J��1�6J�6J�6Jr.)� environmentr0� __class__r-�items)r+r0� this_dictr6s @r,� to_kwargszKwargsHandler.to_kwargsGs���� 3�2�2�2�2�2� � � � � 6� 6��>�>�+�+�3�3�5�5�L� 6� 6� 6� 6� 6� 6� 6� 6� 6� 6� 6���� 6� 6� 6� 6��L�L�N�N� �K�K�K�K����!2�!2�K�K�K�Ks�'A�A � A N)�__name__� __module__� __qualname__�__doc__r-r<r2r.r,r$r$?sA��������,�,�,� L� L� L� L� Lr.r$c��eZdZdZd�ZdS)�EnumWithContainsz\A metaclass that adds the ability to check if `self` contains an item with the `in` operatorc�B� ||��n#t$rYdSwxYwdS)NFT)� ValueError)�cls�items r,� __contains__zEnumWithContains.__contains__Ws=�� � �C��I�I�I�I��� � � ��5�5� �����ts � � �N)r=r>r?r@rGr2r.r,rBrBTs)������b�b�����r.rBc�.�eZdZdZd�Zed���ZdS)�BaseEnumzDAn enum class that can get the value of an item with `str(Enum.key)`c��|jSr&)�valuer*s r,�__str__zBaseEnum.__str__bs ���z�r.c�F�ttt|����S)z.Method to list all the possible items in `cls`)�list�map�str)rEs r,rNz BaseEnum.listes���C��S�M�M�"�"�"r.N)r=r>r?r@rL� classmethodrNr2r.r,rIrI_sD������J�J�����#�#��[�#�#�#r.rI)� metaclassc�0�eZdZUdZdZeed<dZeed<dS)�AutocastKwargsa� Use this object in your [`Accelerator`] to customize how `torch.autocast` behaves. Please refer to the documentation of this [context manager](https://pytorch.org/docs/stable/amp.html#torch.autocast) for more information on each argument. Example: ```python from accelerate import Accelerator from accelerate.utils import AutocastKwargs kwargs = AutocastKwargs(cache_enabled=True) accelerator = Accelerator(kwargs_handlers=[kwargs]) ``` T�enabledN� cache_enabled)r=r>r?r@rU�bool�__annotations__rVr2r.r,rTrTks>��������� �G�T�����M�4�����r.rTc�&�eZdZdZdZdZdZdZdZdS)�DDPCommunicationHookTypea� Represents a type of communication hook used in DDP. Values: - **NO** -- no communication hook - **FP16** -- DDP communication hook to compress the gradients in FP16 - **BF16** -- DDP communication hook to compress the gradients in BF16 - **POWER_SGD** -- DDP communication hook to use PowerSGD - **BATCHED_POWER_SGD** -- DDP communication hook to use batched PowerSGD �no�fp16�bf16� power_sgd�batched_power_sgdN) r=r>r?r@�NO�FP16�BF16� POWER_SGD�BATCHED_POWER_SGDr2r.r,rZrZ�s6������ � � �B� �D� �D��I�+���r.rZc���eZdZUdZdZeed<dZeed<dZ eed<dZ eed <dZ eed <dZ eed <dZ eed <ejZeed <ejZeejejejfed<ee���Zeed<d�fd� Zd�Z�xZS)�DistributedDataParallelKwargsa Use this object in your [`Accelerator`] to customize how your model is wrapped in a `torch.nn.parallel.DistributedDataParallel`. Please refer to the documentation of this [wrapper](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html) for more information on each argument. <Tip warning={true}> `gradient_as_bucket_view` is only available in PyTorch 1.7.0 and later versions. `static_graph` is only available in PyTorch 1.11.0 and later versions. </Tip> Example: ```python from accelerate import Accelerator from accelerate.utils import DistributedDataParallelKwargs kwargs = DistributedDataParallelKwargs(find_unused_parameters=True) accelerator = Accelerator(kwargs_handlers=[kwargs]) ``` r�dimT�broadcast_buffers�� bucket_cap_mbF�find_unused_parameters�check_reduction�gradient_as_bucket_view� static_graph� comm_hook� comm_wrapper)�default_factory�comm_state_option�rorprrc�����fd�t��������D��S)Nc�$��i|] \}}|�v� ||�� Sr2r2)r3r4r5� ignore_keyss �r,r7z9DistributedDataParallelKwargs.to_dict.<locals>.<dictcomp>�s)���S�S�S���A�a�{�>R�>R��1�>R�>R�>Rr.)�superr-r:)r+rvr9s `�r,r-z%DistributedDataParallelKwargs.to_dict�s8����S�S�S�S������!2�!2�!8�!8�!:�!:�S�S�S�Sr.c� �ddlm}m}tj|jtj|jtj|jtj |j i}tj|j tj|j i}|� |j��}|� |j��}|r |r ||��}|rL|jtjtj fvr|jdi|j��nd}|�||���dSdS)Nr)� default_hooks� powerSGD_hook)�state�hookr&)�+torch.distributed.algorithms.ddp_comm_hooksryrzrZra�fp16_compress_hookrb�bf16_compress_hookrcrd�batched_powerSGD_hook�fp16_compress_wrapper�bf16_compress_wrapper�getrorp� PowerSGDStaterr�register_comm_hook) r+�modelryrz�hook_map� wrapper_mapr|�wrapperr{s r,r�z0DistributedDataParallelKwargs.register_comm_hook�s7��\�\�\�\�\�\�\�\� %� )�=�+K� $� )�=�+K� $� .� �0K� $� 6� �8[� > �� %� )�=�+N� $� )�=�+N�A � � $,�<�<���#?�#?��&1�o�o�d�6G�&H�&H�� � !�G� !��7�4�=�=�D� � ��>�&>�&H�Jb�Jt�%u�u�u�,� �+�K�K�D�4J�K�K�K�� � � $� $��� %� � � � � � � r.)rs)r=r>r?r@rg�intrXrhrWrjrkrlrmrnrZr`rorpr rarbr�dictrrr-r�� __classcell__�r9s@r,rfrf�s<����������2�C��L�L�L�"��t�"�"�"��M�3����#(��D�(�(�(�!�O�T�!�!�!�$)��T�)�)�)��L�$����*B�*E�I�'�E�E�E� !�#��'� �#�%=�%B�D\�Da�a��$�$�$�$�e�D�9�9�9��t�9�9�9�T�T�T�T�T�T�������r.rfc�Z�eZdZUdZdZeed<dZeed<dZeed<dZ e ed <d Z e ed <d S) �GradScalerKwargsa� Use this object in your [`Accelerator`] to customize the behavior of mixed precision, specifically how the `torch.cuda.amp.GradScaler` used is created. Please refer to the documentation of this [scaler](https://pytorch.org/docs/stable/amp.html?highlight=gradscaler) for more information on each argument. <Tip warning={true}> `GradScaler` is only available in PyTorch 1.5.0 and later versions. </Tip> Example: ```python from accelerate import Accelerator from accelerate.utils import GradScalerKwargs kwargs = GradScalerKwargs(backoff_factor=0.25) accelerator = Accelerator(kwargs_handlers=[kwargs]) ``` g�@� init_scaleg@� growth_factorg�?�backoff_factori��growth_intervalTrUN) r=r>r?r@r��floatrXr�r�r�r�rUrWr2r.r,r�r��sn���������, �J������M�5�����N�E�����O�S�����G�T�����r.r�c�h�eZdZUdZdZeeed<dZeeed<dZ ee ed<d�Z dS)�InitProcessGroupKwargsa� Use this object in your [`Accelerator`] to customize the initialization of the distributed processes. Please refer to the documentation of this [method](https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group) for more information on each argument. Note: If `timeout` is set to `None`, the default will be based upon how `backend` is set. ```python from datetime import timedelta from accelerate import Accelerator from accelerate.utils import InitProcessGroupKwargs kwargs = InitProcessGroupKwargs(timeout=timedelta(seconds=800)) accelerator = Accelerator(kwargs_handlers=[kwargs]) ``` �nccl�backendN� init_method�timeoutc�`�|j�&|jdkrdnd}t|���|_dSdS)Nr�iiX)�seconds)r�r�r)r+r�s r,� __post_init__z$InitProcessGroupKwargs.__post_init__s=�� �<� �"�l�f�4�4�d�d�#�G�$�W�5�5�5�D�L�L�L� � r.) r=r>r?r@r�r rPrXr�r�rr�r2r.r,r�r�sn���������$$�G�X�c�]�#�#�#�!%�K��#��%�%�%�#'�G�X�i� �'�'�'�6�6�6�6�6r.r�)�MSAMP�TE��O1�O2)�E4M3�HYBRID)�max� most_recentc�H�eZdZUdZdZeded<dZeeed<dS)�AORecipeKwargsa� Use this object in your [`Accelerator`] to customize the initialization of the recipe for FP8 mixed precision training with `torchao` FP8. Args: config (`torchao.float8.Float8LinearConfig`, *optional*, default to `None`): The configuration for the FP8 training. In general, the default config should be sufficient. module_filter_func (`Callable`, *optional*, default to `None`): Optional function that must take in a module and layer name, and returns a boolean indicating whether the module should be converted to FP8. Defaults to `accelerate.utils.ao.filter_linear_layers`. See it for an example. Nr"�config�module_filter_func) r=r>r?r@r�r rXr�r r2r.r,r�r�'sJ������� � �.2�F�H�)� *�1�1�1�-1����*�1�1�1�1�1r.r�c��eZdZUdZdZeed<dZeed<dZ eed<dZ e ed<dZ eed<dZ eed<dZeeeefed <d �ZdS) �TERecipeKwargsa� Use this object in your [`Accelerator`] to customize the initialization of the recipe for FP8 mixed precision training with `transformer-engine`. <Tip> For more information on the args, please refer to the API [documentation](https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/api/common.html). </Tip> ```python from accelerate import Accelerator from accelerate.utils import TERecipeKwargs kwargs = TERecipeKwargs(fp8_format="HYBRID") accelerator = Accelerator(mixed_precision="fp8", kwargs_handlers=[kwargs]) ``` Args: use_autocast_during_eval (`bool`, *optional*, default to `False`): Whether to use FP8 autocast during eval mode. Generally better metrics are found when this is `False`. margin (`int`, *optional*, default to 0): The margin to use for the gradient scaling. interval (`int`, *optional*, default to 1): The interval to use for how often the scaling factor is recomputed. fp8_format (`str`, *optional*, default to "HYBRID"): The format to use for the FP8 recipe. Must be one of `HYBRID` or `E4M3`. (Generally `HYBRID` for training, `E4M3` for evaluation) amax_history_len (`int`, *optional*, default to 1024): The length of the history to use for the scaling factor computation amax_compute_algo (`str`, *optional*, default to "most_recent"): The algorithm to use for the scaling factor computation. Must be one of `max` or `most_recent`. override_linear_precision (`tuple` of three `bool`, *optional*, default to `(False, False, False)`): Whether or not to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision. N�use_autocast_during_eval�margin�interval� fp8_format�amax_history_len�amax_compute_algo�override_linear_precisionc���d}t��std���|j�t|dz��|_|j�5t t j�|dzd����|_|j �5t t j�|dzd����|_ |j �(t j�|dzd ��|_ |j � ��|_ |j tt��vr8td d �tt�����d ����|j�(t j�|d zd��|_|j���|_|jtt$��vr7tdd �tt$���������|j�5t t j�|dzd����|_|j�Bt|dz��}t|dz��}t|dz��}|||f|_dSdS)N�ACCELERATE_FP8_zQTransformerEngine is not available. Please install it or use a different backend.�USE_AUTOCAST_DURING_EVAL�MARGINr�INTERVALr�FORMATr�z`fp8_format` must be one of � or �.�AMAX_COMPUTE_ALGOr�z#`amax_compute_algo` must be one of �AMAX_HISTORY_LEN��OVERRIDE_FPROP�OVERRIDE_DGRAD�OVERRIDE_WGRAD)r� ImportErrorr�rr�r��os�environr�r�r��upperr� FP8FormatrD�joinr��lower�AmaxComputeAlgorithmr�r�)r+� env_prefix�fprop�dgrad�wgrads r,r�zTERecipeKwargs.__post_init__is*��&� �.�0�0� s��q�r�r� r� � (� 0�,?� �Mg�@g�,h�,h�D� )� �;� ��b�j�n�n�Z�(�-B�A�F�F�G�G�D�K� �=� ��� ���z�J�/F�� J� J�K�K�D�M� �?� "� �j�n�n�Z�(�-B�H�M�M�D�O��/�/�/�1�1��� �?�(�9�"5�"5� 5� 5��_�F�K�K��QZ�H[�H[�<\�<\�_�_�_�`�`� `� � !� )�%'�Z�^�^�J�AT�4T�Vc�%d�%d�D� "�!%�!7�!=�!=�!?�!?��� � !��2F�)G�)G� G� G��p�6�;�;�x�Xl�Om�Om�Cn�Cn�p�p�q�q� q� � � (�$'�� ���z�DV�7V�X\�(]�(]�$^�$^�D� !� � )� 1�'� �5E�(E�F�F�E�'� �5E�(E�F�F�E�'� �5E�(E�F�F�E�.3�U�E�-B�D� *� *� *� 2� 1r.)r=r>r?r@r�rWrXr�r�r�r�r�r�r�r�r��tupler�r2r.r,r�r�:s��������#�#�J&*��d�)�)�)��F�C�����H�c���� �J� � � � � ��c� � � �.2��+�2�2�2�9=��u�T�4��%5�6�=�=�=�C�C�C�C�Cr.r�c�(�eZdZUdZdZeed<d�ZdS)�MSAMPRecipeKwargsz� Use this object in your [`Accelerator`] to customize the initialization of the recipe for FP8 mixed precision training with `ms-amp`. N� opt_levelc� �d}|j�(tj�|dzd��|_|jt t ��vr7t dd�t t ���������dS)Nr�� OPT_LEVELr�z`opt_level` must be one of r�)r�r�r�r�r�OptLevelrDr�)r+r�s r,r�zMSAMPRecipeKwargs.__post_init__�st��&� � �>� !��Z�^�^�J��,D�d�K�K�D�N� �>��(�!3�!3� 3� 3��\�6�;�;�x�PX�GY�GY�;Z�;Z�\�\�]�]� ]� 4� 3r.)r=r>r?r@r�r�rXr�r2r.r,r�r��sF��������� �I�x����^�^�^�^�^r.r�c�2��eZdZUdZdZeed<�fd�Z�xZS)�FP8RecipeKwargsz� Deprecated. Please use one of the proper FP8 recipe kwargs classes such as `TERecipeKwargs` or `MSAMPRecipeKwargs` instead. Nr�c���d}tjdt��t��rdnd}|j�(t j�|dz|��|_|j���|_|jtt��vrtd���t��� ��dS)Nr�z�FP8RecipeKwargs is deprecated and will be removed in Accelerate v2.0.0. Please use one of the proper FP8 recipe kwargs classes such as TERecipeKwargs or MSAMPRecipeKwargs instead.�msamp�te�BACKENDzO`backend` must be 'MSAMP' or 'TE' (TransformerEngine) to use `FP8RecipeKwargs`.)�warnings�warn� FutureWarningrr�r�r�r�r�r�BackendrDrwr�)r+r��default_backendr9s �r,r�zFP8RecipeKwargs.__post_init__�s����&� �� � z� � � � � &8�%9�%9�C�'�'�t�� �<� ��:�>�>�*�y�*@�/�R�R�D�L��|�)�)�+�+�� � �<�x��0�0� 0� 0��n�o�o� o� ���������r.) r=r>r?r@r�r�rXr�r�r�s@r,r�r��sV���������� �G�W����  �  �  �  �  �  �  �  �  r.r�)�cpu�xpu�mtia�cuda�hpuc�"�eZdZUdZdZeeeed<dZ ee e e fed<dZ eeed<dZeed<dZeed<dZeed <dZeed <dZeed <dZee ed <d edejjfd�Zdejjfd�ZdS)� ProfileKwargsu@ Use this object in your [`Accelerator`] to customize the initialization of the profiler. Please refer to the documentation of this [context manager](https://pytorch.org/docs/stable/profiler.html#torch.profiler.profile) for more information on each argument. <Tip warning={true}> `torch.profiler` is only available in PyTorch 1.8.1 and later versions. </Tip> Example: ```python from accelerate import Accelerator from accelerate.utils import ProfileKwargs kwargs = ProfileKwargs(activities=["cpu", "cuda"]) accelerator = Accelerator(kwargs_handlers=[kwargs]) ``` Args: activities (`List[str]`, *optional*, default to `None`): The list of activity groups to use in profiling. Must be one of `"cpu"`, `"xpu"`, `"mtia"`, "hpu" or `"cuda"`. schedule_option (`Dict[str, int]`, *optional*, default to `None`): The schedule option to use for the profiler. Available keys are `wait`, `warmup`, `active`, `repeat` and `skip_first`. The profiler will skip the first `skip_first` steps, then wait for `wait` steps, then do the warmup for the next `warmup` steps, then do the active recording for the next `active` steps and then repeat the cycle starting with `wait` steps. The optional number of cycles is specified with the `repeat` parameter, the zero value means that the cycles will continue until the profiling is finished. on_trace_ready (`Callable`, *optional*, default to `None`): Callable that is called at each step when schedule returns `ProfilerAction.RECORD_AND_SAVE` during the profiling. record_shapes (`bool`, *optional*, default to `False`): Save information about operator’s input shapes. profile_memory (`bool`, *optional*, default to `False`): Track tensor memory allocation/deallocation with_stack (`bool`, *optional*, default to `False`): Record source information (file and line number) for the ops. with_flops (`bool`, *optional*, default to `False`): Use formula to estimate the FLOPS of specific operators with_modules (`bool`, *optional*, default to `False`): Record module hierarchy (including function names) corresponding to the callstack of the op. output_trace_dir (`str`, *optional*, default to `None`): Exports the collected trace in Chrome JSON format. Chrome use 'chrome://tracing' view json file. Defaults to None, which means profiling does not store json files. N� activities�schedule_option�on_trace_readyF� record_shapes�profile_memory� with_stack� with_flops� with_modules�output_trace_dir�activity�returnc�8�tjjjtjjjd�}t ��rtjjj|d<tdt��r7tj � ��rtjjj |d<tdt��r7tj � ��rtjjj|d<||vr#td|�dt!|���d����||S) z�Get the profiler activity from the string. Args: activity (str): The profiler activity name. Returns: torch.profiler.ProfilerActivity: The profiler activity. )r�r�r�z>=r�r�zInvalid profiler activity: �. Must be one of r�)�torch�profiler�ProfilerActivity�CPU�CUDAr�HPUr!rr�� is_available�XPUrr��MTIArDrN)r+r��profiler_activity_maps r,�_get_profiler_activityz$ProfileKwargs._get_profiler_activity�s ���>�2�6��N�3�8�M �M �� � � � O�+0�>�+J�+N� !�%� (� �D�"I� J� J� S��y�%�%�'�'� S�/4�~�/N�/R�%�e�,� �D�"J� K� K� U��z�&�&�(�(� U�05��0O�0T�%�f�-� �0� 0� 0��t�8�t�t�VZ�[p�Vq�Vq�t�t�t�u�u� u�$�X�.�.r.c ���d}�j��fd��jD��}d}�j�tjjdi�j��}tj�||�j�j�j�j �j �j ���S)z� Build a profiler object with the current configuration. Returns: torch.profiler.profile: The profiler object. Nc�:��g|]}��|����Sr2)r�)r3r�r+s �r,� <listcomp>z'ProfileKwargs.build.<locals>.<listcomp>s'���`�`�`�H�$�5�5�h�?�?�`�`�`r.)r��scheduler�r�r�r�r�r�r2) r�r�r�r�r�profiler�r�r�r�r�r�)r+r�rs` r,�buildzProfileKwargs.builds����8<� � �?� &�`�`�`�`�PT�P_�`�`�`�J�6:�� � � +��~�.�F�F��1E�F�F�H��~�%�%�!���.��,��.������*�&�  �  � r.)r=r>r?r@r�r rNr�rXr�r�rPr�r�r r�rWr�r�r�r�r�r�r�r�rrr2r.r,r�r��s�������/�/�b48�J���.�/�0�7�7�7�04�O�X�d�3��8�n�-�4�4�4�)-�N�H�X�&�-�-�-��M�4���� �N�D� � � ��J������J������L�$����&*��h�s�m�*�*�*�/�/?�/�E�N�Dc�/�/�/�/�< �u�~�-� � � � � � r.r�c�J�eZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdS)�DistributedTypea� Represents a type of distributed environment. Values: - **NO** -- Not a distributed environment, just a single process. - **MULTI_CPU** -- Distributed on multiple CPU nodes. - **MULTI_GPU** -- Distributed on multiple GPUs. - **MULTI_MLU** -- Distributed on multiple MLUs. - **MULTI_SDAA** -- Distributed on multiple SDAAs. - **MULTI_MUSA** -- Distributed on multiple MUSAs. - **MULTI_NPU** -- Distributed on multiple NPUs. - **MULTI_XPU** -- Distributed on multiple XPUs. - **MULTI_HPU** -- Distributed on multiple HPUs. - **DEEPSPEED** -- Using DeepSpeed. - **XLA** -- Using TorchXLA. r`� MULTI_CPU� MULTI_GPU� MULTI_NPU� MULTI_MLU� MULTI_SDAA� MULTI_MUSA� MULTI_XPU� DEEPSPEED�FSDP�TP�XLA� MEGATRON_LM� MULTI_HPUN)r=r>r?r@r`rrr r r r r rrrrrrr2r.r,rr)s`��������& �B��I��I��I��I��J��J��I��I� �D� �B� �C��K��I�I�Ir.rc��eZdZdZdZdZdZdS)�SageMakerDistributedTypea+ Represents a type of distributed environment. Values: - **NO** -- Not a distributed environment, just a single process. - **DATA_PARALLEL** -- using sagemaker distributed data parallelism. - **MODEL_PARALLEL** -- using sagemaker distributed model parallelism. r`� DATA_PARALLEL�MODEL_PARALLELN)r=r>r?r@r`rrr2r.r,rrMs)�������� �B�#�M�%�N�N�Nr.rc��eZdZdZdZdZdS)�FP8BackendTypez� Represents the backend used for FP8. Values: - **TE** -- using TransformerEngine. - **MSAMP** -- using msamp. r�r�N)r=r>r?r@r�r�r2r.r,rr^s$�������� �B� �E�E�Er.rc��eZdZdZdZdZdS)�ComputeEnvironmentz� Represents a type of the compute environment. Values: - **LOCAL_MACHINE** -- private/custom cluster hardware. - **AMAZON_SAGEMAKER** -- Amazon SageMaker as compute environment. � LOCAL_MACHINE�AMAZON_SAGEMAKERN)r=r>r?r@rrr2r.r,rrms'��������$�M�)���r.rc�R�eZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdS)� DynamoBackenda7 Represents a dynamo backend (see https://pytorch.org/docs/stable/torch.compiler.html). Values: - **NO** -- Do not use torch dynamo. - **EAGER** -- Uses PyTorch to run the extracted GraphModule. This is quite useful in debugging TorchDynamo issues. - **AOT_EAGER** -- Uses AotAutograd with no compiler, i.e, just using PyTorch eager for the AotAutograd's extracted forward and backward graphs. This is useful for debugging, and unlikely to give speedups. - **INDUCTOR** -- Uses TorchInductor backend with AotAutograd and cudagraphs by leveraging codegened Triton kernels. [Read more](https://dev-discuss.pytorch.org/t/torchinductor-a-pytorch-native-compiler-with-define-by-run-ir-and-symbolic-shapes/747) - **AOT_TS_NVFUSER** -- nvFuser with AotAutograd/TorchScript. [Read more](https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593) - **NVPRIMS_NVFUSER** -- nvFuser with PrimTorch. [Read more](https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593) - **CUDAGRAPHS** -- cudagraphs with AotAutograd. [Read more](https://github.com/pytorch/torchdynamo/pull/757) - **OFI** -- Uses Torchscript optimize_for_inference. Inference only. [Read more](https://pytorch.org/docs/stable/generated/torch.jit.optimize_for_inference.html) - **FX2TRT** -- Uses Nvidia TensorRT for inference optimizations. Inference only. [Read more](https://github.com/pytorch/TensorRT/blob/master/docsrc/tutorials/getting_started_with_fx_path.rst) - **ONNXRT** -- Uses ONNXRT for inference on CPU/GPU. Inference only. [Read more](https://onnxruntime.ai/) - **TENSORRT** -- Uses ONNXRT to run TensorRT for inference optimizations. [Read more](https://github.com/onnx/onnx-tensorrt) - **AOT_TORCHXLA_TRACE_ONCE** -- Uses Pytorch/XLA with TorchDynamo optimization, for training. [Read more](https://github.com/pytorch/xla/blob/r2.0/docs/dynamo.md) - **TORCHXLA_TRACE_ONCE** -- Uses Pytorch/XLA with TorchDynamo optimization, for inference. [Read more](https://github.com/pytorch/xla/blob/r2.0/docs/dynamo.md) - **IPEX** -- Uses IPEX for inference on CPU. Inference only. [Read more](https://github.com/intel/intel-extension-for-pytorch). - **TVM** -- Uses Apach TVM for inference optimizations. [Read more](https://tvm.apache.org/) - **HPU_BACKEND** -- Uses HPU backend for inference optimizations. r`�EAGER� AOT_EAGER�INDUCTOR�AOT_TS_NVFUSER�NVPRIMS_NVFUSER� CUDAGRAPHS�OFI�FX2TRT�ONNXRT�TENSORRT�AOT_TORCHXLA_TRACE_ONCE�TORCHXLA_TRACE_ONCE�IPEX�TVM� HPU_BACKENDN)r=r>r?r@r`r r!r"r#r$r%r&r'r(r)r*r+r,r-r.r2r.r,rr|sm������"�"�J �B� �E��I��H�%�N�'�O��J� �C� �F� �F��H�7��/�� �D� �C��K�K�Kr.rc�2�eZdZdZdZdZdZdZdZdZ dZ d Z d S) � LoggerTypea�Represents a type of supported experiment tracker Values: - **ALL** -- all available trackers in the environment that are supported - **TENSORBOARD** -- TensorBoard as an experiment tracker - **WANDB** -- wandb as an experiment tracker - **COMETML** -- comet_ml as an experiment tracker - **DVCLIVE** -- dvclive as an experiment tracker �all�aim� tensorboard�wandb�comet_ml�mlflow�clearml�dvcliveN) r=r>r?r@�ALL�AIM� TENSORBOARD�WANDB�COMETML�MLFLOW�CLEARML�DVCLIVEr2r.r,r0r0�sB������ � � �C� �C��K� �E��G� �F��G��G�G�Gr.r0c�"�eZdZdZdZdZdZdZdS)� PrecisionTypez�Represents a type of precision used on floating point values Values: - **NO** -- using full precision (FP32) - **FP16** -- using half precision - **BF16** -- using brain floating point precision r[�fp8r\r]N)r=r>r?r@r`�FP8rarbr2r.r,rBrB�s.�������� �B� �C� �D� �D�D�Dr.rBc�6�eZdZdZdZdZdZdZdZdZ dZ d Z d Z d S) �RNGTyper�r��mlu�sdaa�musa�npu�xlar�r�� generatorN) r=r>r?�TORCHr��MLU�SDAA�MUSA�NPUrr�r�� GENERATORr2r.r,rFrF�s@������ �E� �D� �C� �D� �D� �C� �C� �C� �C��I�I�Ir.rFc��eZdZdZdZdZdZdS)� CustomDtypezd An enum that contains multiple custom dtypes that can be used for `infer_auto_device_map`. rC�int4�int2N)r=r>r?r@rD�INT4�INT2r2r.r,rTrT�s)�������� �C� �D� �D�D�Dr.rTc�8�eZdZUejed<ejed<dS)�TensorInformation�shape�dtypeN)r=r>r?r��SizerXr\r2r.r,rZrZ�s.������� �:���� �;�����r.rZc�,�eZdZUdZedddi���Zeed<edddi���Zeed <ed dd i���Z eed <eddd i���Z eed<edddi���Z e ed<edddi���Z eed<edddi���Zeed<dS)�DataLoaderConfigurationa� Configuration for dataloader-related items when calling `accelerator.prepare`. Args: split_batches (`bool`, defaults to `False`): Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. If `True`, the actual batch size used will be the same on any kind of distributed processes, but it must be a round multiple of `num_processes` you are using. If `False`, actual batch size used will be the one set in your script multiplied by the number of processes. dispatch_batches (`bool`, defaults to `None`): If set to `True`, the dataloader prepared by the Accelerator is only iterated through on the main process and then the batches are split and broadcast to each process. Will default to `True` for `DataLoader` whose underlying dataset is an `IterableDataset`, `False` otherwise. even_batches (`bool`, defaults to `True`): If set to `True`, in cases where the total batch size across all processes does not exactly divide the dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among all workers. use_seedable_sampler (`bool`, defaults to `False`): Whether or not use a fully seedable random sampler ([`data_loader.SeedableRandomSampler`]). Ensures training results are fully reproducable using a different sampling technique. While seed-to-seed results may differ, on average the differences are neglible when using multiple different seeds to compare. Should also be ran with [`~utils.set_seed`] for the best results. data_seed (`int`, defaults to `None`): The seed to use for the underlying generator when using `use_seedable_sampler`. If `None`, the generator will use the current default seed from torch. non_blocking (`bool`, defaults to `False`): If set to `True`, the dataloader prepared by the Accelerator will utilize non-blocking host-to-device transfers, allowing for better overlap between dataloader communication and computation. Recommended that the prepared dataloader has `pin_memory` set to `True` to work properly. use_stateful_dataloader (`bool`, defaults to `False`): If set to `True`, the dataloader prepared by the Accelerator will be backed by [torchdata.StatefulDataLoader](https://github.com/pytorch/data/tree/main/torchdata/stateful_dataloader). This requires `torchdata` version 0.8.0 or higher that supports StatefulDataLoader to be installed. F�helpauWhether or not the accelerator should split the batches yielded by the dataloaders across the devices. If `True` the actual batch size used will be the same on any kind of distributed processes, but it must be a round multiple of the `num_processes` you are using. If `False`, actual batch size used will be the one set in your script multiplied by the number of processes.��default�metadata� split_batchesNaIf set to `True`, the dataloader prepared by the Accelerator is only iterated through on the main process and then the batches are split and broadcast to each process. Will default to `True` for `DataLoader` whose underlying dataset is an `IterableDataset`, `False` otherwise.�dispatch_batchesTz�If set to `True`, in cases where the total batch size across all processes does not exactly divide the dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among all workers.� even_batchesapWhether or not use a fully seedable random sampler ([`data_loader.SeedableRandomSampler`]).Ensures training results are fully reproducable using a different sampling technique. While seed-to-seed results may differ, on average the differences are neglible when usingmultiple different seeds to compare. Should also be ran with [`~utils.set_seed`] for the best results.�use_seedable_samplerz�The seed to use for the underlying generator when using `use_seedable_sampler`. If `None`, the generator will use the current default seed from torch.� data_seedaIf set to `True`, the dataloader prepared by the Accelerator will utilize non-blocking host-to-device transfers, allowing for better overlap between dataloader communication and computation. Recommended that the prepared dataloader has `pin_memory` set to `True` to work properly.� non_blockingaIf set to `True`, the dataloader prepared by the Accelerator will be backed by [torchdata.StatefulDataLoader](https://github.com/pytorch/data/tree/main/torchdata/stateful_dataloader). This requires `torchdata` version 0.8.0 or higher that supports StatefulDataLoader to be installed.�use_stateful_dataloader)r=r>r?r@rrdrWrXrerfrgrhr�rirjr2r.r,r_r_�s��������!�!�F �%�� �E� ����M�4����#�U�� �N� �����d������� �� ����L�$����"'��� �u� �"�"�"��$�����U�� �=� ����I�s������� �T� ����L�$����%*�E�� �[� �%�%�%��T�����r.r_c��eZdZUdZedddi���Zeed<edddi���Zeed<ed dd i���Z e ed <eddd i���Z e ed <edddi���Z e ed<ed ddi���Ze ed<ddefd�Zd�ZdS)�ProjectConfigurationa� Configuration for the Accelerator object based on inner-project needs. Args: project_dir (`str`, defaults to `None`): A path to a directory for storing data. logging_dir (`str`, defaults to `None`): A path to a directory for storing logs of locally-compatible loggers. If None, defaults to `project_dir`. automatic_checkpoint_naming (`bool`, defaults to `False`): Whether saved states should be automatically iteratively named. total_limit (`int`, defaults to `None`): The maximum number of total saved states to keep. iteration (`int`, defaults to `0`): The current save iteration. save_on_each_node (`bool`, defaults to `False`): When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on the main one. Nr`z'A path to a directory for storing data.ra� project_dirziA path to a directory for storing logs of locally-compatible loggers. If None, defaults to `project_dir`.� logging_dirFz?Whether saved states should be automatically iteratively named.�automatic_checkpoint_namingz1The maximum number of total saved states to keep.� total_limitrzThe current save iteration.� iterationzxWhen doing multi-node distributed training, whether to save models and checkpoints on each node, or only on the main one�save_on_each_nodec�4�||_|j� ||_dSdS)zISets `self.project_dir` and `self.logging_dir` to the appropriate values.N)rmrn)r+rms r,�set_directoriesz$ProjectConfiguration.set_directories�s)��&��� � � #�*�D� � � � $� #r.c�:�|�|j��dSr&)rtrmr*s r,r�z"ProjectConfiguration.__post_init__�s�� ���T�-�.�.�.�.�.r.r&)r=r>r?r@rrmrPrXrnrorWrpr�rqrrrtr�r2r.r,rlrlYs����������&�u�T�V�=f�4g�h�h�h�K��h�h�h��u�� �� ����K����� ).����[�\�)�)�)������ �u���M�N����K����� �U���7�8����I�s���� $�e�� �(� �����t����+�+�3�+�+�+�+� /�/�/�/�/r.rlc��eZdZUdZedddi���Zeed<edddi���Ze ed <eddd i���Z e ed <ed dd i���Z e ed<dS)�GradientAccumulationPlugina� A plugin to configure gradient accumulation behavior. You can only pass one of `gradient_accumulation_plugin` or `gradient_accumulation_steps` to [`Accelerator`]. Passing both raises an error. Parameters: num_steps (`int`): The number of steps to accumulate gradients for. adjust_scheduler (`bool`, *optional*, defaults to `True`): Whether to adjust the scheduler steps to account for the number of steps being accumulated. Should be `True` if the used scheduler was not adjusted for gradient accumulation. sync_with_dataloader (`bool`, *optional*, defaults to `True`): Whether to synchronize setting the gradients when at the end of the dataloader. sync_each_batch (`bool`, *optional*): Whether to synchronize setting the gradients at each data batch. Seting to `True` may reduce memory requirements when using gradient accumulation with distributed training, at expense of speed. Example: ```python from accelerate.utils import GradientAccumulationPlugin gradient_accumulation_plugin = GradientAccumulationPlugin(num_steps=2) accelerator = Accelerator(gradient_accumulation_plugin=gradient_accumulation_plugin) ``` Nr`z0The number of steps to accumulate gradients for.ra� num_stepsTz�Whether to adjust the scheduler steps to account for the number of steps being accumulated. Should be `True` if the used scheduler was not adjusted for gradient accumulation.�adjust_schedulerz�Whether to synchronize setting the gradients when at the end of the dataloader. Should only be set to `False` if you know what you're doing.�sync_with_dataloaderFz�Whether to synchronize setting the gradients at each data batch. Setting to `True` may reduce memory requirements when using gradient accumulation with distributed training, at expense of speed.�sync_each_batch) r=r>r?r@rrxr�rXryrWrzr{r2r.r,rwrw�s����������4�U�4�6�;m�2n�o�o�o�I�s�o�o�o�"�U�� �E� �����d���� "'��� �c� �"�"�"��$���� "�E�� �Y� ����O�T�����r.rwc�*�eZdZUdZedddd�eD����i���Zeed<edddi���Ze ed <eddd i���Z e ed <eddd i���Z e ed <edddi���Z eed<edddi���Ze ed<d�Zd�ZdS)�TorchDynamoPlugina This plugin is used to compile a model with PyTorch 2.0 Args: backend (`DynamoBackend`, defaults to `None`): A valid Dynamo backend. See https://pytorch.org/docs/stable/torch.compiler.html for more details. mode (`str`, defaults to `None`): Possible options are 'default', 'reduce-overhead' or 'max-autotune'. fullgraph (`bool`, defaults to `None`): Whether it is ok to break model into several subgraphs. dynamic (`bool`, defaults to `None`): Whether to use dynamic shape for tracing. options (`Any`, defaults to `None`): A dictionary of options to pass to the backend. disable (`bool`, defaults to `False`): Turn torch.compile() into a no-op for testing Nr`zPossible options are c�@�g|]}|j�����Sr2)rKr�)r3�bs r,rzTorchDynamoPlugin.<listcomp>�s"��2Z�2Z�2Z�q�1�7�=�=�?�?�2Z�2Z�2Zr.rar�zCPossible options are 'default', 'reduce-overhead' or 'max-autotune'�modez6Whether it is ok to break model into several subgraphs� fullgraphz(Whether to use dynamic shape for tracing�dynamicz/A dictionary of options to pass to the backend.�optionsFz-Turn torch.compile() into a no-op for testing�disablec� �d}|j�(tj�|dzd��|_t |j�����|_|j�(tj�|dzd��|_|j�9ttj�|dzd����dk|_|j �;ttj�|d zd����dk|_ dSdS) N�ACCELERATE_DYNAMO_r�r[�MODErb� USE_FULLGRAPH�Falser� USE_DYNAMIC) r�r�r�r�rr�r�r�rr��r+�prefixs r,r�zTorchDynamoPlugin.__post_init__�s���%�� �<� ��:�>�>�&�9�*<�d�C�C�D�L�$�T�\�%7�%7�%9�%9�:�:�� � �9� �� ���v��� �B�B�D�I� �>� !�(�������8P�RY�)Z�)Z�[�[�_`�`�D�N� �<� �&�r�z�~�~�f�}�6L�g�'V�'V�W�W�[\�\�D�L�L�L� � r.c�|�tj|j��}|dj���|d<|S)Nr�)r'r(r)rKr�)r+� dynamo_configs r,r-zTorchDynamoPlugin.to_dict�s7��� �d�m�4�4� �#0��#;�#A�#G�#G�#I�#I� �i� ��r.)r=r>r?r@rrr�rXr�rPr�rWr�r�r r�r�r-r2r.r,r}r}�sW���������$#�U���\�2Z�2Z�M�2Z�2Z�2Z�\�\�]����G�]��������(m�n����D�#�����e�D�F�<t�3u�v�v�v�I�t�v�v�v��E�$�&�:d�1e�f�f�f�G�T�f�f�f��5���9j�0k�l�l�l�G�S�l�l�l��E�%�6�;j�2k�l�l�l�G�T�l�l�l� ]� ]� ]�����r.r}c� �eZdZUdZedddi���Zeed<edddi���Ze ed<eddd i���Z e ed <eddd i���Z e ed <ed ddi���Z eed<edddi���Zeed<edddi���Zeed<edddi���Zeed<edddi���Zeed<edddi���Zeed<edddi���Zeed<edddi���Zeed<edddi���Zeed<edddi���Zeed ed!<d"�Zd6d#�Zd$�Zd7d%�Zd8d'�Zd(�Z d)�Z!d*�Z"e#d9d,���Z$d-�Z%d.�Z&d9d/efd0�Z'd1�Z(d2efd3�Z)e*d4���Z+e+j,d5���Z+dS):�DeepSpeedPluginaW This plugin is used to integrate DeepSpeed. Args: hf_ds_config (`Any`, defaults to `None`): Path to DeepSpeed config file or dict or an object of class `accelerate.utils.deepspeed.HfDeepSpeedConfig`. gradient_accumulation_steps (`int`, defaults to `None`): Number of steps to accumulate gradients before updating optimizer states. If not set, will use the value from the `Accelerator` directly. gradient_clipping (`float`, defaults to `None`): Enable gradient clipping with value. zero_stage (`int`, defaults to `None`): Possible options are 0, 1, 2, 3. Default will be taken from environment variable. is_train_batch_min (`bool`, defaults to `True`): If both train & eval dataloaders are specified, this will decide the `train_batch_size`. offload_optimizer_device (`str`, defaults to `None`): Possible options are none|cpu|nvme. Only applicable with ZeRO Stages 2 and 3. offload_param_device (`str`, defaults to `None`): Possible options are none|cpu|nvme. Only applicable with ZeRO Stage 3. offload_optimizer_nvme_path (`str`, defaults to `None`): Possible options are /nvme|/local_nvme. Only applicable with ZeRO Stage 3. offload_param_nvme_path (`str`, defaults to `None`): Possible options are /nvme|/local_nvme. Only applicable with ZeRO Stage 3. zero3_init_flag (`bool`, defaults to `None`): Flag to indicate whether to save 16-bit model. Only applicable with ZeRO Stage-3. zero3_save_16bit_model (`bool`, defaults to `None`): Flag to indicate whether to save 16-bit model. Only applicable with ZeRO Stage-3. transformer_moe_cls_names (`str`, defaults to `None`): Comma-separated list of Transformers MoE layer class names (case-sensitive). For example, `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention`, `JetMoEBlock`, etc. enable_msamp (`bool`, defaults to `None`): Flag to indicate whether to enable MS-AMP backend for FP8 training. msasmp_opt_level (`Optional[Literal["O1", "O2"]]`, defaults to `None`): Optimization level for MS-AMP (defaults to 'O1'). Only applicable if `enable_msamp` is True. Should be one of ['O1' or 'O2']. Nr`zkpath to DeepSpeed config file or dict or an object of class `accelerate.utils.deepspeed.HfDeepSpeedConfig`.ra� hf_ds_configz�Number of steps to accumulate gradients before updating optimizer states. If not set, will use the value from the `Accelerator` directly.�gradient_accumulation_stepsz#Enable gradient clipping with value�gradient_clippingzMPossible options are 0,1,2,3; Default will be taken from environment variable� zero_stageTzUIf both train & eval dataloaders are specified, this will decide the train_batch_size�is_train_batch_minzMPossible options are none|cpu|nvme. Only applicable with ZeRO Stages 2 and 3.�offload_optimizer_devicezFPossible options are none|cpu|nvme. Only applicable with ZeRO Stage 3.�offload_param_devicezJPossible options are /nvme|/local_nvme. Only applicable with ZeRO Stage 3.�offload_optimizer_nvme_path�offload_param_nvme_pathz{Flag to indicate whether to enable `deepspeed.zero.Init` for constructing massive models.Only applicable with ZeRO Stage-3.�zero3_init_flagzQFlag to indicate whether to save 16-bit model. Only applicable with ZeRO Stage-3.�zero3_save_16bit_modelz�comma-separated list of transformers MoE layer class names (case-sensitive), e.g : `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ...�transformer_moe_cls_nameszCFlag to indicate whether to enable MS-AMP backend for FP8 training.� enable_msampz}Optimization level for MS-AMP (defaults to 'O1'). Only applicable if `enable_msamp` is True. Should be one of ['O1' or 'O2'].r��msamp_opt_levelc �� ��ddlm}�j�Jtj�dd��}|���rt|��n|�_�j�<tj�dd��}|dkr|nt|���_�j �2ttj�dd�����_ �j �%tj�dd ���_ �j �%tj�d d ���_ �j �%tj�d d ���_ �j�%tj�d d ���_�j�)tj�d d��dk�_�j�)tj�dd��dk�_�j�%tj�dd���_�j�%tj�dd ���_t'�jt(��s;t'�jt*��r �jd kst'�j|���r3t'�j|��s|�j���_d�jjvrd�jjd<d�jjvrt/d�������ddddddddd�}�fd �|���D��}|���D]}�j|fi|�d!d"i����j���|���D]8\}}�j�|��}|�|dkrt=�||���9npdd�j�j �j �j d#kr�j ndd$��j �j d#kr�jndd$��jd%�d&�} �jr �j| d<|| ���_�jj�_td'���jd(<�j �ZtCtj�d)t+�j�"��������dk�_ �j r4�j�"��stGj$d*��d"�_ ��%d"���jrOd+�jvrH�j d,krtMd-����jd.vrt/d/���d0�jd1��jd+<dSdSdS)2Nr)�HfDeepSpeedConfig�&ACCELERATE_GRADIENT_ACCUMULATION_STEPS�auto�ACCELERATE_GRADIENT_CLIPPING�ACCELERATE_DEEPSPEED_ZERO_STAGE��-ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_DEVICE�none�)ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_DEVICE�0ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_NVME_PATH�,ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_NVME_PATH�+ACCELERATE_DEEPSPEED_ZERO3_SAVE_16BIT_MODEL�false�true�ACCELERATE_FP8_BACKENDr��ACCELERATE_FP8_OPT_LEVELr�� ACCELERATE_DEEPSPEED_CONFIG_FILEr��zero_optimizationzDPlease specify the ZeRO optimization config in the DeepSpeed config.r�zzero_optimization.stagez*zero_optimization.offload_optimizer.devicez&zero_optimization.offload_param.devicez)zero_optimization.offload_param.nvme_pathz-zero_optimization.offload_optimizer.nvme_pathz;zero_optimization.stage3_gather_16bit_weights_on_model_save)r�r�r�r�r�r�r�r�c�X��i|]&\}}t�|���|t�|����'Sr&)�getattr)r3r4r5r+s �r,r7z1DeepSpeedPlugin.__post_init__.<locals>.<dictcomp>�s;���w�w�w�d�a��Za�bf�hi�Zj�Zj�Zv�a���q�)�)�Zv�Zv�Zvr.� must_matchF�nvme)�device� nvme_path)�stage�offload_optimizer� offload_param�)stage3_gather_16bit_weights_on_model_save)�train_batch_size�train_micro_batch_size_per_gpur�r��inf�steps_per_print�ACCELERATE_DEEPSPEED_ZERO3_INITzSDeepSpeed Zero3 Init flag is only applicable for ZeRO Stage 3. Setting it to False.r��zSMS-AMP is not supported for ZeRO Stage 3. Please use ZeRO Stage 0, 1, or 2 instead.r�zGInvalid optimization level for MS-AMP. Please use one of ['O1' or'O2'].T�rUr�)'� deepspeedr�r�r�r�r��isdigitr�r�r�r�r�r�r�r�r�r�r�r�� isinstancer�rPr�rD�_deepspeed_config_checksr:�keys� fill_match�set_stage_and_offload� get_value�setattr�deepspeed_configr�r�is_zero3r�r�� _set_selected�NotImplementedError) r+r��gasr��plugin_to_config_mapping�kwargs�keyrK� config_valuer�s ` r,r�zDeepSpeedPlugin.__post_init__ds����0�0�0�0�0�0� � +� 3��*�.�.�!I�6�R�R�C�;>�;�;�=�=�/Q�s�3�x�x�x�c�D� ,� � !� )� "� ���/M�v� V� V� �:K�v�:U�:U�%6�%6�[`�ar�[s�[s�D� "� �?� "�!�"�*�.�.�1R�TU�"V�"V�W�W�D�O� � (� 0�,.�J�N�N�;j�lr�,s�,s�D� )� � $� ,�(*� ���7b�dj�(k�(k�D� %� � +� 3�/1�z�~�~�B�F�0�0�D� ,� � '� /�+-�:�>�>�:h�jp�+q�+q�D� (� � &� .�� ���L�g�V�V�Z`�`� � '� � � $� "� ���/G�� N� N�RY� Y�D� � � � '�#%�:�>�>�2L�d�#S�#S�D� � � � $� "� ���/Q�SY� Z� Z�D� � �t�(�$� /� /�8 :��4�,�c�2�2�8 :�7;�7H�F�7R�7R��$�+�->�?�?�8S��d�/�1B�C�C� I�$5�$5�d�6G�$H�$H��!�,�D�4E�4L�L�L�JK��!�(�)F�G�"�$�*;�*B�B�B� �!g�h�h�h� � )� )� +� +� +�/L�%8�7�,X�(P�+V�/^�*g� (� (� $�x�w�w�w�6N�6T�6T�6V�6V�w�w�w�F��{�{�}�}� A� A������@�@�v�@�@�%�@�@�@�@�@� � � 3� 3� 5� 5� 5�7�<�<�>�>� 5� 5� ��U�#�0�:�:�5�A�A� ��+� ��0F�0F��D�#�|�4�4�4�� 5� %+�28�/3�/O�!�_�"&�"?��8�F�B�B�&*�%E�%E�!� *�*�#'�";�EI�E^�bh�Eh�Eh�T�%A�%A�nr�&�&�BF�A\� &� &� ��F�&�%� E�.2�.D��*�+� 1� 1�&� 9� 9�D� � $� 1� 8���38��<�<���/�0� � � '��B�J�N�N�+L�c�RV�Rc�Rl�Rl�Rn�Rn�No�No�p�p�q�q�uv�v� � � � � )��(9�(B�(B�(D�(D� )� �M�o� p� p� p�#(�D� � ���5�!�!�!� � � b���0E�!E�!E���!�#�#�)�i�����#�<�7�7� �!j�k�k�k�9=�D�L`�-a�-a�D� !�'� *� *� *� b� b�!E�!Er.c ��|�gn|}|j�|��\}}|�dS|�|��dkr'||vr ||||<dStd|�d|�d����|sdS|�|��}|�9||vr7|||kr-|�d|�d|�d|�d||����dSdSdSdS)Nr��`z'` not found in kwargs. Please specify `zZ` without `auto` (set to correct value) in the DeepSpeed config file or pass it in kwargs.z- ds �=z vs arg )r��find_config_noder�rD�append)r+� ds_key_long� mismatchesr�r�r��ds_key�ds_vals r,r�zDeepSpeedPlugin.fill_match�s4��%�-�R�R�:� ��*�;�;�K�H�H���� �>� �F� �:�:�f� � �� '� '��f�$�$�!'� �!4��v���� �)� �)�)�'2�)�)�)���� � � �F����F�#�#�� � �+��"7�"7��� �,�,�,��!�!�"k�+�"k�"k��"k�"k� �"k�"k�V\�]h�Vi�"k�"k�l�l�l�l�l� � �"7�"7�,�,r.c�J�|j�|��}|�dS|dkS)NFr��r�r�)r+r��vals r,�is_autozDeepSpeedPlugin.is_auto�s,����)�)�+�6�6�� �;��5��&�=� r.c�8�|j�||��Sr&r�)r+r�rbs r,r�zDeepSpeedPlugin.get_value�s��� �*�*�;��@�@�@r.�c �b�|�gn|}|�|j}|���D]G\}}t|t��r|jd ||zdz|||d�|���3|j||z|fd|i|���Ht |��dkr.|dkr*d�|��}td|�d ����dSdS) z=Process the DeepSpeed config with the values from the kwargs.Nr�)r�r�r�r�r�rr�� zSPlease correct the following DeepSpeed config values that mismatch kwargs values: zF The easiest method is to set these DeepSpeed config values to 'auto'.r2) r�r:r�r��deepspeed_config_processr��lenr�rD) r+r�r�r�r�r�r�rK�mismatches_msgs r,r�z(DeepSpeedPlugin.deepspeed_config_processs��%�-�R�R�:� � �>��*�F� �,�,�.�.� [� [�J�C���%��&�&� [�-��-��!�C�<�#�-�*�U�_i���ms����� ����� �j�Z�Z�Z�Z�SY�Z�Z�Z�Z� �z�?�?�Q� � �6�R�<�<�!�Y�Y�z�2�2�N��u�+�u�u�u��� � � �<�<r.c���|j}|dk|dvd�}|dkr d|vrddd�|d<n|dvr d|vrddi|d<|dkr|jrd |vr d|jd �|d <|d krm|dkrdnd}t|�|i���dd �������d krt d|�d|�d����dD] }||vrddi||<�|jdddi|��|jdddi|��dS)Nr\)r]rC)� fp16.enabled� bf16.enabledT)rU� auto_castr]rUrCr�r�r[r�r�z*`--mixed_precision` arg cannot be set to `z` when `z&` is set in the DeepSpeed config file.)r\r]Fr�r�r�)r�)r�)r�r�r�rPr�r�rDr�)r+�mixed_precision� ds_configr�� diff_dtyper\s r,�set_mixed_precisionz#DeepSpeedPlugin.set_mixed_precisions����)� �+�v�5�+��>� � �� �f� $� $��Y�&�&�04�4�$H�$H� �&�!�� �� /� /��Y�&�&�%.��$5� �&�!� �e� #� #��(9� #��i�'�'�15�D�DX�%Y�%Y� �'�"� �d� "� "�#2�f�#<�#<���&�J��9�=�=��R�0�0�4�4�Y��H�H�I�I�O�O�Q�Q�U[�[�[� �M��M�M�Zd�M�M�M����&� 6� 6�E��I�%�%�$-�u�#5� �%� �����C�C�5�C�F�C�C�C����C�C�5�C�F�C�C�C�C�Cr.c��ddlm}tj|j��}|jr|��st d���d|vs |ddkrd|d<d|vs |ddkrd|d<|�dd��dkr|d=tdd d ��r d d l m }m }nd d l m }m }|��||��|_ dS) Nr)�is_transformers_availablezoWhen `zero3_init_flag` is set, it requires Transformers to be installed. Please run `pip install transformers`.r�r�r�r�� transformers�<z4.46r)r��unset_hf_deepspeed_config)�importsr�r'r(r�r�� Exceptionr�r �transformers.deepspeedr�r��transformers.integrations�dschf)r+r�r�r�r�s r,�set_deepspeed_weakrefz%DeepSpeedPlugin.set_deepspeed_weakref1s9��6�6�6�6�6�6��M�$�"7�8�8� � � � �,�,�.�.� ��=���� )� � 9� 9�Y�Gd�=e�io�=o�=o�78�I�3� 4� +�9� <� <� �Jj�@k�ou�@u�@u�:;�I�6� 7� �=�=�+�T� 2� 2�f� <� <��,�-� �N�C�� 8� 8� _� [� [� [� [� [� [� [� [� [� ^� ^� ^� ^� ^� ^� ^� ^�!�!�#�#�#�&�&�y�1�1�� � � r.c��|jSr&)r�r*s r,�is_zero3_init_enabledz%DeepSpeedPlugin.is_zero3_init_enabledJs ���#�#r.Fc#��K�|j}||krdV�dS||_d|_|���dV�||_d|_|���dSr&)r�r�r�)r+�enable�olds r,�zero3_init_context_managerz*DeepSpeedPlugin.zero3_init_context_managerMsu�����"�� �&�=�=� �E�E�E�E�E�#)�D� ��D�J� � &� &� (� (� (� �E�E�E�#&�D� ��D�J� � &� &� (� (� (� (� (r.c����gd��d��D���tj�dd���d��}t �fd�|D����rt d��d����dS) N) r�r�r�r�r�r�r�r��ACCELERATE_MIXED_PRECISIONc��g|]>}|�dd���dd�������?S)� ACCELERATE_r�� DEEPSPEED_)�replacer�)r3�names r,rz<DeepSpeedPlugin._deepspeed_config_checks.<locals>.<listcomp>gsO��( �( �( �RV�D�L�L��� +� +� 3� 3�L�"� E� E� K� K� M� M�( �( �( r.�ACCELERATE_CONFIG_DS_FIELDSr��,c3� �K�|]}|�vV�� dSr&r2)r3r�env_variable_names_to_ignores �r,� <genexpr>z;DeepSpeedPlugin._deepspeed_config_checks.<locals>.<genexpr>ms)�����h�h��t�3�3�h�h�h�h�h�hr.z_When using `deepspeed_config_file`, the following accelerate config variables will be ignored: am. Please specify them appropriately in the DeepSpeed config file. If you are using an accelerate config file, remove others config variables mentioned in the above specified list. The easiest method is to create a new config following the questionnaire via `accelerate config`. It will only ask for the necessary config variables when using `deepspeed_config_file`.)r�r�r��split�anyrD)r+�'deepspeed_fields_from_accelerate_configr s @r,r�z(DeepSpeedPlugin._deepspeed_config_checks[s���� ( � ( � ( �$�( �( �Zv�( �( �( �$�35�*�.�.�A^�`b�2c�2c�2i�2i�jm�2n�2n�/� �h�h�h�h�@g�h�h�h� h� h� ��j�sO�j�j�j��� � � r.c��|j�%tj�dd��|_|j��t ddd��rt d���ddlm}|j�d��}g}|D]<}t||��}|�td |�d ����|� |���=|||��dSdS) N�(ACCELERATE_DEEPSPEED_MOE_LAYER_CLS_NAMESr�r�z0.14.0zPDeepSpeed version must be >= 0.14.0 to use MOE support. Please update DeepSpeed.r)�set_z3_leaf_modulesr z1Could not find a transformer layer class called 'z' to wrap in the model.) r�r�r�r�r r��deepspeed.utilsrr�get_module_class_from_namer�r�)r+r�r� class_names�transformer_moe_cls� layer_class�transformer_clss r,�set_moe_leaf_modulesz$DeepSpeedPlugin.set_moe_leaf_modulesvs�� � )� 1�-/�Z�^�^�<f�hl�-m�-m�D� *� � )� 5�� �S�(�;�;� v�!�"t�u�u�u� ;� ;� ;� ;� ;� ;��8�>�>�s�C�C�K�"$� �*� @� @� �"<�U�K�"P�"P��"�*�#�p�K�p�p�p����(�.�.��?�?�?�?� � ��':� ;� ;� ;� ;� ;� 6� 5r.�_from_accelerator_statec�z�|std���|���|�d��dS)z_ Sets the HfDeepSpeedWeakref to use the current deepspeed plugin configuration zxA `DeepSpeedPlugin` object must be enabled manually by calling `AcceleratorState().enable_deepspeed_plugin(plugin_key)`.TN)rDr�r�)r+rs r,�selectzDeepSpeedPlugin.select�sR��'� ��K��� � �"�"�$�$�$� ���4� � � � � r.c�0�|�d��dS)NF)r�r*s r,� _unselectzDeepSpeedPlugin._unselect�s�� ���5�!�!�!�!�!r.rKc��||_dS)z= Private setter for the 'enabled' attribute. N�� _selected�r+rKs r,r�zDeepSpeedPlugin._set_selected�s������r.c��|jSr&r!r*s r,�selectedzDeepSpeedPlugin.selected�s ���~�r.c� �td���)Nz\'enabled' can only be set through calling 'AcceleratorState().enable_deepspeed_plugin(key)'.)r�r#s r,r%zDeepSpeedPlugin.selected�s��!� j� � � r.)NTr&)r�NNT)F)-r=r>r?r@rr�r rXr�r�r�r�r�r�rWr�rPr�r�r�r�r�r�r�r�r r r�r�r�r�r�r�r�r�rrr�rrrr��propertyr%�setterr2r.r,r�r��s{�������#�#�J��� �B� ����L�#���� (-�u�� �`� �(�(�(������ %�u�T�V�Ej�<k�l�l�l��u�l�l�l��e���i�j����J����� %�u���q�r� � � ������%*�E���i�j�%�%�%��c����!&����b�c�!�!�!��#����(-�u���f�g�(�(�(������$)�5���f�g�$�$�$��S����"�E�� �1� ����O�T����$)�5���m�n�$�$�$��D����&+�U�� �d� �&�&�&��s��������_�`����L�$����6;�U�� �T� �6�6�6�O�X�g�j�1�2����wb�wb�wb�rm�m�m�m�2!�!�!�A�A�A�A�����&D�D�D�<2�2�2�2$�$�$�� )� )� )��^� )����6<�<�<�( !� !�d� !� !� !� !�"�"�"��4����� ����X���_� � ��_� � � r.r�c���eZdZUdZedddi���Zeed<edddi���Ze e dfed <eddd i���Z e e de fed <eddd i���Z ee e d fed<edddi���Zee eddfed<edddi���Zee eedfed<edddi���Ze e ddfed<edddi���Zeeejjed<edddi���Ze e dfed<edddi���Zee d ed!<eddd"i���Zee d#ed$<ed%dd&i���Ze ed'<eddd(i���Zee ed)<eddd*i���Zeeejjgdfed+<eddd,i���Z ee ed-<eddd.i���Z!e ed/<eddd0i���Z"e ed1<eddd2i���Z#e ed3<eddd4i���Z$ee%e ed5<eddd6i���Z&eeed7<d8�Z'd@d9�Z(d:�Z)dAd<�Z*d=�Z+d>�Z,d?�Z-dS)B�FullyShardedDataParallelPluginai This plugin is used to enable fully sharded data parallelism. Args: fsdp_version (`int`, defaults to `1`): The version of FSDP to use. Defaults to 1. If set to 2, launcher expects the config to be converted to FSDP2 format. sharding_strategy (`Union[str, torch.distributed.fsdp.ShardingStrategy]`, defaults to `'FULL_SHARD'`): Sharding strategy to use. Should be either a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`. Is deprecated in favor of `reshard_after_forward`. reshard_after_forward (`Union[str, torch.distributed.fsdp.ShardingStrategy, bool]`, defaults to `'FULL_SHARD'` for `fsdp_version=1` and `True` for `fsdp_version=2`): Sharding strategy to use. Should be a bool if `fsdp_version` is set to 2 else a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`. backward_prefetch (`Union[str, torch.distributed.fsdp.BackwardPrefetch]`, defaults to `'NO_PREFETCH'`): Backward prefetch strategy to use. Should be either a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.BackwardPrefetch`. mixed_precision_policy (`Optional[Union[dict, torch.distributed.fsdp.MixedPrecision, torch.distributed.fsdp.MixedPrecisionPolicy]]`, defaults to `None`): A config to enable mixed precision training with FullyShardedDataParallel. If passing in a `dict`, it should have the following keys: `param_dtype`, `reduce_dtype`, and `buffer_dtype`, can be an instance of `torch.distributed.fsdp.MixedPrecisionPolicy` if `fsdp_version` is set to 2. auto_wrap_policy (`Optional(Union[Callable, Literal["transformer_based_wrap", "size_based_wrap", "no_wrap"]]), defaults to `NO_WRAP`): A callable or string specifying a policy to recursively wrap layers with FSDP. If a string, it must be one of `transformer_based_wrap`, `size_based_wrap`, or `no_wrap`. See `torch.distributed.fsdp.wrap.size_based_wrap_policy` for a direction on what it should look like. cpu_offload (`Union[bool, torch.distributed.fsdp.CPUOffload, torch.distributed.fsdp.CPUOffloadPolicy]`, defaults to `False`): Whether to offload parameters to CPU. Should be either a `bool` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.CPUOffload` or `torch.distributed.fsdp.fully_sharded_data_parallel.CPUOffloadPolicy` if `fsdp_version` is set to 2. ignored_modules (`Optional[Iterable[torch.nn.Module]]`, defaults to `None`): A list of modules to ignore when wrapping with FSDP. state_dict_type (`Union[str, torch.distributed.fsdp.StateDictType]`, defaults to `'FULL_STATE_DICT'`): State dict type to use. If a string, it must be one of `full_state_dict`, `local_state_dict`, or `sharded_state_dict`. state_dict_config (`Optional[Union[torch.distributed.fsdp.FullStateDictConfig, torch.distributed.fsdp.ShardedStateDictConfig]`, defaults to `None`): State dict config to use. Is determined based on the `state_dict_type` if not passed in. optim_state_dict_config (`Optional[Union[torch.distributed.fsdp.FullOptimStateDictConfig, torch.distributed.fsdp.ShardedOptimStateDictConfig]`, defaults to `None`): Optim state dict config to use. Is determined based on the `state_dict_type` if not passed in. limit_all_gathers (`bool`, defaults to `True`): Whether to have FSDP explicitly synchronizes the CPU thread to prevent too many in-flight all-gathers. This bool only affects the sharded strategies that schedule all-gathers. Enabling this can help lower the number of CUDA malloc retries. use_orig_params (`bool`, defaults to `False`): Whether to use the original parameters for the optimizer. param_init_fn (`Optional[Callable[[torch.nn.Module], None]`, defaults to `None`): A `Callable[torch.nn.Module] -> None` that specifies how modules that are currently on the meta device should be initialized onto an actual device. Only applicable when `sync_module_states` is `True`. By default is a `lambda` which calls `to_empty` on the module. sync_module_states (`bool`, defaults to `False`): Whether each individually wrapped FSDP unit should broadcast module parameters from rank 0 to ensure they are the same across all ranks after initialization. Defaults to `False` unless `cpu_ram_efficient_loading` is `True`, then will be forcibly enabled. forward_prefetch (`bool`, defaults to `False`): Whether to have FSDP explicitly prefetches the next upcoming all-gather while executing in the forward pass. only use with Static graphs. activation_checkpointing (`bool`, defaults to `False`): A technique to reduce memory usage by clearing activations of certain layers and recomputing them during a backward pass. Effectively, this trades extra computation time for reduced memory usage. cpu_ram_efficient_loading (`bool`, defaults to `None`): If True, only the first process loads the pretrained model checkoint while all other processes have empty weights. Only applicable for Transformers. When using this, `sync_module_states` needs to be `True`. transformer_cls_names_to_wrap (`Optional[List[str]]`, defaults to `None`): A list of transformer layer class names to wrap. Only applicable when `auto_wrap_policy` is `transformer_based_wrap`. min_num_params (`Optional[int]`, defaults to `None`): The minimum number of parameters a module must have to be wrapped. Only applicable when `auto_wrap_policy` is `size_based_wrap`. Nr`ztThe version of FSDP to use. Defaults to 1. If set to 2, launcher expects the config to be converted to FSDP2 format.ra� fsdp_versionz�Sharding strategy to use. Should be either a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`. Defaults to 'FULL_SHARD'. Is deprecated in favor of `reshard_after_forward` z'torch.distributed.fsdp.ShardingStrategy�sharding_strategyz�Sharding strategy to use. Should be a bool if `fsdp_version` is set to 2 else a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`. Defaults to 'FULL_SHARD'�reshard_after_forwardz�Backward prefetch strategy to use. Should be either a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.BackwardPrefetch`. Defaults to 'NO_PREFETCH'. This becomes obsolete in FSDP2.z'torch.distributed.fsdp.BackwardPrefetch�backward_prefetchaA config to enable mixed precision training with FullyShardedDataParallel. If passing in a `dict`, it should have the following keys: `param_dtype`, `reduce_dtype`, and `buffer_dtype`.Can also be an instance of `torch.distributed.fsdp.MixedPrecisionPolicy` if `fsdp_version` is set to 2.z%torch.distributed.fsdp.MixedPrecisionz+torch.distributed.fsdp.MixedPrecisionPolicy�mixed_precision_policya$A callable or string specifying a policy to recursively wrap layers with FSDP. If a string, it must be one of `transformer_based_wrap`, `size_based_wrap`, or `no_wrap`. Defaults to `NO_WRAP`. See `torch.distributed.fsdp.wrap.size_based_wrap_policy` for a direction on what it should look like)�transformer_based_wrap�size_based_wrap�no_wrap�auto_wrap_policya Whether to offload parameters to CPU. Should be either a `bool` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.CPUOffload` or `torch.distributed.fsdp.fully_sharded_data_parallel.CPUOffloadPolicy` if `fsdp_version` is set to 2. Defaults to `False`z!torch.distributed.fsdp.CPUOffloadz'torch.distributed.fsdp.CPUOffloadPolicy� cpu_offloadz4A list of modules to ignore when wrapping with FSDP.�ignored_modulesz�State dict type to use. If a string, it must be one of `full_state_dict`, `local_state_dict`, or `sharded_state_dict`. Defaults to `FULL_STATE_DICT`z$torch.distributed.fsdp.StateDictType�state_dict_typezXState dict config to use. Is determined based on the `state_dict_type` if not passed in.)z*torch.distributed.fsdp.FullStateDictConfigz-torch.distributed.fsdp.ShardedStateDictConfig�state_dict_configz^Optim state dict config to use. Is determined based on the `state_dict_type` if not passed in.)z/torch.distributed.fsdp.FullOptimStateDictConfigz2torch.distributed.fsdp.ShardedOptimStateDictConfig�optim_state_dict_configTz�Whether to have FSDP explicitly synchronizes the CPU thread to prevent too many in-flight all-gathers. This bool only affects the sharded strategies that schedule all-gathers. Enabling this can help lower the number of CUDA malloc retries.�limit_all_gathersznWhether to use the original parameters for the optimizer. Defaults to `False`. This becomes obsolete in FSDP2.�use_orig_paramsaA Callable[torch.nn.Module] -> None that specifies how modules that are currently on the meta device should be initialized onto an actual device. Only applicable when `sync_module_states` is `True`. By default is a `lambda` which calls `to_empty` on the module.� param_init_fnaWhether each individually wrapped FSDP unit should broadcast module parameters from rank 0 to ensure they are the same across all ranks after initialization. Defaults to `False` unless `cpu_ram_efficient_loading` is `True`, then will be forcibly enabled. This becomes obsolete in FSDP2.�sync_module_statesz�Whether to have FSDP explicitly prefetches the next upcoming all-gather while executing in the forward pass. only use with Static graphs. Defaults to `False`�forward_prefetchz�A technique to reduce memory usage by clearing activations of certain layers and recomputing them during a backward pass. Effectively, this trades extra computation time for reduced memory usage. Defaults to `False`�activation_checkpointingu�If True, only the first process loads the pretrained model checkoint while all other processes have empty weights. Only applicable for 🤗 Transformers. When using this, `sync_module_states` needs to be `True`. Defaults to `False`.�cpu_ram_efficient_loadingzuA list of transformer layer class names to wrap. Only applicable when `auto_wrap_policy` is `transformer_based_wrap`.�transformer_cls_names_to_wrapz�The minimum number of parameters a module must have to be wrapped. Only applicable when `auto_wrap_policy` is `size_based_wrap`.�min_num_paramsc ���ddlm}m}t��}d}|j�5t t j�|dzd����|_|j �|� d��|jdk�r|j �(t j�|dzd ��|_ t|j t��r�|j � ��tvr3tj|j � ����dz|_ t|j t ��s|j ���r#|t |j ����|_ n$||j � ��|_ |j�r|j �kt j�|d z|jd krd nd ��}|jd kr)t%|���d ���|_n||_t|jt���r|jd kr.t%|j���d ���|_n�|j� ��tvr3tj|j� ����dz|_t|jt ��s|j���r#|t |j����|_n$||j� ��|_|jd kr2t|jt(��st+d|j�d����|jdkr2t|jt(��rt+d|j�d����|j�9t%t j�|dzd����dk|_|���|���|j�(t j�|dzd��|_t|jt��r$|j� ��dkrd|_|j��t|j|��s�t|jt��rS|j� ��t4vr3t5j|j� ����dz|_t|jt ��s|j���r#|t |j����|_n$||j� ��|_|jd kr#|j�|� d��d|_|���|j�(t j�|dzd��|_t|jt���r�|j� ��t:vr8t+d|j�dt=t;j���������ddl m!}m"}|j� ��dkrp||_|j#�(t j�|dzd��|_#t|j#t��r|j#�$d��|_#n�|j� ��dkr�||_|j%�6t t j�|d zd����|_%nkt|j%t ��s,t+d!|j%�d"tM|j%�������n$|j� ��dkrd|_|j'�D|jdkr9t%t j�|d#zd����dk|_'|jd kr#|j'�|� d$��d|_'|j(�D|jdkr9t%t j�|d%zd����dk|_(|jd kr#|j(�|� d&��d|_(|j)�D|jdkr9t%t j�|d'zd����dk|_)|jd kr|j)�t+d(���|j*�9t%t j�|d)zd����dk|_*|j+�9t%t j�|d*zd����dk|_+|jdkr)|j+r"|j(stYj-d+��d |_(t|j.t^��r|�0|j.��|j.�|�1��|j(�r'te��rtfj4�5���n�tm��rtfj7�5���n�tq��rtfj9�5���n�tu��rtfj;�5���nity��rtfj=�5���n<t}��rtfj?�5���nt�d,����fd-�|_A|r/t��Cd.�D|����dSdS)/Nr)�BackwardPrefetch�ShardingStrategy�FSDP_�VERSION�1zzsharding_strategy is deprecated in favor of reshard_after_forward. This will be removed in a future version of Accelerate.r�SHARDING_STRATEGY� FULL_SHARD�RESHARD_AFTER_FORWARDr�r�T)�to_boolzreshard_after_forward set to z:. This is not supported with FSDP2, please set to a `bool`z�. This is not supported with FSDP1, please set to a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`�OFFLOAD_PARAMSr��BACKWARD_PREFETCH� NO_PREFETCHzObackward_prefetch is not supported in FSDP2. Setting backward prefetch to None.�AUTO_WRAP_POLICY�NO_WRAPzInvalid auto wrap policy: r���size_based_auto_wrap_policy�transformer_auto_wrap_policy�TRANSFORMER_BASED_WRAP�TRANSFORMER_CLS_TO_WRAPr �SIZE_BASED_WRAP�MIN_NUM_PARAMSz)`min_num_params` must be an integer. Got z of type �USE_ORIG_PARAMSzSuse_orig_params is obsolete in FSDP2, as FSDP2 always uses the original parameters.�SYNC_MODULE_STATESzhsync_module_states is obsolete in FSDP2, as it is not needed anymore.Setting sync_module_states to None.�FORWARD_PREFETCHzUforward_prefetch is not yet implemented in FSDP2, set to None or use `fsdp_version=1`�ACTIVATION_CHECKPOINTING�CPU_RAM_EFFICIENT_LOADINGzosync_module_states cannot be False since efficient cpu ram loading enabled. Setting sync_module_states to True.zmThere are currently no available devices found, must be one of 'XPU', 'CUDA', 'MLU', 'NPU', 'MUSA', or 'HPU'.c�2��|��d���S)NF)r��recurse)�to_empty)�xr�s �r,�<lambda>z>FullyShardedDataParallelPlugin.__post_init__.<locals>.<lambda>+s���1�:�:�V�U�:�+S�+S�r.z7Multiple deprecation warnings due to FSDP2 conversion: )E�torch.distributed.fsdprCrD�setr+r�r�r�r�r,�addr�rPr�r�indexr�r-rr�rWrDr4�set_cpu_offload�validate_cpu_offloadr.r�set_state_dict_typer3rrNr��torch.distributed.fsdp.wraprRrSr@rrA�typer:r<r=r>r?r�r�r/r�r��validate_mixed_precision_policyrr�rJ�current_devicerrGrrIrr�rr�rr�� RuntimeErrorr;�logger�warningr�) r+rCrD�_fsdp2_warningsr�r-rRrSr�s @r,r�z,FullyShardedDataParallelPlugin.__post_init__�s% ��� � � � � � � � � �%�%��� � � � $� #�B�J�N�N�:� �3I�3�$O�$O� P� P�D� � � !� -� � � �J� � � � � �� !� !��%�-�)+���� �EX�8X�Zf�)g�)g��&��$�0�#�6�6� ^��)�/�/�1�1�5K�K�K�-C�-I�$�J`�Jf�Jf�Jh�Jh�-i�-i�lm�-m�D�*��d�4�c�:�:�^�d�>T�>\�>\�>^�>^�^�-=�-=�c�$�BX�>Y�>Y�-Z�-Z�D�*�*�-=�d�>T�>Z�>Z�>\�>\�-]�D�*� � %� -�$�2H�2P�$&�J�N�N��4�4��@Q�UV�@V�@V�f�f�\h�%�%� !�� �A�%�%�-8�9N�9T�9T�9V�9V�`d�-e�-e�-e��*�*�-B��*� �d�0�#� 6� 6� f�� �A�%�%�-8��9S�9Y�9Y�9[�9[�ei�-j�-j�-j��*�*��-�3�3�5�5�9O�O�O�1G�1M�d�Nh�Nn�Nn�Np�Np�1q�1q�tu�1u�D�.��d�8�#�>�>�f�$�B\�Bd�Bd�Bf�Bf�f�1A�1A�#�d�F`�Ba�Ba�1b�1b�D�.�.�1A�$�B\�Bb�Bb�Bd�Bd�1e�D�.� � �� !� !�*�T�5O�QU�*V�*V� !��G��0J�G�G�G��� � � �� !� !�j��1K�T�&R�&R� !��^��0J�^�^�^��� � � � #�*�2�:�>�>�*�GW�:W�Y`�+a�+a�b�b�fg�g�D� � ������ �!�!�#�#�#� � !� )�%'�Z�^�^�J�AT�4T�VZ�%[�%[�D� "� �d�,�c� 2� 2� *�t�7M�7S�7S�7U�7U�Yf�7f�7f�%)�D� "� � !� -�j��AW�Yi�6j�6j� -��$�0�#�6�6� j�4�;Q�;W�;W�;Y�;Y�]s�;s�;s�)?�)E�d�F\�Fb�Fb�Fd�Fd�)e�)e�hi�)i��&��$�0�#�6�6� Z�$�:P�:X�:X�:Z�:Z� Z�)9�)9�#�d�>T�:U�:U�)V�)V��&�&�)9�$�:P�:V�:V�:X�:X�)Y��&� � �� !� !�d�&<�&H� � � � q� r� r� r�%)�D� "� � � �"�"�"� � � (�$&�J�N�N�:�@R�3R�T]�$^�$^�D� !� �d�+�S� 1� 1� -��$�*�*�,�,�4I�I�I� �}��1F�}�}�Y]�^s�^x�^z�^z�Y{�Y{�}�}���� n� m� m� m� m� m� m� m��$�*�*�,�,�0H�H�H�(D��%��5�=�9;���� �Un�Hn�pt�9u�9u�D�6��d�@�#�F�F�g�9=�9[�9a�9a�be�9f�9f�D�6���&�,�,�.�.�2C�C�C�(C��%��&�.�*-�b�j�n�n�Z�JZ�=Z�\]�.^�.^�*_�*_�D�'�'�#�D�$7��=�=��$�}�D�DW�}�}�bf�gk�gz�b{�b{�}�}������&�,�,�.�.�)�;�;�(,��%� � � '�D�,=��,B�,B�#.�r�z�~�~�j�K\�>\�^e�/f�/f�#g�#g�kl�#l�D� � � �� !� !�d�&:�&F� � � � u� v� v� v�#'�D� � � "� *�t�/@�A�/E�/E�&1�"�*�.�.��Nb�Ab�dk�2l�2l�&m�&m�qr�&r�D� #� � �� !� !�d�&=�&I� � � �6� � � �'+�D� #� � � (�T�->�!�-C�-C�$/�� ���z�L^�?^�`g�0h�0h�$i�$i�mn�$n�D� !� � �� !� !�d�&;�&G��t�u�u� u� � (� 0��B�J�N�N�:�8R�+R�T[�\�\�]�]�ab�b� � )� � )� 1��B�J�N�N�:�8S�+S�U\�]�]�^�^�bc�c� � *� � �� !� !�d�&D� !�T�Md� !� �M�6� � � �'+�D� #� �d�1�4� 8� 8� B� � $� $�T�%@� A� A� A� � &� 2� � 0� 0� 2� 2� 2� � "� T��!�!� ���1�1�3�3���!�#�#� ���1�1�3�3���"�$�$� ���2�2�4�4���"�$�$� ���2�2�4�4���!�#�#� ���1�1�3�3���!�#�#� ���1�1�3�3���"�D���� "T�!S�!S�!S�D� � � m� �N�N�U�Z�Z�[j�k�k� l� l� l� l� l� m� mr.c���ddlm}m}m}m}m}|�||_|j�2tj� d|j dkrdnd��|_t|jt��r`|j� ��r#|t|j����|_n$||j���|_|j|jkr3|j�|dd� ��|_|j�|dd� ��|_n@|j|jkr0|j�|d� ��|_|j�|d� ��|_|j d kr|j|jkrt)d ���dSdS) zI Set the state dict config based on the `StateDictType`. r)�FullOptimStateDictConfig�FullStateDictConfig�ShardedOptimStateDictConfig�ShardedStateDictConfig� StateDictTypeN�FSDP_STATE_DICT_TYPEr�FULL_STATE_DICT�SHARDED_STATE_DICTT)�offload_to_cpu� rank0_only)rzr�zjFSDP2 only supports SHARDED_STATE_DICT for now. Please set `fsdp_state_dict_type` to `SHARDED_STATE_DICT`.)�2torch.distributed.fsdp.fully_sharded_data_parallelrrrsrtrurvr6r�r�r�r+r�rPr�r�r�rxr7r8ryrD)r+r6rrrsrtrurvs r,rhz2FullyShardedDataParallelPlugin.set_state_dict_type1s��� � � � � � � � � � � � � � � � &�#2�D� � � � '�#%�:�>�>�&�T�=N�RS�=S�=S�(9�(9�Ym�$�$�D� � �d�*�C� 0� 0� S��#�+�+�-�-� S�'4�}�S��9M�5N�5N�'O�'O��$�$�'4�T�5I�5O�5O�5Q�5Q�'R��$� � �=�#@� @� @��%�-�)<�)<�D�]a�)b�)b�)b��&��+�3�/G�/G�W[�hl�/m�/m�/m��,�� � !�]�%E� E� E��%�-�)?�)?�t�)T�)T�)T��&��+�3�/J�/J�Z^�/_�/_�/_��,� � �� !� !�d�&:�m�>^�&^�&^��M��� � "� !�&^�&^r.c��ddlm}m}t|dd��}|�t |��ng}|j|kr�|j�||_t��}|jD]<}t||��}|�td|�d����|� |���=tj |j|���|_dS|j|kr;|j dkr'tj |j|j ���|_dSd|_dSdS) z� Given `model`, creates an `auto_wrap_policy` baesd on the passed in policy and if we can use the `transformer_cls_to_wrap` rrQ�_no_split_modulesNz+Could not find the transformer layer class z in the model.)�transformer_layer_cls)rA)rirRrSr�rNr3r@rcrrDrd� functools�partialrA) r+r�rRrS�no_split_modules�%default_transformer_cls_names_to_wrap�transformer_cls_to_wraprrs r,�set_auto_wrap_policyz3FullyShardedDataParallelPlugin.set_auto_wrap_policy^sS�� j�i�i�i�i�i�i�i�#�5�*=�t�D�D��JZ�Jf��5E�0F�0F�0F�ln�-� � �$@� @� @��1�9�5Z��2�&)�e�e� #�#�A� =� =� �"<�U�K�"P�"P��"�*�$�%n�S^�%n�%n�%n�o�o�o�'�+�+�O�<�<�<�<�$-�$5��%�=T�%�%�%�D� !� !� !�� "�&A� A� A��"�Q�&�&�(1�(9�$�:O�`d�`s�(t�(t�(t��%�%�%�(,��%�%�%� B� Ar.Fc �2�� �tjtjtjtjd�� |}t |t ��rM� �|d��}|�4td|�dt� � ���������ndt |tj ��rJ|� � ��vr4td|�dt� � ���������|r tjn|}�j dkrddl m}n�j dkrdd l m}|s�j�*||d �}�j dkr||d <n||d <|di|���_dSt �jt"��r�d dg�j dkrd gnd gz}�fd�|D��} � fd��j���D��} | s| r<td�j�d|�dt� � ���������|di�j���_dSdS)z(Sets the mixed precision policy for FSDP)rCr\r]�fp32NzInvalid mixed precision: r�rr��MixedPrecisionr���MixedPrecisionPolicy)� param_dtype� reduce_dtype� buffer_dtype� output_dtyper�r�c�&��g|] }|�jv� |��Sr2)r/)r3r4r+s �r,rzFFullyShardedDataParallelPlugin.set_mixed_precision.<locals>.<listcomp>�s&���Z�Z�Z�!�Q�d�>Y�5Y�5Y�A�5Y�5Y�5Yr.c�F��g|]\}}|����v�|��Sr2)�values)r3r4r5�mixed_precision_mappings �r,rzFFullyShardedDataParallelPlugin.set_mixed_precision.<locals>.<listcomp>�s;�������a��Q�Ne�Nl�Nl�Nn�Nn�En�En��En�En�Enr.z Invalid mixed precision policy: z. Must be a `dict` with keys z.Values must be one of r2)r��bfloat16�float16�float32r�rPr�rDrNr�r\r�r+rbr�r�r/r�r:) r+r��buffer_autocast�overrider\� buffer_typer�� dtype_args� valid_keys� missing_keys�invalid_valuesr�s ` @r,r�z2FullyShardedDataParallelPlugin.set_mixed_precision}s������>��M��N��M� # �# ��  �� �o�s� +� +� �+�/�/���F�F�E��}� �x��x�x�RV�Wn�Ws�Ws�Wu�Wu�Rv�Rv�x�x��������� 5� 5� �/�Qh�Qo�Qo�Qq�Qq�:q�:q��v�O�v�v�d�Sj�Sq�Sq�Ss�Ss�Nt�Nt�v�v��� �(7�A�e�m�m�E� � � �� !� !� =� =� =� =� =� =� =� � �!� #� #� U� U� U� U� U� U� � X�t�2�:�).��F�F�J�� �A�%�%�-8� �>�*�*�-2� �>�*�*8�.�*F�*F�:�*F�*F�D� '� '� '� ��3�T� :� :� X�'��8�$(�$5��$:�$:�� � ��@P��J�[�Z�Z�Z�z�Z�Z�Z�L�����"�9�?�?�A�A����N�� �~� � �V�t�7R�V�V�2<�V�V�-1�2I�2P�2P�2R�2R�-S�-S�V�V���� +9�.�*W�*W�4�;V�*W�*W�D� '� '� '� X� Xr.c��|jdkrddlm}nddlm}t |j|��s"|jdkrdnd}t d|�d����d S) zr Validates the mixed precision policy, abstracted away to not bring in the imports if not needed. r�rr�r�z-`torch.distributed.fsdp.MixedPrecisionPolicy`z'`torch.distributed.fsdp.MixedPrecision`z.mixed_precision_policy must be an instance of r�N)r+rbr�r�r�r/rD)r+r�� required_types r,rkz>FullyShardedDataParallelPlugin.validate_mixed_precision_policy�s��� � �� !� !� U� U� U� U� U� U� U� =� =� =� =� =� =��$�5�~�F�F� `��$��)�)�@�?�>� � �^�m�^�^�^�_�_� _�  `� `r.c��|jdkr ddlm}m}nddlm}t |jt��rL|jdkr)|js|��|_dS|��|_dS||j���|_dSdS)Nr�r)�CPUOffloadPolicy� OffloadPolicy�� CPUOffload)�offload_params)r+rbr�r�r�r�r4rW)r+r�r�r�s r,rfz.FullyShardedDataParallelPlugin.set_cpu_offload�s��� � �� !� !� N� N� N� N� N� N� N� N� N� 9� 9� 9� 9� 9� 9� �d�&�� -� -� O�� �A�%�%��'�:�'4�}���D�$�$�$�'7�'7�'9�'9�D�$�$�$�#-�:�T�=M�#N�#N�#N�� � � � O� Or.c��|jdkrddlm}nddlm}|jdkr,t |j|��st d|j�����|jdkr,t |j|��st d|j�����dSdS)Nr�r)r�r�zZ`cpu_offload` must be an instance of `torch.distributed.fsdp.OffloadPolicy` in FSDP2, got rzW`cpu_offload` must be an instance of `torch.distributed.fsdp.CPUOffload` in FSDP1, got )r+rbr�r�r�r4rD)r+r�r�s r,rgz3FullyShardedDataParallelPlugin.validate_cpu_offload�s��� � �� !� !� <� <� <� <� <� <� <� 9� 9� 9� 9� 9� 9� � �� !� !�*�T�5E�}�*U�*U� !���mq�m}����� � � �� !� !�*�T�5E�z�*R�*R� !��|�jn�jz�|�|��� � "� !� !� !r.r&)FF).r=r>r?r@rr+r�rXr,r rPr-rWr.r r/r�r3r r r4r5rr��nn�Moduler6r7r8r9r:r;r<r=r>r?r@rNrAr�rhr�r�rkrfrgr2r.r,r*r*�s �������C�C�J��� �K� ����L�#����PU�u�� �o� �P�P�P��u�S�"K�K�L����Z_�Y^�� �^� �Z�Z�Z��5��&O�QU�!U�V���� Z_�Y^�� �f� �Z�Z�Z��x��c�+T�&T� U�V���� ��� �v� � � � ��H� �d�;�=j�j�k�� � � � ����N�� � � ��h�u�X�w�7m�/n�%n�o�p����pu�ot�� �d� �p�p�p�K��t�@�Bk�k�l���� <A�5���P�Q�<�<�<�O�X�h�u�x��7�8���� KP�%�� �k� �K�K�K�O�U�3� F�F�G���� ����t�u� � � � �x� � =� ����� ��� �t� � � � ��X� �u�v�����$�e�� �N� �����t����',�e�� �E� �'�'�'�O�X�d�^���� BG��� �B� �B�B�B�M�8�H�e�h�o�%6��%<�=�>����*/��� �t� �*�*�*��������#�U�� �o� �����d����&+�U�� �<� �&�&�&��d����',�e�� �D� �'�'�'��t����:?��� �L� �:�:�:�!�8�D��I�#6���� %*�E�� �W� �%�%�%�N�H�S�M����om�om�om�b+�+�+�+�Z-�-�-�>2X�2X�2X�2X�h`�`�`�" O� O� O� � � � � r.r*c�p�eZdZUdZedddi���Zeed<ed���Ze d ed <d �Z dS) �TorchTensorParallelPluginzP This plugin is used to enable tensor parallelism using PyTorch >= 2.0. rr`z@tensor parallel size will be used in the device mesh preparationra�tp_sizeN)rbztorch.distributed.DeviceMesh�torch_device_meshc��tj�dd��dkr|jn,t tj�dd����|_|jdkrt d���t dt��rt dt�d����dd lm }td � ��rd }nd }d}|||jf|f���|_ dS)N�TP_SIZErGrzProvide TP degree > 1.r�zMinimum PyTorch version z needed to use tensor parallel.r)�init_device_meshT)� init_hcclr�r��tp)�mesh_dim_names) r�r�r�r�r�rDr!r�torch.distributed.device_meshr�rr�)r+r�r�� mesh_dim_names r,r�z'TorchTensorParallelPlugin.__post_init__�s���')�z�~�~�i��'E�'E��'L�'L�t�|�|�RU�VX�V`�Vd�Vd�en�ps�Vt�Vt�Ru�Ru�� � �<�1� � ��5�6�6� 6� �C�!B� C� C� ��m�+L�m�m�m��� � C�B�B�B�B�B� �d� +� +� +� ��F�F��F�� �!1�!1�&�4�<�/�[h�Zj�!k�!k�!k����r.) r=r>r?r@rr�r�rXr�r r�r2r.r,r�r��s�����������5���\�]����G�S���� CH�%�PT�BU�BU�BU��x� >�?�U�U�U�l�l�l�l�lr.r�c��eZdZUdZedddi���Zeed<edddi���Zeed<eddd i���Z eed <eddd i���Z e ed <eddd i���Z e ed<edddi���Ze ed<edddi���Ze ed<edddi���Zeed<edddi���Zeed<edddi���Zeed<edddi���Zeed<edddi���Zeed<edddi���Zeed <eddd!i���Ze ed"<eddd#i���Ze ed$<ed%dd&i���Zeed'<eddd(i���Zeed)<eddd*i���Zeed+<eddd,i���Zeed-<eddd.i���Zeed/<eddd0i���Ze ed1<ed2dd3i���Ze ed4<eddd5i���Z e!eed6<eddd7i���Z"e#e$ed8<eddd9i���Z%e#e$ed:<ed;dd<i���Z&e ed=<ed>dd?i���Z'e ed@<edddAi���Z(eedB<edddCi���Z)eedD<edddEi���Z*eedF<edddGi���Z+eedH<ed>ddIi���Z,e edJ<edKddLi���Z-eedM<edNddOi���Z.eedP<ed>ddQi���Z/e edR<edddSi���Z0e#e1edT<edddUi���Z2e#e3ee1fedV<edddWi���Z4e#e$edX<edddYi���Z5e#e$edZ<eddd[i���Z6e#e$ed\<eddd]i���Z7e#e$ed^<eddd_i���Z8e#e$ed`<edddai���Z9e#e3ee1fedb<dc�Z:djdd�Z;de�Z<df�Z=dg�Z>dh�Z?di�Z@dS)k�MegatronLMPlugina� Plugin for Megatron-LM to enable tensor, pipeline, sequence and data parallelism. Also to enable selective activation recomputation and optimized fused kernels. Args: tp_degree (`int`, defaults to `None`): Tensor parallelism degree. pp_degree (`int`, defaults to `None`): Pipeline parallelism degree. num_micro_batches (`int`, defaults to `None`): Number of micro-batches. gradient_clipping (`float`, defaults to `None`): Gradient clipping value based on global L2 Norm (0 to disable). sequence_parallelism (`bool`, defaults to `None`): Enable sequence parallelism. recompute_activations (`bool`, defaults to `None`): Enable selective activation recomputation. use_distributed_optimizr (`bool`, defaults to `None`): Enable distributed optimizer. pipeline_model_parallel_split_rank (`int`, defaults to `None`): Rank where encoder and decoder should be split. num_layers_per_virtual_pipeline_stage (`int`, defaults to `None`): Number of layers per virtual pipeline stage. is_train_batch_min (`str`, defaults to `True`): If both tran & eval dataloaders are specified, this will decide the `micro_batch_size`. train_iters (`int`, defaults to `None`): Total number of samples to train over all training runs. Note that either train-iters or train-samples should be provided when using `MegatronLMDummyScheduler`. train_samples (`int`, defaults to `None`): Total number of samples to train over all training runs. Note that either train-iters or train-samples should be provided when using `MegatronLMDummyScheduler`. weight_decay_incr_style (`str`, defaults to `'constant'`): Weight decay increment function. choices=["constant", "linear", "cosine"]. start_weight_decay (`float`, defaults to `None`): Initial weight decay coefficient for L2 regularization. end_weight_decay (`float`, defaults to `None`): End of run weight decay coefficient for L2 regularization. lr_decay_style (`str`, defaults to `'linear'`): Learning rate decay function. choices=['constant', 'linear', 'cosine']. lr_decay_iters (`int`, defaults to `None`): Number of iterations for learning rate decay. If None defaults to `train_iters`. lr_decay_samples (`int`, defaults to `None`): Number of samples for learning rate decay. If None defaults to `train_samples`. lr_warmup_iters (`int`, defaults to `None`): Number of iterations to linearly warmup learning rate over. lr_warmup_samples (`int`, defaults to `None`): Number of samples to linearly warmup learning rate over. lr_warmup_fraction (`float`, defaults to `None`): Fraction of lr-warmup-(iters/samples) to linearly warmup learning rate over. min_lr (`float`, defaults to `0`): Minumum value for learning rate. The scheduler clip values below this threshold. consumed_samples (`List`, defaults to `None`): Number of samples consumed in the same order as the dataloaders to `accelerator.prepare` call. no_wd_decay_cond (`Optional`, defaults to `None`): Condition to disable weight decay. scale_lr_cond (`Optional`, defaults to `None`): Condition to scale learning rate. lr_mult (`float`, defaults to `1.0`): Learning rate multiplier. megatron_dataset_flag (`bool`, defaults to `False`): Whether the format of dataset follows Megatron-LM Indexed/Cached/MemoryMapped format. seq_length (`int`, defaults to `None`): Maximum sequence length to process. encoder_seq_length (`int`, defaults to `None`): Maximum sequence length to process for the encoder. decoder_seq_length (`int`, defaults to `None`): Maximum sequence length to process for the decoder. tensorboard_dir (`str`, defaults to `None`): Path to save tensorboard logs. set_all_logging_options (`bool`, defaults to `False`): Whether to set all logging options. eval_iters (`int`, defaults to `100`): Number of iterations to run for evaluation validation/test for. eval_interval (`int`, defaults to `1000`): Interval between running evaluation on validation set. return_logits (`bool`, defaults to `False`): Whether to return logits from the model. custom_train_step_class (`Optional`, defaults to `None`): Custom train step class. custom_train_step_kwargs (`Optional`, defaults to `None`): Custom train step kwargs. custom_model_provider_function (`Optional`, defaults to `None`): Custom model provider function. custom_prepare_model_function (`Optional`, defaults to `None`): Custom prepare model function. custom_megatron_datasets_provider_function (`Optional`, defaults to `None`): Custom megatron train_valid_test datasets provider function. custom_get_batch_function (`Optional`, defaults to `None`): Custom get batch function. custom_loss_function (`Optional`, defaults to `None`): Custom loss function. other_megatron_args (`Optional`, defaults to `None`): Other Megatron-LM arguments. Please refer Megatron-LM. Nr`ztensor parallelism degree.ra� tp_degreezpipeline parallelism degree.� pp_degreeznumber of micro-batches.�num_micro_batchesz>gradient clipping value based on global L2 Norm (0 to disable)r�zenable sequence parallelism�sequence_parallelismz)enable selective activation recomputation�recompute_activationszenable distributed optimizer�use_distributed_optimizerz/Rank where encoder and decoder should be split.�"pipeline_model_parallel_split_rankz,Number of layers per virtual pipeline stage.�%num_layers_per_virtual_pipeline_stageTzUIf both train & eval dataloaders are specified, this will decide the micro_batch_sizer�z�Total number of iterations to train over all training runs. Note that either train-iters or train-samples should be provided when using `MegatronLMDummyScheduler`� train_itersz�Total number of samples to train over all training runs. Note that either train-iters or train-samples should be provided when using `MegatronLMDummyScheduler`� train_samples�constantzKWeight decay increment function. choices=["constant", "linear", "cosine"]. �weight_decay_incr_stylez7Initial weight decay coefficient for L2 regularization.�start_weight_decayz:End of run weight decay coefficient for L2 regularization.�end_weight_decay�linearzGLearning rate decay function. choices=['constant', 'linear', 'cosine'].�lr_decay_stylezPNumber of iterations for learning rate decay. If None defaults to `train_iters`.�lr_decay_iterszONumber of samples for learning rate decay. If None defaults to `train_samples`.�lr_decay_samplesz;number of iterations to linearly warmup learning rate over.�lr_warmup_itersz8number of samples to linearly warmup learning rate over.�lr_warmup_sampleszLfraction of lr-warmup-(iters/samples) to linearly warmup learning rate over.�lr_warmup_fractionrzPMinumum value for learning rate. The scheduler clip values below this threshold.�min_lrz^Number of samples consumed in the same order as the dataloaders to `accelerator.prepare` call.�consumed_samplesz"Condition to disable weight decay.�no_wd_decay_condz!Condition to scale learning rate.� scale_lr_cond��?zLearning rate multiplier.�lr_multFzUWhether the format of dataset follows Megatron-LM Indexed/Cached/MemoryMapped format.�megatron_dataset_flagz#Maximum sequence length to process.� seq_lengthz3Maximum sequence length to process for the encoder.�encoder_seq_lengthz3Maximum sequence length to process for the decoder.�decoder_seq_lengthzPath to save tensorboard logs.�tensorboard_dirz#Whether to set all logging options.�set_all_logging_options�dz?Number of iterations to run for evaluation validation/test for.� eval_itersi�z6Interval between running evaluation on validation set.� eval_intervalz(Whether to return logits from the model.� return_logitszCustom train step class.�custom_train_step_classzCustom train step kwargs.�custom_train_step_kwargszCustom model provider function.�custom_model_provider_functionzCustom prepare model function.�custom_prepare_model_functionz<Custom megatron train_valid_test datasets provider function.�*custom_megatron_datasets_provider_functionzCustom get batch function.�custom_get_batch_functionzCustom loss function.�custom_loss_functionz5Other Megatron-LM arguments. Please refer Megatron-LM�other_megatron_argsc�j�d}|j�5ttj�|dzd����|_|j�5ttj�|dzd����|_|j�5ttj�|dzd����|_|j�5ttj�|dzd����|_|j �9ttj�|dzd ����dk|_ |j �9ttj�|d zd ����dk|_ |j �9ttj�|d zd ����dk|_ |jdks|j rd |_ nd |_ |j�gt|j��dkr|j�ddg��n2t|j��dkr|j�d��id|j�d|j�d|j�d|j�d|j �d|j �d|j �d|j�d|j�d|j�d|j�d|j�d|j�d|j�d|j�d|j�|_|j r d |jd!<|j�*|j|jd"<|jr|���|j�!|j�|j��dSdS)#N� MEGATRON_LM_� TP_DEGREEr� PP_DEGREE�NUM_MICRO_BATCHES�GRADIENT_CLIPPINGr��RECOMPUTE_ACTIVATIONSr��USE_DISTRIBUTED_OPTIMIZER�SEQUENCE_PARALLELISM�localr�rr��tensor_model_parallel_size�pipeline_model_parallel_sizer�r��DDP_implr��sequence_parallel� clip_gradr�r�r�r�r�r�r�r�� selective�recompute_granularityr�) r�r�r�r�r�r�r�r�r�r�rr�r�r�r�r��extendr�r�r�r�r�r�r�r�r��megatron_lm_default_argsr�r��set_tensorboard_logging_optionsr��updater�s r,r�zMegatronLMPlugin.__post_init__ sj���� �>� !� �������0D�a�!H�!H�I�I�D�N� �>� !� �������0D�a�!H�!H�I�I�D�N� � !� )�%(������AT�8T�VW�)X�)X�%Y�%Y�D� "� � !� )�%*�2�:�>�>�&�CV�:V�X[�+\�+\�%]�%]�D� "� � %� -�)4�R�Z�^�^�F�Md�Dd�fm�5n�5n�)o�)o�st�)t�D� &� � )� 1��B�J�N�N�6�4O�+O�QX�Y�Y�Z�Z�^_�_� � *� � $� ,�(3�B�J�N�N�6�Lb�Cb�dk�4l�4l�(m�(m�qr�(r�D� %� �>�A� � ��!?� �#�D�M�M�#�D�M� � � ,��4�(�)�)�Q�.�.��%�,�,�a��V�4�4�4�4��T�*�+�+�q�0�0��%�,�,�Q�/�/�/�) � (�$�.�) � *�D�N�) � 1�$�2Y�) � 4�T�5_� ) � �� � ) � (��)G� ) � ��!:�) � ��/�) � ��!7�) � �� 5�) � �� 5�) � �T�/�) � �t�|�) � $�T�%?�) � �$�/�) � �T�/�!) ��%�$ � %� Q�EP�D� )�*A� B� � � +�?C�?S�D� )�*;� <��+� 7��4�4�6�6�6� � #� /� � )� 0� 0��1I� J� J� J� J� J� 0� /r.c���|jj���}t���D] }||vrt||||��dS�!t d|�d����)Nz0Accelerate Megatron-LM integration not supports z1 model. You can add your own model config parser.)r�� model_typer��!MODEL_CONFIGS_TO_MEGATRON_PARSERSr�rD)r+r�� batch_data�model_config_typer�s r,�set_network_size_argsz&MegatronLMPlugin.set_network_size_argsD s���!�L�3�9�9�;�;��;�@�@�B�B� � �J��.�.�.�1�*�=�d�E�:�V�V�V����/�� 8�?P� 8� 8� 8� � � r.c�z�|dkr d|jd<dS|dkr"d|jd<d|_|j|jd<dSdS)Nr\Tr]r�r�)r�r�)r+r�s r,r�z$MegatronLMPlugin.set_mixed_precisionO s\�� �f� $� $�48�D� )�&� 1� 1� 1� �� &� &�48�D� )�&� 1�#�D�M�8<� �D� )�*� 5� 5� 5�'� &r.c��||_||_||z|jz|_|j|jd<|j|jd<|j|jd<dS)N�data_parallel_size�micro_batch_size�global_batch_size)rrr�rr�)r+r� dp_degrees r,�set_training_argsz"MegatronLMPlugin.set_training_argsW sa��"+��� 0���!*�-=�!=��@V�!V���>B�>U��%�&:�;�<@�<Q��%�&8�9�=A�=S��%�&9�:�:�:r.c��|jj���}d|vrVd|jd<|jdd|jd<|jdd|jd<|jd|jd <n7d |vr d |jd<|jd |jd <nt d |�d����|jd|jd<|jd|jd<dS)N�adam� optimizer�betasr� adam_beta1r� adam_beta2�eps�adam_eps�sgd�momentum� sgd_momentumz Optimizer z is not supported by Megatron-LM�lr� weight_decay)r9r=r�r��defaultsrD)r+r�optimizer_names r,�set_optimizer_typez#MegatronLMPlugin.set_optimizer_type_ s���"�,�5�;�;�=�=�� �^� #� #�9?�D� )�+� 6�:C�:L�W�:U�VW�:X�D� )�,� 7�:C�:L�W�:U�VW�:X�D� )�,� 7�8A�8J�5�8Q�D� )�*� 5� 5� �n� $� $�9>�D� )�+� 6�<E�<N�z�<Z�D� )�.� 9� 9��Z�.�Z�Z�Z�[�[� [�.7�.@��.F��%�d�+�8A�8J�>�8Z��%�n�5�5�5r.c�z�|j�<|j|jdz|_|j�d|_t jd��|j�<|j|jdz|_|j�t jd��d|_|j|jd<|j|jd<|j|jd<|j|jd<|j |jd <|j |jd <|j |jd <|j |jd <|j |jd <|j|jd<|j|jd<|j|jd<dS)NrzXIgnoring `train_samples` as `train_iters` based on scheduler is being used for training.z`Ignoring `lr_warmup_samples` as `lr_warmup_iters` based on scheduler is being used for training.rr�r�r�r�r�r�r�r�r�r�r�r�)r��total_num_stepsr�r�r�r�r��warmup_num_stepsr�r�r�r�r�r�r�r�r�)r+� schedulers r,�set_scheduler_argsz#MegatronLMPlugin.set_scheduler_argso sh�� � � #�(�8�D�<Y�Zn�<o�o�D� ��!�-�%)��"�� �n���� � � '�#,�#=��A^�_s�At�#t�D� ��%�1�� �v����&'�D� "�7;�7G��%�m�4�;?�;O��%�&7�8�9=�9K��%�o�6�=A�=S��%�&9�:�:>�:M��%�&6�7�<@�<Q��%�&8�9�>B�>U��%�&:�;�:>�:M��%�&6�7�CG�C_��%�&?�@�>B�>U��%�&:�;�<@�<Q��%�&8�9�26�+��%�h�/�/�/r.c��ddlm}tj��}||��}|���}t |d��|_|j���D]X\}}|�d��r d|j |<�%|�d��rd|j |� dd��<�YdS)Nr)�_add_logging_args�log_T�no_log_�no_r�) �megatron.training.argumentsr�argparse�ArgumentParser�parse_known_args�vars� dataset_argsr:� startswithr�r)r+r�parser� logging_argsr�rKs r,r�z0MegatronLMPlugin.set_tensorboard_logging_options� s���A�A�A�A�A�A��(�*�*��"�"�6�*�*���.�.�0�0� � ��a��1�1����+�1�1�3�3� M� M�J�C���~�~�f�%�%� M�59��-�c�2�2���� �*�*� M�HL��-�c�k�k�%��.D�.D�E��  M� Mr.r&)Ar=r>r?r@rr�r�rXr�r�r�r�r�rWr�r�r�r�r�rPr�r�r�r�r�r�r�r�r�r�r�r�r�rNr�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�rrrr�r2r.r,r�r�s� �������]�]�~�U�4�6�;W�2X�Y�Y�Y�I�s�Y�Y�Y��U�4�6�;Y�2Z�[�[�[�I�s�[�[�[�"�U�4�6�C]�:^�_�_�_��s�_�_�_�$�u���(h�i� � � ��u����"'����7�8�"�"�"��$����#(�%���E�F�#�#�#��4����',�e���8�9�'�'�'��t����/4�e���(Y�Z�/�/�/�&�����27����(V�W�2�2�2�)�3����$�e���q�r����������u�� �u� ����K�������� �u� ����M�3����$)�5���g�h�$�$�$��S����!&����S�T�!�!�!������$�e���V�W�����e���� �%���c�d����N�C���� �%���l�m����N�C����"�E���k�l�����c����!�5���W�X����O�S����#�U���T�U�����s����!&����h�i�!�!�!�������E���l�m����F�E����#(�%�� �t� �#�#�#��d�3�i���� ,1�5���Qu�Hv�+w�+w�+w��h�x�(�w�w�w�(-��d�f�Nq�Er�(s�(s�(s�M�8�H�%�s�s�s��U�3�&�:U�1V�W�W�W�G�U�W�W�W�"'�%���q�r�#�#�#��4�����e���?�@����J�����$�e���O�P���������$�e���O�P���������!�5���:�;����O�S����%*�E���?�@�%�%�%��T�����e��v�'h�i����J���������(`�a����M�3���� �%���D�E����M�4���� .3�U���4�5�.�.�.��X�c�]����:?����5�6�:�:�:��h�t�C��H�~�6���� :?����;�<�:�:�:�"�H�X�$6����9>����:�;�9�9�9�!�8�H�#5����FK�U���X�Y�F�F�F�.���0B����5:�E���6�7�5�5�5��x��1����05�u���1�2�0�0�0��(�8�,����5:�E���Q�R�5�5�5���$�s�C�x�.�1���� 7K�7K�7K�r  �  �  �  �F�F�F�T�T�T�[�[�[� >�>�>�: M� M� M� M� Mr.r�r�c����fd�}|S)Nc�\���tj����fd���}�t�<|S)Nc����|i|��Sr&r2)�argsr��funcs �r,r�z\add_model_config_to_megatron_parser.<locals>.add_model_config_parser_helper.<locals>.wrapper� s����4��(��(�(� (r.)r��wrapsr�)r-r�r�s` �r,�add_model_config_parser_helperzKadd_model_config_to_megatron_parser.<locals>.add_model_config_parser_helper� sD���� ��� � � )� )� )� )� � � )�9=�)�*�5��r.r2)r�r/s` r,�#add_model_config_to_megatron_parserr0� s$�������� *�)r.z megatron-bertc��d}|jj}|jj}|jj}|jj}|jj}|jj} d} d|jj� ��vrd} |j �(|j �tj d��|j |_ n6|j � |j |_ n"|�|djd|_ n||_ |j |jd<||jd <||jd <||jd <||jd <||jd <| |jd<| |jd<|jj|jd<||jd<dS)N�bertF�maskedlmTzOBoth `seq_length` and `encoder_seq_length` are set. Using `encoder_seq_length`.� input_idsrr��model_type_name� num_layers� hidden_size�num_attention_heads�max_position_embeddings�pretraining_flag�orig_vocab_size�model_return_dict� num_labels)r��num_hidden_layersr7r8r9r=� vocab_sizer9r=r�r�r�r�r�r[r�� return_dict) �megatron_lm_pluginr�r�r5r6r7r8r9r=r;r:s r,�parse_bert_configrB� s���O���/�J��,�*�K��,�:��#�l�B����(�J��l�-�O����U�_�-�3�3�5�5�5�5����$�0� � 0� <� �M�k� l� l� l�(:�(M��%�%� � .� :�(:�(M��%�%� � �(2�;�(?�(E�a�(H��%�%�(?��%�@R�@]��/� �=�ET��/�0A�B�@J��/� �=�AL��/� �>�I\��/�0E�F�Md��/�0I�J�FV��/�0B�C�ET��/�0A�B�GL�|�G_��/�0C�D�@J��/� �=�=�=r.�gpt2c�T�d}|jj}|jj}|jj}|jj}|jj}d} |j�(|j�tj d��|j|_n6|j� |j|_n"|�|dj d|_n||_|j|j d<|j |j d<d|j d <||j d <||j d <||j d <||j d <||j d<| |j d<||j d<|jj |j d<dS)N�gptTzOBoth `seq_length` and `decoder_seq_length` are set. Using `decoder_seq_length`.r4rr�r��GPT2BPETokenizer�tokenizer_typer5r6r7r8r9r:r;r<)r��n_layer�n_embd�n_head� n_positionsr?r�r�r�r�r[r�r�r@� rAr�r�r5r6r7r8r9r;r:s r,�parse_gpt2_configrM� se���O���%�J��,�%�K��,�-��#�l�6���l�-�O����$�0� � 0� <� �M�k� l� l� l�(:�(M��%�%� � .� :�(:�(M��%�%� � �(2�;�(?�(E�a�(H��%�%�(?��%�@R�@]��/� �=�CU�Cc��/��@�DV��/�0@�A�ET��/�0A�B�@J��/� �=�AL��/� �>�I\��/�0E�F�Md��/�0I�J�FV��/�0B�C�ET��/�0A�B�GL�|�G_��/�0C�D�D�Dr.�t5c�H�d}|jj}|jj}|jj}t |jd��r |jjnd}|jj}d} |j�"|�|djd|_n||_|j �"|�|djd|_ n||_ |j|j d<|j |j d <||j d <||j d <||j d <||j d <||j d<| |j d<||j d<|jj |j d<dS)NrNrKr�Tr4r�labelsr�r�r5r6r7r8r9r:r;r<) r�r6�d_model� num_heads�hasattrrKr?r�r[r�r�r@rLs r,�parse_t5_configrT� sa���O���(�J��,�&�K��,�0��:A�%�,�P]�:^�:^�h�e�l�6�6�dh���l�-�O����,�4� � !�4>�{�4K�4Q�RS�4T� � 1� 1�4K� � 1��,�4� � !�4>�x�4H�4N�q�4Q� � 1� 1�4K� � 1�HZ�Hm��/�0D�E�HZ�Hm��/�0D�E�ET��/�0A�B�@J��/� �=�AL��/� �>�I\��/�0E�F�Md��/�0I�J�FV��/�0B�C�ET��/�0A�B�GL�|�G_��/�0C�D�D�Dr.�llamac�D�d}|jj}d}|jj}|jj}|jj}|jj} t |jdd��} |j�@| �| |_n6|j� |j|_n"|�|dj d|_n| |_|j |j d<d|j d<||j d <||j d <||j d <||j d <||j d <||j d<| |j d<|j|j d<|jj |j d<dS)NrET�max_sequence_lengthr4rr��Llama2TokenizerrGr5r6r:r7r8r;r9r�r<) r�r>r7r8r?r9r�r�r�r[r�r�r@) rAr�r�r5r6r:r7r8r;r9r�s r,�parse_llama_configrY sb���O���/�J����,�*�K��,�:���l�-�O�#�l�B�����'<�d�C�C�J��$�,� � !�,6� � )� )� � 2� >�,>�,Q� � )� )� � #�,6�{�,C�,I�!�,L� � )� )�,C� � )�CU�Cc��/��@�DU��/�0@�A�ET��/�0A�B�@J��/� �=�FV��/�0B�C�AL��/� �>�I\��/�0E�F�ET��/�0A�B�Md��/�0I�J�@R�@]��/� �=�GL�|�G_��/�0C�D�D�Dr.c��eZdZUdZedddi���Zeed<edddi���Ze ed <eddd i���Z eed <ed dd i���Z e ed<edddi���Z eed<edddi���Ze ed<edddi���Zejed<edddi���Zee ed<edddi���Zee ed<d�ZdS)�BnbQuantizationConfiga� A plugin to enable BitsAndBytes 4bit and 8bit quantization Args: load_in_8bit (`bool`, defaults to `False`): Enable 8bit quantization. llm_int8_threshold (`float`, defaults to `6.0`): Value of the outliner threshold. Only relevant when `load_in_8bit=True`. load_in_4_bit (`bool`, defaults to `False`): Enable 4bit quantization. bnb_4bit_quant_type (`str`, defaults to `fp4`): Set the quantization data type in the `bnb.nn.Linear4Bit` layers. Options are {'fp4','np4'}. bnb_4bit_use_double_quant (`bool`, defaults to `False`): Enable nested quantization where the quantization constants from the first quantization are quantized again. bnb_4bit_compute_dtype (`bool`, defaults to `fp16`): This sets the computational type which might be different than the input time. For example, inputs might be fp32, but computation can be set to bf16 for speedups. Options are {'fp32','fp16','bf16'}. torch_dtype (`torch.dtype`, defaults to `None`): This sets the dtype of the remaining non quantized layers. `bitsandbytes` library suggests to set the value to `torch.float16` for 8 bit model and use the same dtype as the compute dtype for 4 bit model. skip_modules (`List[str]`, defaults to `None`): An explicit list of the modules that we don't quantize. The dtype of these modules will be `torch_dtype`. keep_in_fp32_modules (`List`, defaults to `None`): An explicit list of the modules that we don't quantize. We keep them in `torch.float32`. Fr`zenable 8bit quantization.ra� load_in_8bit�@zEvalue of the outliner threshold. only relevant when load_in_8bit=True�llm_int8_thresholdzenable 4bit quantization.� load_in_4bit�fp4z\set the quantization data type in the `bnb.nn.Linear4Bit` layers. Options are {'fp4','nf4'}.�bnb_4bit_quant_typezlenable nested quantization where the quantization constants from the first quantization are quantized again.�bnb_4bit_use_double_quantr\z�This sets the computational type which might be different than the input time. For example, inputs might be fp32, but computation can be set to bf16 for speedups. Options are {'fp32','fp16','bf16'}.�bnb_4bit_compute_dtypeNz�this sets the dtype of the remaining non quantized layers. `bitsandbytes` library suggests to set the valueto `torch.float16` for 8 bit model and use the same dtype as the compute dtype for 4 bit model � torch_dtypezian explicit list of the modules that we don't quantize. The dtype of these modules will be `torch_dtype`.� skip_moduleszXan explicit list of the modules that we don't quantize. We keep them in `torch.float32`.�keep_in_fp32_modulesc��t|jt��std���t|jt��std���|jr|jrtd���|js|jstd���t|jt tf��std���t|jt��std���|jdvrtd|j�����t|j t��std ���t|j t��rn|j d krtj |_ n|j d krtj|_ nb|j d krtj|_ nEtd |j �����t|j tj��std���|j�)t|jt$��std���|j�)t|jt$��std���|jrt(j|_|jrtj|_|jr|jdkrt1jd��t|jt��rn|jd krtj |_nQ|jd krtj|_n4|jd krtj|_ntd|j�����|jr|j�tj|_|jr|j� |j |_t|jtj��std���dS)z~ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values. zload_in_8bit must be a booleanzload_in_4bit must be a booleanz0load_in_4bit and load_in_8bit can't be both Truez1load_in_4bit and load_in_8bit can't be both Falsez,llm_int8_threshold must be a float or an intz$bnb_4bit_quant_type must be a string)r`�nf4z7bnb_4bit_quant_type must be in ['fp4','nf4'] but found z+bnb_4bit_use_double_quant must be a booleanr�r\r]zCbnb_4bit_compute_dtype must be in ['fp32','fp16','bf16'] but found z8bnb_4bit_compute_dtype must be a string or a torch.dtypeNz&skip_modules must be a list of stringsz/keep_in_fp_32_modules must be a list of stringsr]z<llm_int8_threshold can only be used for model loaded in 8bitz8torch_dtype must be in ['fp32','fp16','bf16'] but found z!torch_dtype must be a torch.dtype)r�r\rWrDr_r^r�r�rarPrbrcr�r�r�r�r\rerNrfrTrW� target_dtype�int8r�r�rdr*s r,r�z#BnbQuantizationConfig.__post_init__{ s���$�+�T�2�2� ?��=�>�>� >��$�+�T�2�2� ?��=�>�>� >� � � Q��!2� Q��O�P�P� P�� � R��):� R��P�Q�Q� Q��$�1�C��<�@�@� M��K�L�L� L��$�2�C�8�8� s��C�D�D� D� � %�^� ;� ;��q�W[�Wo�q�q�r�r� r��$�8�$�?�?� L��J�K�K� K� �d�1�3� 7� 7� Y��*�f�4�4�.3�m��+�+��,��6�6�.3�m��+�+��,��6�6�.3�n��+�+� �w�Z^�Zu�w�w�����D�7���E�E� Y��W�X�X� X� � � (��D�<M�t�1T�1T� (��E�F�F� F� � $� 0��D�D]�_c�9d�9d� 0��N�O�O� O� � � 1� +� 0�D� � � � +� %� �D� � � � Z��!8�C�!?�!?� �M�X� Y� Y� Y� �d�&�� ,� ,� p���6�)�)�#(�=�� � ��!�V�+�+�#(�=�� � ��!�V�+�+�#(�>�� � � �!n�\`�\l�!n�!n�o�o�o� � � -��!1�!9�$�}�D� � � � ;��!1�!9�#�:�D� ��$�*�E�K�8�8� B��@�A�A� A� B� Br.)r=r>r?r@rr\rWrXr^r�r_rarPrbrcrdr�r\rerNrfr�r2r.r,r[r[, s���������6��u��@[�7\�]�]�]�L�$�]�]�]� %���v�'n�o�!�!�!��������u��@[�7\�]�]�]�L�$�]�]�]�$�u�� �r� � � � ������',�e�� �C� �'�'�'��t����#(�%�� �i� �#�#�#��C���� %�u�� �n� � � � �K������$�e�� �� ����L�$�s�)����',�e���t�u�'�'�'��$�s�)���� HB�HB�HB�HB�HBr.r[c���t|�����}|jj|kr|jSt |��dkrdS|D]}t ||��}|�|cS�dS)z� Gets a class from a module by its name. Args: module (`torch.nn.Module`): The module to get the class from. name (`str`): The name of the class. rN)rN�childrenr9r=r�r)�moduler�modules_children� child_module� module_classs r,rr� s����F�O�O�-�-�.�.�� �� �D�(�(���� � � � �!� #� #���,� $� $�L�5�l�D�I�I�L��'�#�#�#�#�(� $� $r.)dr@r!r'�enumr��loggingr�r��collections.abcr� contextlibr� dataclassesrr�datetimer�typingrr r r r r rr�� constantsrrrrrrr8rrr�rrrrrrrr�versionsr r!�torchao.float8r"� getLoggerr=rnr$�EnumMetarB�EnumrIrTrZrfr�r�r�r�r�r�r�r�r�r�r�r�rPrrrrrr0rBrFrTrZr_rlrwr}r�r*r�r�r�r0rBrMrTrYr[rr2r.r,�<module>r~s� �������� � � � � � � � ��������� � � � �����$�$�$�$�$�$�%�%�%�%�%�%�(�(�(�(�(�(�(�(�������S�S�S�S�S�S�S�S�S�S�S�S�S�S�S�S�S�S� � � � �����������������:�9�9�9�9�9�9�9� � � � � � � � � � � � � � � � � � � � �9�8�8�8�8�8�8�8��2�1�1�1�1�1�1� �� �8� $� $��L�L�L�L�L�L�L�L�*�����t�}���� #� #� #� #� #�t�y�$4� #� #� #� #� ������]��� ���*,�,�,�,�,�x�,�,�,�( �I�I�I�I�I�M�I�I� ��I�X ������}��� ���< �6�6�6�6�6�]�6�6� ��6�< �-� �� �:� �� �$� %� ��3�4�� �2�2�2�2�2�]�2�2� ��2�$ �HC�HC�HC�HC�HC�]�HC�HC� ��HC�V � ^� ^� ^� ^� ^� � ^� ^� �� ^�  � � � � � �n�&7� � � �� �2�>�?�� �q �q �q �q �q �M�q �q � ��q �h!�!�!�!�!�c�4�9�!�!�!�H&�&�&�&�&�s�D�I�&�&�&�" � � � � �S�$�)� � � � *� *� *� *� *��d�i� *� *� *�5 �5 �5 �5 �5 �C��5 �5 �5 �p���������, � � � � �C�� � � � � � � � �h� � � ������$�)���� �������� ���  �[�[�[�[�[�[�[� ��[�| �;/�;/�;/�;/�;/�;/�;/� ��;/�| �-�-�-�-�-��-�-� ��-�` �.�.�.�.�.� �.�.� ��.�b �j �j �j �j �j �j �j � ��j �Z  �t�t�t�t�t�t�t� ��t�n � l� l� l� l� l� l� l� �� l�F �QM�QM�QM�QM�QM�QM�QM� ��QM�h %'�!� *�C� *� *� *� *�%�$�_�5�5�K�K�6�5�K�B%�$�V�,�,�`�`�-�,�`�>%�$�T�*�*�`�`�+�*�`�<%�$�W�-�-�`�`�.�-�`�B �VB�VB�VB�VB�VB�VB�VB� ��VB�r$�$�$�$�$r.
Memory