



'''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 		__SCREAMING_SNAKE_CASE					(  _UpperCamelCase							):


   """simple docstring"""




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


@require_flax
class        _UpperCAmelCase						:




    def 				lowerCAmelCase__				(			self  :       Tuple  ,     a  :       int  ,     a  :       Dict			):






       '''simple docstring'''






       pass




    def 				lowerCAmelCase__				(			self  :       List[str]			):






       '''simple docstring'''






       pass




    def 				lowerCAmelCase__				(			self  :       Optional[int]			):






       '''simple docstring'''






       pass




    def 				lowerCAmelCase__				(			self  :       Optional[Any]  ,     a  :       List[Any]  ,     a  :       Optional[Any]  ,     a  :       List[str]			):






       '''simple docstring'''






       lowercase_	:    Optional[int]           =     np.abs((a - b)			).max()
       self.assertLessEqual(a  ,     a  ,     f"""Difference between torch and flax is {diff} (>= {tol})."""			)




    def 				lowerCAmelCase__				(			self  :       Any  ,     a  :       Union[str, Any]  ,     a  :       Optional[Any]  ,     a  :       List[Any]  ,     a  :       int  ,     a  :       Optional[int]=None  ,     **a  :       str			):






       '''simple docstring'''






       lowercase_	:    Union[str, Any]           =     VisionTextDualEncoderConfig.from_vision_text_configs(a  ,     a			)

       lowercase_	:    str           =     FlaxVisionTextDualEncoderModel(a			)

       lowercase_	:    int           =     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 				lowerCAmelCase__				(			self  :       Optional[int]  ,     a  :       Optional[Any]  ,     a  :       Dict  ,     a  :       Dict  ,     a  :       Optional[Any]  ,     a  :       List[Any]=None  ,     **a  :       Tuple			):






       '''simple docstring'''






       lowercase_    ,		lowercase_	:    List[str]           =     self.get_vision_text_model(a  ,     a			)
       lowercase_	:    str           =     {"vision_model": vision_model, "text_model": text_model}
       lowercase_	:    str           =     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**a			)

       lowercase_	:    Tuple           =     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 				lowerCAmelCase__				(			self  :       Tuple  ,     a  :       List[Any]  ,     a  :       Dict  ,     a  :       Tuple  ,     a  :       Optional[Any]  ,     a  :       Any=None  ,     **a  :       Optional[int]			):






       '''simple docstring'''






       lowercase_    ,		lowercase_	:    List[str]           =     self.get_vision_text_model(a  ,     a			)
       lowercase_	:    Optional[int]           =     {"vision_model": vision_model, "text_model": text_model}
       lowercase_	:    str           =     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**a			)

       lowercase_	:    Union[str, Any]           =     model(input_ids=a  ,     pixel_values=a  ,     attention_mask=a			)
       lowercase_	:    Any           =     output[0]

       with tempfile.TemporaryDirectory() as tmpdirname:
          model.save_pretrained(a			)
          lowercase_	:    Optional[int]           =     FlaxVisionTextDualEncoderModel.from_pretrained(a			)

          lowercase_	:    List[str]           =     model(input_ids=a  ,     pixel_values=a  ,     attention_mask=a			)
          lowercase_	:    List[Any]           =     after_output[0]
          lowercase_	:    Union[str, Any]           =     np.amax(np.abs(out_a - out_a			)			)
          self.assertLessEqual(a  ,     1e-3			)




    def 				lowerCAmelCase__				(			self  :       Union[str, Any]  ,     a  :       Optional[Any]  ,     a  :       str  ,     a  :       str  ,     a  :       Union[str, Any]  ,     a  :       Dict=None  ,     **a  :       Dict			):






       '''simple docstring'''






       lowercase_    ,		lowercase_	:    Any           =     self.get_vision_text_model(a  ,     a			)
       lowercase_	:    Union[str, Any]           =     {"vision_model": vision_model, "text_model": text_model}
       lowercase_	:    Optional[int]           =     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**a			)

       lowercase_	:    int           =     model(
           input_ids=a  ,     pixel_values=a  ,     attention_mask=a  ,     output_attentions=a			)

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

       lowercase_	:    Any           =     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 				lowerCAmelCase__				(			self  :       Union[str, Any]  ,     a  :       List[Any]  ,     a  :       Tuple  ,     a  :       List[str]			):






       '''simple docstring'''






       pt_model.to(a			)
       pt_model.eval()

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

       with torch.no_grad():
          lowercase_	:    Dict           =     pt_model(**a			).to_tuple()

       lowercase_	:    Any           =     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			)
          lowercase_	:    Optional[int]           =     FlaxVisionTextDualEncoderModel.from_pretrained(a  ,     from_pt=a			)

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

       pt_model_loaded.to(a			)
       pt_model_loaded.eval()

       with torch.no_grad():
          lowercase_	:    List[str]           =     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 				lowerCAmelCase__				(			self  :       int  ,     a  :       str  ,     a  :       Optional[int]  ,     a  :       Optional[Any]			):






       '''simple docstring'''






       lowercase_	:    str           =     VisionTextDualEncoderConfig.from_vision_text_configs(a  ,     a			)

       lowercase_	:    List[str]           =     VisionTextDualEncoderModel(a			)
       lowercase_	:    List[Any]           =     FlaxVisionTextDualEncoderModel(a			)

       lowercase_	:    Tuple           =     convert_pytorch_state_dict_to_flax(pt_model.state_dict()  ,     a			)
       lowercase_	:    Union[str, Any]           =     fx_state

       self.check_pt_flax_equivalence(a  ,     a  ,     a			)




    def 				lowerCAmelCase__				(			self  :       str  ,     a  :       List[Any]  ,     a  :       List[str]  ,     a  :       Optional[int]			):






       '''simple docstring'''






       lowercase_	:    Any           =     VisionTextDualEncoderConfig.from_vision_text_configs(a  ,     a			)

       lowercase_	:    Optional[int]           =     VisionTextDualEncoderModel(a			)
       lowercase_	:    Union[str, Any]           =     FlaxVisionTextDualEncoderModel(a			)

       lowercase_	:    Any           =     load_flax_weights_in_pytorch_model(a  ,     fx_model.params			)

       self.check_pt_flax_equivalence(a  ,     a  ,     a			)




    def 				lowerCAmelCase__				(			self  :       Union[str, Any]			):






       '''simple docstring'''






       lowercase_	:    str           =     self.prepare_config_and_inputs()
       self.check_model_from_pretrained_configs(**a			)




    def 				lowerCAmelCase__				(			self  :       List[str]			):






       '''simple docstring'''






       lowercase_	:    Union[str, Any]           =     self.prepare_config_and_inputs()
       self.check_vision_text_dual_encoder_from_pretrained(**a			)




    def 				lowerCAmelCase__				(			self  :       List[str]			):






       '''simple docstring'''






       lowercase_	:    Optional[int]           =     self.prepare_config_and_inputs()
       self.check_save_load(**a			)




    def 				lowerCAmelCase__				(			self  :       Union[str, Any]			):






       '''simple docstring'''






       lowercase_	:    Tuple           =     self.prepare_config_and_inputs()
       self.check_vision_text_output_attention(**a			)




    @is_pt_flax_cross_test
    def 				lowerCAmelCase__				(			self  :       Any			):






       '''simple docstring'''






       lowercase_	:    str           =     self.prepare_config_and_inputs()
       lowercase_	:    str           =     config_inputs_dict.pop("vision_config"			)
       lowercase_	:    Tuple           =     config_inputs_dict.pop("text_config"			)

       lowercase_	:    Dict           =     config_inputs_dict

       self.check_equivalence_pt_to_flax(a  ,     a  ,     a			)
       self.check_equivalence_flax_to_pt(a  ,     a  ,     a			)





    @slow
    def 				lowerCAmelCase__				(			self  :       Any			):






       '''simple docstring'''






       lowercase_    ,		lowercase_	:    Any           =     self.get_pretrained_model_and_inputs()

       lowercase_	:    List[str]           =     model_a(**a			)
       lowercase_	:    Optional[Any]           =     outputs[0]

       with tempfile.TemporaryDirectory() as tmp_dirname:
          model_a.save_pretrained(a			)
          lowercase_	:    Optional[Any]           =     FlaxVisionTextDualEncoderModel.from_pretrained(a			)

          lowercase_	:    int           =     model_a(**a			)
          lowercase_	:    List[str]           =     after_outputs[0]
          lowercase_	:    str           =     np.amax(np.abs(out_a - out_a			)			)
          self.assertLessEqual(a  ,     1e-5			)


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




    def 				lowerCAmelCase__				(			self  :       Optional[int]			):






       '''simple docstring'''






       lowercase_	:    List[str]           =     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
           "hf-internal-testing/tiny-random-vit"  ,     "hf-internal-testing/tiny-bert"  ,     vision_from_pt=a  ,     text_from_pt=a  ,     )
       lowercase_	:    Optional[int]           =     1_3
       lowercase_	:    List[Any]           =     floats_tensor(
           [
               batch_size,
               model.config.vision_config.num_channels,
               model.config.vision_config.image_size,
               model.config.vision_config.image_size,
           ]			)
       lowercase_	:    List[str]           =     ids_tensor([batch_size, 4]  ,     model.config.text_config.vocab_size			)
       lowercase_	:    List[str]           =     random_attention_mask([batch_size, 4]			)
       lowercase_	:    str           =     {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

       return model, inputs




    def 				lowerCAmelCase__				(			self  :       List[str]  ,     a  :       Optional[Any]  ,     a  :       Optional[int]			):






       '''simple docstring'''






       lowercase_	:    Dict           =     FlaxViTModel(a			)
       lowercase_	:    Optional[Any]           =     FlaxBertModel(a			)
       return vision_model, text_model





    def 				lowerCAmelCase__				(			self  :       Optional[int]			):






       '''simple docstring'''






       lowercase_	:    Optional[int]           =     FlaxViTModelTester(self			)
       lowercase_	:    str           =     FlaxBertModelTester(self			)
       lowercase_	:    Optional[Any]           =     vit_model_tester.prepare_config_and_inputs()
       lowercase_	:    Any           =     bert_model_tester.prepare_config_and_inputs()

       lowercase_    ,		lowercase_	:    Optional[Any]           =     vision_config_and_inputs

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




    def 				lowerCAmelCase__				(			self  :       Tuple			):






       '''simple docstring'''






       lowercase_	:    Tuple           =     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
           "hf-internal-testing/tiny-random-clip"  ,     "hf-internal-testing/tiny-bert"  ,     vision_from_pt=a  ,     text_from_pt=a  ,     )
       lowercase_	:    int           =     1_3
       lowercase_	:    Any           =     floats_tensor(
           [
               batch_size,
               model.config.vision_config.num_channels,
               model.config.vision_config.image_size,
               model.config.vision_config.image_size,
           ]			)
       lowercase_	:    Optional[Any]           =     ids_tensor([batch_size, 4]  ,     model.config.text_config.vocab_size			)
       lowercase_	:    str           =     random_attention_mask([batch_size, 4]			)
       lowercase_	:    Optional[int]           =     {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

       return model, inputs




    def 				lowerCAmelCase__				(			self  :       Any  ,     a  :       int  ,     a  :       Tuple			):






       '''simple docstring'''






       lowercase_	:    Optional[Any]           =     FlaxCLIPVisionModel(a			)
       lowercase_	:    Optional[int]           =     FlaxBertModel(a			)
       return vision_model, text_model





    def 				lowerCAmelCase__				(			self  :       List[Any]			):






       '''simple docstring'''






       lowercase_	:    Tuple           =     FlaxCLIPVisionModelTester(self			)
       lowercase_	:    int           =     FlaxBertModelTester(self			)
       lowercase_	:    Dict           =     clip_model_tester.prepare_config_and_inputs()
       lowercase_	:    Tuple           =     bert_model_tester.prepare_config_and_inputs()

       lowercase_    ,		lowercase_	:    List[str]           =     vision_config_and_inputs

       lowercase_    ,		lowercase_    ,		lowercase_    ,		lowercase_	:    Optional[Any]           =     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 				lowerCAmelCase__				(			self  :       int			):






       '''simple docstring'''






       lowercase_	:    Optional[Any]           =     FlaxVisionTextDualEncoderModel.from_pretrained("clip-italian/clip-italian"  ,     logit_scale_init_value=1.0			)
       lowercase_	:    Optional[Any]           =     VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian"			)

       lowercase_	:    Optional[int]           =     Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"			)
       lowercase_	:    Dict           =     processor(
           text=["una foto di un gatto", "una foto di un cane"]  ,     images=a  ,     padding=a  ,     return_tensors="np"			)

       lowercase_	:    Tuple           =     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])  ,     )

       lowercase_	:    List[str]           =     np.array([[1.228_4727, 0.310_4122]]			)

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












'''simple docstring'''
# limitations under the License.

# NOTE: This file is deprecated and will be removed in a future version.
# It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works

from .pipelines import DiffusionPipeline, ImagePipelineOutput  # noqa: F401
from .utils import deprecate


deprecate(
    'pipelines_utils',
    '0.22.0',
    'Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.',
    standard_warn=False,
    stacklevel=3,
)




