





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     SCREAMING_SNAKE_CASE			(      lowerCAmelCase					):
       if isinstance(lowerCAmelCase    ,       collections.abc.Iterable					):
              return x
       return (x, x)

@require_flax
class  __A:

     def 	_UpperCamelCase     (      self,       A,       A      ):





            """simple docstring"""

            pass

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            pass

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            pass

     def 	_UpperCamelCase     (      self,       A,       A,       A      ):





            """simple docstring"""

            _UpperCamelCase              =						np.abs((a - b)      ).max()
            self.assertLessEqual(A,       A,       F'''Difference between torch and flax is {diff} (>= {tol}).'''      )

     def 	_UpperCamelCase     (      self,       A,       A,       A,       A,       A=None,       **A      ):





            """simple docstring"""

            _UpperCamelCase              =						VisionTextDualEncoderConfig.from_vision_text_configs(A,       A      )

            _UpperCamelCase              =						FlaxVisionTextDualEncoderModel(A      )

            _UpperCamelCase              =						model(input_ids=A,       pixel_values=A,       attention_mask=A      )

            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 	_UpperCamelCase     (      self,       A,       A,       A,       A,       A=None,       **A      ):





            """simple docstring"""

            _UpperCamelCase       ,		_UpperCamelCase              =						self.get_vision_text_model(A,       A      )
            _UpperCamelCase              =						{'''vision_model''': vision_model, '''text_model''': text_model}
            _UpperCamelCase              =						FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**A      )

            _UpperCamelCase              =						model(input_ids=A,       pixel_values=A,       attention_mask=A      )

            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 	_UpperCamelCase     (      self,       A,       A,       A,       A,       A=None,       **A      ):





            """simple docstring"""

            _UpperCamelCase       ,		_UpperCamelCase              =						self.get_vision_text_model(A,       A      )
            _UpperCamelCase              =						{'''vision_model''': vision_model, '''text_model''': text_model}
            _UpperCamelCase              =						FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**A      )

            _UpperCamelCase              =						model(input_ids=A,       pixel_values=A,       attention_mask=A      )
            _UpperCamelCase              =						output[0]

            with tempfile.TemporaryDirectory() as tmpdirname:
                   model.save_pretrained(A      )
                   _UpperCamelCase              =						FlaxVisionTextDualEncoderModel.from_pretrained(A      )

                   _UpperCamelCase              =						model(input_ids=A,       pixel_values=A,       attention_mask=A      )
                   _UpperCamelCase              =						after_output[0]
                   _UpperCamelCase              =						np.amax(np.abs(out_a - out_a      )      )
                   self.assertLessEqual(A,       1E-3      )

     def 	_UpperCamelCase     (      self,       A,       A,       A,       A,       A=None,       **A      ):





            """simple docstring"""

            _UpperCamelCase       ,		_UpperCamelCase              =						self.get_vision_text_model(A,       A      )
            _UpperCamelCase              =						{'''vision_model''': vision_model, '''text_model''': text_model}
            _UpperCamelCase              =						FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**A      )

            _UpperCamelCase              =						model(
                input_ids=A,       pixel_values=A,       attention_mask=A,       output_attentions=A      )

            _UpperCamelCase              =						output.vision_model_output.attentions
            self.assertEqual(len(A      ),       vision_config.num_hidden_layers      )

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

            _UpperCamelCase              =						output.text_model_output.attentions
            self.assertEqual(len(A      ),       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 	_UpperCamelCase     (      self,       A,       A,       A      ):





            """simple docstring"""

            pt_model.to(A      )
            pt_model.eval()

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

            with torch.no_grad():
                   _UpperCamelCase              =						pt_model(**A      ).to_tuple()

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

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

            _UpperCamelCase              =						fx_model_loaded(**A      ).to_tuple()
            self.assertEqual(len(A      ),       len(A      ),       '''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(A,       pt_output.numpy(),       4E-2      )

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

            pt_model_loaded.to(A      )
            pt_model_loaded.eval()

            with torch.no_grad():
                   _UpperCamelCase              =						pt_model_loaded(**A      ).to_tuple()

            self.assertEqual(len(A      ),       len(A      ),       '''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(A,       pt_output_loaded.numpy(),       4E-2      )

     def 	_UpperCamelCase     (      self,       A,       A,       A      ):





            """simple docstring"""

            _UpperCamelCase              =						VisionTextDualEncoderConfig.from_vision_text_configs(A,       A      )

            _UpperCamelCase              =						VisionTextDualEncoderModel(A      )
            _UpperCamelCase              =						FlaxVisionTextDualEncoderModel(A      )

            _UpperCamelCase              =						convert_pytorch_state_dict_to_flax(pt_model.state_dict(),       A      )
            _UpperCamelCase              =						fx_state

            self.check_pt_flax_equivalence(A,       A,       A      )

     def 	_UpperCamelCase     (      self,       A,       A,       A      ):





            """simple docstring"""

            _UpperCamelCase              =						VisionTextDualEncoderConfig.from_vision_text_configs(A,       A      )

            _UpperCamelCase              =						VisionTextDualEncoderModel(A      )
            _UpperCamelCase              =						FlaxVisionTextDualEncoderModel(A      )

            _UpperCamelCase              =						load_flax_weights_in_pytorch_model(A,       fx_model.params      )

            self.check_pt_flax_equivalence(A,       A,       A      )

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						self.prepare_config_and_inputs()
            self.check_model_from_pretrained_configs(**A      )

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						self.prepare_config_and_inputs()
            self.check_vision_text_dual_encoder_from_pretrained(**A      )

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						self.prepare_config_and_inputs()
            self.check_save_load(**A      )

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						self.prepare_config_and_inputs()
            self.check_vision_text_output_attention(**A      )

     @is_pt_flax_cross_test
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						self.prepare_config_and_inputs()
            _UpperCamelCase              =						config_inputs_dict.pop('''vision_config'''      )
            _UpperCamelCase              =						config_inputs_dict.pop('''text_config'''      )

            _UpperCamelCase              =						config_inputs_dict

            self.check_equivalence_pt_to_flax(A,       A,       A      )
            self.check_equivalence_flax_to_pt(A,       A,       A      )



     @slow
     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase       ,		_UpperCamelCase              =						self.get_pretrained_model_and_inputs()

            _UpperCamelCase              =						model_a(**A      )
            _UpperCamelCase              =						outputs[0]

            with tempfile.TemporaryDirectory() as tmp_dirname:
                   model_a.save_pretrained(A      )
                   _UpperCamelCase              =						FlaxVisionTextDualEncoderModel.from_pretrained(A      )

                   _UpperCamelCase              =						model_a(**A      )
                   _UpperCamelCase              =						after_outputs[0]
                   _UpperCamelCase              =						np.amax(np.abs(out_a - out_a      )      )
                   self.assertLessEqual(A,       1E-5      )






@require_flax
class  __A(						__UpperCAmelCase						,			unittest.TestCase ):

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

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

            return model, inputs

     def 	_UpperCamelCase     (      self,       A,       A      ):





            """simple docstring"""

            _UpperCamelCase              =						FlaxViTModel(A      )
            _UpperCamelCase              =						FlaxBertModel(A      )
            return vision_model, text_model



     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						FlaxViTModelTester(self      )
            _UpperCamelCase              =						FlaxBertModelTester(self      )
            _UpperCamelCase              =						vit_model_tester.prepare_config_and_inputs()
            _UpperCamelCase              =						bert_model_tester.prepare_config_and_inputs()

            _UpperCamelCase       ,		_UpperCamelCase              =						vision_config_and_inputs

            _UpperCamelCase       ,		_UpperCamelCase       ,		_UpperCamelCase       ,		_UpperCamelCase              =						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(						__UpperCAmelCase						,			unittest.TestCase ):

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

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

            return model, inputs

     def 	_UpperCamelCase     (      self,       A,       A      ):





            """simple docstring"""

            _UpperCamelCase              =						FlaxCLIPVisionModel(A      )
            _UpperCamelCase              =						FlaxBertModel(A      )
            return vision_model, text_model



     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						FlaxCLIPVisionModelTester(self      )
            _UpperCamelCase              =						FlaxBertModelTester(self      )
            _UpperCamelCase              =						clip_model_tester.prepare_config_and_inputs()
            _UpperCamelCase              =						bert_model_tester.prepare_config_and_inputs()

            _UpperCamelCase       ,		_UpperCamelCase              =						vision_config_and_inputs

            _UpperCamelCase       ,		_UpperCamelCase       ,		_UpperCamelCase       ,		_UpperCamelCase              =						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 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						FlaxVisionTextDualEncoderModel.from_pretrained('''clip-italian/clip-italian''',       logit_scale_init_value=1.0      )
            _UpperCamelCase              =						VisionTextDualEncoderProcessor.from_pretrained('''clip-italian/clip-italian'''      )

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

            _UpperCamelCase              =						model(**A      )

            # 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]),       )

            _UpperCamelCase              =						np.array([[1.2_284_727, 0.3_104_122]]      )

            self.assertTrue(np.allclose(outputs.logits_per_image,       A,       atol=1E-3      )      )













import os
from shutil import copyfile
from typing import List, Optional, Tuple

from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
       from .tokenization_big_bird import BigBirdTokenizer
else:
       lowercase    : Union[str, Any]    	=  None

lowercase    : Union[str, Any]    	=  logging.get_logger(__name__)
lowercase    : Tuple    	=  {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""}

lowercase    : Any    	=  {
    """vocab_file""": {
        """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model""",
        """google/bigbird-roberta-large""": (
            """https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model"""
        ),
        """google/bigbird-base-trivia-itc""": (
            """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model"""
        ),
    },
    """tokenizer_file""": {
        """google/bigbird-roberta-base""": (
            """https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json"""
        ),
        """google/bigbird-roberta-large""": (
            """https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json"""
        ),
        """google/bigbird-base-trivia-itc""": (
            """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json"""
        ),
    },
}

lowercase    : Tuple    	=  {
    """google/bigbird-roberta-base""": 4096,
    """google/bigbird-roberta-large""": 4096,
    """google/bigbird-base-trivia-itc""": 4096,
}


lowercase    : List[str]    	=  """▁"""

class  __A(						__UpperCAmelCase ):
     __A	  =       VOCAB_FILES_NAMES
     __A	  =       PRETRAINED_VOCAB_FILES_MAP
     __A	  =       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     __A	  =       BigBirdTokenizer
     __A	  =       ["input_ids", "attention_mask"]
     __A	  =       []

     def __init__(      self,       A=None,       A=None,       A="<unk>",       A="<s>",       A="</s>",       A="<pad>",       A="[SEP]",       A="[MASK]",       A="[CLS]",       **A,       ):





            """simple docstring"""

            _UpperCamelCase              =						AddedToken(A,       lstrip=A,       rstrip=A      ) if isinstance(A,       A      ) else bos_token
            _UpperCamelCase              =						AddedToken(A,       lstrip=A,       rstrip=A      ) if isinstance(A,       A      ) else eos_token
            _UpperCamelCase              =						AddedToken(A,       lstrip=A,       rstrip=A      ) if isinstance(A,       A      ) else unk_token
            _UpperCamelCase              =						AddedToken(A,       lstrip=A,       rstrip=A      ) if isinstance(A,       A      ) else pad_token
            _UpperCamelCase              =						AddedToken(A,       lstrip=A,       rstrip=A      ) if isinstance(A,       A      ) else cls_token
            _UpperCamelCase              =						AddedToken(A,       lstrip=A,       rstrip=A      ) if isinstance(A,       A      ) else sep_token

            # Mask token behave like a normal word, i.e. include the space before it
            _UpperCamelCase              =						AddedToken(A,       lstrip=A,       rstrip=A      ) if isinstance(A,       A      ) else mask_token

            super().__init__(
                A,       tokenizer_file=A,       bos_token=A,       eos_token=A,       unk_token=A,       sep_token=A,       pad_token=A,       cls_token=A,       mask_token=A,       **A,       )

            _UpperCamelCase              =						vocab_file
            _UpperCamelCase              =						False if not self.vocab_file else True

     def 	_UpperCamelCase     (      self,       A,       A = None      ):





            """simple docstring"""

            _UpperCamelCase              =						[self.sep_token_id]
            _UpperCamelCase              =						[self.cls_token_id]
            if token_ids_a is None:
                   return cls + token_ids_a + sep
            return cls + token_ids_a + sep + token_ids_a + sep

     def 	_UpperCamelCase     (      self,       A,       A = None,       A = False      ):





            """simple docstring"""

            if already_has_special_tokens:
                   if token_ids_a is not None:
                          raise ValueError(
                              '''You should not supply a second sequence if the provided sequence of '''
                              '''ids is already formatted with special tokens for the model.'''      )
                   return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]

            if token_ids_a is None:
                   return [1] + ([0] * len(A      )) + [1]
            return [1] + ([0] * len(A      )) + [1] + ([0] * len(A      )) + [1]

     def 	_UpperCamelCase     (      self,       A,       A = None      ):





            """simple docstring"""

            _UpperCamelCase              =						[self.sep_token_id]
            _UpperCamelCase              =						[self.cls_token_id]

            if token_ids_a is None:
                   return len(cls + token_ids_a + sep      ) * [0]
            return len(cls + token_ids_a + sep      ) * [0] + len(token_ids_a + sep      ) * [1]



     def 	_UpperCamelCase     (      self,       A,       A = None      ):





            """simple docstring"""

            if not self.can_save_slow_tokenizer:
                   raise ValueError(
                       '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow '''
                       '''tokenizer.'''      )

            if not os.path.isdir(A      ):
                   logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''      )
                   return
            _UpperCamelCase              =						os.path.join(
                A,       (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']      )

            if os.path.abspath(self.vocab_file      ) != os.path.abspath(A      ):
                   copyfile(self.vocab_file,       A      )

            return (out_vocab_file,)






