




import inspect
import logging
import os
import random
import shutil
import tempfile
import unittest

import pytest
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

from accelerate import Accelerator
from accelerate.test_utils import execute_subprocess_async, require_cuda
from accelerate.utils import ProjectConfiguration, set_seed


__a							     =					logging.getLogger(__name__)







def lowerCamelCase__  (     _lowercase=2					,		_lowercase=3					,		_lowercase=16					,		_lowercase = 10					,		_lowercase = 2 ):

     '''simple docstring'''


     def get_dataset(_lowercase ):
          UpperCAmelCase_     :				Optional[int]  =     torch.randn(batch_size * n_batches					,		1 )
          return TensorDataset(_lowercase					,		a * x + b + 0.1 * torch.randn(batch_size * n_batches					,		1 ) )

     UpperCAmelCase_     :				Tuple  =     get_dataset(_lowercase )
     UpperCAmelCase_     :				List[Any]  =     get_dataset(_lowercase )
     UpperCAmelCase_     :				Optional[int]  =     DataLoader(_lowercase					,		shuffle=_lowercase					,		batch_size=_lowercase					,		num_workers=4 )
     UpperCAmelCase_     :				int  =     DataLoader(_lowercase					,		shuffle=_lowercase					,		batch_size=_lowercase					,		num_workers=4 )
     return (train_dataloader, valid_dataloader)







def lowerCamelCase__  (     _lowercase					,		_lowercase					,		_lowercase					,		_lowercase					,		_lowercase					,		_lowercase=None ):

     '''simple docstring'''


     UpperCAmelCase_     :				List[Any]  =     []
     for epoch in range(_lowercase ):
          # Train quickly
          model.train()
          for batch in dataloader:
               UpperCAmelCase_,       UpperCAmelCase_     :				int  =     batch
               UpperCAmelCase_     :				List[Any]  =     model(_lowercase )
               UpperCAmelCase_     :				Dict  =     torch.nn.functional.mse_loss(_lowercase					,		_lowercase )
               accelerator.backward(_lowercase )
               optimizer.step()
               optimizer.zero_grad()
          rands.append(random.random() )  # Introduce some randomness
          if scheduler is not None:
               scheduler.step()
     return rands

class     __a(	nn.Module  ):






    """simple docstring"""





    def __init__( self    )					->						Dict:
         super().__init__()
         UpperCAmelCase_     :				List[str]  =     nn.Parameter(torch.randn(1    )    )
         UpperCAmelCase_     :				int  =     nn.Parameter(torch.randn(1    )    )





    def 				a__ ( self  ,_SCREAMING_SNAKE_CASE    )					->						Optional[int]:
         return x * self.a + self.b


