






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




@require_flax
class 				lowerCAmelCase       :







   """simple docstring"""







   def  __magic_name__     (			self , _A , _A      )     -> str:
    pass



   def  __magic_name__     (			self      )     -> int:
    pass



   def  __magic_name__     (			self      )     -> Dict:
    pass



   def  __magic_name__     (			self , _A , _A , _A      )     -> Optional[Any]:
    __a     :						Any          =    np.abs((a - b)      ).max()
    self.assertLessEqual(snake_case_ , snake_case_ , f'''Difference between torch and flax is {diff} (>= {tol}).'''      )



   def  __magic_name__     (			self , _A , _A , _A , _A , _A=None , **_A      )     -> Any:
    __a     :						Tuple          =    VisionTextDualEncoderConfig.from_vision_text_configs(snake_case_ , snake_case_      )

    __a     :						str          =    FlaxVisionTextDualEncoderModel(snake_case_      )

    __a     :						Optional[Any]          =    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  __magic_name__     (			self , _A , _A , _A , _A , _A=None , **_A      )     -> str:
    __a     :						List[Any]          =    self.get_vision_text_model(snake_case_ , snake_case_      )
    __a     :						List[Any]          =    {"""vision_model""": vision_model, """text_model""": text_model}
    __a     :						Dict          =    FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**snake_case_      )

    __a     :						Union[str, Any]          =    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  __magic_name__     (			self , _A , _A , _A , _A , _A=None , **_A      )     -> List[Any]:
    __a     :						Tuple          =    self.get_vision_text_model(snake_case_ , snake_case_      )
    __a     :						Optional[int]          =    {"""vision_model""": vision_model, """text_model""": text_model}
    __a     :						List[Any]          =    FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**snake_case_      )

    __a     :						Any          =    model(input_ids=snake_case_ , pixel_values=snake_case_ , attention_mask=snake_case_      )
    __a     :						List[Any]          =    output[0]

    with tempfile.TemporaryDirectory() as tmpdirname:
     model.save_pretrained(snake_case_      )
     __a     :						Tuple          =    FlaxVisionTextDualEncoderModel.from_pretrained(snake_case_      )

     __a     :						str          =    model(input_ids=snake_case_ , pixel_values=snake_case_ , attention_mask=snake_case_      )
     __a     :						List[Any]          =    after_output[0]
     __a     :						str          =    np.amax(np.abs(out_a - out_a      )      )
     self.assertLessEqual(snake_case_ , 1E-3      )



   def  __magic_name__     (			self , _A , _A , _A , _A , _A=None , **_A      )     -> Dict:
    __a     :						Optional[int]          =    self.get_vision_text_model(snake_case_ , snake_case_      )
    __a     :						Dict          =    {"""vision_model""": vision_model, """text_model""": text_model}
    __a     :						Dict          =    FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**snake_case_      )

    __a     :						Optional[int]          =    model(
        input_ids=snake_case_ , pixel_values=snake_case_ , attention_mask=snake_case_ , output_attentions=snake_case_      )

    __a     :						str          =    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)
    __a     :						Union[str, Any]          =    to_atuple(vision_model.config.image_size      )
    __a     :						List[str]          =    to_atuple(vision_model.config.patch_size      )
    __a     :						Tuple          =    (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     :						Optional[Any]          =    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  __magic_name__     (			self , _A , _A , _A      )     -> int:
    pt_model.to(snake_case_      )
    pt_model.eval()

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

    with torch.no_grad():
     __a     :						List[Any]          =    pt_model(**snake_case_      ).to_tuple()

    __a     :						Any          =    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_      )
     __a     :						Any          =    FlaxVisionTextDualEncoderModel.from_pretrained(snake_case_ , from_pt=snake_case_      )

    __a     :						int          =    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_      )
     __a     :						Any          =    VisionTextDualEncoderModel.from_pretrained(snake_case_ , from_flax=snake_case_      )

    pt_model_loaded.to(snake_case_      )
    pt_model_loaded.eval()

    with torch.no_grad():
     __a     :						Union[str, Any]          =    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  __magic_name__     (			self , _A , _A , _A      )     -> Union[str, Any]:
    __a     :						Dict          =    VisionTextDualEncoderConfig.from_vision_text_configs(snake_case_ , snake_case_      )

    __a     :						Optional[Any]          =    VisionTextDualEncoderModel(snake_case_      )
    __a     :						Optional[int]          =    FlaxVisionTextDualEncoderModel(snake_case_      )

    __a     :						Dict          =    convert_pytorch_state_dict_to_flax(pt_model.state_dict() , snake_case_      )
    __a     :						Optional[Any]          =    fx_state

    self.check_pt_flax_equivalence(snake_case_ , snake_case_ , snake_case_      )



   def  __magic_name__     (			self , _A , _A , _A      )     -> List[Any]:
    __a     :						Union[str, Any]          =    VisionTextDualEncoderConfig.from_vision_text_configs(snake_case_ , snake_case_      )

    __a     :						Optional[Any]          =    VisionTextDualEncoderModel(snake_case_      )
    __a     :						List[Any]          =    FlaxVisionTextDualEncoderModel(snake_case_      )

    __a     :						int          =    load_flax_weights_in_pytorch_model(snake_case_ , fx_model.params      )

    self.check_pt_flax_equivalence(snake_case_ , snake_case_ , snake_case_      )



   def  __magic_name__     (			self      )     -> Any:
    __a     :						List[Any]          =    self.prepare_config_and_inputs()
    self.check_model_from_pretrained_configs(**snake_case_      )



   def  __magic_name__     (			self      )     -> List[str]:
    __a     :						Optional[int]          =    self.prepare_config_and_inputs()
    self.check_vision_text_dual_encoder_from_pretrained(**snake_case_      )



   def  __magic_name__     (			self      )     -> str:
    __a     :						int          =    self.prepare_config_and_inputs()
    self.check_save_load(**snake_case_      )



   def  __magic_name__     (			self      )     -> Optional[Any]:
    __a     :						Dict          =    self.prepare_config_and_inputs()
    self.check_vision_text_output_attention(**snake_case_      )



   @is_pt_flax_cross_test
   def  __magic_name__     (			self      )     -> Dict:
    __a     :						Tuple          =    self.prepare_config_and_inputs()
    __a     :						Optional[int]          =    config_inputs_dict.pop('vision_config'      )
    __a     :						Optional[Any]          =    config_inputs_dict.pop('text_config'      )

    __a     :						List[Any]          =    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  __magic_name__     (			self      )     -> Any:
    __a     :						Any          =    self.get_pretrained_model_and_inputs()

    __a     :						int          =    model_a(**snake_case_      )
    __a     :						str          =    outputs[0]

    with tempfile.TemporaryDirectory() as tmp_dirname:
     model_a.save_pretrained(snake_case_      )
     __a     :						Any          =    FlaxVisionTextDualEncoderModel.from_pretrained(snake_case_      )

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




