






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 					lowercase_ (    __snake_case     :							Any      )     -> Any:





				'''simple docstring'''


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


@require_flax
class 					_snake_case						:






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase       )						->    str:
					pass






	def    lowerCAmelCase_							(		self       )						->    str:
					pass






	def    lowerCAmelCase_							(		self       )						->    List[str]:
					pass






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase       )						->    Tuple:
					snake_case__      :Optional[int]         =   np.abs((a - b)       ).max()
					self.assertLessEqual(UpperCamelCase					,UpperCamelCase					,f'Difference between torch and flax is {diff} (>= {tol}).'       )






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase=None					,**UpperCamelCase       )						->    Dict:
					snake_case__      :Optional[int]         =   VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase					,UpperCamelCase       )

					snake_case__      :List[str]         =   FlaxVisionTextDualEncoderModel(UpperCamelCase       )

					snake_case__      :Dict         =   model(input_ids=UpperCamelCase					,pixel_values=UpperCamelCase					,attention_mask=UpperCamelCase       )

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

					snake_case__      :str         =   model(input_ids=UpperCamelCase					,pixel_values=UpperCamelCase					,attention_mask=UpperCamelCase       )

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

					snake_case__      :Any         =   model(input_ids=UpperCamelCase					,pixel_values=UpperCamelCase					,attention_mask=UpperCamelCase       )
					snake_case__      :Any         =   output[0]

					with tempfile.TemporaryDirectory() as tmpdirname:
									model.save_pretrained(UpperCamelCase       )
									snake_case__      :Any         =   FlaxVisionTextDualEncoderModel.from_pretrained(UpperCamelCase       )

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






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase=None					,**UpperCamelCase       )						->    int:
					snake_case__      :List[Any]         =   self.get_vision_text_model(UpperCamelCase					,UpperCamelCase       )
					snake_case__      :Union[str, Any]         =   {"vision_model": vision_model, "text_model": text_model}
					snake_case__      :Optional[Any]         =   FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCamelCase       )

					snake_case__      :int         =   model(
					    input_ids=UpperCamelCase					,pixel_values=UpperCamelCase					,attention_mask=UpperCamelCase					,output_attentions=UpperCamelCase       )

					snake_case__      :Tuple         =   output.vision_model_output.attentions
					self.assertEqual(len(UpperCamelCase       )					,vision_config.num_hidden_layers       )

					# in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
					snake_case__      :Optional[Any]         =   to_atuple(vision_model.config.image_size       )
					snake_case__      :int         =   to_atuple(vision_model.config.patch_size       )
					snake_case__      :List[Any]         =   (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
					snake_case__      :List[str]         =   num_patches + 1
					self.assertEqual(vision_attentions[0].shape[-3:]					,(vision_config.num_attention_heads, seq_len, seq_len)       )

					snake_case__      :Optional[Any]         =   output.text_model_output.attentions
					self.assertEqual(len(UpperCamelCase       )					,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					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase       )						->    Union[str, Any]:
					pt_model.to(UpperCamelCase       )
					pt_model.eval()

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

					with torch.no_grad():
									snake_case__      :str         =   pt_model(**UpperCamelCase       ).to_tuple()

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

					# PT -> Flax
					with tempfile.TemporaryDirectory() as tmpdirname:
									pt_model.save_pretrained(UpperCamelCase       )
									snake_case__      :Optional[int]         =   FlaxVisionTextDualEncoderModel.from_pretrained(UpperCamelCase					,from_pt=UpperCamelCase       )

					snake_case__      :str         =   fx_model_loaded(**UpperCamelCase       ).to_tuple()
					self.assertEqual(len(UpperCamelCase       )					,len(UpperCamelCase       )					,"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(UpperCamelCase					,pt_output.numpy()					,4E-2       )

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

					pt_model_loaded.to(UpperCamelCase       )
					pt_model_loaded.eval()

					with torch.no_grad():
									snake_case__      :Tuple         =   pt_model_loaded(**UpperCamelCase       ).to_tuple()

					self.assertEqual(len(UpperCamelCase       )					,len(UpperCamelCase       )					,"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(UpperCamelCase					,pt_output_loaded.numpy()					,4E-2       )






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase       )						->    Optional[int]:
					snake_case__      :List[Any]         =   VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase					,UpperCamelCase       )

					snake_case__      :str         =   VisionTextDualEncoderModel(UpperCamelCase       )
					snake_case__      :int         =   FlaxVisionTextDualEncoderModel(UpperCamelCase       )

					snake_case__      :Optional[Any]         =   convert_pytorch_state_dict_to_flax(pt_model.state_dict()					,UpperCamelCase       )
					snake_case__      :int         =   fx_state

					self.check_pt_flax_equivalence(UpperCamelCase					,UpperCamelCase					,UpperCamelCase       )






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase					,UpperCamelCase       )						->    Optional[int]:
					snake_case__      :Union[str, Any]         =   VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase					,UpperCamelCase       )

					snake_case__      :Tuple         =   VisionTextDualEncoderModel(UpperCamelCase       )
					snake_case__      :Union[str, Any]         =   FlaxVisionTextDualEncoderModel(UpperCamelCase       )

					snake_case__      :List[Any]         =   load_flax_weights_in_pytorch_model(UpperCamelCase					,fx_model.params       )

					self.check_pt_flax_equivalence(UpperCamelCase					,UpperCamelCase					,UpperCamelCase       )






	def    lowerCAmelCase_							(		self       )						->    int:
					snake_case__      :Optional[Any]         =   self.prepare_config_and_inputs()
					self.check_model_from_pretrained_configs(**UpperCamelCase       )






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






	def    lowerCAmelCase_							(		self       )						->    List[str]:
					snake_case__      :Optional[int]         =   self.prepare_config_and_inputs()
					self.check_save_load(**UpperCamelCase       )






	def    lowerCAmelCase_							(		self       )						->    Optional[int]:
					snake_case__      :List[str]         =   self.prepare_config_and_inputs()
					self.check_vision_text_output_attention(**UpperCamelCase       )






	@is_pt_flax_cross_test
	def    lowerCAmelCase_							(		self       )						->    int:
					snake_case__      :List[Any]         =   self.prepare_config_and_inputs()
					snake_case__      :Optional[int]         =   config_inputs_dict.pop("vision_config"       )
					snake_case__      :Dict         =   config_inputs_dict.pop("text_config"       )

					snake_case__      :Optional[Any]         =   config_inputs_dict

					self.check_equivalence_pt_to_flax(UpperCamelCase					,UpperCamelCase					,UpperCamelCase       )
					self.check_equivalence_flax_to_pt(UpperCamelCase					,UpperCamelCase					,UpperCamelCase       )






	@slow
	def    lowerCAmelCase_							(		self       )						->    Optional[int]:
					snake_case__      :Dict         =   self.get_pretrained_model_and_inputs()

					snake_case__      :List[Any]         =   model_a(**UpperCamelCase       )
					snake_case__      :Optional[int]         =   outputs[0]

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

									snake_case__      :List[str]         =   model_a(**UpperCamelCase       )
									snake_case__      :Tuple         =   after_outputs[0]
									snake_case__      :Optional[int]         =   np.amax(np.abs(out_a - out_a       )       )
									self.assertLessEqual(UpperCamelCase					,1E-5       )




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






	def    lowerCAmelCase_							(		self       )						->    List[str]:
					snake_case__      :Any         =   FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
					    "hf-internal-testing/tiny-random-vit"					,"hf-internal-testing/tiny-bert"					,vision_from_pt=UpperCamelCase					,text_from_pt=UpperCamelCase					,)
					snake_case__      :Union[str, Any]         =   13
					snake_case__      :List[Any]         =   floats_tensor(
					    [
					        batch_size,
					        model.config.vision_config.num_channels,
					        model.config.vision_config.image_size,
					        model.config.vision_config.image_size,
					    ]       )
					snake_case__      :Union[str, Any]         =   ids_tensor([batch_size, 4]					,model.config.text_config.vocab_size       )
					snake_case__      :Optional[int]         =   random_attention_mask([batch_size, 4]       )
					snake_case__      :Optional[Any]         =   {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

					return model, inputs






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase       )						->    List[str]:
					snake_case__      :Dict         =   FlaxViTModel(UpperCamelCase       )
					snake_case__      :Tuple         =   FlaxBertModel(UpperCamelCase       )
					return vision_model, text_model






	def    lowerCAmelCase_							(		self       )						->    List[Any]:
					snake_case__      :Optional[int]         =   FlaxViTModelTester(self       )
					snake_case__      :Optional[Any]         =   FlaxBertModelTester(self       )
					snake_case__      :Dict         =   vit_model_tester.prepare_config_and_inputs()
					snake_case__      :int         =   bert_model_tester.prepare_config_and_inputs()

					snake_case__      :int         =   vision_config_and_inputs

					snake_case__      :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_torch
