


"""simple docstring"""





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






     def      lowerCamelCase__     (	self  :					Optional[int]				):
           lowerCAmelCase					:	Optional[Any]       =   0






     @slow
     def      lowerCamelCase__     (	self  :					Dict				):
           for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x):
                 lowerCAmelCase					:	Optional[Any]       =   AutoTokenizer.from_pretrained(UpperCamelCase_				)
                 self.assertIsNotNone(UpperCamelCase_				)
                 self.assertIsInstance(UpperCamelCase_					,				(BertTokenizer, BertTokenizerFast)				)
                 self.assertGreater(len(UpperCamelCase_				)					,				0				)

           for model_name in GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP.keys():
                 lowerCAmelCase					:	Tuple       =   AutoTokenizer.from_pretrained(UpperCamelCase_				)
                 self.assertIsNotNone(UpperCamelCase_				)
                 self.assertIsInstance(UpperCamelCase_					,				(GPTaTokenizer, GPTaTokenizerFast)				)
                 self.assertGreater(len(UpperCamelCase_				)					,				0				)






     def      lowerCamelCase__     (	self  :					Union[str, Any]				):
           lowerCAmelCase					:	Optional[Any]       =   AutoTokenizer.from_pretrained(UpperCamelCase_				)
           self.assertIsInstance(UpperCamelCase_					,				(BertTokenizer, BertTokenizerFast)				)
           self.assertEqual(tokenizer.vocab_size					,				1_2				)






     def      lowerCamelCase__     (	self  :					Dict				):
           lowerCAmelCase					:	Tuple       =   AutoTokenizer.from_pretrained(UpperCamelCase_				)
           self.assertIsInstance(UpperCamelCase_					,				(RobertaTokenizer, RobertaTokenizerFast)				)
           self.assertEqual(tokenizer.vocab_size					,				2_0				)






     def      lowerCamelCase__     (	self  :					Dict				):
           lowerCAmelCase					:	int       =   AutoConfig.from_pretrained(UpperCamelCase_				)
           self.assertIsInstance(UpperCamelCase_					,				UpperCamelCase_				)
           # Check that tokenizer_type ≠ model_type
           lowerCAmelCase					:	List[Any]       =   AutoTokenizer.from_pretrained(UpperCamelCase_					,				config=UpperCamelCase_				)
           self.assertIsInstance(UpperCamelCase_					,				(BertTokenizer, BertTokenizerFast)				)
           self.assertEqual(tokenizer.vocab_size					,				1_2				)






     def      lowerCamelCase__     (	self  :					Any				):
           with tempfile.TemporaryDirectory() as tmp_dir:
                 shutil.copy('''./tests/fixtures/vocab.txt'''					,				os.path.join(UpperCamelCase_					,				'''vocab.txt'''				)				)

                 lowerCAmelCase					:	Any       =   AutoTokenizer.from_pretrained(UpperCamelCase_					,				tokenizer_type='''bert'''					,				use_fast=UpperCamelCase_				)
                 self.assertIsInstance(UpperCamelCase_					,				UpperCamelCase_				)

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

                 lowerCAmelCase					:	List[Any]       =   AutoTokenizer.from_pretrained(UpperCamelCase_					,				tokenizer_type='''gpt2'''					,				use_fast=UpperCamelCase_				)
                 self.assertIsInstance(UpperCamelCase_					,				UpperCamelCase_				)






     @require_tokenizers
     def      lowerCamelCase__     (	self  :					Union[str, Any]				):
           with tempfile.TemporaryDirectory() as tmp_dir:
                 shutil.copy('''./tests/fixtures/vocab.txt'''					,				os.path.join(UpperCamelCase_					,				'''vocab.txt'''				)				)

                 lowerCAmelCase					:	Optional[Any]       =   AutoTokenizer.from_pretrained(UpperCamelCase_					,				tokenizer_type='''bert'''				)
                 self.assertIsInstance(UpperCamelCase_					,				UpperCamelCase_				)

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

                 lowerCAmelCase					:	int       =   AutoTokenizer.from_pretrained(UpperCamelCase_					,				tokenizer_type='''gpt2'''				)
                 self.assertIsInstance(UpperCamelCase_					,				UpperCamelCase_				)






     def      lowerCamelCase__     (	self  :					Dict				):
           with pytest.raises(UpperCamelCase_				):
                 AutoTokenizer.from_pretrained('''./'''					,				tokenizer_type='''xxx'''				)






     @require_tokenizers
     def      lowerCamelCase__     (	self  :					str				):
           for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]:
                 lowerCAmelCase					:	Dict       =   tokenizer_class.from_pretrained('''wietsedv/bert-base-dutch-cased'''				)
                 self.assertIsInstance(UpperCamelCase_					,				(BertTokenizer, BertTokenizerFast)				)

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

                 self.assertEqual(tokenizer.model_max_length					,				5_1_2				)






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






     def      lowerCamelCase__     (	self  :					Tuple				):
           # 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
           lowerCAmelCase					:	Optional[Any]       =   TOKENIZER_MAPPING.values()
           lowerCAmelCase					:	Optional[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(UpperCamelCase_				)






     @require_tokenizers
     def      lowerCamelCase__     (	self  :					Any				):
           self.assertIsInstance(AutoTokenizer.from_pretrained('''bert-base-cased'''					,				use_fast=UpperCamelCase_				)					,				UpperCamelCase_				)
           self.assertIsInstance(AutoTokenizer.from_pretrained('''bert-base-cased'''				)					,				UpperCamelCase_				)






     @require_tokenizers
     def      lowerCamelCase__     (	self  :					Dict				):
           lowerCAmelCase					:	List[Any]       =   AutoTokenizer.from_pretrained('''distilbert-base-uncased'''					,				do_lower_case=UpperCamelCase_				)
           lowerCAmelCase					:	Union[str, Any]       =   '''Hello, world. How are you?'''
           lowerCAmelCase					:	Optional[Any]       =   tokenizer.tokenize(UpperCamelCase_				)
           self.assertEqual('''[UNK]'''					,				tokens[0]				)

           lowerCAmelCase					:	List[str]       =   AutoTokenizer.from_pretrained('''microsoft/mpnet-base'''					,				do_lower_case=UpperCamelCase_				)
           lowerCAmelCase					:	Optional[int]       =   tokenizer.tokenize(UpperCamelCase_				)
           self.assertEqual('''[UNK]'''					,				tokens[0]				)






     @require_tokenizers
     def      lowerCamelCase__     (	self  :					int				):
           lowerCAmelCase					:	Union[str, Any]       =   AutoTokenizer.from_pretrained('''robot-test/dummy-tokenizer-fast-with-model-config'''				)
           self.assertEqual(type(UpperCamelCase_				)					,				UpperCamelCase_				)
           self.assertEqual(tokenizer.model_max_length					,				5_1_2				)
           self.assertEqual(tokenizer.vocab_size					,				3_0_0_0_0				)
           self.assertEqual(tokenizer.unk_token					,				'''[UNK]'''				)
           self.assertEqual(tokenizer.padding_side					,				'''right'''				)
           self.assertEqual(tokenizer.truncation_side					,				'''right'''				)






     def      lowerCamelCase__     (	self  :					List[Any]				):
           lowerCAmelCase					:	int       =   AutoTokenizer.from_pretrained(UpperCamelCase_				)
           self.assertIsInstance(UpperCamelCase_					,				(BertTokenizer, BertTokenizerFast)				)
           with tempfile.TemporaryDirectory() as tmp_dir:
                 tokenizer.save_pretrained(UpperCamelCase_				)
                 lowerCAmelCase					:	List[Any]       =   AutoTokenizer.from_pretrained(UpperCamelCase_				)

           self.assertIsInstance(UpperCamelCase_					,				tokenizer.__class__				)
           self.assertEqual(tokenizera.vocab_size					,				1_2				)






     def      lowerCamelCase__     (	self  :					List[str]				):
           lowerCAmelCase					:	List[Any]       =   AutoTokenizer.from_pretrained('''ctrl'''				)
           # There is no fast CTRL so this always gives us a slow tokenizer.
           self.assertIsInstance(UpperCamelCase_					,				UpperCamelCase_				)






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

           # This model does not have a tokenizer_config so we get back an empty dict.
           lowerCAmelCase					:	Union[str, Any]       =   get_tokenizer_config(UpperCamelCase_				)
           self.assertDictEqual(UpperCamelCase_					,				{}				)

           # A tokenizer saved with `save_pretrained` always creates a tokenizer config.
           lowerCAmelCase					:	List[Any]       =   AutoTokenizer.from_pretrained(UpperCamelCase_				)
           with tempfile.TemporaryDirectory() as tmp_dir:
                 tokenizer.save_pretrained(UpperCamelCase_				)
                 lowerCAmelCase					:	Dict       =   get_tokenizer_config(UpperCamelCase_				)

           # 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  :					Optional[int]				):
           try:
                 AutoConfig.register('''custom'''					,				UpperCamelCase_				)

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

                 lowerCAmelCase					:	Union[str, Any]       =   CustomTokenizer.from_pretrained(UpperCamelCase_				)
                 with tempfile.TemporaryDirectory() as tmp_dir:
                       tokenizer.save_pretrained(UpperCamelCase_				)

                       lowerCAmelCase					:	Tuple       =   AutoTokenizer.from_pretrained(UpperCamelCase_				)
                       self.assertIsInstance(UpperCamelCase_					,				UpperCamelCase_				)

           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  :					str				):
           try:
                 AutoConfig.register('''custom'''					,				UpperCamelCase_				)

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

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

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

                 # 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:
                       lowerCAmelCase					:	Dict       =   BertTokenizerFast.from_pretrained(UpperCamelCase_				)
                       bert_tokenizer.save_pretrained(UpperCamelCase_				)
                       lowerCAmelCase					:	int       =   CustomTokenizerFast.from_pretrained(UpperCamelCase_				)

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

                       lowerCAmelCase					:	Optional[int]       =   AutoTokenizer.from_pretrained(UpperCamelCase_				)
                       self.assertIsInstance(UpperCamelCase_					,				UpperCamelCase_				)

                       lowerCAmelCase					:	List[str]       =   AutoTokenizer.from_pretrained(UpperCamelCase_					,				use_fast=UpperCamelCase_				)
                       self.assertIsInstance(UpperCamelCase_					,				UpperCamelCase_				)

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

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



           class 		snake_case_(       a__			):
                __UpperCamelCase  =					False



           class 		snake_case_(       a__			):
                __UpperCamelCase  =					NewTokenizer
                __UpperCamelCase  =					False

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

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

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

                 # Test we can also load the slow version
                 lowerCAmelCase					:	List[str]       =   AutoTokenizer.from_pretrained(
                     '''hf-internal-testing/test_dynamic_tokenizer_legacy'''					,				trust_remote_code=UpperCamelCase_					,				use_fast=UpperCamelCase_				)
                 self.assertTrue(tokenizer.special_attribute_present				)
                 self.assertEqual(tokenizer.__class__.__name__					,				'''NewTokenizer'''				)
           else:
                 self.assertEqual(tokenizer.__class__.__name__					,				'''NewTokenizer'''				)






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






     def      lowerCamelCase__     (	self  :					int				):
           with self.assertRaisesRegex(
               UpperCamelCase_					,				r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''				):
                 lowerCAmelCase					:	List[Any]       =   AutoTokenizer.from_pretrained(UpperCamelCase_					,				revision='''aaaaaa'''				)






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






