

import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_flax_cross_test,
    require_flax,
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import is_flax_available, is_torch_available, is_vision_available

from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_flax_bert import FlaxBertModelTester
from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester
from ..vit.test_modeling_flax_vit import FlaxViTModelTester


if is_flax_available():
      from transformers import (
          FlaxBertModel,
          FlaxCLIPVisionModel,
          FlaxVisionTextDualEncoderModel,
          FlaxViTModel,
          VisionTextDualEncoderConfig,
          VisionTextDualEncoderProcessor,
      )
      from transformers.modeling_flax_pytorch_utils import (
          convert_pytorch_state_dict_to_flax,
          load_flax_weights_in_pytorch_model,
      )


if is_torch_available():
      import torch

      from transformers import VisionTextDualEncoderModel

if is_vision_available():
      from PIL import Image
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     Dict:
       if isinstance(UpperCAmelCase__,    collections.abc.Iterable			):
              return x
       return (x, x)


@require_flax
class    A__ :



    def    snake_case_     (   self						,			UpperCamelCase__						,			UpperCamelCase__    )  -> Tuple:





           '''simple docstring'''
           pass



    def    snake_case_     (   self    )  -> Tuple:





           '''simple docstring'''
           pass



    def    snake_case_     (   self    )  -> Optional[Any]:





           '''simple docstring'''
           pass



    def    snake_case_     (   self						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__    )  -> Dict:





           '''simple docstring'''
           A_		   = np.abs((a - b)    ).max()
           self.assertLessEqual(UpperCamelCase__						,			UpperCamelCase__						,			f'''Difference between torch and flax is {diff} (>= {tol}).'''    )



    def    snake_case_     (   self						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__=None						,			**UpperCamelCase__    )  -> List[str]:





           '''simple docstring'''
           A_		   = VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase__						,			UpperCamelCase__    )

           A_		   = FlaxVisionTextDualEncoderModel(UpperCamelCase__    )

           A_		   = model(input_ids=UpperCamelCase__						,			pixel_values=UpperCamelCase__						,			attention_mask=UpperCamelCase__    )

           self.assertEqual(output["""text_embeds"""].shape						,			(input_ids.shape[0], config.projection_dim)    )
           self.assertEqual(output["""image_embeds"""].shape						,			(pixel_values.shape[0], config.projection_dim)    )



    def    snake_case_     (   self						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__=None						,			**UpperCamelCase__    )  -> str:





           '''simple docstring'''
           A_   ,     A_		   = self.get_vision_text_model(UpperCamelCase__						,			UpperCamelCase__    )
           A_		   = {"""vision_model""": vision_model, """text_model""": text_model}
           A_		   = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCamelCase__    )

           A_		   = model(input_ids=UpperCamelCase__						,			pixel_values=UpperCamelCase__						,			attention_mask=UpperCamelCase__    )

           self.assertEqual(output["""text_embeds"""].shape						,			(input_ids.shape[0], model.config.projection_dim)    )
           self.assertEqual(output["""image_embeds"""].shape						,			(pixel_values.shape[0], model.config.projection_dim)    )



    def    snake_case_     (   self						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__=None						,			**UpperCamelCase__    )  -> Optional[Any]:





           '''simple docstring'''
           A_   ,     A_		   = self.get_vision_text_model(UpperCamelCase__						,			UpperCamelCase__    )
           A_		   = {"""vision_model""": vision_model, """text_model""": text_model}
           A_		   = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCamelCase__    )

           A_		   = model(input_ids=UpperCamelCase__						,			pixel_values=UpperCamelCase__						,			attention_mask=UpperCamelCase__    )
           A_		   = output[0]

           with tempfile.TemporaryDirectory() as tmpdirname:
                  model.save_pretrained(UpperCamelCase__    )
                  A_		   = FlaxVisionTextDualEncoderModel.from_pretrained(UpperCamelCase__    )

                  A_		   = model(input_ids=UpperCamelCase__						,			pixel_values=UpperCamelCase__						,			attention_mask=UpperCamelCase__    )
                  A_		   = after_output[0]
                  A_		   = np.amax(np.abs(out_a - out_a    )    )
                  self.assertLessEqual(UpperCamelCase__						,			1e-3    )



    def    snake_case_     (   self						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__=None						,			**UpperCamelCase__    )  -> int:





           '''simple docstring'''
           A_   ,     A_		   = self.get_vision_text_model(UpperCamelCase__						,			UpperCamelCase__    )
           A_		   = {"""vision_model""": vision_model, """text_model""": text_model}
           A_		   = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCamelCase__    )

           A_		   = model(
               input_ids=UpperCamelCase__						,			pixel_values=UpperCamelCase__						,			attention_mask=UpperCamelCase__						,			output_attentions=UpperCamelCase__    )

           A_		   = output.vision_model_output.attentions
           self.assertEqual(len(UpperCamelCase__    )						,			vision_config.num_hidden_layers    )

           # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
           A_		   = to_atuple(vision_model.config.image_size    )
           A_		   = to_atuple(vision_model.config.patch_size    )
           A_		   = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
           A_		   = num_patches + 1
           self.assertEqual(vision_attentions[0].shape[-3:]						,			(vision_config.num_attention_heads, seq_len, seq_len)    )

           A_		   = output.text_model_output.attentions
           self.assertEqual(len(UpperCamelCase__    )						,			text_config.num_hidden_layers    )

           self.assertEqual(
               text_attentions[0].shape[-3:]						,			(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])						,			)



    def    snake_case_     (   self						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__    )  -> str:





           '''simple docstring'''
           pt_model.to(UpperCamelCase__    )
           pt_model.eval()

           # prepare inputs
           A_		   = inputs_dict
           A_		   = {k: torch.tensor(v.tolist()    ) for k, v in flax_inputs.items()}

           with torch.no_grad():
                  A_		   = pt_model(**UpperCamelCase__    ).to_tuple()

           A_		   = fx_model(**UpperCamelCase__    ).to_tuple()
           self.assertEqual(len(UpperCamelCase__    )						,			len(UpperCamelCase__    )						,			"""Output lengths differ between Flax and PyTorch"""    )
           for fx_output, pt_output in zip(fx_outputs[:4]						,			pt_outputs[:4]    ):
                  self.assert_almost_equals(UpperCamelCase__						,			pt_output.numpy()						,			4e-2    )

           # PT -> Flax
           with tempfile.TemporaryDirectory() as tmpdirname:
                  pt_model.save_pretrained(UpperCamelCase__    )
                  A_		   = FlaxVisionTextDualEncoderModel.from_pretrained(UpperCamelCase__						,			from_pt=UpperCamelCase__    )

           A_		   = fx_model_loaded(**UpperCamelCase__    ).to_tuple()
           self.assertEqual(len(UpperCamelCase__    )						,			len(UpperCamelCase__    )						,			"""Output lengths differ between Flax and PyTorch"""    )
           for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4]						,			pt_outputs[:4]    ):
                  self.assert_almost_equals(UpperCamelCase__						,			pt_output.numpy()						,			4e-2    )

           # Flax -> PT
           with tempfile.TemporaryDirectory() as tmpdirname:
                  fx_model.save_pretrained(UpperCamelCase__    )
                  A_		   = VisionTextDualEncoderModel.from_pretrained(UpperCamelCase__						,			from_flax=UpperCamelCase__    )

           pt_model_loaded.to(UpperCamelCase__    )
           pt_model_loaded.eval()

           with torch.no_grad():
                  A_		   = pt_model_loaded(**UpperCamelCase__    ).to_tuple()

           self.assertEqual(len(UpperCamelCase__    )						,			len(UpperCamelCase__    )						,			"""Output lengths differ between Flax and PyTorch"""    )
           for fx_output, pt_output_loaded in zip(fx_outputs[:4]						,			pt_outputs_loaded[:4]    ):
                  self.assert_almost_equals(UpperCamelCase__						,			pt_output_loaded.numpy()						,			4e-2    )



    def    snake_case_     (   self						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__    )  -> int:





           '''simple docstring'''
           A_		   = VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase__						,			UpperCamelCase__    )

           A_		   = VisionTextDualEncoderModel(UpperCamelCase__    )
           A_		   = FlaxVisionTextDualEncoderModel(UpperCamelCase__    )

           A_		   = convert_pytorch_state_dict_to_flax(pt_model.state_dict()						,			UpperCamelCase__    )
           A_		   = fx_state

           self.check_pt_flax_equivalence(UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__    )



    def    snake_case_     (   self						,			UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__    )  -> int:





           '''simple docstring'''
           A_		   = VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase__						,			UpperCamelCase__    )

           A_		   = VisionTextDualEncoderModel(UpperCamelCase__    )
           A_		   = FlaxVisionTextDualEncoderModel(UpperCamelCase__    )

           A_		   = load_flax_weights_in_pytorch_model(UpperCamelCase__						,			fx_model.params    )

           self.check_pt_flax_equivalence(UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__    )



    def    snake_case_     (   self    )  -> Dict:





           '''simple docstring'''
           A_		   = self.prepare_config_and_inputs()
           self.check_model_from_pretrained_configs(**UpperCamelCase__    )



    def    snake_case_     (   self    )  -> Any:





           '''simple docstring'''
           A_		   = self.prepare_config_and_inputs()
           self.check_vision_text_dual_encoder_from_pretrained(**UpperCamelCase__    )



    def    snake_case_     (   self    )  -> Dict:





           '''simple docstring'''
           A_		   = self.prepare_config_and_inputs()
           self.check_save_load(**UpperCamelCase__    )



    def    snake_case_     (   self    )  -> Optional[int]:





           '''simple docstring'''
           A_		   = self.prepare_config_and_inputs()
           self.check_vision_text_output_attention(**UpperCamelCase__    )



    @is_pt_flax_cross_test
    def    snake_case_     (   self    )  -> List[Any]:





           '''simple docstring'''
           A_		   = self.prepare_config_and_inputs()
           A_		   = config_inputs_dict.pop("""vision_config"""    )
           A_		   = config_inputs_dict.pop("""text_config"""    )

           A_		   = config_inputs_dict

           self.check_equivalence_pt_to_flax(UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__    )
           self.check_equivalence_flax_to_pt(UpperCamelCase__						,			UpperCamelCase__						,			UpperCamelCase__    )







    @slow
    def    snake_case_     (   self    )  -> Optional[int]:





           '''simple docstring'''
           A_   ,     A_		   = self.get_pretrained_model_and_inputs()

           A_		   = model_a(**UpperCamelCase__    )
           A_		   = outputs[0]

           with tempfile.TemporaryDirectory() as tmp_dirname:
                  model_a.save_pretrained(UpperCamelCase__    )
                  A_		   = FlaxVisionTextDualEncoderModel.from_pretrained(UpperCamelCase__    )

                  A_		   = model_a(**UpperCamelCase__    )
                  A_		   = after_outputs[0]
                  A_		   = np.amax(np.abs(out_a - out_a    )    )
                  self.assertLessEqual(UpperCamelCase__						,			1e-5    )