@require_flax
class 				lowerCAmelCase       (				_A				,   unittest.TestCase ):







   """simple docstring"""







   def  __magic_name__     (			self      )     -> int:
    __a     :						int          =    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_ , )
    __a     :						Tuple          =    13
    __a     :						Optional[int]          =    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     :						Optional[Any]          =    random_attention_mask([batch_size, 4]      )
    __a     :						Any          =    {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

    return model, inputs



   def  __magic_name__     (			self , _A , _A      )     -> Dict:
    __a     :						Union[str, Any]          =    FlaxViTModel(snake_case_      )
    __a     :						Tuple          =    FlaxBertModel(snake_case_      )
    return vision_model, text_model



   def  __magic_name__     (			self      )     -> Optional[Any]:
    __a     :						Optional[Any]          =    FlaxViTModelTester(self      )
    __a     :						int          =    FlaxBertModelTester(self      )
    __a     :						Union[str, Any]          =    vit_model_tester.prepare_config_and_inputs()
    __a     :						List[str]          =    bert_model_tester.prepare_config_and_inputs()

    __a     :						str          =    vision_config_and_inputs

    __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       (				_A				,   unittest.TestCase ):







   """simple docstring"""







   def  __magic_name__     (			self      )     -> List[Any]:
    __a     :						Optional[Any]          =    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_ , )
    __a     :						Optional[int]          =    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     :						Optional[int]          =    ids_tensor([batch_size, 4] , model.config.text_config.vocab_size      )
    __a     :						Dict          =    random_attention_mask([batch_size, 4]      )
    __a     :						int          =    {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

    return model, inputs



   def  __magic_name__     (			self , _A , _A      )     -> Tuple:
    __a     :						Union[str, Any]          =    FlaxCLIPVisionModel(snake_case_      )
    __a     :						str          =    FlaxBertModel(snake_case_      )
    return vision_model, text_model



   def  __magic_name__     (			self      )     -> Optional[Any]:
    __a     :						Dict          =    FlaxCLIPVisionModelTester(self      )
    __a     :						int          =    FlaxBertModelTester(self      )
    __a     :						List[str]          =    clip_model_tester.prepare_config_and_inputs()
    __a     :						Tuple          =    bert_model_tester.prepare_config_and_inputs()

    __a     :						List[str]          =    vision_config_and_inputs

    __a     :						Optional[int]          =    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  __magic_name__     (			self      )     -> List[Any]:
    __a     :						List[str]          =    FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian' , logit_scale_init_value=1.0      )
    __a     :						Optional[int]          =    VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian'      )

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

    __a     :						int          =    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]) , )

    __a     :						Union[str, Any]          =    np.array([[1.2_284_727, 0.3_104_122]]      )

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






