






'''simple docstring'''

# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import warnings
from typing import List
from unittest.mock import Mock

import torch
from torch.utils.data import DataLoader, IterableDataset, TensorDataset

from accelerate.accelerator import Accelerator
from accelerate.utils.dataclasses import DistributedType







class 	SCREAMING_SNAKE_CASE	(      lowerCAmelCase_  ):




       def __init__(					self      : List[Any]	,    A__      : Optional[int]					):


            """simple docstring"""







            __lowerCamelCase						:       List[str]				   =				data




       def __iter__(					self      : str					):


            """simple docstring"""







            for element in self.data:
                 yield element

def     __lowercase  (_lowercase=True     )   ->     Tuple:


     """simple docstring"""
     __lowerCamelCase						:       Optional[Any]				   =				Accelerator(even_batches=_lowercase     )
     assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
     return accelerator
def     __lowercase  (_lowercase,						_lowercase,						_lowercase,						_lowercase = False     )   ->     Dict:


     """simple docstring"""
     if iterable:
          __lowerCamelCase						:       str				   =				DummyIterableDataset(torch.as_tensor(range(_lowercase     )     )     )
     else:
          __lowerCamelCase						:       Any				   =				TensorDataset(torch.as_tensor(range(_lowercase     )     )     )

     __lowerCamelCase						:       List[str]				   =				DataLoader(_lowercase,						batch_size=_lowercase     )
     __lowerCamelCase						:       Union[str, Any]				   =				accelerator.prepare(_lowercase     )

     return dl
def     __lowercase  (_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						)   ->     Tuple:


     """simple docstring"""
     __lowerCamelCase						:       List[Any]				   =				create_dataloader(accelerator=_lowercase,						dataset_size=_lowercase,						batch_size=_lowercase     )

     __lowerCamelCase						:       Optional[Any]				   =				[len(batch[0]     ) for batch in dl]

     if accelerator.process_index == 0:
          assert batch_sizes == process_0_expected_batch_sizes
     elif accelerator.process_index == 1:
          assert batch_sizes == process_1_expected_batch_sizes
def     __lowercase  ()   ->     Any:


     """simple docstring"""
     __lowerCamelCase						:       int				   =				create_accelerator()

     # without padding, we would expect a different number of batches
     verify_dataloader_batch_sizes(
         _lowercase,						dataset_size=3,						batch_size=1,						process_0_expected_batch_sizes=[1, 1],						process_1_expected_batch_sizes=[1, 1],						)

     # without padding, we would expect the same number of batches, but different sizes
     verify_dataloader_batch_sizes(
         _lowercase,						dataset_size=7,						batch_size=2,						process_0_expected_batch_sizes=[2, 2],						process_1_expected_batch_sizes=[2, 2],						)
def     __lowercase  ()   ->     str:


     """simple docstring"""
     __lowerCamelCase						:       Optional[int]				   =				create_accelerator(even_batches=_lowercase     )

     verify_dataloader_batch_sizes(
         _lowercase,						dataset_size=3,						batch_size=1,						process_0_expected_batch_sizes=[1, 1],						process_1_expected_batch_sizes=[1],						)

     verify_dataloader_batch_sizes(
         _lowercase,						dataset_size=7,						batch_size=2,						process_0_expected_batch_sizes=[2, 2],						process_1_expected_batch_sizes=[2, 1],						)
