


'''simple docstring'''
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       _lowercase							(					UpperCamelCase__							:       Any      ):
 if isinstance(__snake_case,					collections.abc.Iterable      ):
  return x
 return (x, x)

@require_flax
class     _lowerCamelCase       :




 '''simple docstring'''


 def 			snake_case__ (   self   ,   __lowercase   ,   __lowercase    ):

  """simple docstring"""







  pass


 def 			snake_case__ (   self    ):

  """simple docstring"""







  pass


 def 			snake_case__ (   self    ):

  """simple docstring"""







  pass


 def 			snake_case__ (   self   ,   __lowercase   ,   __lowercase   ,   __lowercase    ):

  """simple docstring"""







  __A	:		Union[str, Any]	  =      np.abs((a - b)    ).max()
  self.assertLessEqual(UpperCamelCase__   ,   UpperCamelCase__   ,   F"""Difference between torch and flax is {diff} (>= {tol})."""    )


 def 			snake_case__ (   self   ,   __lowercase   ,   __lowercase   ,   __lowercase   ,   __lowercase   ,   __lowercase=None   ,   **__lowercase    ):

  """simple docstring"""







  __A	:		Optional[Any]	  =      VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase__   ,   UpperCamelCase__    )

  __A	:		Dict	  =      FlaxVisionTextDualEncoderModel(UpperCamelCase__    )

  __A	:		Optional[int]	  =      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   ,   __lowercase   ,   __lowercase   ,   __lowercase   ,   __lowercase   ,   __lowercase=None   ,   **__lowercase    ):

  """simple docstring"""







  __A  ,__A	:		Union[str, Any]	  =      self.get_vision_text_model(UpperCamelCase__   ,   UpperCamelCase__    )
  __A	:		int	  =      {'vision_model': vision_model, 'text_model': text_model}
  __A	:		Optional[Any]	  =      FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCamelCase__    )

  __A	:		Any	  =      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   ,   __lowercase   ,   __lowercase   ,   __lowercase   ,   __lowercase   ,   __lowercase=None   ,   **__lowercase    ):

  """simple docstring"""







  __A  ,__A	:		Union[str, Any]	  =      self.get_vision_text_model(UpperCamelCase__   ,   UpperCamelCase__    )
  __A	:		int	  =      {'vision_model': vision_model, 'text_model': text_model}
  __A	:		str	  =      FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCamelCase__    )

  __A	:		Optional[Any]	  =      model(input_ids=UpperCamelCase__   ,   pixel_values=UpperCamelCase__   ,   attention_mask=UpperCamelCase__    )
  __A	:		List[Any]	  =      output[0]

  with tempfile.TemporaryDirectory() as tmpdirname:
   model.save_pretrained(UpperCamelCase__    )
   __A	:		List[Any]	  =      FlaxVisionTextDualEncoderModel.from_pretrained(UpperCamelCase__    )

   __A	:		Tuple	  =      model(input_ids=UpperCamelCase__   ,   pixel_values=UpperCamelCase__   ,   attention_mask=UpperCamelCase__    )
   __A	:		List[str]	  =      after_output[0]
   __A	:		int	  =      np.amax(np.abs(out_a - out_a    )    )
   self.assertLessEqual(UpperCamelCase__   ,   1E-3    )


 def 			snake_case__ (   self   ,   __lowercase   ,   __lowercase   ,   __lowercase   ,   __lowercase   ,   __lowercase=None   ,   **__lowercase    ):

  """simple docstring"""







  __A  ,__A	:		Optional[int]	  =      self.get_vision_text_model(UpperCamelCase__   ,   UpperCamelCase__    )
  __A	:		int	  =      {'vision_model': vision_model, 'text_model': text_model}
  __A	:		List[Any]	  =      FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCamelCase__    )

  __A	:		str	  =      model(
      input_ids=UpperCamelCase__   ,   pixel_values=UpperCamelCase__   ,   attention_mask=UpperCamelCase__   ,   output_attentions=UpperCamelCase__    )

  __A	:		List[str]	  =      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	:		int	  =      to_atuple(vision_model.config.image_size    )
  __A	:		List[str]	  =      to_atuple(vision_model.config.patch_size    )
  __A	:		Any	  =      (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
  __A	:		Union[str, Any]	  =      num_patches + 1
  self.assertEqual(vision_attentions[0].shape[-3:]   ,   (vision_config.num_attention_heads, seq_len, seq_len)    )

  __A	:		Dict	  =      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   ,   __lowercase   ,   __lowercase   ,   __lowercase    ):

  """simple docstring"""







  pt_model.to(UpperCamelCase__    )
  pt_model.eval()

  # prepare inputs
  __A	:		Tuple	  =      inputs_dict
  __A	:		Optional[Any]	  =      {k: torch.tensor(v.tolist()    ) for k, v in flax_inputs.items()}

  with torch.no_grad():
   __A	:		Union[str, Any]	  =      pt_model(**UpperCamelCase__    ).to_tuple()

  __A	:		Tuple	  =      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	:		Optional[Any]	  =      FlaxVisionTextDualEncoderModel.from_pretrained(UpperCamelCase__   ,   from_pt=UpperCamelCase__    )

  __A	:		List[Any]	  =      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	:		str	  =      VisionTextDualEncoderModel.from_pretrained(UpperCamelCase__   ,   from_flax=UpperCamelCase__    )

  pt_model_loaded.to(UpperCamelCase__    )
  pt_model_loaded.eval()

  with torch.no_grad():
   __A	:		Any	  =      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   ,   __lowercase   ,   __lowercase   ,   __lowercase    ):

  """simple docstring"""







  __A	:		List[Any]	  =      VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase__   ,   UpperCamelCase__    )

  __A	:		int	  =      VisionTextDualEncoderModel(UpperCamelCase__    )
  __A	:		int	  =      FlaxVisionTextDualEncoderModel(UpperCamelCase__    )

  __A	:		str	  =      convert_pytorch_state_dict_to_flax(pt_model.state_dict()   ,   UpperCamelCase__    )
  __A	:		Optional[int]	  =      fx_state

  self.check_pt_flax_equivalence(UpperCamelCase__   ,   UpperCamelCase__   ,   UpperCamelCase__    )


 def 			snake_case__ (   self   ,   __lowercase   ,   __lowercase   ,   __lowercase    ):

  """simple docstring"""







  __A	:		Tuple	  =      VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase__   ,   UpperCamelCase__    )

  __A	:		Union[str, Any]	  =      VisionTextDualEncoderModel(UpperCamelCase__    )
  __A	:		str	  =      FlaxVisionTextDualEncoderModel(UpperCamelCase__    )

  __A	:		str	  =      load_flax_weights_in_pytorch_model(UpperCamelCase__   ,   fx_model.params    )

  self.check_pt_flax_equivalence(UpperCamelCase__   ,   UpperCamelCase__   ,   UpperCamelCase__    )


 def 			snake_case__ (   self    ):

  """simple docstring"""







  __A	:		Any	  =      self.prepare_config_and_inputs()
  self.check_model_from_pretrained_configs(**UpperCamelCase__    )


 def 			snake_case__ (   self    ):

  """simple docstring"""







  __A	:		Any	  =      self.prepare_config_and_inputs()
  self.check_vision_text_dual_encoder_from_pretrained(**UpperCamelCase__    )


 def 			snake_case__ (   self    ):

  """simple docstring"""







  __A	:		str	  =      self.prepare_config_and_inputs()
  self.check_save_load(**UpperCamelCase__    )


 def 			snake_case__ (   self    ):

  """simple docstring"""







  __A	:		int	  =      self.prepare_config_and_inputs()
  self.check_vision_text_output_attention(**UpperCamelCase__    )


 @is_pt_flax_cross_test
 def 			snake_case__ (   self    ):

  """simple docstring"""







  __A	:		List[str]	  =      self.prepare_config_and_inputs()
  __A	:		List[Any]	  =      config_inputs_dict.pop('vision_config'    )
  __A	:		int	  =      config_inputs_dict.pop('text_config'    )

  __A	:		Union[str, Any]	  =      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    ):

  """simple docstring"""







  __A  ,__A	:		Any	  =      self.get_pretrained_model_and_inputs()

  __A	:		Tuple	  =      model_a(**UpperCamelCase__    )
  __A	:		Optional[int]	  =      outputs[0]

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

   __A	:		List[Any]	  =      model_a(**UpperCamelCase__    )
   __A	:		Optional[int]	  =      after_outputs[0]
   __A	:		Any	  =      np.amax(np.abs(out_a - out_a    )    )
   self.assertLessEqual(UpperCamelCase__   ,   1E-5    )


