
# 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       __A(				UpperCAmelCase       ):

					def __init__(	self					:     Dict   ,					__UpperCamelCase					:     int   ):
												lowerCamelCase_							  =					data



					def __iter__(	self					:     Optional[Any]   ):
												for element in self.data:
																			yield element



def      __lowerCAmelCase						(							UpperCAmelCase__				:      List[str]=True       )  ->    Tuple:
							lowerCamelCase_							  =					Accelerator(even_batches=UpperCAmelCase__       )
							assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
							return accelerator



def      __lowerCAmelCase						(							UpperCAmelCase__				:      Accelerator			,				UpperCAmelCase__				:      int			,				UpperCAmelCase__				:      int			,				UpperCAmelCase__				:      bool = False       )  ->    Union[str, Any]:
							if iterable:
														lowerCamelCase_							  =					DummyIterableDataset(torch.as_tensor(range(UpperCAmelCase__       )       )       )
							else:
														lowerCamelCase_							  =					TensorDataset(torch.as_tensor(range(UpperCAmelCase__       )       )       )

							lowerCamelCase_							  =					DataLoader(UpperCAmelCase__			,				batch_size=UpperCAmelCase__       )
							lowerCamelCase_							  =					accelerator.prepare(UpperCAmelCase__       )

							return dl