@require_flax
class    A__ ( _snake_case  ,  unittest.TestCase     ):



    def    snake_case_     (   self    )  -> Union[str, Any]:





           '''simple docstring'''
           A_		   = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
               """hf-internal-testing/tiny-random-vit"""						,			"""hf-internal-testing/tiny-bert"""						,			vision_from_pt=UpperCamelCase__						,			text_from_pt=UpperCamelCase__						,			)
           A_		   = 13
           A_		   = floats_tensor(
               [
                   batch_size,
                   model.config.vision_config.num_channels,
                   model.config.vision_config.image_size,
                   model.config.vision_config.image_size,
               ]    )
           A_		   = ids_tensor([batch_size, 4]						,			model.config.text_config.vocab_size    )
           A_		   = random_attention_mask([batch_size, 4]    )
           A_		   = {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

           return model, inputs



    def    snake_case_     (   self						,			UpperCamelCase__						,			UpperCamelCase__    )  -> Optional[Any]:





           '''simple docstring'''
           A_		   = FlaxViTModel(UpperCamelCase__    )
           A_		   = FlaxBertModel(UpperCamelCase__    )
           return vision_model, text_model







    def    snake_case_     (   self    )  -> str:





           '''simple docstring'''
           A_		   = FlaxViTModelTester(self    )
           A_		   = FlaxBertModelTester(self    )
           A_		   = vit_model_tester.prepare_config_and_inputs()
           A_		   = bert_model_tester.prepare_config_and_inputs()

           A_   ,     A_		   = vision_config_and_inputs

           A_   ,     A_   ,     A_   ,     A_		   = text_config_and_inputs

           # make sure that cross attention layers are added
           return {
               "text_config": text_config,
               "vision_config": vision_config,
               "pixel_values": pixel_values,
               "attention_mask": attention_mask,
               "input_ids": input_ids,
               "token_type_ids": token_type_ids,
           }


@require_torch
class    A__ ( _snake_case  ,  unittest.TestCase     ):



    def    snake_case_     (   self    )  -> Any:





           '''simple docstring'''
           A_		   = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
               """hf-internal-testing/tiny-random-clip"""						,			"""hf-internal-testing/tiny-bert"""						,			vision_from_pt=UpperCamelCase__						,			text_from_pt=UpperCamelCase__						,			)
           A_		   = 13
           A_		   = floats_tensor(
               [
                   batch_size,
                   model.config.vision_config.num_channels,
                   model.config.vision_config.image_size,
                   model.config.vision_config.image_size,
               ]    )
           A_		   = ids_tensor([batch_size, 4]						,			model.config.text_config.vocab_size    )
           A_		   = random_attention_mask([batch_size, 4]    )
           A_		   = {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

           return model, inputs



    def    snake_case_     (   self						,			UpperCamelCase__						,			UpperCamelCase__    )  -> Union[str, Any]:





           '''simple docstring'''
           A_		   = FlaxCLIPVisionModel(UpperCamelCase__    )
           A_		   = FlaxBertModel(UpperCamelCase__    )
           return vision_model, text_model







    def    snake_case_     (   self    )  -> List[Any]:





           '''simple docstring'''
           A_		   = FlaxCLIPVisionModelTester(self    )
           A_		   = FlaxBertModelTester(self    )
           A_		   = clip_model_tester.prepare_config_and_inputs()
           A_		   = bert_model_tester.prepare_config_and_inputs()

           A_   ,     A_		   = vision_config_and_inputs

           A_   ,     A_   ,     A_   ,     A_		   = text_config_and_inputs

           # make sure that cross attention layers are added
           return {
               "text_config": text_config,
               "vision_config": vision_config,
               "pixel_values": pixel_values,
               "attention_mask": attention_mask,
               "input_ids": input_ids,
               "token_type_ids": token_type_ids,
           }


@require_flax
@require_vision
class    A__ ( unittest.TestCase     ):



    @slow
    def    snake_case_     (   self    )  -> Dict:





           '''simple docstring'''
           A_		   = FlaxVisionTextDualEncoderModel.from_pretrained("""clip-italian/clip-italian"""						,			logit_scale_init_value=1.0    )
           A_		   = VisionTextDualEncoderProcessor.from_pretrained("""clip-italian/clip-italian"""    )

           A_		   = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    )
           A_		   = processor(
               text=["""una foto di un gatto""", """una foto di un cane"""]						,			images=UpperCamelCase__						,			padding=UpperCamelCase__						,			return_tensors="""np"""    )

           A_		   = model(**UpperCamelCase__    )

           # verify the logits
           self.assertEqual(outputs.logits_per_image.shape						,			(inputs.pixel_values.shape[0], inputs.input_ids.shape[0])    )
           self.assertEqual(
               outputs.logits_per_text.shape						,			(inputs.input_ids.shape[0], inputs.pixel_values.shape[0])						,			)

           A_		   = np.array([[1.2284727, 0.3104122]]    )

           self.assertTrue(np.allclose(outputs.logits_per_image						,			UpperCamelCase__						,			atol=1e-3    )    )