def     __lowercase  ()   ->     int:


     """simple docstring"""
     __lowerCamelCase						:       Optional[int]				   =				create_accelerator(even_batches=_lowercase     )

     __lowerCamelCase						:       List[Any]				   =				torch.nn.Linear(1,						1     )
     __lowerCamelCase						:       Tuple				   =				accelerator.prepare(_lowercase     )

     __lowerCamelCase						:       List[str]				   =				create_dataloader(_lowercase,						dataset_size=3,						batch_size=1     )

     __lowerCamelCase						:       Optional[int]				   =				[]
     with accelerator.join_uneven_inputs([ddp_model]     ):
          for batch_idx, batch in enumerate(_lowercase     ):
               __lowerCamelCase						:       Any				   =				ddp_model(batch[0].float()     )
               __lowerCamelCase						:       Any				   =				output.sum()
               loss.backward()
               batch_idxs.append(_lowercase     )

     accelerator.wait_for_everyone()

     if accelerator.process_index == 0:
          assert batch_idxs == [0, 1]
     elif accelerator.process_index == 1:
          assert batch_idxs == [0]
def     __lowercase  (_lowercase     )   ->     List[Any]:


     """simple docstring"""
     with warnings.catch_warnings(record=_lowercase     ) as w:
          with accelerator.join_uneven_inputs([Mock()]     ):
               pass

          assert issubclass(w[-1].category,						_lowercase     )
          assert "only supported for multi-GPU" in str(w[-1].message     )
def     __lowercase  ()   ->     Tuple:


     """simple docstring"""
     __lowerCamelCase						:       int				   =				True
     __lowerCamelCase						:       Union[str, Any]				   =				False
     __lowerCamelCase						:       List[Any]				   =				create_accelerator(even_batches=_lowercase     )
     __lowerCamelCase						:       List[str]				   =				torch.nn.Linear(1,						1     )
     __lowerCamelCase						:       str				   =				accelerator.prepare(_lowercase     )
     __lowerCamelCase						:       Optional[int]				   =				create_dataloader(_lowercase,						dataset_size=3,						batch_size=1     )
     __lowerCamelCase						:       List[str]				   =				create_dataloader(_lowercase,						dataset_size=3,						batch_size=1     )

     with accelerator.join_uneven_inputs([ddp_model],						even_batches=_lowercase     ):
          __lowerCamelCase						:       List[str]				   =				train_dl.batch_sampler.even_batches
          __lowerCamelCase						:       str				   =				valid_dl.batch_sampler.even_batches

     assert train_dl_overridden_value == overridden_even_batches
     assert valid_dl_overridden_value == overridden_even_batches
     assert train_dl.batch_sampler.even_batches == default_even_batches
     assert valid_dl.batch_sampler.even_batches == default_even_batches
def     __lowercase  ()   ->     Union[str, Any]:


     """simple docstring"""
     __lowerCamelCase						:       Optional[int]				   =				True
     __lowerCamelCase						:       Optional[Any]				   =				False
     __lowerCamelCase						:       List[Any]				   =				create_accelerator(even_batches=_lowercase     )
     __lowerCamelCase						:       Optional[int]				   =				torch.nn.Linear(1,						1     )
     __lowerCamelCase						:       Union[str, Any]				   =				accelerator.prepare(_lowercase     )
     create_dataloader(_lowercase,						dataset_size=3,						batch_size=1,						iterable=_lowercase     )
     __lowerCamelCase						:       Optional[int]				   =				create_dataloader(_lowercase,						dataset_size=3,						batch_size=1     )

     with warnings.catch_warnings():
          warnings.filterwarnings("""ignore"""     )
          try:
               with accelerator.join_uneven_inputs([ddp_model],						even_batches=_lowercase     ):
                    __lowerCamelCase						:       Dict				   =				batch_dl.batch_sampler.even_batches
          except AttributeError:
               # ensure attribute error is not raised when processing iterable dl
               raise AssertionError

     assert batch_dl_overridden_value == overridden_even_batches
     assert batch_dl.batch_sampler.even_batches == default_even_batches
def     __lowercase  ()   ->     Optional[Any]:


     """simple docstring"""
     __lowerCamelCase						:       List[Any]				   =				create_accelerator()
     __lowerCamelCase						:       Any				   =				torch.nn.Linear(1,						1     )
     __lowerCamelCase						:       Tuple				   =				accelerator.prepare(_lowercase     )
     create_dataloader(_lowercase,						dataset_size=3,						batch_size=1,						iterable=_lowercase     )

     with warnings.catch_warnings(record=_lowercase     ) as w:
          with accelerator.join_uneven_inputs([ddp_model],						even_batches=_lowercase     ):
               pass

          assert issubclass(w[-1].category,						_lowercase     )
          assert "only supported for map-style datasets" in str(w[-1].message     )
