






import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()



class   lowerCamelCase      (_a ,  unittest.TestCase			):







		'''simple docstring'''



		_snake_case    :    Any       						=  KandinskyImgaImgPipeline
		_snake_case    :    Union[str, Any]       						=  ["""prompt""", """image_embeds""", """negative_image_embeds""", """image"""]
		_snake_case    :    Any       						=  [
		    """prompt""",
		    """negative_prompt""",
		    """image_embeds""",
		    """negative_image_embeds""",
		    """image""",
		]
		_snake_case    :    List[Any]       						=  [
		    """generator""",
		    """height""",
		    """width""",
		    """strength""",
		    """guidance_scale""",
		    """negative_prompt""",
		    """num_inference_steps""",
		    """return_dict""",
		    """guidance_scale""",
		    """num_images_per_prompt""",
		    """output_type""",
		    """return_dict""",
		]
		_snake_case    :    Union[str, Any]       						=  False



		@property
		def 					__UpperCAmelCase			(							self   )	->							str:
							return 3_2



		@property
		def 					__UpperCAmelCase			(							self   )	->							int:
							return 3_2



		@property
		def 					__UpperCAmelCase			(							self   )	->							Tuple:
							return self.time_input_dim



		@property
		def 					__UpperCAmelCase			(							self   )	->							Optional[Any]:
							return self.time_input_dim * 4



		@property
		def 					__UpperCAmelCase			(							self   )	->							List[str]:
							return 1_0_0



		@property
		def 					__UpperCAmelCase			(							self   )	->							str:
							UpperCAmelCase_    :      str            =						XLMRobertaTokenizerFast.from_pretrained('YiYiXu/tiny-random-mclip-base'   )
							return tokenizer



		@property
		def 					__UpperCAmelCase			(							self   )	->							int:
							torch.manual_seed(0   )
							UpperCAmelCase_    :      Optional[int]            =						MCLIPConfig(
							    numDims=self.cross_attention_dim				,		transformerDimensions=self.text_embedder_hidden_size				,		hidden_size=self.text_embedder_hidden_size				,		intermediate_size=3_7				,		num_attention_heads=4				,		num_hidden_layers=5				,		vocab_size=1_0_0_5				,		)

							UpperCAmelCase_    :      Optional[int]            =						MultilingualCLIP(_UpperCamelCase   )
							UpperCAmelCase_    :      List[str]            =						text_encoder.eval()

							return text_encoder



		@property
		def 					__UpperCAmelCase			(							self   )	->							List[str]:
							torch.manual_seed(0   )

							UpperCAmelCase_    :      Union[str, Any]            =						{
							    'in_channels': 4,
							    # Out channels is double in channels because predicts mean and variance
							    'out_channels': 8,
							    'addition_embed_type': 'text_image',
							    'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'),
							    'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'),
							    'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn',
							    'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2),
							    'layers_per_block': 1,
							    'encoder_hid_dim': self.text_embedder_hidden_size,
							    'encoder_hid_dim_type': 'text_image_proj',
							    'cross_attention_dim': self.cross_attention_dim,
							    'attention_head_dim': 4,
							    'resnet_time_scale_shift': 'scale_shift',
							    'class_embed_type': None,
							}

							UpperCAmelCase_    :      Optional[Any]            =						UNetaDConditionModel(**_UpperCamelCase   )
							return model



		@property
		def 					__UpperCAmelCase			(							self   )	->							str:
							return {
							    "block_out_channels": [3_2, 6_4],
							    "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
							    "in_channels": 3,
							    "latent_channels": 4,
							    "layers_per_block": 1,
							    "norm_num_groups": 8,
							    "norm_type": "spatial",
							    "num_vq_embeddings": 1_2,
							    "out_channels": 3,
							    "up_block_types": [
							        "AttnUpDecoderBlock2D",
							        "UpDecoderBlock2D",
							    ],
							    "vq_embed_dim": 4,
							}



		@property
		def 					__UpperCAmelCase			(							self   )	->							List[str]:
							torch.manual_seed(0   )
							UpperCAmelCase_    :      Dict            =						VQModel(**self.dummy_movq_kwargs   )
							return model



		def 					__UpperCAmelCase			(							self   )	->							List[str]:
							UpperCAmelCase_    :      Any            =						self.dummy_text_encoder
							UpperCAmelCase_    :      List[Any]            =						self.dummy_tokenizer
							UpperCAmelCase_    :      int            =						self.dummy_unet
							UpperCAmelCase_    :      int            =						self.dummy_movq

							UpperCAmelCase_    :      Optional[int]            =						{
							    'num_train_timesteps': 1_0_0_0,
							    'beta_schedule': 'linear',
							    'beta_start': 0.0_00_85,
							    'beta_end': 0.0_12,
							    'clip_sample': False,
							    'set_alpha_to_one': False,
							    'steps_offset': 0,
							    'prediction_type': 'epsilon',
							    'thresholding': False,
							}

							UpperCAmelCase_    :      List[Any]            =						DDIMScheduler(**_UpperCamelCase   )

							UpperCAmelCase_    :      List[Any]            =						{
							    'text_encoder': text_encoder,
							    'tokenizer': tokenizer,
							    'unet': unet,
							    'scheduler': scheduler,
							    'movq': movq,
							}

							return components



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase=0   )	->							Dict:
							UpperCAmelCase_    :      List[str]            =						floats_tensor((1, self.cross_attention_dim)				,		rng=random.Random(_UpperCamelCase   )   ).to(_UpperCamelCase   )
							UpperCAmelCase_    :      Optional[Any]            =						floats_tensor((1, self.cross_attention_dim)				,		rng=random.Random(seed + 1   )   ).to(_UpperCamelCase   )
							# create init_image
							UpperCAmelCase_    :      Tuple            =						floats_tensor((1, 3, 6_4, 6_4)				,		rng=random.Random(_UpperCamelCase   )   ).to(_UpperCamelCase   )
							UpperCAmelCase_    :      Optional[int]            =						image.cpu().permute(0				,		2				,		3				,		1   )[0]
							UpperCAmelCase_    :      Tuple            =						Image.fromarray(np.uinta(_UpperCamelCase   )   ).convert('RGB'   ).resize((2_5_6, 2_5_6)   )

							if str(_UpperCamelCase   ).startswith('mps'   ):
												UpperCAmelCase_    :      List[str]            =						torch.manual_seed(_UpperCamelCase   )
							else:
												UpperCAmelCase_    :      Optional[Any]            =						torch.Generator(device=_UpperCamelCase   ).manual_seed(_UpperCamelCase   )
							UpperCAmelCase_    :      Tuple            =						{
							    'prompt': 'horse',
							    'image': init_image,
							    'image_embeds': image_embeds,
							    'negative_image_embeds': negative_image_embeds,
							    'generator': generator,
							    'height': 6_4,
							    'width': 6_4,
							    'num_inference_steps': 1_0,
							    'guidance_scale': 7.0,
							    'strength': 0.2,
							    'output_type': 'np',
							}
							return inputs



		def 					__UpperCAmelCase			(							self   )	->							Tuple:
							UpperCAmelCase_    :      Dict            =						'cpu'

							UpperCAmelCase_    :      Tuple            =						self.get_dummy_components()

							UpperCAmelCase_    :      str            =						self.pipeline_class(**_UpperCamelCase   )
							UpperCAmelCase_    :      str            =						pipe.to(_UpperCamelCase   )

							pipe.set_progress_bar_config(disable=_UpperCamelCase   )

							UpperCAmelCase_    :      List[str]            =						pipe(**self.get_dummy_inputs(_UpperCamelCase   )   )
							UpperCAmelCase_    :      Optional[int]            =						output.images

							UpperCAmelCase_    :      List[Any]            =						pipe(
							    **self.get_dummy_inputs(_UpperCamelCase   )				,		return_dict=_UpperCamelCase				,		)[0]

							UpperCAmelCase_    :      List[str]            =						image[0, -3:, -3:, -1]
							UpperCAmelCase_    :      List[Any]            =						image_from_tuple[0, -3:, -3:, -1]

							assert image.shape == (1, 6_4, 6_4, 3)

							UpperCAmelCase_    :      Tuple            =						np.array(
							    [0.61_47_49_43, 0.6_07_35_39, 0.43_30_85_44, 0.5_92_82_69, 0.47_49_35_95, 0.46_75_59_73, 0.4_61_38_38, 0.45_36_87_97, 0.50_11_92_33]   )
							assert (
							    np.abs(image_slice.flatten() - expected_slice   ).max() < 1E-2
							), f" expected_slice {expected_slice}, but got {image_slice.flatten()}"
							assert (
							    np.abs(image_from_tuple_slice.flatten() - expected_slice   ).max() < 1E-2
							), f" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}"