@require_flax
class     _lowerCamelCase       (     _UpperCamelCase     ,		unittest.TestCase					):




 '''simple docstring'''


 def 			snake_case__ (   self    ):

  """simple docstring"""







  __A	:		Tuple	  =      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	:		str	  =      13
  __A	:		List[Any]	  =      floats_tensor(
      [
          batch_size,
          model.config.vision_config.num_channels,
          model.config.vision_config.image_size,
          model.config.vision_config.image_size,
      ]    )
  __A	:		Tuple	  =      ids_tensor([batch_size, 4]   ,   model.config.text_config.vocab_size    )
  __A	:		Optional[int]	  =      random_attention_mask([batch_size, 4]    )
  __A	:		List[str]	  =      {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

  return model, inputs


 def 			snake_case__ (   self   ,   __lowercase   ,   __lowercase    ):

  """simple docstring"""







  __A	:		Optional[Any]	  =      FlaxViTModel(UpperCamelCase__    )
  __A	:		Tuple	  =      FlaxBertModel(UpperCamelCase__    )
  return vision_model, text_model







 def 			snake_case__ (   self    ):

  """simple docstring"""







  __A	:		Any	  =      FlaxViTModelTester(self    )
  __A	:		str	  =      FlaxBertModelTester(self    )
  __A	:		Any	  =      vit_model_tester.prepare_config_and_inputs()
  __A	:		Dict	  =      bert_model_tester.prepare_config_and_inputs()

  __A  ,__A	:		Union[str, Any]	  =      vision_config_and_inputs

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




 '''simple docstring'''


 def 			snake_case__ (   self    ):

  """simple docstring"""







  __A	:		int	  =      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	:		Union[str, Any]	  =      13
  __A	:		Tuple	  =      floats_tensor(
      [
          batch_size,
          model.config.vision_config.num_channels,
          model.config.vision_config.image_size,
          model.config.vision_config.image_size,
      ]    )
  __A	:		Dict	  =      ids_tensor([batch_size, 4]   ,   model.config.text_config.vocab_size    )
  __A	:		Tuple	  =      random_attention_mask([batch_size, 4]    )
  __A	:		Optional[int]	  =      {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

  return model, inputs


 def 			snake_case__ (   self   ,   __lowercase   ,   __lowercase    ):

  """simple docstring"""







  __A	:		List[str]	  =      FlaxCLIPVisionModel(UpperCamelCase__    )
  __A	:		Tuple	  =      FlaxBertModel(UpperCamelCase__    )
  return vision_model, text_model







 def 			snake_case__ (   self    ):

  """simple docstring"""







  __A	:		Any	  =      FlaxCLIPVisionModelTester(self    )
  __A	:		List[Any]	  =      FlaxBertModelTester(self    )
  __A	:		int	  =      clip_model_tester.prepare_config_and_inputs()
  __A	:		Dict	  =      bert_model_tester.prepare_config_and_inputs()

  __A  ,__A	:		str	  =      vision_config_and_inputs

  __A  ,__A  ,__A  ,__A	:		List[str]	  =      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     _lowerCamelCase       (     unittest.TestCase					):




 '''simple docstring'''


 @slow
 def 			snake_case__ (   self    ):

  """simple docstring"""







  __A	:		Any	  =      FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian'   ,   logit_scale_init_value=1.0    )
  __A	:		Dict	  =      VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian'    )

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

  __A	:		List[str]	  =      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	:		Any	  =      np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]]    )

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







