
'''simple docstring'''






import argparse
import os

import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed

from accelerate import Accelerator, DistributedType


########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to properly calculate the metrics on the
# validation dataset when in a distributed system, and builds off the
# `nlp_example.py` script.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
#   - single CPU or single GPU
#   - multi GPUS (using PyTorch distributed mode)
#   - (multi) TPUs
#   - fp16 (mixed-precision) or fp32 (normal precision)
#
# To help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################


UpperCAmelCase_							: int =							16
UpperCAmelCase_							: Union[str, Any] =							32







def 		A_							(						_lowerCAmelCase :     Accelerator					,						_lowerCAmelCase :     int = 16				):



      """simple docstring"""




      _lowerCamelCase					: Tuple		    = AutoTokenizer.from_pretrained("bert-base-cased"				)
      _lowerCamelCase					: List[str]		    = load_dataset("glue"					,						"mrpc"				)

      def tokenize_function(_lowerCAmelCase :     List[str]				):
            # max_length=None => use the model max length (it's actually the default)
            _lowerCamelCase					: str		    = tokenizer(examples["sentence1"]					,						examples["sentence2"]					,						truncation=_lowerCAmelCase					,						max_length=_lowerCAmelCase				)
            return outputs

      # Apply the method we just defined to all the examples in all the splits of the dataset
      # starting with the main process first:
      with accelerator.main_process_first():
            _lowerCamelCase					: Optional[int]		    = datasets.map(
                _lowerCAmelCase					,						batched=_lowerCAmelCase					,						remove_columns=["idx", "sentence1", "sentence2"]					,						)

      # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
      # transformers library
      _lowerCamelCase					: Optional[Any]		    = tokenized_datasets.rename_column("label"					,						"labels"				)

      def collate_fn(_lowerCAmelCase :     List[Any]				):
            # On TPU it's best to pad everything to the same length or training will be very slow.
            _lowerCamelCase					: List[Any]		    = 128 if accelerator.distributed_type == DistributedType.TPU else None
            # When using mixed precision we want round multiples of 8/16
            if accelerator.mixed_precision == "fp8":
                  _lowerCamelCase					: List[Any]		    = 16
            elif accelerator.mixed_precision != "no":
                  _lowerCamelCase					: str		    = 8
            else:
                  _lowerCamelCase					: Optional[Any]		    = None

            return tokenizer.pad(
                _lowerCAmelCase					,						padding="longest"					,						max_length=_lowerCAmelCase					,						pad_to_multiple_of=_lowerCAmelCase					,						return_tensors="pt"					,						)

      # Instantiate dataloaders.
      _lowerCamelCase					: List[Any]		    = DataLoader(
          tokenized_datasets["train"]					,						shuffle=_lowerCAmelCase					,						collate_fn=_lowerCAmelCase					,						batch_size=_lowerCAmelCase				)
      _lowerCamelCase					: List[Any]		    = DataLoader(
          tokenized_datasets["validation"]					,						shuffle=_lowerCAmelCase					,						collate_fn=_lowerCAmelCase					,						batch_size=_lowerCAmelCase				)

      return train_dataloader, eval_dataloader


# For testing only
if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1":
 from accelerate.test_utils.training import mocked_dataloaders

 UpperCAmelCase_							: List[Any] =							mocked_dataloaders  # noqa: F811