@slow
@require_torch_gpu
class   lowerCamelCase      (unittest.TestCase			):







		'''simple docstring'''



		def 					__UpperCAmelCase			(							self   )	->							Tuple:
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()



		def 					__UpperCAmelCase			(							self   )	->							Union[str, Any]:
							UpperCAmelCase_    :      int            =						load_numpy(
							    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
							    '/kandinsky/kandinsky_img2img_frog.npy'   )

							UpperCAmelCase_    :      str            =						load_image(
							    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png'   )
							UpperCAmelCase_    :      Optional[int]            =						'A red cartoon frog, 4k'

							UpperCAmelCase_    :      Union[str, Any]            =						KandinskyPriorPipeline.from_pretrained(
							    'kandinsky-community/kandinsky-2-1-prior'				,		torch_dtype=torch.floataa   )
							pipe_prior.to(_UpperCamelCase   )

							UpperCAmelCase_    :      Optional[Any]            =						KandinskyImgaImgPipeline.from_pretrained(
							    'kandinsky-community/kandinsky-2-1'				,		torch_dtype=torch.floataa   )
							UpperCAmelCase_    :      List[Any]            =						pipeline.to(_UpperCamelCase   )

							pipeline.set_progress_bar_config(disable=_UpperCamelCase   )

							UpperCAmelCase_    :      str            =						torch.Generator(device='cpu'   ).manual_seed(0   )
							UpperCAmelCase_    :      List[Any]            =						pipe_prior(
							    _UpperCamelCase				,		generator=_UpperCamelCase				,		num_inference_steps=5				,		negative_prompt=''				,		).to_tuple()

							UpperCAmelCase_    :      Union[str, Any]            =						pipeline(
							    _UpperCamelCase				,		image=_UpperCamelCase				,		image_embeds=_UpperCamelCase				,		negative_image_embeds=_UpperCamelCase				,		generator=_UpperCamelCase				,		num_inference_steps=1_0_0				,		height=7_6_8				,		width=7_6_8				,		strength=0.2				,		output_type='np'				,		)

							UpperCAmelCase_    :      Dict            =						output.images[0]

							assert image.shape == (7_6_8, 7_6_8, 3)

							assert_mean_pixel_difference(_UpperCamelCase				,		_UpperCamelCase   )










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_ )    ->						Optional[int]:
    if isinstance(lowerCamelCase_							, collections.abc.Iterable ):
        return x
    return (x, x)