def     __lowercase  ()   ->     List[Any]:


     """simple docstring"""
     __lowerCamelCase						:       Tuple				   =				create_accelerator()

     accelerator.print("""Test that even_batches variable ensures uniform batches across processes"""     )
     test_default_ensures_even_batch_sizes()

     accelerator.print("""Run tests with even_batches disabled"""     )
     test_can_disable_even_batches()

     accelerator.print("""Test joining uneven inputs"""     )
     test_can_join_uneven_inputs()

     accelerator.print("""Test overriding even_batches when joining uneven inputs"""     )
     test_join_can_override_even_batches()

     accelerator.print("""Test overriding even_batches for mixed dataloader types"""     )
     test_join_can_override_for_mixed_type_dataloaders()

     accelerator.print("""Test overriding even_batches raises a warning for iterable dataloaders"""     )
     test_join_raises_warning_for_iterable_when_overriding_even_batches()

     accelerator.print("""Test join with non DDP distributed raises warning"""     )
     __lowerCamelCase						:       Tuple				   =				accelerator.state.distributed_type
     __lowerCamelCase						:       Optional[int]				   =				DistributedType.FSDP
     test_join_raises_warning_for_non_ddp_distributed(_lowercase     )
     __lowerCamelCase						:       List[Any]				   =				original_state


if __name__ == "__main__":
   main()











'''simple docstring'''

import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase__						:Optional[int]          =			logging.get_logger(__name__)

UpperCAmelCase__						:List[Any]          =			{
    """asapp/sew-d-tiny-100k""": """https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json""",
    # See all SEW-D models at https://huggingface.co/models?filter=sew-d
}







