


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




@require_flax
class        _UpperCamelCase	:


				'''simple docstring'''


				def 	a__		(     self							,      a_							,      a_							)    ->  Optional[int]:
					pass

				def 	a__		(     self							)    ->  Tuple:
					pass

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

				def 	a__		(     self							,      a_							,      a_							,      a_							)    ->  str:
					lowercase						:		str   					=		np.abs((a - b)							).max()
					self.assertLessEqual(a_							,      a_							,      F'''Difference between torch and flax is {diff} (>= {tol}).'''							)

				def 	a__		(     self							,      a_							,      a_							,      a_							,      a_							,      a_=None							,      **a_							)    ->  Tuple:
					lowercase						:		Tuple   					=		VisionTextDualEncoderConfig.from_vision_text_configs(a_							,      a_							)

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

					lowercase						:		Optional[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						:		str   					=		FlaxVisionTextDualEncoderModel.from_pretrained(a_							)

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

				def 	a__		(     self							,      a_							,      a_							,      a_							,      a_							,      a_=None							,      **a_							)    ->  int:
					lowercase					,		lowercase						:		List[str]   					=		self.get_vision_text_model(a_							,      a_							)
					lowercase						:		Dict   					=		{"vision_model": vision_model, "text_model": text_model}
					lowercase						:		Dict   					=		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**a_							)

					lowercase						:		Optional[Any]   					=		model(
					    input_ids=a_							,      pixel_values=a_							,      attention_mask=a_							,      output_attentions=a_							)

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

					lowercase						:		Optional[int]   					=		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 	a__		(     self							,      a_							,      a_							,      a_							)    ->  List[Any]:
					pt_model.to(a_							)
					pt_model.eval()

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

					with torch.no_grad():
						lowercase						:		Optional[int]   					=		pt_model(**a_							).to_tuple()

					lowercase						:		List[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						:		List[str]   					=		FlaxVisionTextDualEncoderModel.from_pretrained(a_							,      from_pt=a_							)

					lowercase						:		Optional[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						:		Union[str, 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 	a__		(     self							,      a_							,      a_							,      a_							)    ->  List[str]:
					lowercase						:		int   					=		VisionTextDualEncoderConfig.from_vision_text_configs(a_							,      a_							)

					lowercase						:		Optional[int]   					=		VisionTextDualEncoderModel(a_							)
					lowercase						:		Union[str, Any]   					=		FlaxVisionTextDualEncoderModel(a_							)

					lowercase						:		List[str]   					=		convert_pytorch_state_dict_to_flax(pt_model.state_dict()							,      a_							)
					lowercase						:		Tuple   					=		fx_state

					self.check_pt_flax_equivalence(a_							,      a_							,      a_							)

				def 	a__		(     self							,      a_							,      a_							,      a_							)    ->  Tuple:
					lowercase						:		str   					=		VisionTextDualEncoderConfig.from_vision_text_configs(a_							,      a_							)

					lowercase						:		Optional[int]   					=		VisionTextDualEncoderModel(a_							)
					lowercase						:		Optional[int]   					=		FlaxVisionTextDualEncoderModel(a_							)

					lowercase						:		int   					=		load_flax_weights_in_pytorch_model(a_							,      fx_model.params							)

					self.check_pt_flax_equivalence(a_							,      a_							,      a_							)

				def 	a__		(     self							)    ->  List[str]:
					lowercase						:		Optional[int]   					=		self.prepare_config_and_inputs()
					self.check_model_from_pretrained_configs(**a_							)

				def 	a__		(     self							)    ->  Dict:
					lowercase						:		Optional[int]   					=		self.prepare_config_and_inputs()
					self.check_vision_text_dual_encoder_from_pretrained(**a_							)

				def 	a__		(     self							)    ->  int:
					lowercase						:		int   					=		self.prepare_config_and_inputs()
					self.check_save_load(**a_							)

				def 	a__		(     self							)    ->  int:
					lowercase						:		Tuple   					=		self.prepare_config_and_inputs()
					self.check_vision_text_output_attention(**a_							)

				@is_pt_flax_cross_test
				def 	a__		(     self							)    ->  Optional[int]:
					lowercase						:		Union[str, Any]   					=		self.prepare_config_and_inputs()
					lowercase						:		int   					=		config_inputs_dict.pop("vision_config"							)
					lowercase						:		Optional[int]   					=		config_inputs_dict.pop("text_config"							)

					lowercase						:		Optional[Any]   					=		config_inputs_dict

					self.check_equivalence_pt_to_flax(a_							,      a_							,      a_							)
					self.check_equivalence_flax_to_pt(a_							,      a_							,      a_							)


				@slow
				def 	a__		(     self							)    ->  Tuple:
					lowercase					,		lowercase						:		Dict   					=		self.get_pretrained_model_and_inputs()

					lowercase						:		int   					=		model_a(**a_							)
					lowercase						:		int   					=		outputs[0]

					with tempfile.TemporaryDirectory() as tmp_dirname:
						model_a.save_pretrained(a_							)
						lowercase						:		List[str]   					=		FlaxVisionTextDualEncoderModel.from_pretrained(a_							)

						lowercase						:		Dict   					=		model_a(**a_							)
						lowercase						:		int   					=		after_outputs[0]
						lowercase						:		int   					=		np.amax(np.abs(out_a - out_a							)							)
						self.assertLessEqual(a_							,      1e-5							)




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


				'''simple docstring'''


				def 	a__		(     self							)    ->  Tuple:
					lowercase						:		List[Any]   					=		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						:		str   					=		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						:		str   					=		random_attention_mask([batch_size, 4]							)
					lowercase						:		Any   					=		{"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

					return model, inputs

				def 	a__		(     self							,      a_							,      a_							)    ->  int:
					lowercase						:		Dict   					=		FlaxViTModel(a_							)
					lowercase						:		int   					=		FlaxBertModel(a_							)
					return vision_model, text_model


				def 	a__		(     self							)    ->  Dict:
					lowercase						:		int   					=		FlaxViTModelTester(self							)
					lowercase						:		Tuple   					=		FlaxBertModelTester(self							)
					lowercase						:		Any   					=		vit_model_tester.prepare_config_and_inputs()
					lowercase						:		int   					=		bert_model_tester.prepare_config_and_inputs()

					lowercase					,		lowercase						:		int   					=		vision_config_and_inputs

					lowercase					,		lowercase					,		lowercase					,		lowercase						:		Dict   					=		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	(    SCREAMING_SNAKE_CASE						,			unittest.TestCase):


				'''simple docstring'''


				def 	a__		(     self							)    ->  Any:
					lowercase						:		Dict   					=		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						:		Tuple   					=		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						:		List[Any]   					=		ids_tensor([batch_size, 4]							,      model.config.text_config.vocab_size							)
					lowercase						:		Any   					=		random_attention_mask([batch_size, 4]							)
					lowercase						:		List[str]   					=		{"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

					return model, inputs

				def 	a__		(     self							,      a_							,      a_							)    ->  Dict:
					lowercase						:		Dict   					=		FlaxCLIPVisionModel(a_							)
					lowercase						:		Union[str, Any]   					=		FlaxBertModel(a_							)
					return vision_model, text_model


				def 	a__		(     self							)    ->  Optional[Any]:
					lowercase						:		List[str]   					=		FlaxCLIPVisionModelTester(self							)
					lowercase						:		List[Any]   					=		FlaxBertModelTester(self							)
					lowercase						:		Optional[int]   					=		clip_model_tester.prepare_config_and_inputs()
					lowercase						:		List[Any]   					=		bert_model_tester.prepare_config_and_inputs()

					lowercase					,		lowercase						:		str   					=		vision_config_and_inputs

					lowercase					,		lowercase					,		lowercase					,		lowercase						:		str   					=		text_config_and_inputs

					# make sure that cross attention layers are added
					return {
					    "text_config": text_config,
					    "vision_config": vision_config,
					    "pixel_values": pixel_values,
					    "attention_mask": attention_mask,
					    "input_ids": input_ids,
					    "token_type_ids": token_type_ids,
					}




@require_flax
@require_vision
class        _UpperCamelCase	(    unittest.TestCase):


				'''simple docstring'''


				@slow
				def 	a__		(     self							)    ->  Tuple:
					lowercase						:		List[str]   					=		FlaxVisionTextDualEncoderModel.from_pretrained("clip-italian/clip-italian"							,      logit_scale_init_value=1.0							)
					lowercase						:		Dict   					=		VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian"							)

					lowercase						:		List[str]   					=		Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"							)
					lowercase						:		List[str]   					=		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						:		Optional[Any]   					=		np.array([[1.2_28_47_27, 0.3_10_41_22]]							)

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






'''simple docstring'''
import unittest

import numpy as np

from transformers import DistilBertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
					import jax.numpy as jnp

					from transformers.models.distilbert.modeling_flax_distilbert import (
					    FlaxDistilBertForMaskedLM,
					    FlaxDistilBertForMultipleChoice,
					    FlaxDistilBertForQuestionAnswering,
					    FlaxDistilBertForSequenceClassification,
					    FlaxDistilBertForTokenClassification,
					    FlaxDistilBertModel,
					)




class        _UpperCamelCase	(    unittest.TestCase):


				'''simple docstring'''


				def __init__(     self							,      a_							,      a_=1_3							,      a_=7							,      a_=True							,      a_=True							,      a_=True							,      a_=True							,      a_=9_9							,      a_=3_2							,      a_=5							,      a_=4							,      a_=3_7							,      a_="gelu"							,      a_=0.1							,      a_=0.1							,      a_=5_1_2							,      a_=1_6							,      a_=2							,      a_=0.02							,      a_=4							,      )    ->  Tuple:
					lowercase						:		Optional[Any]   					=		parent
					lowercase						:		int   					=		batch_size
					lowercase						:		int   					=		seq_length
					lowercase						:		List[str]   					=		is_training
					lowercase						:		str   					=		use_attention_mask
					lowercase						:		List[str]   					=		use_token_type_ids
					lowercase						:		Optional[Any]   					=		use_labels
					lowercase						:		Dict   					=		vocab_size
					lowercase						:		Union[str, Any]   					=		hidden_size
					lowercase						:		int   					=		num_hidden_layers
					lowercase						:		Optional[Any]   					=		num_attention_heads
					lowercase						:		Optional[Any]   					=		intermediate_size
					lowercase						:		int   					=		hidden_act
					lowercase						:		Dict   					=		hidden_dropout_prob
					lowercase						:		Optional[Any]   					=		attention_probs_dropout_prob
					lowercase						:		Dict   					=		max_position_embeddings
					lowercase						:		Tuple   					=		type_vocab_size
					lowercase						:		int   					=		type_sequence_label_size
					lowercase						:		Optional[Any]   					=		initializer_range
					lowercase						:		Union[str, Any]   					=		num_choices

				def 	a__		(     self							)    ->  Optional[int]:
					lowercase						:		List[Any]   					=		ids_tensor([self.batch_size, self.seq_length]							,      self.vocab_size							)

					lowercase						:		Any   					=		None
					if self.use_attention_mask:
						lowercase						:		str   					=		random_attention_mask([self.batch_size, self.seq_length]							)

					lowercase						:		Optional[Any]   					=		DistilBertConfig(
					    vocab_size=self.vocab_size							,      dim=self.hidden_size							,      n_layers=self.num_hidden_layers							,      n_heads=self.num_attention_heads							,      hidden_dim=self.intermediate_size							,      hidden_act=self.hidden_act							,      dropout=self.hidden_dropout_prob							,      attention_dropout=self.attention_probs_dropout_prob							,      max_position_embeddings=self.max_position_embeddings							,      initializer_range=self.initializer_range							,      tie_weights_=a_							,      )

					return config, input_ids, attention_mask


				def 	a__		(     self							)    ->  List[str]:
					lowercase						:		Dict   					=		self.prepare_config_and_inputs()
					lowercase					,		lowercase					,		lowercase						:		Dict   					=		config_and_inputs
					lowercase						:		Any   					=		{"input_ids": input_ids, "attention_mask": attention_mask}
					return config, inputs_dict




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


				'''simple docstring'''


				_snake_case						       =				(
				    (
				        FlaxDistilBertModel,
				        FlaxDistilBertForMaskedLM,
				        FlaxDistilBertForMultipleChoice,
				        FlaxDistilBertForQuestionAnswering,
				        FlaxDistilBertForSequenceClassification,
				        FlaxDistilBertForTokenClassification,
				        FlaxDistilBertForQuestionAnswering,
				    )
				    if is_flax_available()
				    else ()
				)

				def 	a__		(     self							)    ->  Dict:
					lowercase						:		Optional[int]   					=		FlaxDistilBertModelTester(self							)


				@slow
				def 	a__		(     self							)    ->  Union[str, Any]:
					for model_class_name in self.all_model_classes:
						lowercase						:		int   					=		model_class_name.from_pretrained("distilbert-base-uncased"							)
						lowercase						:		Tuple   					=		model(np.ones((1, 1)							)							)
						self.assertIsNotNone(a_							)




@require_flax
class        _UpperCamelCase	(    unittest.TestCase):


				'''simple docstring'''


				@slow
				def 	a__		(     self							)    ->  Union[str, Any]:
					lowercase						:		str   					=		FlaxDistilBertModel.from_pretrained("distilbert-base-uncased"							)
					lowercase						:		int   					=		np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]							)
					lowercase						:		int   					=		np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]							)
					lowercase						:		List[str]   					=		model(a_							,      attention_mask=a_							)[0]
					lowercase						:		int   					=		(1, 1_1, 7_6_8)
					self.assertEqual(output.shape							,      a_							)
					lowercase						:		List[str]   					=		np.array([[[-0.16_39, 0.32_99, 0.16_48], [-0.17_46, 0.32_89, 0.17_10], [-0.18_84, 0.33_57, 0.18_10]]]							)

					self.assertTrue(jnp.allclose(output[:, 1:4, 1:4]							,      a_							,      atol=1e-4							)							)