@require_flax
class _lowerCamelCase:
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase)       ->   Union[str, Any]:




           """simple docstring"""

           pass
       def 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

           pass
       def 			UpperCamelCase     (					self)       ->   Optional[int]:




           """simple docstring"""

           pass
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase)       ->   Any:




           """simple docstring"""

           _lowercase       :							str      		=		np.abs((a - b)).max()
           self.assertLessEqual(lowerCamelCase,      lowerCamelCase,      F'''Difference between torch and flax is {diff} (>= {tol}).''')
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase=None,      **lowerCamelCase)       ->   Union[str, Any]:




           """simple docstring"""

           _lowercase       :							Any      		=		VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase,      lowerCamelCase)

           _lowercase       :							Optional[int]      		=		FlaxVisionTextDualEncoderModel(lowerCamelCase)

           _lowercase       :							Any      		=		model(input_ids=lowerCamelCase,      pixel_values=lowerCamelCase,      attention_mask=lowerCamelCase)

           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 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase=None,      **lowerCamelCase)       ->   Any:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Union[str, Any]      		=		self.get_vision_text_model(lowerCamelCase,      lowerCamelCase)
           _lowercase       :							str      		=		{'vision_model': vision_model, 'text_model': text_model}
           _lowercase       :							Dict      		=		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase)

           _lowercase       :							List[str]      		=		model(input_ids=lowerCamelCase,      pixel_values=lowerCamelCase,      attention_mask=lowerCamelCase)

           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 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase=None,      **lowerCamelCase)       ->   Union[str, Any]:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Tuple      		=		self.get_vision_text_model(lowerCamelCase,      lowerCamelCase)
           _lowercase       :							List[str]      		=		{'vision_model': vision_model, 'text_model': text_model}
           _lowercase       :							Dict      		=		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase)

           _lowercase       :							List[str]      		=		model(input_ids=lowerCamelCase,      pixel_values=lowerCamelCase,      attention_mask=lowerCamelCase)
           _lowercase       :							Tuple      		=		output[0]

           with tempfile.TemporaryDirectory() as tmpdirname:
               model.save_pretrained(lowerCamelCase)
               _lowercase       :							Any      		=		FlaxVisionTextDualEncoderModel.from_pretrained(lowerCamelCase)

               _lowercase       :							Tuple      		=		model(input_ids=lowerCamelCase,      pixel_values=lowerCamelCase,      attention_mask=lowerCamelCase)
               _lowercase       :							str      		=		after_output[0]
               _lowercase       :							Optional[Any]      		=		np.amax(np.abs(out_a - out_a))
               self.assertLessEqual(lowerCamelCase,      1E-3)
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase=None,      **lowerCamelCase)       ->   str:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Any      		=		self.get_vision_text_model(lowerCamelCase,      lowerCamelCase)
           _lowercase       :							Optional[int]      		=		{'vision_model': vision_model, 'text_model': text_model}
           _lowercase       :							Dict      		=		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase)

           _lowercase       :							Tuple      		=		model(
               input_ids=lowerCamelCase,      pixel_values=lowerCamelCase,      attention_mask=lowerCamelCase,      output_attentions=lowerCamelCase)

           _lowercase       :							int      		=		output.vision_model_output.attentions
           self.assertEqual(len(lowerCamelCase),      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       :							Any      		=		to_atuple(vision_model.config.patch_size)
           _lowercase       :							Dict      		=		(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
           _lowercase       :							Dict      		=		num_patches + 1
           self.assertEqual(vision_attentions[0].shape[-3:],      (vision_config.num_attention_heads, seq_len, seq_len))

           _lowercase       :							List[str]      		=		output.text_model_output.attentions
           self.assertEqual(len(lowerCamelCase),      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 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase)       ->   Optional[int]:




           """simple docstring"""

           pt_model.to(lowerCamelCase)
           pt_model.eval()

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

           with torch.no_grad():
               _lowercase       :							Tuple      		=		pt_model(**lowerCamelCase).to_tuple()

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

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

           _lowercase       :							List[Any]      		=		fx_model_loaded(**lowerCamelCase).to_tuple()
           self.assertEqual(len(lowerCamelCase),      len(lowerCamelCase),      '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(lowerCamelCase,      pt_output.numpy(),      4E-2)

           # Flax -> PT
           with tempfile.TemporaryDirectory() as tmpdirname:
               fx_model.save_pretrained(lowerCamelCase)
               _lowercase       :							List[Any]      		=		VisionTextDualEncoderModel.from_pretrained(lowerCamelCase,      from_flax=lowerCamelCase)

           pt_model_loaded.to(lowerCamelCase)
           pt_model_loaded.eval()

           with torch.no_grad():
               _lowercase       :							Optional[Any]      		=		pt_model_loaded(**lowerCamelCase).to_tuple()

           self.assertEqual(len(lowerCamelCase),      len(lowerCamelCase),      '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(lowerCamelCase,      pt_output_loaded.numpy(),      4E-2)
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase)       ->   Tuple:




           """simple docstring"""

           _lowercase       :							Dict      		=		VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase,      lowerCamelCase)

           _lowercase       :							Optional[Any]      		=		VisionTextDualEncoderModel(lowerCamelCase)
           _lowercase       :							str      		=		FlaxVisionTextDualEncoderModel(lowerCamelCase)

           _lowercase       :							Tuple      		=		convert_pytorch_state_dict_to_flax(pt_model.state_dict(),      lowerCamelCase)
           _lowercase       :							List[Any]      		=		fx_state

           self.check_pt_flax_equivalence(lowerCamelCase,      lowerCamelCase,      lowerCamelCase)
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase)       ->   Dict:




           """simple docstring"""

           _lowercase       :							str      		=		VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase,      lowerCamelCase)

           _lowercase       :							Tuple      		=		VisionTextDualEncoderModel(lowerCamelCase)
           _lowercase       :							Optional[int]      		=		FlaxVisionTextDualEncoderModel(lowerCamelCase)

           _lowercase       :							List[str]      		=		load_flax_weights_in_pytorch_model(lowerCamelCase,      fx_model.params)

           self.check_pt_flax_equivalence(lowerCamelCase,      lowerCamelCase,      lowerCamelCase)
       def 			UpperCamelCase     (					self)       ->   List[Any]:




           """simple docstring"""

           _lowercase       :							int      		=		self.prepare_config_and_inputs()
           self.check_model_from_pretrained_configs(**lowerCamelCase)
       def 			UpperCamelCase     (					self)       ->   Tuple:




           """simple docstring"""

           _lowercase       :							List[str]      		=		self.prepare_config_and_inputs()
           self.check_vision_text_dual_encoder_from_pretrained(**lowerCamelCase)
       def 			UpperCamelCase     (					self)       ->   Union[str, Any]:




           """simple docstring"""

           _lowercase       :							Optional[int]      		=		self.prepare_config_and_inputs()
           self.check_save_load(**lowerCamelCase)
       def 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

           _lowercase       :							str      		=		self.prepare_config_and_inputs()
           self.check_vision_text_output_attention(**lowerCamelCase)
       @is_pt_flax_cross_test
       def 			UpperCamelCase     (					self)       ->   Tuple:




           """simple docstring"""

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

           _lowercase       :							int      		=		config_inputs_dict

           self.check_equivalence_pt_to_flax(lowerCamelCase,      lowerCamelCase,      lowerCamelCase)
           self.check_equivalence_flax_to_pt(lowerCamelCase,      lowerCamelCase,      lowerCamelCase)




       @slow
       def 			UpperCamelCase     (					self)       ->   List[str]:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Optional[Any]      		=		self.get_pretrained_model_and_inputs()

           _lowercase       :							Optional[int]      		=		model_a(**lowerCamelCase)
           _lowercase       :							Tuple      		=		outputs[0]

           with tempfile.TemporaryDirectory() as tmp_dirname:
               model_a.save_pretrained(lowerCamelCase)
               _lowercase       :							int      		=		FlaxVisionTextDualEncoderModel.from_pretrained(lowerCamelCase)

               _lowercase       :							List[Any]      		=		model_a(**lowerCamelCase)
               _lowercase       :							Tuple      		=		after_outputs[0]
               _lowercase       :							Dict      		=		np.amax(np.abs(out_a - out_a))
               self.assertLessEqual(lowerCamelCase,      1E-5)