class 	SCREAMING_SNAKE_CASE	(      lowerCAmelCase_  ):
       snake_case__    :     Dict   		=			'sew-d'




       def __init__(					self      : Tuple	,    A__      : Optional[int]=32	,    A__      : Optional[int]=768	,    A__      : Any=12	,    A__      : List[str]=12	,    A__      : List[Any]=3072	,    A__      : str=2	,    A__      : Dict=512	,    A__      : Optional[Any]=256	,    A__      : Optional[Any]=True	,    A__      : Any=True	,    A__      : List[str]=("p2c", "c2p")	,    A__      : List[Any]="layer_norm"	,    A__      : Union[str, Any]="gelu_python"	,    A__      : int=0.1	,    A__      : Dict=0.1	,    A__      : int=0.1	,    A__      : Dict=0.0	,    A__      : Optional[Any]=0.1	,    A__      : Dict=0.02	,    A__      : Dict=1e-7	,    A__      : List[Any]=1e-5	,    A__      : Any="group"	,    A__      : Any="gelu"	,    A__      : Dict=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512)	,    A__      : Dict=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)	,    A__      : str=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)	,    A__      : Optional[Any]=False	,    A__      : Any=128	,    A__      : Optional[Any]=16	,    A__      : Union[str, Any]=True	,    A__      : Any=0.05	,    A__      : List[str]=10	,    A__      : Union[str, Any]=2	,    A__      : Dict=0.0	,    A__      : str=10	,    A__      : Tuple=0	,    A__      : Any="mean"	,    A__      : Optional[int]=False	,    A__      : int=False	,    A__      : List[str]=256	,    A__      : Union[str, Any]=0	,    A__      : int=1	,    A__      : Optional[Any]=2	,    **A__      : List[Any]	,    ):


            """simple docstring"""







            super().__init__(**A__	,    pad_token_id=A__	,    bos_token_id=A__	,    eos_token_id=A__					)
            __lowerCamelCase						:       List[str]				   =				hidden_size
            __lowerCamelCase						:       Tuple				   =				feat_extract_norm
            __lowerCamelCase						:       Tuple				   =				feat_extract_activation
            __lowerCamelCase						:       List[Any]				   =				list(A__					)
            __lowerCamelCase						:       int				   =				list(A__					)
            __lowerCamelCase						:       Optional[Any]				   =				list(A__					)
            __lowerCamelCase						:       Tuple				   =				conv_bias
            __lowerCamelCase						:       List[str]				   =				num_conv_pos_embeddings
            __lowerCamelCase						:       Tuple				   =				num_conv_pos_embedding_groups
            __lowerCamelCase						:       int				   =				len(self.conv_dim					)
            __lowerCamelCase						:       Optional[int]				   =				num_hidden_layers
            __lowerCamelCase						:       Dict				   =				intermediate_size
            __lowerCamelCase						:       Optional[int]				   =				squeeze_factor
            __lowerCamelCase						:       Union[str, Any]				   =				max_position_embeddings
            __lowerCamelCase						:       int				   =				position_buckets
            __lowerCamelCase						:       Tuple				   =				share_att_key
            __lowerCamelCase						:       Any				   =				relative_attention
            __lowerCamelCase						:       Any				   =				norm_rel_ebd
            __lowerCamelCase						:       Dict				   =				list(A__					)
            __lowerCamelCase						:       Optional[Any]				   =				hidden_act
            __lowerCamelCase						:       List[str]				   =				num_attention_heads
            __lowerCamelCase						:       List[str]				   =				hidden_dropout
            __lowerCamelCase						:       Union[str, Any]				   =				attention_dropout
            __lowerCamelCase						:       Tuple				   =				activation_dropout
            __lowerCamelCase						:       Union[str, Any]				   =				feat_proj_dropout
            __lowerCamelCase						:       Union[str, Any]				   =				final_dropout
            __lowerCamelCase						:       List[str]				   =				layer_norm_eps
            __lowerCamelCase						:       Tuple				   =				feature_layer_norm_eps
            __lowerCamelCase						:       Union[str, Any]				   =				initializer_range
            __lowerCamelCase						:       List[str]				   =				vocab_size

            if (
                (len(self.conv_stride					) != self.num_feat_extract_layers)
                or (len(self.conv_kernel					) != self.num_feat_extract_layers)
                or (len(self.conv_dim					) != self.num_feat_extract_layers)
            ):
                 raise ValueError(
                     """Configuration for convolutional layers is incorrect."""
                     """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"""
                     f"but is `len(config.conv_dim) = {len(self.conv_dim					)}`, `len(config.conv_stride)"
                     f"= {len(self.conv_stride					)}`, `len(config.conv_kernel) = {len(self.conv_kernel					)}`."					)

            # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
            __lowerCamelCase						:       Any				   =				apply_spec_augment
            __lowerCamelCase						:       str				   =				mask_time_prob
            __lowerCamelCase						:       Tuple				   =				mask_time_length
            __lowerCamelCase						:       Optional[int]				   =				mask_time_min_masks
            __lowerCamelCase						:       Dict				   =				mask_feature_prob
            __lowerCamelCase						:       Optional[Any]				   =				mask_feature_length
            __lowerCamelCase						:       str				   =				mask_feature_min_masks

            # ctc loss
            __lowerCamelCase						:       Any				   =				ctc_loss_reduction
            __lowerCamelCase						:       str				   =				ctc_zero_infinity

            # sequence classification
            __lowerCamelCase						:       Dict				   =				use_weighted_layer_sum
            __lowerCamelCase						:       List[Any]				   =				classifier_proj_size




       @property
       def 					a_					(					self      : Optional[int]					):


            """simple docstring"""







            return functools.reduce(operator.mul	,    self.conv_stride	,    1					)



