
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 							A__       (    lowerCamelCase    )	->						List[str]:
				if isinstance(lowerCamelCase  ,     collections.abc.Iterable    ):
								return x
				return (x, x)

@require_flax
class 							_UpperCamelCase					:






			'''simple docstring'''

			def    lowerCAmelCase__						(							self			:							Optional[Any]    ,						snake_case_			:							Tuple    ,						snake_case_			:							Any   ):
							pass

			def    lowerCAmelCase__						(							self			:							Any   ):
							pass

			def    lowerCAmelCase__						(							self			:							List[str]   ):
							pass

			def    lowerCAmelCase__						(							self			:							Tuple    ,						snake_case_			:							np.ndarray    ,						snake_case_			:							np.ndarray    ,						snake_case_			:							float   ):
							UpperCamelCase_:				Any						=    np.abs((a - b)   ).max()
							self.assertLessEqual(snake_case_    ,						snake_case_    ,						f'''Difference between torch and flax is {diff} (>= {tol}).'''   )

			def    lowerCAmelCase__						(							self			:							Union[str, Any]    ,						snake_case_			:							List[str]    ,						snake_case_			:							Dict    ,						snake_case_			:							Dict    ,						snake_case_			:							str    ,						snake_case_			:							List[Any]=None    ,						**snake_case_			:							Any   ):
							UpperCamelCase_:				Tuple						=    VisionTextDualEncoderConfig.from_vision_text_configs(snake_case_    ,						snake_case_   )

							UpperCamelCase_:				str						=    FlaxVisionTextDualEncoderModel(snake_case_   )

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

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

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

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

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

			def    lowerCAmelCase__						(							self			:							Union[str, Any]    ,						snake_case_			:							Optional[int]    ,						snake_case_			:							Tuple    ,						snake_case_			:							List[Any]    ,						snake_case_			:							Optional[Any]    ,						snake_case_			:							Dict=None    ,						**snake_case_			:							Any   ):
							UpperCamelCase_, UpperCamelCase_:				Optional[int]						=    self.get_vision_text_model(snake_case_    ,						snake_case_   )
							UpperCamelCase_:				Dict						=    {"""vision_model""": vision_model, """text_model""": text_model}
							UpperCamelCase_:				Dict						=    FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**snake_case_   )

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

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

							UpperCamelCase_:				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    lowerCAmelCase__						(							self			:							List[Any]    ,						snake_case_			:							str    ,						snake_case_			:							Optional[int]    ,						snake_case_			:							int   ):
							pt_model.to(snake_case_   )
							pt_model.eval()

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

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

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

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

							pt_model_loaded.to(snake_case_   )
							pt_model_loaded.eval()

							with torch.no_grad():
											UpperCamelCase_:				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    lowerCAmelCase__						(							self			:							List[Any]    ,						snake_case_			:							List[Any]    ,						snake_case_			:							str    ,						snake_case_			:							Optional[int]   ):
							UpperCamelCase_:				Dict						=    VisionTextDualEncoderConfig.from_vision_text_configs(snake_case_    ,						snake_case_   )

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

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

							self.check_pt_flax_equivalence(snake_case_    ,						snake_case_    ,						snake_case_   )

			def    lowerCAmelCase__						(							self			:							Dict    ,						snake_case_			:							Dict    ,						snake_case_			:							int    ,						snake_case_			:							Optional[Any]   ):
							UpperCamelCase_:				Union[str, Any]						=    VisionTextDualEncoderConfig.from_vision_text_configs(snake_case_    ,						snake_case_   )

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

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

							self.check_pt_flax_equivalence(snake_case_    ,						snake_case_    ,						snake_case_   )

			def    lowerCAmelCase__						(							self			:							int   ):
							UpperCamelCase_:				List[Any]						=    self.prepare_config_and_inputs()
							self.check_model_from_pretrained_configs(**snake_case_   )

			def    lowerCAmelCase__						(							self			:							Optional[int]   ):
							UpperCamelCase_:				Optional[int]						=    self.prepare_config_and_inputs()
							self.check_vision_text_dual_encoder_from_pretrained(**snake_case_   )

			def    lowerCAmelCase__						(							self			:							Union[str, Any]   ):
							UpperCamelCase_:				int						=    self.prepare_config_and_inputs()
							self.check_save_load(**snake_case_   )

			def    lowerCAmelCase__						(							self			:							Dict   ):
							UpperCamelCase_:				Dict						=    self.prepare_config_and_inputs()
							self.check_vision_text_output_attention(**snake_case_   )

			@is_pt_flax_cross_test
			def    lowerCAmelCase__						(							self			:							int   ):
							UpperCamelCase_:				Tuple						=    self.prepare_config_and_inputs()
							UpperCamelCase_:				Optional[int]						=    config_inputs_dict.pop("""vision_config"""   )
							UpperCamelCase_:				Optional[Any]						=    config_inputs_dict.pop("""text_config"""   )

							UpperCamelCase_:				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    lowerCAmelCase__						(							self			:							Dict   ):
							UpperCamelCase_, UpperCamelCase_:				Any						=    self.get_pretrained_model_and_inputs()

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

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

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




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






			'''simple docstring'''

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

							return model, inputs

			def    lowerCAmelCase__						(							self			:							List[Any]    ,						snake_case_			:							Dict    ,						snake_case_			:							Optional[int]   ):
							UpperCamelCase_:				Union[str, Any]						=    FlaxViTModel(snake_case_   )
							UpperCamelCase_:				Tuple						=    FlaxBertModel(snake_case_   )
							return vision_model, text_model




			def    lowerCAmelCase__						(							self			:							Dict   ):
							UpperCamelCase_:				Optional[Any]						=    FlaxViTModelTester(self   )
							UpperCamelCase_:				int						=    FlaxBertModelTester(self   )
							UpperCamelCase_:				Union[str, Any]						=    vit_model_tester.prepare_config_and_inputs()
							UpperCamelCase_:				List[str]						=    bert_model_tester.prepare_config_and_inputs()

							UpperCamelCase_, UpperCamelCase_:				str						=    vision_config_and_inputs

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






			'''simple docstring'''

			def    lowerCAmelCase__						(							self			:							Tuple   ):
							UpperCamelCase_:				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_    ,						)
							UpperCamelCase_:				Optional[int]						=    13
							UpperCamelCase_:				List[Any]						=    floats_tensor(
							    [
							        batch_size,
							        model.config.vision_config.num_channels,
							        model.config.vision_config.image_size,
							        model.config.vision_config.image_size,
							    ]   )
							UpperCamelCase_:				Optional[int]						=    ids_tensor([batch_size, 4]    ,						model.config.text_config.vocab_size   )
							UpperCamelCase_:				Dict						=    random_attention_mask([batch_size, 4]   )
							UpperCamelCase_:				int						=    {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

							return model, inputs

			def    lowerCAmelCase__						(							self			:							List[str]    ,						snake_case_			:							List[str]    ,						snake_case_			:							Dict   ):
							UpperCamelCase_:				Union[str, Any]						=    FlaxCLIPVisionModel(snake_case_   )
							UpperCamelCase_:				str						=    FlaxBertModel(snake_case_   )
							return vision_model, text_model




			def    lowerCAmelCase__						(							self			:							Optional[Any]   ):
							UpperCamelCase_:				Dict						=    FlaxCLIPVisionModelTester(self   )
							UpperCamelCase_:				int						=    FlaxBertModelTester(self   )
							UpperCamelCase_:				List[str]						=    clip_model_tester.prepare_config_and_inputs()
							UpperCamelCase_:				Tuple						=    bert_model_tester.prepare_config_and_inputs()

							UpperCamelCase_, UpperCamelCase_:				List[str]						=    vision_config_and_inputs

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






			'''simple docstring'''

			@slow
			def    lowerCAmelCase__						(							self			:							str   ):
							UpperCamelCase_:				List[str]						=    FlaxVisionTextDualEncoderModel.from_pretrained("""clip-italian/clip-italian"""    ,						logit_scale_init_value=1.0   )
							UpperCamelCase_:				Optional[int]						=    VisionTextDualEncoderProcessor.from_pretrained("""clip-italian/clip-italian"""   )

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

							UpperCamelCase_:				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])    ,						)

							UpperCamelCase_:				Union[str, Any]						=    np.array([[1.228_4727, 0.310_4122]]   )

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