class     __a(	unittest.TestCase  ):






    """simple docstring"""





    def 				a__ ( self    )					->						Optional[int]:
         with tempfile.TemporaryDirectory() as tmpdir:
              set_seed(42    )
              UpperCAmelCase_     :				Tuple  =     DummyModel()
              UpperCAmelCase_     :				str  =     torch.optim.Adam(params=model.parameters()  ,lr=1e-3    )
              UpperCAmelCase_,       UpperCAmelCase_     :				str  =     dummy_dataloaders()
              UpperCAmelCase_     :				Any  =     ProjectConfiguration(total_limit=1  ,project_dir=_SCREAMING_SNAKE_CASE  ,automatic_checkpoint_naming=_SCREAMING_SNAKE_CASE    )
              # Train baseline
              UpperCAmelCase_     :				str  =     Accelerator(project_config=_SCREAMING_SNAKE_CASE    )
              UpperCAmelCase_,       UpperCAmelCase_,       UpperCAmelCase_,       UpperCAmelCase_     :				int  =     accelerator.prepare(
                  _SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              # Save initial
              accelerator.save_state()

              # Save second state
              accelerator.save_state()
              self.assertEqual(len(os.listdir(accelerator.project_dir    )    )  ,1    )





    def 				a__ ( self    )					->						Any:
         with tempfile.TemporaryDirectory() as tmpdir:
              set_seed(42    )
              UpperCAmelCase_     :				Optional[int]  =     DummyModel()
              UpperCAmelCase_     :				Union[str, Any]  =     torch.optim.Adam(params=model.parameters()  ,lr=1e-3    )
              UpperCAmelCase_,       UpperCAmelCase_     :				Optional[Any]  =     dummy_dataloaders()
              # Train baseline
              UpperCAmelCase_     :				Union[str, Any]  =     Accelerator()
              UpperCAmelCase_,       UpperCAmelCase_,       UpperCAmelCase_,       UpperCAmelCase_     :				int  =     accelerator.prepare(
                  _SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              # Save initial
              UpperCAmelCase_     :				Union[str, Any]  =     os.path.join(_SCREAMING_SNAKE_CASE  ,'''initial'''    )
              accelerator.save_state(_SCREAMING_SNAKE_CASE    )
              ((UpperCAmelCase_),       (UpperCAmelCase_))     :				Optional[Any]  =     model.a.item(), model.b.item()
              UpperCAmelCase_     :				List[Any]  =     optimizer.state_dict()
              UpperCAmelCase_     :				Optional[Any]  =     train(3  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              ((UpperCAmelCase_),       (UpperCAmelCase_))     :				int  =     model.a.item(), model.b.item()
              UpperCAmelCase_     :				Tuple  =     optimizer.state_dict()

              # Train partially
              set_seed(42    )
              UpperCAmelCase_     :				Tuple  =     DummyModel()
              UpperCAmelCase_     :				Dict  =     torch.optim.Adam(params=model.parameters()  ,lr=1e-3    )
              UpperCAmelCase_,       UpperCAmelCase_     :				List[Any]  =     dummy_dataloaders()
              UpperCAmelCase_     :				List[str]  =     Accelerator()
              UpperCAmelCase_,       UpperCAmelCase_,       UpperCAmelCase_,       UpperCAmelCase_     :				Union[str, Any]  =     accelerator.prepare(
                  _SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              accelerator.load_state(_SCREAMING_SNAKE_CASE    )
              ((UpperCAmelCase_),       (UpperCAmelCase_))     :				Union[str, Any]  =     model.a.item(), model.b.item()
              UpperCAmelCase_     :				Any  =     optimizer.state_dict()
              self.assertEqual(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              self.assertEqual(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              self.assertEqual(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )

              UpperCAmelCase_     :				str  =     train(2  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              # Save everything
              UpperCAmelCase_     :				Union[str, Any]  =     os.path.join(_SCREAMING_SNAKE_CASE  ,'''checkpoint'''    )
              accelerator.save_state(_SCREAMING_SNAKE_CASE    )

              # Load everything back in and make sure all states work
              accelerator.load_state(_SCREAMING_SNAKE_CASE    )
              test_rands += train(1  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              ((UpperCAmelCase_),       (UpperCAmelCase_))     :				Union[str, Any]  =     model.a.item(), model.b.item()
              UpperCAmelCase_     :				Any  =     optimizer.state_dict()
              self.assertEqual(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              self.assertEqual(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              self.assertEqual(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              self.assertEqual(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )





    def 				a__ ( self    )					->						Optional[int]:
         with tempfile.TemporaryDirectory() as tmpdir:
              set_seed(42    )
              UpperCAmelCase_     :				str  =     DummyModel()
              UpperCAmelCase_     :				List[str]  =     torch.optim.Adam(params=model.parameters()  ,lr=1e-3    )
              UpperCAmelCase_,       UpperCAmelCase_     :				int  =     dummy_dataloaders()
              UpperCAmelCase_     :				Union[str, Any]  =     ProjectConfiguration(automatic_checkpoint_naming=_SCREAMING_SNAKE_CASE    )

              # Train baseline
              UpperCAmelCase_     :				Optional[int]  =     Accelerator(project_dir=_SCREAMING_SNAKE_CASE  ,project_config=_SCREAMING_SNAKE_CASE    )
              UpperCAmelCase_,       UpperCAmelCase_,       UpperCAmelCase_,       UpperCAmelCase_     :				str  =     accelerator.prepare(
                  _SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              # Save initial
              accelerator.save_state()
              ((UpperCAmelCase_),       (UpperCAmelCase_))     :				int  =     model.a.item(), model.b.item()
              UpperCAmelCase_     :				List[Any]  =     optimizer.state_dict()
              UpperCAmelCase_     :				int  =     train(3  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              ((UpperCAmelCase_),       (UpperCAmelCase_))     :				Optional[int]  =     model.a.item(), model.b.item()
              UpperCAmelCase_     :				List[str]  =     optimizer.state_dict()

              # Train partially
              set_seed(42    )
              UpperCAmelCase_     :				Optional[int]  =     DummyModel()
              UpperCAmelCase_     :				str  =     torch.optim.Adam(params=model.parameters()  ,lr=1e-3    )
              UpperCAmelCase_,       UpperCAmelCase_     :				Optional[Any]  =     dummy_dataloaders()
              UpperCAmelCase_     :				List[str]  =     ProjectConfiguration(iteration=1  ,automatic_checkpoint_naming=_SCREAMING_SNAKE_CASE    )
              UpperCAmelCase_     :				str  =     Accelerator(project_dir=_SCREAMING_SNAKE_CASE  ,project_config=_SCREAMING_SNAKE_CASE    )
              UpperCAmelCase_,       UpperCAmelCase_,       UpperCAmelCase_,       UpperCAmelCase_     :				Union[str, Any]  =     accelerator.prepare(
                  _SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              accelerator.load_state(os.path.join(_SCREAMING_SNAKE_CASE  ,'''checkpoints'''  ,'''checkpoint_0'''    )    )
              ((UpperCAmelCase_),       (UpperCAmelCase_))     :				Dict  =     model.a.item(), model.b.item()
              UpperCAmelCase_     :				List[Any]  =     optimizer.state_dict()
              self.assertEqual(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              self.assertEqual(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              self.assertEqual(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )

              UpperCAmelCase_     :				Dict  =     train(2  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              # Save everything
              accelerator.save_state()

              # Load everything back in and make sure all states work
              accelerator.load_state(os.path.join(_SCREAMING_SNAKE_CASE  ,'''checkpoints'''  ,'''checkpoint_1'''    )    )
              test_rands += train(1  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              ((UpperCAmelCase_),       (UpperCAmelCase_))     :				Optional[int]  =     model.a.item(), model.b.item()
              UpperCAmelCase_     :				str  =     optimizer.state_dict()
              self.assertEqual(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              self.assertEqual(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              self.assertEqual(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              self.assertEqual(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )





    def 				a__ ( self    )					->						Optional[int]:
         UpperCAmelCase_     :				str  =     torch.tensor([1, 2, 3]    )
         UpperCAmelCase_     :				Any  =     torch.tensor([2, 3, 4]    )
         UpperCAmelCase_     :				int  =     DummyModel()
         UpperCAmelCase_     :				Tuple  =     torch.optim.Adam(net.parameters()    )
         UpperCAmelCase_     :				Optional[int]  =     Accelerator()
         with self.assertRaises(_SCREAMING_SNAKE_CASE    ) as ve:
              accelerator.register_for_checkpointing(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
         UpperCAmelCase_     :				Optional[int]  =     str(ve.exception    )
         self.assertTrue('''Item at index 0''' in message    )
         self.assertTrue('''Item at index 1''' in message    )
         self.assertFalse('''Item at index 2''' in message    )
         self.assertFalse('''Item at index 3''' in message    )





    def 				a__ ( self    )					->						List[Any]:
         with tempfile.TemporaryDirectory() as tmpdir:
              set_seed(42    )
              UpperCAmelCase_     :				Any  =     DummyModel()
              UpperCAmelCase_     :				Any  =     torch.optim.Adam(params=model.parameters()  ,lr=1e-3    )
              UpperCAmelCase_     :				Union[str, Any]  =     torch.optim.lr_scheduler.StepLR(_SCREAMING_SNAKE_CASE  ,step_size=1  ,gamma=0.99    )
              UpperCAmelCase_,       UpperCAmelCase_     :				Tuple  =     dummy_dataloaders()
              UpperCAmelCase_     :				str  =     ProjectConfiguration(automatic_checkpoint_naming=_SCREAMING_SNAKE_CASE    )
              # Train baseline
              UpperCAmelCase_     :				List[str]  =     Accelerator(project_dir=_SCREAMING_SNAKE_CASE  ,project_config=_SCREAMING_SNAKE_CASE    )
              UpperCAmelCase_,       UpperCAmelCase_,       UpperCAmelCase_,       UpperCAmelCase_,       UpperCAmelCase_     :				List[Any]  =     accelerator.prepare(
                  _SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              # Save initial
              accelerator.save_state()
              UpperCAmelCase_     :				int  =     scheduler.state_dict()
              train(3  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
              self.assertNotEqual(_SCREAMING_SNAKE_CASE  ,scheduler.state_dict()    )

              # Load everything back in and make sure all states work
              accelerator.load_state(os.path.join(_SCREAMING_SNAKE_CASE  ,'''checkpoints'''  ,'''checkpoint_0'''    )    )
              self.assertEqual(_SCREAMING_SNAKE_CASE  ,scheduler.state_dict()    )





    def 				a__ ( self    )					->						str:
         with tempfile.TemporaryDirectory() as tmpdir:
              set_seed(42    )
              UpperCAmelCase_     :				List[str]  =     DummyModel()
              UpperCAmelCase_     :				Dict  =     ProjectConfiguration(automatic_checkpoint_naming=_SCREAMING_SNAKE_CASE  ,total_limit=2    )
              # Train baseline
              UpperCAmelCase_     :				Tuple  =     Accelerator(project_dir=_SCREAMING_SNAKE_CASE  ,project_config=_SCREAMING_SNAKE_CASE    )
              UpperCAmelCase_     :				Union[str, Any]  =     accelerator.prepare(_SCREAMING_SNAKE_CASE    )
              # Save 3 states:
              for _ in range(11    ):
                   accelerator.save_state()
              self.assertTrue(not os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE  ,'''checkpoints'''  ,'''checkpoint_0'''    )    )    )
              self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE  ,'''checkpoints'''  ,'''checkpoint_9'''    )    )    )
              self.assertTrue(os.path.exists(os.path.join(_SCREAMING_SNAKE_CASE  ,'''checkpoints'''  ,'''checkpoint_10'''    )    )    )





    @require_cuda
    def 				a__ ( self    )					->						Optional[Any]:
         UpperCAmelCase_     :				List[Any]  =     ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__    )]
         execute_subprocess_async(_SCREAMING_SNAKE_CASE  ,env=os.environ.copy()    )


if __name__ == "__main__":
     __a							     =					'/tmp/accelerate/state_checkpointing'
     __a							     =					DummyModel()
     __a							     =					torch.optim.Adam(params=model.parameters(), lr=1E-3)
     __a							     =					torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
     __a     ,__a							     =					dummy_dataloaders()
     __a							     =					ProjectConfiguration(automatic_checkpoint_naming=True)
     # Train baseline
     __a							     =					Accelerator(project_dir=savedir, project_config=project_config, mixed_precision='no')
     if accelerator.process_index == 0:
          if os.path.exists(savedir):
               shutil.rmtree(savedir)
          os.makedirs(savedir)
     __a     ,__a     ,__a     ,__a     ,__a							     =					accelerator.prepare(
         model, optimizer, train_dataloader, valid_dataloader, scheduler
     )
     __a     ,__a							     =					accelerator.prepare(model, optimizer)
     train(3, model, train_dataloader, optimizer, accelerator, scheduler)
     # Check that the intial optimizer is loaded on the GPU
     for group in optimizer.param_groups:
          __a							     =					group['params'][0].device
          break
     assert param_device.type == accelerator.device.type
     __a							     =					model.cpu()
     accelerator.wait_for_everyone()
     accelerator.save_state()
     accelerator.wait_for_everyone()

     # Check CPU state
     accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='cpu')
     for group in optimizer.param_groups:
          __a							     =					group['params'][0].device
          break
     assert (
         param_device.type == torch.device('cpu').type
     ), F"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}"

     # Check device state
     model.to(accelerator.device)
     accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='on_device')
     for group in optimizer.param_groups:
          __a							     =					group['params'][0].device
          break
     assert (
         param_device.type == accelerator.device.type
     ), F"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}"

     # Check error
     with pytest.raises(TypeError, match='Unsupported optimizer map location passed'):
          accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='invalid')
     accelerator.wait_for_everyone()
     if accelerator.process_index == 0:
          shutil.rmtree(savedir)
     accelerator.wait_for_everyone()





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     __a(	unittest.TestCase  ):






    """simple docstring"""





    def 				a__ ( self    )					->						Union[str, Any]:
         UpperCAmelCase_     :				Tuple  =     0





    @slow
    def 				a__ ( self    )					->						Any:
         for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x):
              UpperCAmelCase_     :				Optional[Any]  =     AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE    )
              self.assertIsNotNone(_SCREAMING_SNAKE_CASE    )
              self.assertIsInstance(_SCREAMING_SNAKE_CASE  ,(BertTokenizer, BertTokenizerFast)    )
              self.assertGreater(len(_SCREAMING_SNAKE_CASE    )  ,0    )

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





    def 				a__ ( self    )					->						Optional[Any]:
         UpperCAmelCase_     :				List[str]  =     AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE    )
         self.assertIsInstance(_SCREAMING_SNAKE_CASE  ,(BertTokenizer, BertTokenizerFast)    )
         self.assertEqual(tokenizer.vocab_size  ,12    )





    def 				a__ ( self    )					->						Tuple:
         UpperCAmelCase_     :				Any  =     AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE    )
         self.assertIsInstance(_SCREAMING_SNAKE_CASE  ,(RobertaTokenizer, RobertaTokenizerFast)    )
         self.assertEqual(tokenizer.vocab_size  ,20    )





    def 				a__ ( self    )					->						List[str]:
         UpperCAmelCase_     :				int  =     AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE    )
         self.assertIsInstance(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )
         # Check that tokenizer_type ≠ model_type
         UpperCAmelCase_     :				Optional[int]  =     AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE  ,config=_SCREAMING_SNAKE_CASE    )
         self.assertIsInstance(_SCREAMING_SNAKE_CASE  ,(BertTokenizer, BertTokenizerFast)    )
         self.assertEqual(tokenizer.vocab_size  ,12    )





    def 				a__ ( self    )					->						Dict:
         with tempfile.TemporaryDirectory() as tmp_dir:
              shutil.copy('''./tests/fixtures/vocab.txt'''  ,os.path.join(_SCREAMING_SNAKE_CASE  ,'''vocab.txt'''    )    )

              UpperCAmelCase_     :				Optional[int]  =     AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE  ,tokenizer_type='''bert'''  ,use_fast=_SCREAMING_SNAKE_CASE    )
              self.assertIsInstance(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )

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

              UpperCAmelCase_     :				Optional[Any]  =     AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE  ,tokenizer_type='''gpt2'''  ,use_fast=_SCREAMING_SNAKE_CASE    )
              self.assertIsInstance(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )





    @require_tokenizers
    def 				a__ ( self    )					->						Optional[int]:
         with tempfile.TemporaryDirectory() as tmp_dir:
              shutil.copy('''./tests/fixtures/vocab.txt'''  ,os.path.join(_SCREAMING_SNAKE_CASE  ,'''vocab.txt'''    )    )

              UpperCAmelCase_     :				Tuple  =     AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE  ,tokenizer_type='''bert'''    )
              self.assertIsInstance(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )

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

              UpperCAmelCase_     :				Union[str, Any]  =     AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE  ,tokenizer_type='''gpt2'''    )
              self.assertIsInstance(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )





    def 				a__ ( self    )					->						int:
         with pytest.raises(_SCREAMING_SNAKE_CASE    ):
              AutoTokenizer.from_pretrained('''./'''  ,tokenizer_type='''xxx'''    )





    @require_tokenizers
    def 				a__ ( self    )					->						Optional[Any]:
         for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]:
              UpperCAmelCase_     :				Any  =     tokenizer_class.from_pretrained('''wietsedv/bert-base-dutch-cased'''    )
              self.assertIsInstance(_SCREAMING_SNAKE_CASE  ,(BertTokenizer, BertTokenizerFast)    )

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

              self.assertEqual(tokenizer.model_max_length  ,512    )





    @require_tokenizers
    def 				a__ ( self    )					->						List[Any]:
         for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]:
              with self.assertRaisesRegex(
                  _SCREAMING_SNAKE_CASE  ,'''julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier'''  ,):
                   UpperCAmelCase_     :				int  =     tokenizer_class.from_pretrained('''julien-c/herlolip-not-exists'''    )





    def 				a__ ( self    )					->						Optional[Any]:
         # tests: https://github.com/huggingface/transformers/pull/13251
         # 1. models with `-`, e.g. xlm-roberta -> xlm_roberta
         # 2. models that don't remap 1-1 from model-name to model file, e.g., openai-gpt -> openai
         UpperCAmelCase_     :				int  =     TOKENIZER_MAPPING.values()
         UpperCAmelCase_     :				List[Any]  =     []

         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(_SCREAMING_SNAKE_CASE    )





    @require_tokenizers
    def 				a__ ( self    )					->						Tuple:
         self.assertIsInstance(AutoTokenizer.from_pretrained('''bert-base-cased'''  ,use_fast=_SCREAMING_SNAKE_CASE    )  ,_SCREAMING_SNAKE_CASE    )
         self.assertIsInstance(AutoTokenizer.from_pretrained('''bert-base-cased'''    )  ,_SCREAMING_SNAKE_CASE    )





    @require_tokenizers
    def 				a__ ( self    )					->						Optional[int]:
         UpperCAmelCase_     :				str  =     AutoTokenizer.from_pretrained('''distilbert-base-uncased'''  ,do_lower_case=_SCREAMING_SNAKE_CASE    )
         UpperCAmelCase_     :				int  =     '''Hello, world. How are you?'''
         UpperCAmelCase_     :				List[Any]  =     tokenizer.tokenize(_SCREAMING_SNAKE_CASE    )
         self.assertEqual('''[UNK]'''  ,tokens[0]    )

         UpperCAmelCase_     :				Any  =     AutoTokenizer.from_pretrained('''microsoft/mpnet-base'''  ,do_lower_case=_SCREAMING_SNAKE_CASE    )
         UpperCAmelCase_     :				Tuple  =     tokenizer.tokenize(_SCREAMING_SNAKE_CASE    )
         self.assertEqual('''[UNK]'''  ,tokens[0]    )





    @require_tokenizers
    def 				a__ ( self    )					->						Dict:
         UpperCAmelCase_     :				List[Any]  =     AutoTokenizer.from_pretrained('''robot-test/dummy-tokenizer-fast-with-model-config'''    )
         self.assertEqual(type(_SCREAMING_SNAKE_CASE    )  ,_SCREAMING_SNAKE_CASE    )
         self.assertEqual(tokenizer.model_max_length  ,512    )
         self.assertEqual(tokenizer.vocab_size  ,30_000    )
         self.assertEqual(tokenizer.unk_token  ,'''[UNK]'''    )
         self.assertEqual(tokenizer.padding_side  ,'''right'''    )
         self.assertEqual(tokenizer.truncation_side  ,'''right'''    )





    def 				a__ ( self    )					->						Dict:
         UpperCAmelCase_     :				Any  =     AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE    )
         self.assertIsInstance(_SCREAMING_SNAKE_CASE  ,(BertTokenizer, BertTokenizerFast)    )
         with tempfile.TemporaryDirectory() as tmp_dir:
              tokenizer.save_pretrained(_SCREAMING_SNAKE_CASE    )
              UpperCAmelCase_     :				Dict  =     AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE    )

         self.assertIsInstance(_SCREAMING_SNAKE_CASE  ,tokenizer.__class__    )
         self.assertEqual(tokenizera.vocab_size  ,12    )





    def 				a__ ( self    )					->						Optional[Any]:
         UpperCAmelCase_     :				Tuple  =     AutoTokenizer.from_pretrained('''ctrl'''    )
         # There is no fast CTRL so this always gives us a slow tokenizer.
         self.assertIsInstance(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )





    def 				a__ ( self    )					->						str:
         # Check we can load the tokenizer config of an online model.
         UpperCAmelCase_     :				int  =     get_tokenizer_config('''bert-base-cased'''    )
         UpperCAmelCase_     :				Optional[int]  =     config.pop('''_commit_hash'''  ,_SCREAMING_SNAKE_CASE    )
         # If we ever update bert-base-cased tokenizer config, this dict here will need to be updated.
         self.assertEqual(_SCREAMING_SNAKE_CASE  ,{'''do_lower_case''': False}    )

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

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

         # Check the class of the tokenizer was properly saved (note that it always saves the slow class).
         self.assertEqual(config['''tokenizer_class''']  ,'''BertTokenizer'''    )





    def 				a__ ( self    )					->						str:
         try:
              AutoConfig.register('''custom'''  ,_SCREAMING_SNAKE_CASE    )

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

              UpperCAmelCase_     :				str  =     CustomTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE    )
              with tempfile.TemporaryDirectory() as tmp_dir:
                   tokenizer.save_pretrained(_SCREAMING_SNAKE_CASE    )

                   UpperCAmelCase_     :				Dict  =     AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE    )
                   self.assertIsInstance(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )

         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 				a__ ( self    )					->						int:
         try:
              AutoConfig.register('''custom'''  ,_SCREAMING_SNAKE_CASE    )

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

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

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

              # 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:
                   UpperCAmelCase_     :				List[str]  =     BertTokenizerFast.from_pretrained(_SCREAMING_SNAKE_CASE    )
                   bert_tokenizer.save_pretrained(_SCREAMING_SNAKE_CASE    )
                   UpperCAmelCase_     :				str  =     CustomTokenizerFast.from_pretrained(_SCREAMING_SNAKE_CASE    )

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

                   UpperCAmelCase_     :				Optional[int]  =     AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE    )
                   self.assertIsInstance(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )

                   UpperCAmelCase_     :				Any  =     AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE  ,use_fast=_SCREAMING_SNAKE_CASE    )
                   self.assertIsInstance(_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE    )

         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 				a__ ( self    )					->						Optional[int]:
         # If remote code is not set, we will time out when asking whether to load the model.
         with self.assertRaises(_SCREAMING_SNAKE_CASE    ):
              UpperCAmelCase_     :				Tuple  =     AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer'''    )
         # If remote code is disabled, we can't load this config.
         with self.assertRaises(_SCREAMING_SNAKE_CASE    ):
              UpperCAmelCase_     :				Union[str, Any]  =     AutoTokenizer.from_pretrained(
                  '''hf-internal-testing/test_dynamic_tokenizer'''  ,trust_remote_code=_SCREAMING_SNAKE_CASE    )

         UpperCAmelCase_     :				Dict  =     AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer'''  ,trust_remote_code=_SCREAMING_SNAKE_CASE    )
         self.assertTrue(tokenizer.special_attribute_present    )
         # Test tokenizer can be reloaded.
         with tempfile.TemporaryDirectory() as tmp_dir:
              tokenizer.save_pretrained(_SCREAMING_SNAKE_CASE    )
              UpperCAmelCase_     :				int  =     AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE  ,trust_remote_code=_SCREAMING_SNAKE_CASE    )
         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
              UpperCAmelCase_     :				List[str]  =     AutoTokenizer.from_pretrained(
                  '''hf-internal-testing/test_dynamic_tokenizer'''  ,trust_remote_code=_SCREAMING_SNAKE_CASE  ,use_fast=_SCREAMING_SNAKE_CASE    )
              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(_SCREAMING_SNAKE_CASE    )
                   UpperCAmelCase_     :				Optional[int]  =     AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE  ,trust_remote_code=_SCREAMING_SNAKE_CASE  ,use_fast=_SCREAMING_SNAKE_CASE    )
              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 				a__ ( self    )					->						Optional[int]:

         class     __a(	_a  ):






             """simple docstring"""





             lowerCAmelCase         = False


         class     __a(	_a  ):






             """simple docstring"""





             lowerCAmelCase         = NewTokenizer
             lowerCAmelCase         = False

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

              # If remote code is disabled, we load the local one.
              UpperCAmelCase_     :				Tuple  =     AutoTokenizer.from_pretrained(
                  '''hf-internal-testing/test_dynamic_tokenizer'''  ,trust_remote_code=_SCREAMING_SNAKE_CASE    )
              self.assertEqual(tokenizer.__class__.__name__  ,'''NewTokenizerFast'''    )
              self.assertFalse(tokenizer.special_attribute_present    )
              UpperCAmelCase_     :				List[str]  =     AutoTokenizer.from_pretrained(
                  '''hf-internal-testing/test_dynamic_tokenizer'''  ,trust_remote_code=_SCREAMING_SNAKE_CASE  ,use_fast=_SCREAMING_SNAKE_CASE    )
              self.assertEqual(tokenizer.__class__.__name__  ,'''NewTokenizer'''    )
              self.assertFalse(tokenizer.special_attribute_present    )

              # If remote is enabled, we load from the Hub
              UpperCAmelCase_     :				Optional[int]  =     AutoTokenizer.from_pretrained(
                  '''hf-internal-testing/test_dynamic_tokenizer'''  ,trust_remote_code=_SCREAMING_SNAKE_CASE    )
              self.assertEqual(tokenizer.__class__.__name__  ,'''NewTokenizerFast'''    )
              self.assertTrue(tokenizer.special_attribute_present    )
              UpperCAmelCase_     :				Any  =     AutoTokenizer.from_pretrained(
                  '''hf-internal-testing/test_dynamic_tokenizer'''  ,trust_remote_code=_SCREAMING_SNAKE_CASE  ,use_fast=_SCREAMING_SNAKE_CASE    )
              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 				a__ ( self    )					->						int:
         UpperCAmelCase_     :				Optional[int]  =     AutoTokenizer.from_pretrained(
             '''hf-internal-testing/test_dynamic_tokenizer_legacy'''  ,trust_remote_code=_SCREAMING_SNAKE_CASE    )
         self.assertTrue(tokenizer.special_attribute_present    )
         if is_tokenizers_available():
              self.assertEqual(tokenizer.__class__.__name__  ,'''NewTokenizerFast'''    )

              # Test we can also load the slow version
              UpperCAmelCase_     :				Tuple  =     AutoTokenizer.from_pretrained(
                  '''hf-internal-testing/test_dynamic_tokenizer_legacy'''  ,trust_remote_code=_SCREAMING_SNAKE_CASE  ,use_fast=_SCREAMING_SNAKE_CASE    )
              self.assertTrue(tokenizer.special_attribute_present    )
              self.assertEqual(tokenizer.__class__.__name__  ,'''NewTokenizer'''    )
         else:
              self.assertEqual(tokenizer.__class__.__name__  ,'''NewTokenizer'''    )





    def 				a__ ( self    )					->						Optional[Any]:
         with self.assertRaisesRegex(
             _SCREAMING_SNAKE_CASE  ,'''bert-base is not a local folder and is not a valid model identifier'''    ):
              UpperCAmelCase_     :				Tuple  =     AutoTokenizer.from_pretrained('''bert-base'''    )





    def 				a__ ( self    )					->						List[Any]:
         with self.assertRaisesRegex(
             _SCREAMING_SNAKE_CASE  ,R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''    ):
              UpperCAmelCase_     :				str  =     AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE  ,revision='''aaaaaa'''    )





    def 				a__ ( self    )					->						Any:
         # Make sure we have cached the tokenizer.
         UpperCAmelCase_     :				Optional[int]  =     AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert'''    )
         with RequestCounter() as counter:
              UpperCAmelCase_     :				List[str]  =     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    )