





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__				(		lowerCAmelCase  ):





      """simple docstring"""


      if isinstance(lowerCAmelCase							,     collections.abc.Iterable  ):
            return x
      return (x, x)




@require_flax
class 			UpperCAmelCase					:




      def     lowercase__   (      self      :			Any      ,      __snake_case      :			Optional[int]      ,      __snake_case      :			Optional[int]  )    ->				Optional[int]:
            pass




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




      def     lowercase__   (      self      :			int  )    ->				Tuple:
            pass




      def     lowercase__   (      self      :			Optional[int]      ,      __snake_case      :			np.ndarray      ,      __snake_case      :			np.ndarray      ,      __snake_case      :			float  )    ->				Dict:
            _lowerCAmelCase												=							np.abs((a - b)  ).max()
            self.assertLessEqual(__snake_case      ,      __snake_case      ,      f"Difference between torch and flax is {diff} (>= {tol})."  )




      def     lowercase__   (      self      :			Optional[Any]      ,      __snake_case      :			List[Any]      ,      __snake_case      :			Tuple      ,      __snake_case      :			Any      ,      __snake_case      :			Tuple      ,      __snake_case      :			Dict=None      ,      **__snake_case      :			int  )    ->				List[str]:
            _lowerCAmelCase												=							VisionTextDualEncoderConfig.from_vision_text_configs(__snake_case      ,      __snake_case  )

            _lowerCAmelCase												=							FlaxVisionTextDualEncoderModel(__snake_case  )

            _lowerCAmelCase												=							model(input_ids=__snake_case      ,      pixel_values=__snake_case      ,      attention_mask=__snake_case  )

            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     lowercase__   (      self      :			Tuple      ,      __snake_case      :			str      ,      __snake_case      :			Dict      ,      __snake_case      :			List[str]      ,      __snake_case      :			int      ,      __snake_case      :			Optional[int]=None      ,      **__snake_case      :			str  )    ->				Tuple:
            _lowerCAmelCase												=							self.get_vision_text_model(__snake_case      ,      __snake_case  )
            _lowerCAmelCase												=							{'vision_model': vision_model, 'text_model': text_model}
            _lowerCAmelCase												=							FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__snake_case  )

            _lowerCAmelCase												=							model(input_ids=__snake_case      ,      pixel_values=__snake_case      ,      attention_mask=__snake_case  )

            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     lowercase__   (      self      :			str      ,      __snake_case      :			List[Any]      ,      __snake_case      :			Tuple      ,      __snake_case      :			Dict      ,      __snake_case      :			Optional[Any]      ,      __snake_case      :			Any=None      ,      **__snake_case      :			List[str]  )    ->				Any:
            _lowerCAmelCase												=							self.get_vision_text_model(__snake_case      ,      __snake_case  )
            _lowerCAmelCase												=							{'vision_model': vision_model, 'text_model': text_model}
            _lowerCAmelCase												=							FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__snake_case  )

            _lowerCAmelCase												=							model(input_ids=__snake_case      ,      pixel_values=__snake_case      ,      attention_mask=__snake_case  )
            _lowerCAmelCase												=							output[0]

            with tempfile.TemporaryDirectory() as tmpdirname:
                  model.save_pretrained(__snake_case  )
                  _lowerCAmelCase												=							FlaxVisionTextDualEncoderModel.from_pretrained(__snake_case  )

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




      def     lowercase__   (      self      :			Optional[Any]      ,      __snake_case      :			int      ,      __snake_case      :			List[str]      ,      __snake_case      :			Any      ,      __snake_case      :			str      ,      __snake_case      :			List[str]=None      ,      **__snake_case      :			str  )    ->				List[Any]:
            _lowerCAmelCase												=							self.get_vision_text_model(__snake_case      ,      __snake_case  )
            _lowerCAmelCase												=							{'vision_model': vision_model, 'text_model': text_model}
            _lowerCAmelCase												=							FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__snake_case  )

            _lowerCAmelCase												=							model(
                input_ids=__snake_case      ,      pixel_values=__snake_case      ,      attention_mask=__snake_case      ,      output_attentions=__snake_case  )

            _lowerCAmelCase												=							output.vision_model_output.attentions
            self.assertEqual(len(__snake_case  )      ,      vision_config.num_hidden_layers  )

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

            _lowerCAmelCase												=							output.text_model_output.attentions
            self.assertEqual(len(__snake_case  )      ,      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     lowercase__   (      self      :			Tuple      ,      __snake_case      :			Dict      ,      __snake_case      :			Any      ,      __snake_case      :			Optional[int]  )    ->				str:
            pt_model.to(__snake_case  )
            pt_model.eval()

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

            with torch.no_grad():
                  _lowerCAmelCase												=							pt_model(**__snake_case  ).to_tuple()

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

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

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

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

            pt_model_loaded.to(__snake_case  )
            pt_model_loaded.eval()

            with torch.no_grad():
                  _lowerCAmelCase												=							pt_model_loaded(**__snake_case  ).to_tuple()

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




      def     lowercase__   (      self      :			List[str]      ,      __snake_case      :			Optional[int]      ,      __snake_case      :			str      ,      __snake_case      :			Optional[Any]  )    ->				List[str]:
            _lowerCAmelCase												=							VisionTextDualEncoderConfig.from_vision_text_configs(__snake_case      ,      __snake_case  )

            _lowerCAmelCase												=							VisionTextDualEncoderModel(__snake_case  )
            _lowerCAmelCase												=							FlaxVisionTextDualEncoderModel(__snake_case  )

            _lowerCAmelCase												=							convert_pytorch_state_dict_to_flax(pt_model.state_dict()      ,      __snake_case  )
            _lowerCAmelCase												=							fx_state

            self.check_pt_flax_equivalence(__snake_case      ,      __snake_case      ,      __snake_case  )




      def     lowercase__   (      self      :			Any      ,      __snake_case      :			Union[str, Any]      ,      __snake_case      :			Dict      ,      __snake_case      :			Tuple  )    ->				List[Any]:
            _lowerCAmelCase												=							VisionTextDualEncoderConfig.from_vision_text_configs(__snake_case      ,      __snake_case  )

            _lowerCAmelCase												=							VisionTextDualEncoderModel(__snake_case  )
            _lowerCAmelCase												=							FlaxVisionTextDualEncoderModel(__snake_case  )

            _lowerCAmelCase												=							load_flax_weights_in_pytorch_model(__snake_case      ,      fx_model.params  )

            self.check_pt_flax_equivalence(__snake_case      ,      __snake_case      ,      __snake_case  )




      def     lowercase__   (      self      :			List[str]  )    ->				Dict:
            _lowerCAmelCase												=							self.prepare_config_and_inputs()
            self.check_model_from_pretrained_configs(**__snake_case  )




      def     lowercase__   (      self      :			str  )    ->				Tuple:
            _lowerCAmelCase												=							self.prepare_config_and_inputs()
            self.check_vision_text_dual_encoder_from_pretrained(**__snake_case  )




      def     lowercase__   (      self      :			Optional[int]  )    ->				List[str]:
            _lowerCAmelCase												=							self.prepare_config_and_inputs()
            self.check_save_load(**__snake_case  )




      def     lowercase__   (      self      :			Dict  )    ->				Union[str, Any]:
            _lowerCAmelCase												=							self.prepare_config_and_inputs()
            self.check_vision_text_output_attention(**__snake_case  )




      @is_pt_flax_cross_test
      def     lowercase__   (      self      :			List[Any]  )    ->				str:
            _lowerCAmelCase												=							self.prepare_config_and_inputs()
            _lowerCAmelCase												=							config_inputs_dict.pop("""vision_config"""  )
            _lowerCAmelCase												=							config_inputs_dict.pop("""text_config"""  )

            _lowerCAmelCase												=							config_inputs_dict

            self.check_equivalence_pt_to_flax(__snake_case      ,      __snake_case      ,      __snake_case  )
            self.check_equivalence_flax_to_pt(__snake_case      ,      __snake_case      ,      __snake_case  )




      @slow
      def     lowercase__   (      self      :			Optional[int]  )    ->				Union[str, Any]:
            _lowerCAmelCase												=							self.get_pretrained_model_and_inputs()

            _lowerCAmelCase												=							model_a(**__snake_case  )
            _lowerCAmelCase												=							outputs[0]

            with tempfile.TemporaryDirectory() as tmp_dirname:
                  model_a.save_pretrained(__snake_case  )
                  _lowerCAmelCase												=							FlaxVisionTextDualEncoderModel.from_pretrained(__snake_case  )

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




@require_flax
class 			UpperCAmelCase					(      snake_case_							,		unittest.TestCase       ):




      def     lowercase__   (      self      :			Optional[Any]  )    ->				Optional[Any]:
            _lowerCAmelCase												=							FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
                """hf-internal-testing/tiny-random-vit"""      ,      """hf-internal-testing/tiny-bert"""      ,      vision_from_pt=__snake_case      ,      text_from_pt=__snake_case      ,      )
            _lowerCAmelCase												=							13
            _lowerCAmelCase												=							floats_tensor(
                [
                    batch_size,
                    model.config.vision_config.num_channels,
                    model.config.vision_config.image_size,
                    model.config.vision_config.image_size,
                ]  )
            _lowerCAmelCase												=							ids_tensor([batch_size, 4]      ,      model.config.text_config.vocab_size  )
            _lowerCAmelCase												=							random_attention_mask([batch_size, 4]  )
            _lowerCAmelCase												=							{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

            return model, inputs




      def     lowercase__   (      self      :			Tuple      ,      __snake_case      :			Union[str, Any]      ,      __snake_case      :			int  )    ->				Tuple:
            _lowerCAmelCase												=							FlaxViTModel(__snake_case  )
            _lowerCAmelCase												=							FlaxBertModel(__snake_case  )
            return vision_model, text_model




      def     lowercase__   (      self      :			Optional[int]  )    ->				Optional[int]:
            _lowerCAmelCase												=							FlaxViTModelTester(self  )
            _lowerCAmelCase												=							FlaxBertModelTester(self  )
            _lowerCAmelCase												=							vit_model_tester.prepare_config_and_inputs()
            _lowerCAmelCase												=							bert_model_tester.prepare_config_and_inputs()

            _lowerCAmelCase												=							vision_config_and_inputs

            _lowerCAmelCase												=							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 			UpperCAmelCase					(      snake_case_							,		unittest.TestCase       ):




      def     lowercase__   (      self      :			List[str]  )    ->				List[Any]:
            _lowerCAmelCase												=							FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
                """hf-internal-testing/tiny-random-clip"""      ,      """hf-internal-testing/tiny-bert"""      ,      vision_from_pt=__snake_case      ,      text_from_pt=__snake_case      ,      )
            _lowerCAmelCase												=							13
            _lowerCAmelCase												=							floats_tensor(
                [
                    batch_size,
                    model.config.vision_config.num_channels,
                    model.config.vision_config.image_size,
                    model.config.vision_config.image_size,
                ]  )
            _lowerCAmelCase												=							ids_tensor([batch_size, 4]      ,      model.config.text_config.vocab_size  )
            _lowerCAmelCase												=							random_attention_mask([batch_size, 4]  )
            _lowerCAmelCase												=							{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

            return model, inputs




      def     lowercase__   (      self      :			Union[str, Any]      ,      __snake_case      :			Optional[int]      ,      __snake_case      :			int  )    ->				Any:
            _lowerCAmelCase												=							FlaxCLIPVisionModel(__snake_case  )
            _lowerCAmelCase												=							FlaxBertModel(__snake_case  )
            return vision_model, text_model




      def     lowercase__   (      self      :			Union[str, Any]  )    ->				List[Any]:
            _lowerCAmelCase												=							FlaxCLIPVisionModelTester(self  )
            _lowerCAmelCase												=							FlaxBertModelTester(self  )
            _lowerCAmelCase												=							clip_model_tester.prepare_config_and_inputs()
            _lowerCAmelCase												=							bert_model_tester.prepare_config_and_inputs()

            _lowerCAmelCase												=							vision_config_and_inputs

            _lowerCAmelCase												=							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 			UpperCAmelCase					(      unittest.TestCase       ):




      @slow
      def     lowercase__   (      self      :			str  )    ->				str:
            _lowerCAmelCase												=							FlaxVisionTextDualEncoderModel.from_pretrained("""clip-italian/clip-italian"""      ,      logit_scale_init_value=1.0  )
            _lowerCAmelCase												=							VisionTextDualEncoderProcessor.from_pretrained("""clip-italian/clip-italian"""  )

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

            _lowerCAmelCase												=							model(**__snake_case  )

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

            _lowerCAmelCase												=							np.array([[1.2_28_47_27, 0.3_10_41_22]]  )

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













'''simple docstring'''






import inspect
import os
import unittest

import torch

import accelerate
from accelerate import debug_launcher
from accelerate.test_utils import (
    execute_subprocess_async,
    require_cpu,
    require_huggingface_suite,
    require_multi_gpu,
    require_single_gpu,
)
from accelerate.utils import patch_environment




@require_huggingface_suite
class 			UpperCAmelCase					(      unittest.TestCase       ):




      def     lowercase__   (      self      :			int  )    ->				Union[str, Any]:
            _lowerCAmelCase												=							inspect.getfile(accelerate.test_utils  )
            _lowerCAmelCase												=							os.path.sep.join(
                mod_file.split(os.path.sep  )[:-1] + ["""scripts""", """external_deps""", """test_metrics.py"""]  )

            from accelerate.test_utils.scripts.external_deps import test_metrics  # noqa: F401

            _lowerCAmelCase												=							test_metrics




      @require_cpu
      def     lowercase__   (      self      :			Optional[Any]  )    ->				Optional[Any]:
            debug_launcher(self.test_metrics.main      ,      num_processes=1  )




      @require_cpu
      def     lowercase__   (      self      :			Tuple  )    ->				Tuple:
            debug_launcher(self.test_metrics.main  )




      @require_single_gpu
      def     lowercase__   (      self      :			Union[str, Any]  )    ->				str:
            self.test_metrics.main()




      @require_multi_gpu
      def     lowercase__   (      self      :			str  )    ->				List[str]:
            print(f"Found {torch.cuda.device_count()} devices."  )
            _lowerCAmelCase												=							["""torchrun""", f"--nproc_per_node={torch.cuda.device_count()}", self.test_file_path]
            with patch_environment(omp_num_threads=1  ):
                  execute_subprocess_async(__snake_case      ,      env=os.environ.copy()  )