'''simple docstring'''







import unittest

from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin


__lowerCamelCase						    =      get_tests_dir('''fixtures/test_sentencepiece.model''')


@require_sentencepiece
@require_tokenizers
class    A__ ( _snake_case  ,  unittest.TestCase     ):
    lowercase		   =						ReformerTokenizer
    lowercase		   =						ReformerTokenizerFast
    lowercase		   =						True
    lowercase		   =						False
    lowercase		   =						True



    def    snake_case_     (   self    )  -> str:





           '''simple docstring'''
           super().setUp()

           A_		   = ReformerTokenizer(UpperCamelCase__						,			keep_accents=UpperCamelCase__    )
           tokenizer.save_pretrained(self.tmpdirname    )



    def    snake_case_     (   self    )  -> Union[str, Any]:





           '''simple docstring'''
           A_		   = """<s>"""
           A_		   = 1

           self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCamelCase__    )						,			UpperCamelCase__    )
           self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCamelCase__    )						,			UpperCamelCase__    )



    def    snake_case_     (   self    )  -> Tuple:





           '''simple docstring'''
           A_		   = list(self.get_tokenizer().get_vocab().keys()    )

           self.assertEqual(vocab_keys[0]						,			"""<unk>"""    )
           self.assertEqual(vocab_keys[1]						,			"""<s>"""    )
           self.assertEqual(vocab_keys[-1]						,			"""j"""    )
           self.assertEqual(len(UpperCamelCase__    )						,			1000    )



    def    snake_case_     (   self    )  -> Dict:





           '''simple docstring'''
           self.assertEqual(self.get_tokenizer().vocab_size						,			1000    )



    def    snake_case_     (   self    )  -> Union[str, Any]:





           '''simple docstring'''
           if not self.test_rust_tokenizer:
                  return

           A_		   = self.get_tokenizer()
           A_		   = self.get_rust_tokenizer()

           A_		   = """I was born in 92000, and this is falsé."""

           A_		   = tokenizer.tokenize(UpperCamelCase__    )
           A_		   = rust_tokenizer.tokenize(UpperCamelCase__    )
           self.assertListEqual(UpperCamelCase__						,			UpperCamelCase__    )

           A_		   = tokenizer.encode(UpperCamelCase__						,			add_special_tokens=UpperCamelCase__    )
           A_		   = rust_tokenizer.encode(UpperCamelCase__						,			add_special_tokens=UpperCamelCase__    )
           self.assertListEqual(UpperCamelCase__						,			UpperCamelCase__    )

           A_		   = self.get_rust_tokenizer()
           A_		   = tokenizer.encode(UpperCamelCase__    )
           A_		   = rust_tokenizer.encode(UpperCamelCase__    )
           self.assertListEqual(UpperCamelCase__						,			UpperCamelCase__    )



    def    snake_case_     (   self						,			UpperCamelCase__=15    )  -> int:





           '''simple docstring'''
           for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
                  with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})'''    ):
                         A_		   = self.rust_tokenizer_class.from_pretrained(UpperCamelCase__						,			**UpperCamelCase__    )

                         # Simple input
                         A_		   = """This is a simple input"""
                         A_		   = ["""This is a simple input 1""", """This is a simple input 2"""]
                         A_		   = ("""This is a simple input""", """This is a pair""")
                         A_		   = [
                             ("""This is a simple input 1""", """This is a simple input 2"""),
                             ("""This is a simple pair 1""", """This is a simple pair 2"""),
                         ]

                         # Simple input tests
                         self.assertRaises(UpperCamelCase__						,			tokenizer_r.encode						,			UpperCamelCase__						,			max_length=UpperCamelCase__						,			padding="""max_length"""    )

                         # Simple input
                         self.assertRaises(UpperCamelCase__						,			tokenizer_r.encode_plus						,			UpperCamelCase__						,			max_length=UpperCamelCase__						,			padding="""max_length"""    )

                         # Simple input
                         self.assertRaises(
                             UpperCamelCase__						,			tokenizer_r.batch_encode_plus						,			UpperCamelCase__						,			max_length=UpperCamelCase__						,			padding="""max_length"""						,			)

                         # Pair input
                         self.assertRaises(UpperCamelCase__						,			tokenizer_r.encode						,			UpperCamelCase__						,			max_length=UpperCamelCase__						,			padding="""max_length"""    )

                         # Pair input
                         self.assertRaises(UpperCamelCase__						,			tokenizer_r.encode_plus						,			UpperCamelCase__						,			max_length=UpperCamelCase__						,			padding="""max_length"""    )

                         # Pair input
                         self.assertRaises(
                             UpperCamelCase__						,			tokenizer_r.batch_encode_plus						,			UpperCamelCase__						,			max_length=UpperCamelCase__						,			padding="""max_length"""						,			)



    def    snake_case_     (   self    )  -> Optional[Any]:





           '''simple docstring'''
           pass



    def    snake_case_     (   self    )  -> Union[str, Any]:





           '''simple docstring'''
           A_		   = ReformerTokenizer(UpperCamelCase__						,			keep_accents=UpperCamelCase__    )

           A_		   = tokenizer.tokenize("""This is a test"""    )
           self.assertListEqual(UpperCamelCase__						,			["""▁This""", """▁is""", """▁a""", """▁t""", """est"""]    )

           self.assertListEqual(
               tokenizer.convert_tokens_to_ids(UpperCamelCase__    )						,			[285, 46, 10, 170, 382]						,			)

           A_		   = tokenizer.tokenize("""I was born in 92000, and this is falsé."""    )
           self.assertListEqual(
               UpperCamelCase__						,			[
                   SPIECE_UNDERLINE + """I""",
                   SPIECE_UNDERLINE + """was""",
                   SPIECE_UNDERLINE + """b""",
                   """or""",
                   """n""",
                   SPIECE_UNDERLINE + """in""",
                   SPIECE_UNDERLINE + """""",
                   """9""",
                   """2""",
                   """0""",
                   """0""",
                   """0""",
                   """,""",
                   SPIECE_UNDERLINE + """and""",
                   SPIECE_UNDERLINE + """this""",
                   SPIECE_UNDERLINE + """is""",
                   SPIECE_UNDERLINE + """f""",
                   """al""",
                   """s""",
                   """é""",
                   """.""",
               ]						,			)
           A_		   = tokenizer.convert_tokens_to_ids(UpperCamelCase__    )
           self.assertListEqual(
               UpperCamelCase__						,			[8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4]						,			)

           A_		   = tokenizer.convert_ids_to_tokens(UpperCamelCase__    )
           self.assertListEqual(
               UpperCamelCase__						,			[
                   SPIECE_UNDERLINE + """I""",
                   SPIECE_UNDERLINE + """was""",
                   SPIECE_UNDERLINE + """b""",
                   """or""",
                   """n""",
                   SPIECE_UNDERLINE + """in""",
                   SPIECE_UNDERLINE + """""",
                   """<unk>""",
                   """2""",
                   """0""",
                   """0""",
                   """0""",
                   """,""",
                   SPIECE_UNDERLINE + """and""",
                   SPIECE_UNDERLINE + """this""",
                   SPIECE_UNDERLINE + """is""",
                   SPIECE_UNDERLINE + """f""",
                   """al""",
                   """s""",
                   """<unk>""",
                   """.""",
               ]						,			)



    @cached_property
    def    snake_case_     (   self    )  -> Optional[int]:





           '''simple docstring'''
           return ReformerTokenizer.from_pretrained("""google/reformer-crime-and-punishment"""    )



    @slow
    def    snake_case_     (   self    )  -> Dict:





           '''simple docstring'''
           A_		   = """Hello World!"""
           A_		   = [126, 32, 262, 152, 38, 72, 287]

           self.assertListEqual(UpperCamelCase__						,			self.big_tokenizer.encode(UpperCamelCase__    )    )



    @slow
    def    snake_case_     (   self    )  -> Any:





           '''simple docstring'''
           A_		   = (
               """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will"""
               """ add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth"""
           )
           A_		   = [
               108,
               265,
               24,
               111,
               4,
               258,
               156,
               35,
               28,
               275,
               3,
               259,
               297,
               260,
               84,
               4,
               35,
               110,
               44,
               8,
               259,
               91,
               268,
               21,
               11,
               209,
               274,
               109,
               266,
               277,
               117,
               86,
               93,
               315,
               258,
               278,
               258,
               277,
               258,
               0,
               258,
               288,
               258,
               319,
               258,
               0,
               258,
               0,
               258,
               0,
               258,
               0,
               258,
               287,
               258,
               315,
               258,
               289,
               258,
               278,
               99,
               269,
               266,
               262,
               8,
               259,
               241,
               4,
               217,
               230,
               268,
               266,
               55,
               168,
               106,
               75,
               193,
               266,
               223,
               27,
               49,
               26,
               282,
               25,
               264,
               299,
               19,
               26,
               0,
               258,
               277,
               117,
               86,
               93,
               176,
               183,
               270,
               11,
               262,
               42,
               61,
               265,
           ]

           self.assertListEqual(UpperCamelCase__						,			self.big_tokenizer.encode(UpperCamelCase__    )    )



    @require_torch
    @slow
    def    snake_case_     (   self    )  -> str:





           '''simple docstring'''
           import torch

           from transformers import ReformerConfig, ReformerModel

           # Build sequence
           A_		   = list(self.big_tokenizer.get_vocab().keys()    )[:10]
           A_		   = """ """.join(UpperCamelCase__    )
           A_		   = self.big_tokenizer.encode_plus(UpperCamelCase__						,			return_tensors="""pt"""    )
           A_		   = self.big_tokenizer.batch_encode_plus([sequence, sequence]						,			return_tensors="""pt"""    )

           A_		   = ReformerConfig()
           # The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024)
           A_		   = encoded_sequence["""input_ids"""].shape
           A_		   = ReformerModel(UpperCamelCase__    )

           # Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320)
           assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size

           with torch.no_grad():
                  model(**UpperCamelCase__    )
                  model(**UpperCamelCase__    )







    @slow
    def    snake_case_     (   self    )  -> Optional[int]:





           '''simple docstring'''
           # fmt: off
           A_		   = {"""input_ids""": [[108, 265, 24, 111, 4, 258, 156, 7, 51, 279, 58, 7, 76, 25, 69, 278], [140, 243, 264, 134, 17, 267, 77, 263, 22, 262, 297, 258, 304, 177, 279, 266, 14, 89, 13, 35, 261, 299, 272, 137, 275, 278]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]}  # noqa: E501
           # fmt: on

           # This tokenizer does not know some characters like ")".
           # That is the reason why we use very simple texts here.
           # Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064
           A_		   = [
               """This is a very simple sentence.""",
               """The quick brown fox jumps over the lazy dog.""",
           ]

           self.tokenizer_integration_test_util(
               expected_encoding=UpperCamelCase__						,			model_name="""google/reformer-crime-and-punishment"""						,			revision="""0e6c3decb8211d49bf881013425dc8b0448b3f5a"""						,			padding=UpperCamelCase__						,			sequences=UpperCamelCase__						,			)