"""simple docstring"""





import unittest

import numpy as np
import timeout_decorator  # noqa

from transformers import BlenderbotConfig, is_flax_available
from transformers.testing_utils import jax_device, require_flax, slow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor


if is_flax_available():
 import os

 # The slow tests are often failing with OOM error on GPU
 # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
 # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
 snake_case__		:     int    				=				'''platform'''

 import jax
 import jax.numpy as jnp

 from transformers import BlenderbotTokenizer
 from transformers.models.blenderbot.modeling_flax_blenderbot import (
     FlaxBlenderbotForConditionalGeneration,
     FlaxBlenderbotModel,
     shift_tokens_right,
 )


def      _snake_case						(						_snake_case				:			str ,   _snake_case				:			Any ,   _snake_case				:			str=None ,   _snake_case				:			str=None ,   _snake_case				:			Dict=None ,   _snake_case				:			Tuple=None ,   _snake_case				:			str=None ,   _snake_case				:			Any=None ,   ):
      if attention_mask is None:
            lowerCAmelCase					:	List[str]       =   np.where(input_ids != config.pad_token_id ,   1 ,   0			)
      if decoder_attention_mask is None:
            lowerCAmelCase					:	Optional[int]       =   np.where(decoder_input_ids != config.pad_token_id ,   1 ,   0			)
      if head_mask is None:
            lowerCAmelCase					:	Any       =   np.ones((config.encoder_layers, config.encoder_attention_heads)			)
      if decoder_head_mask is None:
            lowerCAmelCase					:	int       =   np.ones((config.decoder_layers, config.decoder_attention_heads)			)
      if cross_attn_head_mask is None:
            lowerCAmelCase					:	List[str]       =   np.ones((config.decoder_layers, config.decoder_attention_heads)			)
      return {
          "input_ids": input_ids,
          "decoder_input_ids": decoder_input_ids,
          "attention_mask": attention_mask,
          "decoder_attention_mask": attention_mask,
      }