class 					_snake_case						(			_A       ,    unittest.TestCase ):






	def    lowerCAmelCase_							(		self       )						->    Any:
					snake_case__      :int         =   FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
					    "hf-internal-testing/tiny-random-clip"					,"hf-internal-testing/tiny-bert"					,vision_from_pt=UpperCamelCase					,text_from_pt=UpperCamelCase					,)
					snake_case__      :List[Any]         =   13
					snake_case__      :Dict         =   floats_tensor(
					    [
					        batch_size,
					        model.config.vision_config.num_channels,
					        model.config.vision_config.image_size,
					        model.config.vision_config.image_size,
					    ]       )
					snake_case__      :Union[str, Any]         =   ids_tensor([batch_size, 4]					,model.config.text_config.vocab_size       )
					snake_case__      :Optional[Any]         =   random_attention_mask([batch_size, 4]       )
					snake_case__      :Optional[int]         =   {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

					return model, inputs






	def    lowerCAmelCase_							(		self					,UpperCamelCase					,UpperCamelCase       )						->    int:
					snake_case__      :Any         =   FlaxCLIPVisionModel(UpperCamelCase       )
					snake_case__      :Union[str, Any]         =   FlaxBertModel(UpperCamelCase       )
					return vision_model, text_model






	def    lowerCAmelCase_							(		self       )						->    List[Any]:
					snake_case__      :Optional[Any]         =   FlaxCLIPVisionModelTester(self       )
					snake_case__      :Optional[int]         =   FlaxBertModelTester(self       )
					snake_case__      :Tuple         =   clip_model_tester.prepare_config_and_inputs()
					snake_case__      :int         =   bert_model_tester.prepare_config_and_inputs()

					snake_case__      :Optional[int]         =   vision_config_and_inputs

					snake_case__      :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 					_snake_case						(			unittest.TestCase ):






	@slow
	def    lowerCAmelCase_							(		self       )						->    Dict:
					snake_case__      :Dict         =   FlaxVisionTextDualEncoderModel.from_pretrained("clip-italian/clip-italian"					,logit_scale_init_value=1.0       )
					snake_case__      :Any         =   VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian"       )

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

					snake_case__      :List[Any]         =   model(**UpperCamelCase       )

					# 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])					,)

					snake_case__      :Dict         =   np.array([[1.2284727, 0.3104122]]       )

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







__UpperCAmelCase							:   int							=  {"a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": []}
__UpperCAmelCase							:   List[str]							=  ["a", "b", "c", "d", "e"]





def 					lowercase_ (    __snake_case     :							Optional[Any]	,	__snake_case     :							List[Any]	,	__snake_case     :							Tuple      )     -> Optional[int]:





				'''simple docstring'''


				snake_case__      :List[Any]         =   start
				# add current to visited
				visited.append(__snake_case      )
				snake_case__      :List[str]         =   edges[current]
				for neighbor in neighbors:
								# if neighbor not in visited, visit
								if neighbor not in visited:
												snake_case__      :Any         =   topological_sort(__snake_case	,	__snake_case	,	__snake_case      )
    # if all neighbors visited add current to sort
				sort.append(__snake_case      )
				# if all vertices haven't been visited select a new one to visit
				if len(__snake_case      ) != len(__snake_case      ):
								for vertice in vertices:
												if vertice not in visited:
																snake_case__      :Any         =   topological_sort(__snake_case	,	__snake_case	,	__snake_case      )
    # return sort
				return sort


if __name__ == "__main__":
	__UpperCAmelCase							:   Tuple							=  topological_sort("a", [], [])
	print(sort)