def 		A_							(						_lowerCAmelCase :     Tuple					,						_lowerCAmelCase :     Optional[int]				):



      """simple docstring"""




      if os.environ.get("TESTING_MOCKED_DATALOADERS"					,						_lowerCAmelCase				) == "1":
            _lowerCamelCase					: Union[str, Any]		    = 2
      # Initialize accelerator
      _lowerCamelCase					: Union[str, Any]		    = Accelerator(cpu=args.cpu					,						mixed_precision=args.mixed_precision				)
      # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
      _lowerCamelCase					: Tuple		    = config["lr"]
      _lowerCamelCase					: int		    = int(config["num_epochs"]				)
      _lowerCamelCase					: Any		    = int(config["seed"]				)
      _lowerCamelCase					: Tuple		    = int(config["batch_size"]				)

      _lowerCamelCase					: Optional[int]		    = evaluate.load("glue"					,						"mrpc"				)

      # If the batch size is too big we use gradient accumulation
      _lowerCamelCase					: Union[str, Any]		    = 1
      if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
            _lowerCamelCase					: List[Any]		    = batch_size // MAX_GPU_BATCH_SIZE
            _lowerCamelCase					: Any		    = MAX_GPU_BATCH_SIZE

      set_seed(_lowerCAmelCase				)
      _lowerCamelCase    ,		_lowerCamelCase					: Optional[int]		    = get_dataloaders(_lowerCAmelCase					,						_lowerCAmelCase				)
      # Instantiate the model (we build the model here so that the seed also control new weights initialization)
      _lowerCamelCase					: Dict		    = AutoModelForSequenceClassification.from_pretrained("bert-base-cased"					,						return_dict=_lowerCAmelCase				)

      # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
      # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
      # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
      _lowerCamelCase					: Tuple		    = model.to(accelerator.device				)

      # Instantiate optimizer
      _lowerCamelCase					: Dict		    = AdamW(params=model.parameters()					,						lr=_lowerCAmelCase				)

      # Instantiate scheduler
      _lowerCamelCase					: Optional[int]		    = get_linear_schedule_with_warmup(
          optimizer=_lowerCAmelCase					,						num_warmup_steps=100					,						num_training_steps=(len(_lowerCAmelCase				) * num_epochs) // gradient_accumulation_steps					,						)

      # Prepare everything
      # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
      # prepare method.
      _lowerCamelCase    ,		_lowerCamelCase    ,		_lowerCamelCase    ,		_lowerCamelCase    ,		_lowerCamelCase					: Optional[int]		    = accelerator.prepare(
          _lowerCAmelCase					,						_lowerCAmelCase					,						_lowerCAmelCase					,						_lowerCAmelCase					,						_lowerCAmelCase				)

      # Now we train the model
      for epoch in range(_lowerCAmelCase				):
            model.train()
            for step, batch in enumerate(_lowerCAmelCase				):
                  # We could avoid this line since we set the accelerator with `device_placement=True`.
                  batch.to(accelerator.device				)
                  _lowerCamelCase					: Any		    = model(**_lowerCAmelCase				)
                  _lowerCamelCase					: Optional[Any]		    = outputs.loss
                  _lowerCamelCase					: List[Any]		    = loss / gradient_accumulation_steps
                  accelerator.backward(_lowerCAmelCase				)
                  if step % gradient_accumulation_steps == 0:
                        optimizer.step()
                        lr_scheduler.step()
                        optimizer.zero_grad()

            model.eval()
            _lowerCamelCase					: Union[str, Any]		    = 0
            for step, batch in enumerate(_lowerCAmelCase				):
                  # We could avoid this line since we set the accelerator with `device_placement=True`.
                  batch.to(accelerator.device				)
                  with torch.no_grad():
                        _lowerCamelCase					: Any		    = model(**_lowerCAmelCase				)
                  _lowerCamelCase					: Dict		    = outputs.logits.argmax(dim=-1				)
                  _lowerCamelCase    ,		_lowerCamelCase					: int		    = accelerator.gather((predictions, batch["labels"])				)
                  # New Code #
                  # First we check if it's a distributed system
                  if accelerator.use_distributed:
                        # Then see if we're on the last batch of our eval dataloader
                        if step == len(_lowerCAmelCase				) - 1:
                              # Last batch needs to be truncated on distributed systems as it contains additional samples
                              _lowerCamelCase					: Any		    = predictions[: len(eval_dataloader.dataset				) - samples_seen]
                              _lowerCamelCase					: Union[str, Any]		    = references[: len(eval_dataloader.dataset				) - samples_seen]
                        else:
                              # Otherwise we add the number of samples seen
                              samples_seen += references.shape[0]
            # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`:
            # accelerator.gather_for_metrics((predictions, batch["labels"]))
                  metric.add_batch(
                      predictions=_lowerCAmelCase					,						references=_lowerCAmelCase					,						)

            _lowerCamelCase					: Optional[int]		    = metric.compute()
            # Use accelerator.print to print only on the main process.
            accelerator.print(F'epoch {epoch}:'					,						_lowerCAmelCase				)







def 		A_							(						):



      """simple docstring"""




      _lowerCamelCase					: Union[str, Any]		    = argparse.ArgumentParser(description="Simple example of training script."				)
      parser.add_argument(
          "--mixed_precision"					,						type=_lowerCAmelCase					,						default=_lowerCAmelCase					,						choices=["no", "fp16", "bf16", "fp8"]					,						help="Whether to use mixed precision. Choose"
          "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
          "and an Nvidia Ampere GPU."					,						)
      parser.add_argument("--cpu"					,						action="store_true"					,						help="If passed, will train on the CPU."				)
      _lowerCamelCase					: str		    = parser.parse_args()
      _lowerCamelCase					: Optional[Any]		    = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
      training_function(_lowerCAmelCase					,						_lowerCAmelCase				)


if __name__ == "__main__":
 main()





import os
import shutil
import sys
import tempfile
import unittest
from pathlib import Path

import pytest

import transformers
from transformers import (
    BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    AutoTokenizer,
    BertConfig,
    BertTokenizer,
    BertTokenizerFast,
    CTRLTokenizer,
    GPTaTokenizer,
    GPTaTokenizerFast,
    PreTrainedTokenizerFast,
    RobertaTokenizer,
    RobertaTokenizerFast,
    is_tokenizers_available,
)
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.auto.tokenization_auto import (
    TOKENIZER_MAPPING,
    get_tokenizer_config,
    tokenizer_class_from_name,
)
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import (
    DUMMY_DIFF_TOKENIZER_IDENTIFIER,
    DUMMY_UNKNOWN_IDENTIFIER,
    SMALL_MODEL_IDENTIFIER,
    RequestCounter,
    require_tokenizers,
    slow,
)


sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils"))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_tokenization import CustomTokenizer  # noqa E402


if is_tokenizers_available():
		from test_module.custom_tokenization_fast import CustomTokenizerFast

class 						__lowerCAmelCase      (      unittest.TestCase					):
							def  lowerCamelCase__				(		self		:Optional[Any]							):







								'''simple docstring'''







								a									=				0
							@slow
							def  lowerCamelCase__				(		self		:Tuple							):







								'''simple docstring'''







								for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x):
									a									=				AutoTokenizer.from_pretrained(__magic_name__							)
									self.assertIsNotNone(__magic_name__							)
									self.assertIsInstance(__magic_name__						, (BertTokenizer, BertTokenizerFast)							)
									self.assertGreater(len(__magic_name__							)						, 0							)

								for model_name in GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP.keys():
									a									=				AutoTokenizer.from_pretrained(__magic_name__							)
									self.assertIsNotNone(__magic_name__							)
									self.assertIsInstance(__magic_name__						, (GPTaTokenizer, GPTaTokenizerFast)							)
									self.assertGreater(len(__magic_name__							)						, 0							)
							def  lowerCamelCase__				(		self		:Union[str, Any]							):







								'''simple docstring'''







								a									=				AutoTokenizer.from_pretrained(__magic_name__							)
								self.assertIsInstance(__magic_name__						, (BertTokenizer, BertTokenizerFast)							)
								self.assertEqual(tokenizer.vocab_size						, 12							)
							def  lowerCamelCase__				(		self		:Dict							):







								'''simple docstring'''







								a									=				AutoTokenizer.from_pretrained(__magic_name__							)
								self.assertIsInstance(__magic_name__						, (RobertaTokenizer, RobertaTokenizerFast)							)
								self.assertEqual(tokenizer.vocab_size						, 20							)
							def  lowerCamelCase__				(		self		:str							):







								'''simple docstring'''







								a									=				AutoConfig.from_pretrained(__magic_name__							)
								self.assertIsInstance(__magic_name__						, __magic_name__							)
								# Check that tokenizer_type ≠ model_type
								a									=				AutoTokenizer.from_pretrained(__magic_name__						, config=__magic_name__							)
								self.assertIsInstance(__magic_name__						, (BertTokenizer, BertTokenizerFast)							)
								self.assertEqual(tokenizer.vocab_size						, 12							)
							def  lowerCamelCase__				(		self		:int							):







								'''simple docstring'''







								with tempfile.TemporaryDirectory() as tmp_dir:
									shutil.copy("""./tests/fixtures/vocab.txt"""						, os.path.join(__magic_name__						, """vocab.txt"""							)							)

									a									=				AutoTokenizer.from_pretrained(__magic_name__						, tokenizer_type="""bert"""						, use_fast=__magic_name__							)
									self.assertIsInstance(__magic_name__						, __magic_name__							)

								with tempfile.TemporaryDirectory() as tmp_dir:
									shutil.copy("""./tests/fixtures/vocab.json"""						, os.path.join(__magic_name__						, """vocab.json"""							)							)
									shutil.copy("""./tests/fixtures/merges.txt"""						, os.path.join(__magic_name__						, """merges.txt"""							)							)

									a									=				AutoTokenizer.from_pretrained(__magic_name__						, tokenizer_type="""gpt2"""						, use_fast=__magic_name__							)
									self.assertIsInstance(__magic_name__						, __magic_name__							)
							@require_tokenizers
							def  lowerCamelCase__				(		self		:List[str]							):







								'''simple docstring'''







								with tempfile.TemporaryDirectory() as tmp_dir:
									shutil.copy("""./tests/fixtures/vocab.txt"""						, os.path.join(__magic_name__						, """vocab.txt"""							)							)

									a									=				AutoTokenizer.from_pretrained(__magic_name__						, tokenizer_type="""bert"""							)
									self.assertIsInstance(__magic_name__						, __magic_name__							)

								with tempfile.TemporaryDirectory() as tmp_dir:
									shutil.copy("""./tests/fixtures/vocab.json"""						, os.path.join(__magic_name__						, """vocab.json"""							)							)
									shutil.copy("""./tests/fixtures/merges.txt"""						, os.path.join(__magic_name__						, """merges.txt"""							)							)

									a									=				AutoTokenizer.from_pretrained(__magic_name__						, tokenizer_type="""gpt2"""							)
									self.assertIsInstance(__magic_name__						, __magic_name__							)
							def  lowerCamelCase__				(		self		:Dict							):







								'''simple docstring'''







								with pytest.raises(__magic_name__							):
									AutoTokenizer.from_pretrained("""./"""						, tokenizer_type="""xxx"""							)
							@require_tokenizers
							def  lowerCamelCase__				(		self		:Tuple							):







								'''simple docstring'''







								for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]:
									a									=				tokenizer_class.from_pretrained("""wietsedv/bert-base-dutch-cased"""							)
									self.assertIsInstance(__magic_name__						, (BertTokenizer, BertTokenizerFast)							)

									if isinstance(__magic_name__						, __magic_name__							):
										self.assertEqual(tokenizer.basic_tokenizer.do_lower_case						, __magic_name__							)
									else:
										self.assertEqual(tokenizer.do_lower_case						, __magic_name__							)

									self.assertEqual(tokenizer.model_max_length						, 512							)
							@require_tokenizers
							def  lowerCamelCase__				(		self		:Union[str, Any]							):







								'''simple docstring'''







								for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]:
									with self.assertRaisesRegex(
									    __magic_name__						, """julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier"""						, ):
										a									=				tokenizer_class.from_pretrained("""julien-c/herlolip-not-exists"""							)
							def  lowerCamelCase__				(		self		:Union[str, Any]							):







								'''simple docstring'''







								a									=				TOKENIZER_MAPPING.values()
								a									=				[]

								for slow_tok, fast_tok in tokenizers:
									if slow_tok is not None:
										tokenizer_names.append(slow_tok.__name__							)

									if fast_tok is not None:
										tokenizer_names.append(fast_tok.__name__							)

								for tokenizer_name in tokenizer_names:
									# must find the right class
									tokenizer_class_from_name(__magic_name__							)
							@require_tokenizers
							def  lowerCamelCase__				(		self		:str							):







								'''simple docstring'''







								self.assertIsInstance(AutoTokenizer.from_pretrained("""bert-base-cased"""						, use_fast=__magic_name__							)						, __magic_name__							)
								self.assertIsInstance(AutoTokenizer.from_pretrained("""bert-base-cased"""							)						, __magic_name__							)
							@require_tokenizers
							def  lowerCamelCase__				(		self		:str							):







								'''simple docstring'''







								a									=				AutoTokenizer.from_pretrained("""distilbert-base-uncased"""						, do_lower_case=__magic_name__							)
								a									=				"""Hello, world. How are you?"""
								a									=				tokenizer.tokenize(__magic_name__							)
								self.assertEqual("""[UNK]"""						, tokens[0]							)

								a									=				AutoTokenizer.from_pretrained("""microsoft/mpnet-base"""						, do_lower_case=__magic_name__							)
								a									=				tokenizer.tokenize(__magic_name__							)
								self.assertEqual("""[UNK]"""						, tokens[0]							)
							@require_tokenizers
							def  lowerCamelCase__				(		self		:int							):







								'''simple docstring'''







								a									=				AutoTokenizer.from_pretrained("""robot-test/dummy-tokenizer-fast-with-model-config"""							)
								self.assertEqual(type(__magic_name__							)						, __magic_name__							)
								self.assertEqual(tokenizer.model_max_length						, 512							)
								self.assertEqual(tokenizer.vocab_size						, 3_0000							)
								self.assertEqual(tokenizer.unk_token						, """[UNK]"""							)
								self.assertEqual(tokenizer.padding_side						, """right"""							)
								self.assertEqual(tokenizer.truncation_side						, """right"""							)
							def  lowerCamelCase__				(		self		:int							):







								'''simple docstring'''







								a									=				AutoTokenizer.from_pretrained(__magic_name__							)
								self.assertIsInstance(__magic_name__						, (BertTokenizer, BertTokenizerFast)							)
								with tempfile.TemporaryDirectory() as tmp_dir:
									tokenizer.save_pretrained(__magic_name__							)
									a									=				AutoTokenizer.from_pretrained(__magic_name__							)

								self.assertIsInstance(__magic_name__						, tokenizer.__class__							)
								self.assertEqual(tokenizera.vocab_size						, 12							)
							def  lowerCamelCase__				(		self		:Union[str, Any]							):







								'''simple docstring'''







								a									=				AutoTokenizer.from_pretrained("""ctrl"""							)
								# There is no fast CTRL so this always gives us a slow tokenizer.
								self.assertIsInstance(__magic_name__						, __magic_name__							)
							def  lowerCamelCase__				(		self		:str							):







								'''simple docstring'''







								a									=				get_tokenizer_config("""bert-base-cased"""							)
								a									=				config.pop("""_commit_hash"""						, __magic_name__							)
								# If we ever update bert-base-cased tokenizer config, this dict here will need to be updated.
								self.assertEqual(__magic_name__						, {"""do_lower_case""": False}							)

								# This model does not have a tokenizer_config so we get back an empty dict.
								a									=				get_tokenizer_config(__magic_name__							)
								self.assertDictEqual(__magic_name__						, {}							)

								# A tokenizer saved with `save_pretrained` always creates a tokenizer config.
								a									=				AutoTokenizer.from_pretrained(__magic_name__							)
								with tempfile.TemporaryDirectory() as tmp_dir:
									tokenizer.save_pretrained(__magic_name__							)
									a									=				get_tokenizer_config(__magic_name__							)

								# Check the class of the tokenizer was properly saved (note that it always saves the slow class).
								self.assertEqual(config["""tokenizer_class"""]						, """BertTokenizer"""							)
							def  lowerCamelCase__				(		self		:Union[str, Any]							):







								'''simple docstring'''







								try:
									AutoConfig.register("""custom"""						, __magic_name__							)

									AutoTokenizer.register(__magic_name__						, slow_tokenizer_class=__magic_name__							)
									# Trying to register something existing in the Transformers library will raise an error
									with self.assertRaises(__magic_name__							):
										AutoTokenizer.register(__magic_name__						, slow_tokenizer_class=__magic_name__							)

									a									=				CustomTokenizer.from_pretrained(__magic_name__							)
									with tempfile.TemporaryDirectory() as tmp_dir:
										tokenizer.save_pretrained(__magic_name__							)

										a									=				AutoTokenizer.from_pretrained(__magic_name__							)
										self.assertIsInstance(__magic_name__						, __magic_name__							)

								finally:
									if "custom" in CONFIG_MAPPING._extra_content:
										del CONFIG_MAPPING._extra_content["custom"]
									if CustomConfig in TOKENIZER_MAPPING._extra_content:
										del TOKENIZER_MAPPING._extra_content[CustomConfig]
							@require_tokenizers
							def  lowerCamelCase__				(		self		:Tuple							):







								'''simple docstring'''







								try:
									AutoConfig.register("""custom"""						, __magic_name__							)

									# Can register in two steps
									AutoTokenizer.register(__magic_name__						, slow_tokenizer_class=__magic_name__							)
									self.assertEqual(TOKENIZER_MAPPING[CustomConfig]						, (CustomTokenizer, None)							)
									AutoTokenizer.register(__magic_name__						, fast_tokenizer_class=__magic_name__							)
									self.assertEqual(TOKENIZER_MAPPING[CustomConfig]						, (CustomTokenizer, CustomTokenizerFast)							)

									del TOKENIZER_MAPPING._extra_content[CustomConfig]
									# Can register in one step
									AutoTokenizer.register(
									    __magic_name__						, slow_tokenizer_class=__magic_name__						, fast_tokenizer_class=__magic_name__							)
									self.assertEqual(TOKENIZER_MAPPING[CustomConfig]						, (CustomTokenizer, CustomTokenizerFast)							)

									# Trying to register something existing in the Transformers library will raise an error
									with self.assertRaises(__magic_name__							):
										AutoTokenizer.register(__magic_name__						, fast_tokenizer_class=__magic_name__							)

									# We pass through a bert tokenizer fast cause there is no converter slow to fast for our new toknizer
									# and that model does not have a tokenizer.json
									with tempfile.TemporaryDirectory() as tmp_dir:
										a									=				BertTokenizerFast.from_pretrained(__magic_name__							)
										bert_tokenizer.save_pretrained(__magic_name__							)
										a									=				CustomTokenizerFast.from_pretrained(__magic_name__							)

									with tempfile.TemporaryDirectory() as tmp_dir:
										tokenizer.save_pretrained(__magic_name__							)

										a									=				AutoTokenizer.from_pretrained(__magic_name__							)
										self.assertIsInstance(__magic_name__						, __magic_name__							)

										a									=				AutoTokenizer.from_pretrained(__magic_name__						, use_fast=__magic_name__							)
										self.assertIsInstance(__magic_name__						, __magic_name__							)

								finally:
									if "custom" in CONFIG_MAPPING._extra_content:
										del CONFIG_MAPPING._extra_content["custom"]
									if CustomConfig in TOKENIZER_MAPPING._extra_content:
										del TOKENIZER_MAPPING._extra_content[CustomConfig]
							def  lowerCamelCase__				(		self		:int							):







								'''simple docstring'''







								with self.assertRaises(__magic_name__							):
									a									=				AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer"""							)
								# If remote code is disabled, we can't load this config.
								with self.assertRaises(__magic_name__							):
									a									=				AutoTokenizer.from_pretrained(
									    """hf-internal-testing/test_dynamic_tokenizer"""						, trust_remote_code=__magic_name__							)

								a									=				AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer"""						, trust_remote_code=__magic_name__							)
								self.assertTrue(tokenizer.special_attribute_present							)
								# Test tokenizer can be reloaded.
								with tempfile.TemporaryDirectory() as tmp_dir:
									tokenizer.save_pretrained(__magic_name__							)
									a									=				AutoTokenizer.from_pretrained(__magic_name__						, trust_remote_code=__magic_name__							)
								self.assertTrue(reloaded_tokenizer.special_attribute_present							)

								if is_tokenizers_available():
									self.assertEqual(tokenizer.__class__.__name__						, """NewTokenizerFast"""							)
									self.assertEqual(reloaded_tokenizer.__class__.__name__						, """NewTokenizerFast"""							)

									# Test we can also load the slow version
									a									=				AutoTokenizer.from_pretrained(
									    """hf-internal-testing/test_dynamic_tokenizer"""						, trust_remote_code=__magic_name__						, use_fast=__magic_name__							)
									self.assertTrue(tokenizer.special_attribute_present							)
									self.assertEqual(tokenizer.__class__.__name__						, """NewTokenizer"""							)
									# Test tokenizer can be reloaded.
									with tempfile.TemporaryDirectory() as tmp_dir:
										tokenizer.save_pretrained(__magic_name__							)
										a									=				AutoTokenizer.from_pretrained(__magic_name__						, trust_remote_code=__magic_name__						, use_fast=__magic_name__							)
									self.assertEqual(reloaded_tokenizer.__class__.__name__						, """NewTokenizer"""							)
									self.assertTrue(reloaded_tokenizer.special_attribute_present							)
								else:
									self.assertEqual(tokenizer.__class__.__name__						, """NewTokenizer"""							)
									self.assertEqual(reloaded_tokenizer.__class__.__name__						, """NewTokenizer"""							)
							@require_tokenizers
							def  lowerCamelCase__				(		self		:str							):







								'''simple docstring'''







								class 						__lowerCAmelCase      (      __magic_name__					):
															UpperCamelCase__   	=    False







								class 						__lowerCAmelCase      (      __magic_name__					):
															UpperCamelCase__   	=    NewTokenizer
															UpperCamelCase__   	=    False

								try:
									AutoConfig.register("""custom"""						, __magic_name__							)
									AutoTokenizer.register(__magic_name__						, slow_tokenizer_class=__magic_name__							)
									AutoTokenizer.register(__magic_name__						, fast_tokenizer_class=__magic_name__							)
									# If remote code is not set, the default is to use local
									a									=				AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer"""							)
									self.assertEqual(tokenizer.__class__.__name__						, """NewTokenizerFast"""							)
									self.assertFalse(tokenizer.special_attribute_present							)
									a									=				AutoTokenizer.from_pretrained("""hf-internal-testing/test_dynamic_tokenizer"""						, use_fast=__magic_name__							)
									self.assertEqual(tokenizer.__class__.__name__						, """NewTokenizer"""							)
									self.assertFalse(tokenizer.special_attribute_present							)

									# If remote code is disabled, we load the local one.
									a									=				AutoTokenizer.from_pretrained(
									    """hf-internal-testing/test_dynamic_tokenizer"""						, trust_remote_code=__magic_name__							)
									self.assertEqual(tokenizer.__class__.__name__						, """NewTokenizerFast"""							)
									self.assertFalse(tokenizer.special_attribute_present							)
									a									=				AutoTokenizer.from_pretrained(
									    """hf-internal-testing/test_dynamic_tokenizer"""						, trust_remote_code=__magic_name__						, use_fast=__magic_name__							)
									self.assertEqual(tokenizer.__class__.__name__						, """NewTokenizer"""							)
									self.assertFalse(tokenizer.special_attribute_present							)

									# If remote is enabled, we load from the Hub
									a									=				AutoTokenizer.from_pretrained(
									    """hf-internal-testing/test_dynamic_tokenizer"""						, trust_remote_code=__magic_name__							)
									self.assertEqual(tokenizer.__class__.__name__						, """NewTokenizerFast"""							)
									self.assertTrue(tokenizer.special_attribute_present							)
									a									=				AutoTokenizer.from_pretrained(
									    """hf-internal-testing/test_dynamic_tokenizer"""						, trust_remote_code=__magic_name__						, use_fast=__magic_name__							)
									self.assertEqual(tokenizer.__class__.__name__						, """NewTokenizer"""							)
									self.assertTrue(tokenizer.special_attribute_present							)

								finally:
									if "custom" in CONFIG_MAPPING._extra_content:
										del CONFIG_MAPPING._extra_content["custom"]
									if CustomConfig in TOKENIZER_MAPPING._extra_content:
										del TOKENIZER_MAPPING._extra_content[CustomConfig]
							def  lowerCamelCase__				(		self		:Any							):







								'''simple docstring'''







								a									=				AutoTokenizer.from_pretrained(
								    """hf-internal-testing/test_dynamic_tokenizer_legacy"""						, trust_remote_code=__magic_name__							)
								self.assertTrue(tokenizer.special_attribute_present							)
								if is_tokenizers_available():
									self.assertEqual(tokenizer.__class__.__name__						, """NewTokenizerFast"""							)

									# Test we can also load the slow version
									a									=				AutoTokenizer.from_pretrained(
									    """hf-internal-testing/test_dynamic_tokenizer_legacy"""						, trust_remote_code=__magic_name__						, use_fast=__magic_name__							)
									self.assertTrue(tokenizer.special_attribute_present							)
									self.assertEqual(tokenizer.__class__.__name__						, """NewTokenizer"""							)
								else:
									self.assertEqual(tokenizer.__class__.__name__						, """NewTokenizer"""							)
							def  lowerCamelCase__				(		self		:Union[str, Any]							):







								'''simple docstring'''







								with self.assertRaisesRegex(
								    __magic_name__						, """bert-base is not a local folder and is not a valid model identifier"""							):
									a									=				AutoTokenizer.from_pretrained("""bert-base"""							)
							def  lowerCamelCase__				(		self		:List[str]							):







								'''simple docstring'''







								with self.assertRaisesRegex(
								    __magic_name__						, r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""							):
									a									=				AutoTokenizer.from_pretrained(__magic_name__						, revision="""aaaaaa"""							)





							def  lowerCamelCase__				(		self		:str							):







								'''simple docstring'''







								a									=				AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert"""							)
								with RequestCounter() as counter:
									a									=				AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert"""							)
									self.assertEqual(counter.get_request_count						, 0							)
									self.assertEqual(counter.head_request_count						, 1							)
									self.assertEqual(counter.other_request_count						, 0							)