class 		snake_case_:






     def __init__(	self  :					int					,				UpperCamelCase_  :					Tuple					,				UpperCamelCase_  :					int=1_3					,				UpperCamelCase_  :					Union[str, Any]=7					,				UpperCamelCase_  :					Union[str, Any]=True					,				UpperCamelCase_  :					List[Any]=False					,				UpperCamelCase_  :					Dict=9_9					,				UpperCamelCase_  :					Optional[int]=1_6					,				UpperCamelCase_  :					str=2					,				UpperCamelCase_  :					List[str]=4					,				UpperCamelCase_  :					List[Any]=4					,				UpperCamelCase_  :					int="gelu"					,				UpperCamelCase_  :					Optional[int]=0.1					,				UpperCamelCase_  :					Any=0.1					,				UpperCamelCase_  :					str=3_2					,				UpperCamelCase_  :					str=2					,				UpperCamelCase_  :					Tuple=1					,				UpperCamelCase_  :					List[Any]=0					,				UpperCamelCase_  :					Any=0.02					,				):
           lowerCAmelCase					:	Tuple       =   parent
           lowerCAmelCase					:	str       =   batch_size
           lowerCAmelCase					:	List[Any]       =   seq_length
           lowerCAmelCase					:	Optional[int]       =   is_training
           lowerCAmelCase					:	int       =   use_labels
           lowerCAmelCase					:	List[Any]       =   vocab_size
           lowerCAmelCase					:	str       =   hidden_size
           lowerCAmelCase					:	List[Any]       =   num_hidden_layers
           lowerCAmelCase					:	Any       =   num_attention_heads
           lowerCAmelCase					:	List[Any]       =   intermediate_size
           lowerCAmelCase					:	Optional[int]       =   hidden_act
           lowerCAmelCase					:	Dict       =   hidden_dropout_prob
           lowerCAmelCase					:	Optional[int]       =   attention_probs_dropout_prob
           lowerCAmelCase					:	List[Any]       =   max_position_embeddings
           lowerCAmelCase					:	Union[str, Any]       =   eos_token_id
           lowerCAmelCase					:	Dict       =   pad_token_id
           lowerCAmelCase					:	Optional[Any]       =   bos_token_id
           lowerCAmelCase					:	List[str]       =   initializer_range






     def      lowerCamelCase__     (	self  :					Dict				):
           lowerCAmelCase					:	List[Any]       =   np.clip(ids_tensor([self.batch_size, self.seq_length - 1]					,				self.vocab_size				)					,				3					,				self.vocab_size				)
           lowerCAmelCase					:	str       =   np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1)					,				dtype=np.intaa				))					,				-1				)

           lowerCAmelCase					:	Tuple       =   shift_tokens_right(UpperCamelCase_					,				1					,				2				)

           lowerCAmelCase					:	Union[str, Any]       =   BlenderbotConfig(
               vocab_size=self.vocab_size					,				d_model=self.hidden_size					,				encoder_layers=self.num_hidden_layers					,				decoder_layers=self.num_hidden_layers					,				encoder_attention_heads=self.num_attention_heads					,				decoder_attention_heads=self.num_attention_heads					,				encoder_ffn_dim=self.intermediate_size					,				decoder_ffn_dim=self.intermediate_size					,				dropout=self.hidden_dropout_prob					,				attention_dropout=self.attention_probs_dropout_prob					,				max_position_embeddings=self.max_position_embeddings					,				eos_token_id=self.eos_token_id					,				bos_token_id=self.bos_token_id					,				pad_token_id=self.pad_token_id					,				initializer_range=self.initializer_range					,				use_cache=UpperCamelCase_					,				)
           lowerCAmelCase					:	Union[str, Any]       =   prepare_blenderbot_inputs_dict(UpperCamelCase_					,				UpperCamelCase_					,				UpperCamelCase_				)
           return config, inputs_dict






     def      lowerCamelCase__     (	self  :					str				):
           lowerCAmelCase,      lowerCAmelCase					:	Optional[int]       =   self.prepare_config_and_inputs()
           return config, inputs_dict






     def      lowerCamelCase__     (	self  :					List[str]					,				UpperCamelCase_  :					List[str]					,				UpperCamelCase_  :					str					,				UpperCamelCase_  :					Tuple				):
           lowerCAmelCase					:	int       =   2_0
           lowerCAmelCase					:	Tuple       =   model_class_name(UpperCamelCase_				)

           lowerCAmelCase					:	Optional[Any]       =   model.encode(inputs_dict['''input_ids''']				)

           lowerCAmelCase,      lowerCAmelCase					:	str       =   (
               inputs_dict['''decoder_input_ids'''],
               inputs_dict['''decoder_attention_mask'''],
           )

           lowerCAmelCase					:	str       =   model.init_cache(decoder_input_ids.shape[0]					,				UpperCamelCase_					,				UpperCamelCase_				)
           lowerCAmelCase					:	Union[str, Any]       =   jnp.ones((decoder_input_ids.shape[0], max_decoder_length)					,				dtype='''i4'''				)

           lowerCAmelCase					:	Tuple       =   jnp.broadcast_to(
               jnp.arange(decoder_input_ids.shape[-1] - 1				)[None, :]					,				(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)					,				)
           lowerCAmelCase					:	List[Any]       =   model.decode(
               decoder_input_ids[:, :-1]					,				UpperCamelCase_					,				decoder_attention_mask=UpperCamelCase_					,				past_key_values=UpperCamelCase_					,				decoder_position_ids=UpperCamelCase_					,				)

           lowerCAmelCase					:	Any       =   jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]					,				dtype='''i4'''				)
           lowerCAmelCase					:	List[str]       =   model.decode(
               decoder_input_ids[:, -1:]					,				UpperCamelCase_					,				decoder_attention_mask=UpperCamelCase_					,				past_key_values=outputs_cache.past_key_values					,				decoder_position_ids=UpperCamelCase_					,				)

           lowerCAmelCase					:	Union[str, Any]       =   model.decode(UpperCamelCase_					,				UpperCamelCase_				)

           lowerCAmelCase					:	int       =   np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])				)				)
           self.parent.assertTrue(diff < 1E-3					,				msg=F'''Max diff is {diff}'''				)






     def      lowerCamelCase__     (	self  :					Union[str, Any]					,				UpperCamelCase_  :					Any					,				UpperCamelCase_  :					Any					,				UpperCamelCase_  :					List[str]				):
           lowerCAmelCase					:	Optional[int]       =   2_0
           lowerCAmelCase					:	List[Any]       =   model_class_name(UpperCamelCase_				)

           lowerCAmelCase					:	Union[str, Any]       =   model.encode(inputs_dict['''input_ids''']				)

           lowerCAmelCase,      lowerCAmelCase					:	Optional[int]       =   (
               inputs_dict['''decoder_input_ids'''],
               inputs_dict['''decoder_attention_mask'''],
           )

           lowerCAmelCase					:	str       =   jnp.concatenate(
               [
                   decoder_attention_mask,
                   jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])				),
               ]					,				axis=-1					,				)

           lowerCAmelCase					:	Union[str, Any]       =   model.init_cache(decoder_input_ids.shape[0]					,				UpperCamelCase_					,				UpperCamelCase_				)
           lowerCAmelCase					:	str       =   jnp.broadcast_to(
               jnp.arange(decoder_input_ids.shape[-1] - 1				)[None, :]					,				(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)					,				)

           lowerCAmelCase					:	Dict       =   model.decode(
               decoder_input_ids[:, :-1]					,				UpperCamelCase_					,				decoder_attention_mask=UpperCamelCase_					,				past_key_values=UpperCamelCase_					,				decoder_position_ids=UpperCamelCase_					,				)
           lowerCAmelCase					:	Any       =   jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]					,				dtype='''i4'''				)
           lowerCAmelCase					:	Union[str, Any]       =   model.decode(
               decoder_input_ids[:, -1:]					,				UpperCamelCase_					,				past_key_values=outputs_cache.past_key_values					,				decoder_attention_mask=UpperCamelCase_					,				decoder_position_ids=UpperCamelCase_					,				)

           lowerCAmelCase					:	Dict       =   model.decode(UpperCamelCase_					,				UpperCamelCase_					,				decoder_attention_mask=UpperCamelCase_				)

           lowerCAmelCase					:	Any       =   np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])				)				)
           self.parent.assertTrue(diff < 1E-3					,				msg=F'''Max diff is {diff}'''				)