import random
import unittest

import torch

from diffusers import IFInpaintingSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin

@skip_mps
class 							_UpperCamelCase					(       _A  ,							_A  ,							unittest.TestCase	):






			'''simple docstring'''

			__UpperCamelCase   :    str          =			IFInpaintingSuperResolutionPipeline
			__UpperCamelCase   :    str          =			TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"""width""", """height"""}
			__UpperCamelCase   :    Optional[Any]          =			TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({"""original_image"""}	)
			__UpperCamelCase   :    Dict          =			PipelineTesterMixin.required_optional_params - {"""latents"""}

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

			def    lowerCAmelCase__						(							self			:							Dict    ,						snake_case_			:							Optional[int]    ,						snake_case_			:							str=0   ):
							if str(snake_case_   ).startswith("""mps"""   ):
											UpperCamelCase_:				Union[str, Any]						=    torch.manual_seed(snake_case_   )
							else:
											UpperCamelCase_:				Tuple						=    torch.Generator(device=snake_case_   ).manual_seed(snake_case_   )

							UpperCamelCase_:				Dict						=    floats_tensor((1, 3, 16, 16)    ,						rng=random.Random(snake_case_   )   ).to(snake_case_   )
							UpperCamelCase_:				int						=    floats_tensor((1, 3, 32, 32)    ,						rng=random.Random(snake_case_   )   ).to(snake_case_   )
							UpperCamelCase_:				str						=    floats_tensor((1, 3, 32, 32)    ,						rng=random.Random(snake_case_   )   ).to(snake_case_   )

							UpperCamelCase_:				Dict						=    {
							    """prompt""": """A painting of a squirrel eating a burger""",
							    """image""": image,
							    """original_image""": original_image,
							    """mask_image""": mask_image,
							    """generator""": generator,
							    """num_inference_steps""": 2,
							    """output_type""": """numpy""",
							}

							return inputs

			@unittest.skipIf(
			    torch_device != """cuda""" or not is_xformers_available()    ,						reason="""XFormers attention is only available with CUDA and `xformers` installed"""    ,						)
			def    lowerCAmelCase__						(							self			:							Tuple   ):
							self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3   )

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

			@unittest.skipIf(torch_device != """cuda"""    ,						reason="""float16 requires CUDA"""   )
			def    lowerCAmelCase__						(							self			:							List[Any]   ):
							# Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
							super().test_save_load_floataa(expected_max_diff=1e-1   )

			def    lowerCAmelCase__						(							self			:							str   ):
							self._test_attention_slicing_forward_pass(expected_max_diff=1e-2   )

			def    lowerCAmelCase__						(							self			:							str   ):
							self._test_save_load_local()




			def    lowerCAmelCase__						(							self			:							Union[str, Any]   ):
							self._test_inference_batch_single_identical(
							    expected_max_diff=1e-2    ,						)