@require_flax
class _lowerCamelCase(						_a, unittest.TestCase   ):
       def 			UpperCamelCase     (					self)       ->   List[str]:




           """simple docstring"""

           _lowercase       :							Union[str, Any]      		=		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
               'hf-internal-testing/tiny-random-vit',      'hf-internal-testing/tiny-bert',      vision_from_pt=lowerCamelCase,      text_from_pt=lowerCamelCase,      )
           _lowercase       :							List[Any]      		=		13
           _lowercase       :							str      		=		floats_tensor(
               [
                   batch_size,
                   model.config.vision_config.num_channels,
                   model.config.vision_config.image_size,
                   model.config.vision_config.image_size,
               ])
           _lowercase       :							Tuple      		=		ids_tensor([batch_size, 4],      model.config.text_config.vocab_size)
           _lowercase       :							Union[str, Any]      		=		random_attention_mask([batch_size, 4])
           _lowercase       :							int      		=		{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

           return model, inputs
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase)       ->   Any:




           """simple docstring"""

           _lowercase       :							List[Any]      		=		FlaxViTModel(lowerCamelCase)
           _lowercase       :							Optional[Any]      		=		FlaxBertModel(lowerCamelCase)
           return vision_model, text_model




       def 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

           _lowercase       :							List[Any]      		=		FlaxViTModelTester(self)
           _lowercase       :							Any      		=		FlaxBertModelTester(self)
           _lowercase       :							Dict      		=		vit_model_tester.prepare_config_and_inputs()
           _lowercase       :							Any      		=		bert_model_tester.prepare_config_and_inputs()

           _lowercase		,				_lowercase       :							List[str]      		=		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 _lowerCamelCase(						_a, unittest.TestCase   ):
       def 			UpperCamelCase     (					self)       ->   Tuple:




           """simple docstring"""

           _lowercase       :							str      		=		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
               'hf-internal-testing/tiny-random-clip',      'hf-internal-testing/tiny-bert',      vision_from_pt=lowerCamelCase,      text_from_pt=lowerCamelCase,      )
           _lowercase       :							Tuple      		=		13
           _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       :							Union[str, Any]      		=		ids_tensor([batch_size, 4],      model.config.text_config.vocab_size)
           _lowercase       :							Any      		=		random_attention_mask([batch_size, 4])
           _lowercase       :							Dict      		=		{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

           return model, inputs
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase)       ->   Optional[int]:




           """simple docstring"""

           _lowercase       :							Any      		=		FlaxCLIPVisionModel(lowerCamelCase)
           _lowercase       :							Optional[Any]      		=		FlaxBertModel(lowerCamelCase)
           return vision_model, text_model




       def 			UpperCamelCase     (					self)       ->   Dict:




           """simple docstring"""

           _lowercase       :							Tuple      		=		FlaxCLIPVisionModelTester(self)
           _lowercase       :							Union[str, Any]      		=		FlaxBertModelTester(self)
           _lowercase       :							Tuple      		=		clip_model_tester.prepare_config_and_inputs()
           _lowercase       :							str      		=		bert_model_tester.prepare_config_and_inputs()

           _lowercase		,				_lowercase       :							Dict      		=		vision_config_and_inputs

           _lowercase		,				_lowercase		,				_lowercase		,				_lowercase       :							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   ):
       @slow
       def 			UpperCamelCase     (					self)       ->   Optional[int]:




           """simple docstring"""

           _lowercase       :							List[str]      		=		FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian',      logit_scale_init_value=1.0)
           _lowercase       :							List[str]      		=		VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian')

           _lowercase       :							List[Any]      		=		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
           _lowercase       :							List[Any]      		=		processor(
               text=['una foto di un gatto', 'una foto di un cane'],      images=lowerCamelCase,      padding=lowerCamelCase,      return_tensors='np')

           _lowercase       :							List[Any]      		=		model(**lowerCamelCase)

           # 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       :							Optional[int]      		=		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,      lowerCamelCase,      atol=1E-3))