@require_flax
class 		snake_case_(       unittest.TestCase			):
     __UpperCamelCase  =					99






     def      lowerCamelCase__     (	self  :					str				):
           lowerCAmelCase					:	List[Any]       =   np.array(
               [
                   [7_1, 8_2, 1_8, 3_3, 4_6, 9_1, 2],
                   [6_8, 3_4, 2_6, 5_8, 3_0, 8_2, 2],
                   [5, 9_7, 1_7, 3_9, 9_4, 4_0, 2],
                   [7_6, 8_3, 9_4, 2_5, 7_0, 7_8, 2],
                   [8_7, 5_9, 4_1, 3_5, 4_8, 6_6, 2],
                   [5_5, 1_3, 1_6, 5_8, 5, 2, 1],  # note padding
                   [6_4, 2_7, 3_1, 5_1, 1_2, 7_5, 2],
                   [5_2, 6_4, 8_6, 1_7, 8_3, 3_9, 2],
                   [4_8, 6_1, 9, 2_4, 7_1, 8_2, 2],
                   [2_6, 1, 6_0, 4_8, 2_2, 1_3, 2],
                   [2_1, 5, 6_2, 2_8, 1_4, 7_6, 2],
                   [4_5, 9_8, 3_7, 8_6, 5_9, 4_8, 2],
                   [7_0, 7_0, 5_0, 9, 2_8, 0, 2],
               ]					,				dtype=np.intaa					,				)

           lowerCAmelCase					:	List[Any]       =   input_ids.shape[0]
           lowerCAmelCase					:	Optional[Any]       =   BlenderbotConfig(
               vocab_size=self.vocab_size					,				d_model=2_4					,				encoder_layers=2					,				decoder_layers=2					,				encoder_attention_heads=2					,				decoder_attention_heads=2					,				encoder_ffn_dim=3_2					,				decoder_ffn_dim=3_2					,				max_position_embeddings=4_8					,				eos_token_id=2					,				pad_token_id=1					,				bos_token_id=0					,				)
           return config, input_ids, batch_size






     def      lowerCamelCase__     (	self  :					List[str]				):
           lowerCAmelCase,      lowerCAmelCase,      lowerCAmelCase					:	Any       =   self._get_config_and_data()
           lowerCAmelCase					:	Any       =   FlaxBlenderbotForConditionalGeneration(UpperCamelCase_				)
           lowerCAmelCase					:	Optional[int]       =   lm_model(input_ids=UpperCamelCase_				)
           lowerCAmelCase					:	Tuple       =   (batch_size, input_ids.shape[1], config.vocab_size)
           self.assertEqual(outputs['''logits'''].shape					,				UpperCamelCase_				)






     def      lowerCamelCase__     (	self  :					Any				):
           lowerCAmelCase					:	Any       =   BlenderbotConfig(
               vocab_size=self.vocab_size					,				d_model=1_4					,				encoder_layers=2					,				decoder_layers=2					,				encoder_attention_heads=2					,				decoder_attention_heads=2					,				encoder_ffn_dim=8					,				decoder_ffn_dim=8					,				max_position_embeddings=4_8					,				)
           lowerCAmelCase					:	int       =   FlaxBlenderbotForConditionalGeneration(UpperCamelCase_				)
           lowerCAmelCase					:	Optional[Any]       =   np.array([[7_1, 8_2, 1_8, 3_3, 4_6, 9_1, 2], [6_8, 3_4, 2_6, 5_8, 3_0, 2, 1]]					,				dtype=np.intaa				)
           lowerCAmelCase					:	List[str]       =   np.array([[8_2, 7_1, 8_2, 1_8, 2], [5_8, 6_8, 2, 1, 1]]					,				dtype=np.intaa				)
           lowerCAmelCase					:	List[Any]       =   lm_model(input_ids=UpperCamelCase_					,				decoder_input_ids=UpperCamelCase_				)
           lowerCAmelCase					:	str       =   (*summary.shape, config.vocab_size)
           self.assertEqual(outputs['''logits'''].shape					,				UpperCamelCase_				)






     def      lowerCamelCase__     (	self  :					int				):
           lowerCAmelCase					:	Any       =   np.array([[7_1, 8_2, 1_8, 3_3, 2, 1, 1], [6_8, 3_4, 2_6, 5_8, 3_0, 8_2, 2]]					,				dtype=np.intaa				)
           lowerCAmelCase					:	Tuple       =   shift_tokens_right(UpperCamelCase_					,				1					,				2				)
           lowerCAmelCase					:	Optional[int]       =   np.equal(UpperCamelCase_					,				1				).astype(np.floataa				).sum()
           lowerCAmelCase					:	str       =   np.equal(UpperCamelCase_					,				1				).astype(np.floataa				).sum()
           self.assertEqual(shifted.shape					,				input_ids.shape				)
           self.assertEqual(UpperCamelCase_					,				n_pad_before - 1				)
           self.assertTrue(np.equal(shifted[:, 0]					,				2				).all()				)