import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch


if is_torch_available():
							import torch

							from transformers.generation import DisjunctiveConstraint

@require_torch
class 							_UpperCamelCase					(       unittest.TestCase	):






			'''simple docstring'''

			def    lowerCAmelCase__						(							self			:							Dict   ):
							# For consistency across different places the DisjunctiveConstraint is called,
							# dc.token_ids is a list of integers. It is also initialized only by integers.

							UpperCamelCase_:				Optional[int]						=    [[1, 2, 4], [1, 2, 3, 4]]
							UpperCamelCase_:				List[str]						=    DisjunctiveConstraint(snake_case_   )
							self.assertTrue(isinstance(dc.token_ids    ,						snake_case_   )   )

							with self.assertRaises(snake_case_   ):
											DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]]   )   )

							with self.assertRaises(snake_case_   ):
											DisjunctiveConstraint([torch.LongTensor([1, 2, 4]   ), torch.LongTensor([1, 2, 3, 4, 5]   )]   )

			def    lowerCAmelCase__						(							self			:							Optional[Any]   ):
							# We can't have constraints that are complete subsets of another. This leads to a preverse
							# interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint?
							# It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially
							# fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm
							# will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it).
							UpperCamelCase_:				Dict						=    [[1, 2], [1, 2, 3, 4]]

							with self.assertRaises(snake_case_   ):
											DisjunctiveConstraint(snake_case_   )  # fails here

			def    lowerCAmelCase__						(							self			:							int   ):
							UpperCamelCase_:				Dict						=    [[1, 2, 3], [1, 2, 4]]

							UpperCamelCase_:				Dict						=    DisjunctiveConstraint(snake_case_   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				str						=    dc.update(1   )
							UpperCamelCase_:				Union[str, Any]						=    stepped is True and completed is False and reset is False
							self.assertTrue(snake_case_   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.current_seq == [1]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				Optional[int]						=    dc.update(2   )
							UpperCamelCase_:				Tuple						=    stepped is True and completed is False and reset is False
							self.assertTrue(snake_case_   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.current_seq == [1, 2]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				Optional[int]						=    dc.update(3   )
							UpperCamelCase_:				Union[str, Any]						=    stepped is True and completed is True and reset is False
							self.assertTrue(snake_case_   )
							self.assertTrue(dc.completed   )  # Completed!
							self.assertTrue(dc.current_seq == [1, 2, 3]   )




			def    lowerCAmelCase__						(							self			:							List[str]   ):
							UpperCamelCase_:				Optional[int]						=    [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]]

							UpperCamelCase_:				Tuple						=    DisjunctiveConstraint(snake_case_   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				Dict						=    dc.update(1   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.current_seq == [1]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				Union[str, Any]						=    dc.update(2   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.current_seq == [1, 2]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				Any						=    dc.update(4   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.current_seq == [1, 2, 4]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				int						=    dc.update(5   )
							self.assertTrue(dc.completed   )  # Completed!
							self.assertTrue(dc.current_seq == [1, 2, 4, 5]   )

							dc.reset()

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				int						=    dc.update(1   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.remaining() == 3   )
							self.assertTrue(dc.current_seq == [1]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				Tuple						=    dc.update(2   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.remaining() == 2   )
							self.assertTrue(dc.current_seq == [1, 2]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				List[str]						=    dc.update(5   )
							self.assertTrue(dc.completed   )  # Completed!
							self.assertTrue(dc.remaining() == 0   )
							self.assertTrue(dc.current_seq == [1, 2, 5]   )