def      __lowerCAmelCase						(							UpperCAmelCase__				:      Accelerator			,				UpperCAmelCase__				:      int			,				UpperCAmelCase__				:      int			,				UpperCAmelCase__				:      List[int]			,				UpperCAmelCase__				:      List[int]			,				)  ->    int:
							lowerCamelCase_							  =					create_dataloader(accelerator=UpperCAmelCase__			,				dataset_size=UpperCAmelCase__			,				batch_size=UpperCAmelCase__       )

							lowerCamelCase_							  =					[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      __lowerCAmelCase						(							)  ->    List[str]:
							lowerCamelCase_							  =					create_accelerator()

							# without padding, we would expect a different number of batches
							verify_dataloader_batch_sizes(
							    UpperCAmelCase__			,				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(
							    UpperCAmelCase__			,				dataset_size=7			,				batch_size=2			,				process_0_expected_batch_sizes=[2, 2]			,				process_1_expected_batch_sizes=[2, 2]			,				)



def      __lowerCAmelCase						(							)  ->    List[str]:
							lowerCamelCase_							  =					create_accelerator(even_batches=UpperCAmelCase__       )

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

							verify_dataloader_batch_sizes(
							    UpperCAmelCase__			,				dataset_size=7			,				batch_size=2			,				process_0_expected_batch_sizes=[2, 2]			,				process_1_expected_batch_sizes=[2, 1]			,				)



def      __lowerCAmelCase						(							)  ->    Tuple:
							lowerCamelCase_							  =					create_accelerator(even_batches=UpperCAmelCase__       )

							lowerCamelCase_							  =					torch.nn.Linear(1			,				1       )
							lowerCamelCase_							  =					accelerator.prepare(UpperCAmelCase__       )

							lowerCamelCase_							  =					create_dataloader(UpperCAmelCase__			,				dataset_size=3			,				batch_size=1       )

							lowerCamelCase_							  =					[]
							with accelerator.join_uneven_inputs([ddp_model]       ):
														for batch_idx, batch in enumerate(UpperCAmelCase__       ):
																					lowerCamelCase_							  =					ddp_model(batch[0].float()       )
																					lowerCamelCase_							  =					output.sum()
																					loss.backward()
																					batch_idxs.append(UpperCAmelCase__       )

							accelerator.wait_for_everyone()

							if accelerator.process_index == 0:
														assert batch_idxs == [0, 1]
							elif accelerator.process_index == 1:
														assert batch_idxs == [0]



def      __lowerCAmelCase						(							UpperCAmelCase__				:      Tuple       )  ->    List[Any]:
							with warnings.catch_warnings(record=UpperCAmelCase__       ) as w:
														with accelerator.join_uneven_inputs([Mock()]       ):
																					pass

														assert issubclass(w[-1].category			,				UpperCAmelCase__       )
														assert "only supported for multi-GPU" in str(w[-1].message       )



def      __lowerCAmelCase						(							)  ->    Optional[Any]:
							lowerCamelCase_							  =					True
							lowerCamelCase_							  =					False
							lowerCamelCase_							  =					create_accelerator(even_batches=UpperCAmelCase__       )
							lowerCamelCase_							  =					torch.nn.Linear(1			,				1       )
							lowerCamelCase_							  =					accelerator.prepare(UpperCAmelCase__       )
							lowerCamelCase_							  =					create_dataloader(UpperCAmelCase__			,				dataset_size=3			,				batch_size=1       )
							lowerCamelCase_							  =					create_dataloader(UpperCAmelCase__			,				dataset_size=3			,				batch_size=1       )

							with accelerator.join_uneven_inputs([ddp_model]			,				even_batches=UpperCAmelCase__       ):
														lowerCamelCase_							  =					train_dl.batch_sampler.even_batches
														lowerCamelCase_							  =					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      __lowerCAmelCase						(							)  ->    Optional[Any]:
							lowerCamelCase_							  =					True
							lowerCamelCase_							  =					False
							lowerCamelCase_							  =					create_accelerator(even_batches=UpperCAmelCase__       )
							lowerCamelCase_							  =					torch.nn.Linear(1			,				1       )
							lowerCamelCase_							  =					accelerator.prepare(UpperCAmelCase__       )
							create_dataloader(UpperCAmelCase__			,				dataset_size=3			,				batch_size=1			,				iterable=UpperCAmelCase__       )
							lowerCamelCase_							  =					create_dataloader(UpperCAmelCase__			,				dataset_size=3			,				batch_size=1       )

							with warnings.catch_warnings():
														warnings.filterwarnings("""ignore"""       )
														try:
																					with accelerator.join_uneven_inputs([ddp_model]			,				even_batches=UpperCAmelCase__       ):
																												lowerCamelCase_							  =					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      __lowerCAmelCase						(							)  ->    str:
							lowerCamelCase_							  =					create_accelerator()
							lowerCamelCase_							  =					torch.nn.Linear(1			,				1       )
							lowerCamelCase_							  =					accelerator.prepare(UpperCAmelCase__       )
							create_dataloader(UpperCAmelCase__			,				dataset_size=3			,				batch_size=1			,				iterable=UpperCAmelCase__       )

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

														assert issubclass(w[-1].category			,				UpperCAmelCase__       )
														assert "only supported for map-style datasets" in str(w[-1].message       )



def      __lowerCAmelCase						(							)  ->    Union[str, Any]:
							lowerCamelCase_							  =					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_							  =					accelerator.state.distributed_type
							lowerCamelCase_							  =					DistributedType.FSDP
							test_join_raises_warning_for_non_ddp_distributed(UpperCAmelCase__       )
							lowerCamelCase_							  =					original_state


if __name__ == "__main__":
		main()







import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_mobilebert import MobileBertTokenizer


lowercase        =  logging.get_logger(__name__)

lowercase        =  {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}

lowercase        =  {
    '''vocab_file''': {'''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/vocab.txt'''},
    '''tokenizer_file''': {
        '''mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/tokenizer.json'''
    },
}

lowercase        =  {'''mobilebert-uncased''': 5_1_2}


lowercase        =  {}





class       __A(				UpperCAmelCase       ):
					SCREAMING_SNAKE_CASE			    =    VOCAB_FILES_NAMES
					SCREAMING_SNAKE_CASE			    =    PRETRAINED_VOCAB_FILES_MAP
					SCREAMING_SNAKE_CASE			    =    PRETRAINED_INIT_CONFIGURATION
					SCREAMING_SNAKE_CASE			    =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
					SCREAMING_SNAKE_CASE			    =    MobileBertTokenizer

					def __init__(	self					:     Union[str, Any]   ,					__UpperCamelCase					:     str=None   ,					__UpperCamelCase					:     str=None   ,					__UpperCamelCase					:     Dict=True   ,					__UpperCamelCase					:     Any="[UNK]"   ,					__UpperCamelCase					:     str="[SEP]"   ,					__UpperCamelCase					:     Dict="[PAD]"   ,					__UpperCamelCase					:     List[str]="[CLS]"   ,					__UpperCamelCase					:     Any="[MASK]"   ,					__UpperCamelCase					:     Any=True   ,					__UpperCamelCase					:     int=None   ,					**__UpperCamelCase					:     Dict   ,					):
												super().__init__(
												    __UpperCamelCase   ,					tokenizer_file=__UpperCamelCase   ,					do_lower_case=__UpperCamelCase   ,					unk_token=__UpperCamelCase   ,					sep_token=__UpperCamelCase   ,					pad_token=__UpperCamelCase   ,					cls_token=__UpperCamelCase   ,					mask_token=__UpperCamelCase   ,					tokenize_chinese_chars=__UpperCamelCase   ,					strip_accents=__UpperCamelCase   ,					**__UpperCamelCase   ,					)

												lowerCamelCase_							  =					json.loads(self.backend_tokenizer.normalizer.__getstate__()   )
												if (
												    normalizer_state.get("""lowercase"""   ,					__UpperCamelCase   ) != do_lower_case
												    or normalizer_state.get("""strip_accents"""   ,					__UpperCamelCase   ) != strip_accents
												    or normalizer_state.get("""handle_chinese_chars"""   ,					__UpperCamelCase   ) != tokenize_chinese_chars
												):
																			lowerCamelCase_							  =					getattr(__UpperCamelCase   ,					normalizer_state.pop("""type"""   )   )
																			lowerCamelCase_							  =					do_lower_case
																			lowerCamelCase_							  =					strip_accents
																			lowerCamelCase_							  =					tokenize_chinese_chars
																			lowerCamelCase_							  =					normalizer_class(**__UpperCamelCase   )

												lowerCamelCase_							  =					do_lower_case

					def    lowercase__      (	self					:     List[str]   ,					__UpperCamelCase					:     Union[str, Any]   ,					__UpperCamelCase					:     Dict=None   ):
												lowerCamelCase_							  =					[self.cls_token_id] + token_ids_a + [self.sep_token_id]

												if token_ids_a:
																			output += token_ids_a + [self.sep_token_id]

												return output

					def    lowercase__      (	self					:     Tuple   ,					__UpperCamelCase					:     List[int]   ,					__UpperCamelCase					:     Optional[List[int]] = None   ):
												lowerCamelCase_							  =					[self.sep_token_id]
												lowerCamelCase_							  =					[self.cls_token_id]
												if token_ids_a is None:
																			return len(cls + token_ids_a + sep   ) * [0]
												return len(cls + token_ids_a + sep   ) * [0] + len(token_ids_a + sep   ) * [1]



					def    lowercase__      (	self					:     List[str]   ,					__UpperCamelCase					:     str   ,					__UpperCamelCase					:     Optional[str] = None   ):
												lowerCamelCase_							  =					self._tokenizer.model.save(__UpperCamelCase   ,					name=__UpperCamelCase   )
												return tuple(__UpperCamelCase   )