'''simple docstring'''






from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


_UpperCAmelCase    :     Any         =       {
    '''configuration_maskformer''': ['''MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MaskFormerConfig'''],
    '''configuration_maskformer_swin''': ['''MaskFormerSwinConfig'''],
}

try:
   if not is_vision_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _UpperCAmelCase    :     str         =       ['''MaskFormerFeatureExtractor''']
   _UpperCAmelCase    :     str         =       ['''MaskFormerImageProcessor''']


try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _UpperCAmelCase    :     Tuple         =       [
       '''MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
       '''MaskFormerForInstanceSegmentation''',
       '''MaskFormerModel''',
       '''MaskFormerPreTrainedModel''',
   ]
   _UpperCAmelCase    :     int         =       [
       '''MaskFormerSwinBackbone''',
       '''MaskFormerSwinModel''',
       '''MaskFormerSwinPreTrainedModel''',
   ]

if TYPE_CHECKING:
   from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig
   from .configuration_maskformer_swin import MaskFormerSwinConfig

   try:
      if not is_vision_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .feature_extraction_maskformer import MaskFormerFeatureExtractor
      from .image_processing_maskformer import MaskFormerImageProcessor
   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_maskformer import (
          MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
          MaskFormerForInstanceSegmentation,
          MaskFormerModel,
          MaskFormerPreTrainedModel,
      )
      from .modeling_maskformer_swin import (
          MaskFormerSwinBackbone,
          MaskFormerSwinModel,
          MaskFormerSwinPreTrainedModel,
      )


else:
   import sys

   _UpperCAmelCase    :     str         =       _LazyModule(__name__, globals()['''__file__'''], _import_structure)