@require_flax
class 		snake_case_(       a__							,					unittest.TestCase							,					a__			):
     __UpperCamelCase  =					True
     __UpperCamelCase  =					(
         (
             FlaxBlenderbotModel,
             FlaxBlenderbotForConditionalGeneration,
         )
         if is_flax_available()
         else ()
     )
     __UpperCamelCase  =					(FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else ()






     def      lowerCamelCase__     (	self  :					Dict				):
           lowerCAmelCase					:	Any       =   FlaxBlenderbotModelTester(self				)






     def      lowerCamelCase__     (	self  :					Tuple				):
           lowerCAmelCase,      lowerCAmelCase					:	List[str]       =   self.model_tester.prepare_config_and_inputs()
           for model_class in self.all_model_classes:
                 self.model_tester.check_use_cache_forward(UpperCamelCase_					,				UpperCamelCase_					,				UpperCamelCase_				)






     def      lowerCamelCase__     (	self  :					List[str]				):
           lowerCAmelCase,      lowerCAmelCase					:	Union[str, Any]       =   self.model_tester.prepare_config_and_inputs()
           for model_class in self.all_model_classes:
                 self.model_tester.check_use_cache_forward_with_attn_mask(UpperCamelCase_					,				UpperCamelCase_					,				UpperCamelCase_				)






     def      lowerCamelCase__     (	self  :					Tuple				):
           lowerCAmelCase,      lowerCAmelCase					:	str       =   self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 with self.subTest(model_class.__name__				):
                       lowerCAmelCase					:	Optional[int]       =   self._prepare_for_class(UpperCamelCase_					,				UpperCamelCase_				)
                       lowerCAmelCase					:	Optional[Any]       =   model_class(UpperCamelCase_				)

                       @jax.jit
                       def encode_jitted(UpperCamelCase_  :					List[str]					,				UpperCamelCase_  :					Optional[Any]=None					,				**UpperCamelCase_  :					List[str]				):
                             return model.encode(input_ids=UpperCamelCase_					,				attention_mask=UpperCamelCase_				)

                       with self.subTest('''JIT Enabled'''				):
                             lowerCAmelCase					:	List[str]       =   encode_jitted(**UpperCamelCase_				).to_tuple()

                       with self.subTest('''JIT Disabled'''				):
                             with jax.disable_jit():
                                   lowerCAmelCase					:	int       =   encode_jitted(**UpperCamelCase_				).to_tuple()

                       self.assertEqual(len(UpperCamelCase_				)					,				len(UpperCamelCase_				)				)
                       for jitted_output, output in zip(UpperCamelCase_					,				UpperCamelCase_				):
                             self.assertEqual(jitted_output.shape					,				output.shape				)






     def      lowerCamelCase__     (	self  :					Union[str, Any]				):
           lowerCAmelCase,      lowerCAmelCase					:	Any       =   self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 with self.subTest(model_class.__name__				):
                       lowerCAmelCase					:	Tuple       =   model_class(UpperCamelCase_				)
                       lowerCAmelCase					:	int       =   model.encode(inputs_dict['''input_ids''']					,				inputs_dict['''attention_mask''']				)

                       lowerCAmelCase					:	List[Any]       =   {
                           '''decoder_input_ids''': inputs_dict['''decoder_input_ids'''],
                           '''decoder_attention_mask''': inputs_dict['''decoder_attention_mask'''],
                           '''encoder_outputs''': encoder_outputs,
                       }

                       @jax.jit
                       def decode_jitted(UpperCamelCase_  :					Union[str, Any]					,				UpperCamelCase_  :					Dict					,				UpperCamelCase_  :					int				):
                             return model.decode(
                                 decoder_input_ids=UpperCamelCase_					,				decoder_attention_mask=UpperCamelCase_					,				encoder_outputs=UpperCamelCase_					,				)

                       with self.subTest('''JIT Enabled'''				):
                             lowerCAmelCase					:	str       =   decode_jitted(**UpperCamelCase_				).to_tuple()

                       with self.subTest('''JIT Disabled'''				):
                             with jax.disable_jit():
                                   lowerCAmelCase					:	Union[str, Any]       =   decode_jitted(**UpperCamelCase_				).to_tuple()

                       self.assertEqual(len(UpperCamelCase_				)					,				len(UpperCamelCase_				)				)
                       for jitted_output, output in zip(UpperCamelCase_					,				UpperCamelCase_				):
                             self.assertEqual(jitted_output.shape					,				output.shape				)






     @slow
     def      lowerCamelCase__     (	self  :					Optional[int]				):
           for model_class_name in self.all_model_classes:
                 lowerCAmelCase					:	Optional[int]       =   model_class_name.from_pretrained('''facebook/blenderbot-400M-distill'''				)
                 # FlaxBlenderbotForSequenceClassification expects eos token in input_ids
                 lowerCAmelCase					:	int       =   np.ones((1, 1)				) * model.config.eos_token_id
                 lowerCAmelCase					:	List[str]       =   model(UpperCamelCase_				)
                 self.assertIsNotNone(UpperCamelCase_				)






     @unittest.skipUnless(jax_device != '''cpu'''					,				'''3B test too slow on CPU.'''				)
     @slow
     def      lowerCamelCase__     (	self  :					Union[str, Any]				):
           lowerCAmelCase					:	Dict       =   {'''num_beams''': 1, '''early_stopping''': True, '''min_length''': 1_5, '''max_length''': 2_5}
           lowerCAmelCase					:	List[str]       =   {'''skip_special_tokens''': True, '''clean_up_tokenization_spaces''': True}

           lowerCAmelCase					:	Tuple       =   FlaxBlenderbotForConditionalGeneration.from_pretrained('''facebook/blenderbot-3B'''					,				from_pt=UpperCamelCase_				)
           lowerCAmelCase					:	Union[str, Any]       =   BlenderbotTokenizer.from_pretrained('''facebook/blenderbot-3B'''				)

           lowerCAmelCase					:	List[Any]       =   ['''Sam''']
           lowerCAmelCase					:	str       =   tokenizer(UpperCamelCase_					,				return_tensors='''jax'''				)

           lowerCAmelCase					:	Union[str, Any]       =   model.generate(**UpperCamelCase_					,				**UpperCamelCase_				)
           lowerCAmelCase					:	Tuple       =   '''Sam is a great name. It means "sun" in Gaelic.'''

           lowerCAmelCase					:	Union[str, Any]       =   tokenizer.batch_decode(UpperCamelCase_					,				**UpperCamelCase_				)
           assert generated_txt[0].strip() == tgt_text


