





import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_flax_cross_test,
    require_flax,
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import is_flax_available, is_torch_available, is_vision_available

from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_flax_bert import FlaxBertModelTester
from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester
from ..vit.test_modeling_flax_vit import FlaxViTModelTester


if is_flax_available():
				from transformers import (
				    FlaxBertModel,
				    FlaxCLIPVisionModel,
				    FlaxVisionTextDualEncoderModel,
				    FlaxViTModel,
				    VisionTextDualEncoderConfig,
				    VisionTextDualEncoderProcessor,
				)
				from transformers.modeling_flax_pytorch_utils import (
				    convert_pytorch_state_dict_to_flax,
				    load_flax_weights_in_pytorch_model,
				)


if is_torch_available():
				import torch

				from transformers import VisionTextDualEncoderModel

if is_vision_available():
				from PIL import Image


def  SCREAMING_SNAKE_CASE   ( _UpperCAmelCase				)    ->  Optional[Any]:
				if isinstance(_UpperCAmelCase		,			collections.abc.Iterable				):
								return x
				return (x, x)

@require_flax
class      lowerCAmelCase							:
	def   A_			(   self						:   List[str]    ,  UpperCAmelCase						:   Dict    ,  UpperCAmelCase						:   str			)    ->			str:
					pass
	def   A_			(   self						:   List[Any]			)    ->			str:
					pass
	def   A_			(   self						:   str			)    ->			Any:
					pass
	def   A_			(   self						:   Optional[int]    ,  UpperCAmelCase						:   np.ndarray    ,  UpperCAmelCase						:   np.ndarray    ,  UpperCAmelCase						:   float			)    ->			List[str]:
					lowerCamelCase__					:   Optional[int]      				=	np.abs((a - b)			).max()
					self.assertLessEqual(UpperCAmelCase    ,  UpperCAmelCase    ,  F"""Difference between torch and flax is {diff} (>= {tol})."""			)
	def   A_			(   self						:   List[str]    ,  UpperCAmelCase						:   Optional[int]    ,  UpperCAmelCase						:   int    ,  UpperCAmelCase						:   Union[str, Any]    ,  UpperCAmelCase						:   Dict    ,  UpperCAmelCase						:   int=None    ,  **UpperCAmelCase						:   Tuple			)    ->			List[str]:
					lowerCamelCase__					:   int      				=	VisionTextDualEncoderConfig.from_vision_text_configs(UpperCAmelCase    ,  UpperCAmelCase			)

					lowerCamelCase__					:   List[str]      				=	FlaxVisionTextDualEncoderModel(UpperCAmelCase			)

					lowerCamelCase__					:   str      				=	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   A_			(   self						:   Union[str, Any]    ,  UpperCAmelCase						:   List[str]    ,  UpperCAmelCase						:   str    ,  UpperCAmelCase						:   List[Any]    ,  UpperCAmelCase						:   str    ,  UpperCAmelCase						:   Any=None    ,  **UpperCAmelCase						:   List[Any]			)    ->			Union[str, Any]:
					lowerCamelCase__					:   List[Any]      				=	self.get_vision_text_model(UpperCAmelCase    ,  UpperCAmelCase			)
					lowerCamelCase__					:   int      				=	{'vision_model': vision_model, 'text_model': text_model}
					lowerCamelCase__					:   Dict      				=	FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCAmelCase			)

					lowerCamelCase__					:   Optional[int]      				=	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   A_			(   self						:   Tuple    ,  UpperCAmelCase						:   Tuple    ,  UpperCAmelCase						:   Union[str, Any]    ,  UpperCAmelCase						:   Any    ,  UpperCAmelCase						:   Tuple    ,  UpperCAmelCase						:   List[Any]=None    ,  **UpperCAmelCase						:   Dict			)    ->			Optional[int]:
					lowerCamelCase__					:   int      				=	self.get_vision_text_model(UpperCAmelCase    ,  UpperCAmelCase			)
					lowerCamelCase__					:   List[Any]      				=	{'vision_model': vision_model, 'text_model': text_model}
					lowerCamelCase__					:   List[Any]      				=	FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCAmelCase			)

					lowerCamelCase__					:   Dict      				=	model(input_ids=UpperCAmelCase    ,  pixel_values=UpperCAmelCase    ,  attention_mask=UpperCAmelCase			)
					lowerCamelCase__					:   str      				=	output[0]

					with tempfile.TemporaryDirectory() as tmpdirname:
									model.save_pretrained(UpperCAmelCase			)
									lowerCamelCase__					:   Optional[Any]      				=	FlaxVisionTextDualEncoderModel.from_pretrained(UpperCAmelCase			)

									lowerCamelCase__					:   int      				=	model(input_ids=UpperCAmelCase    ,  pixel_values=UpperCAmelCase    ,  attention_mask=UpperCAmelCase			)
									lowerCamelCase__					:   Union[str, Any]      				=	after_output[0]
									lowerCamelCase__					:   Tuple      				=	np.amax(np.abs(out_a - out_a			)			)
									self.assertLessEqual(UpperCAmelCase    ,  1e-3			)
	def   A_			(   self						:   Any    ,  UpperCAmelCase						:   str    ,  UpperCAmelCase						:   Optional[int]    ,  UpperCAmelCase						:   Union[str, Any]    ,  UpperCAmelCase						:   Any    ,  UpperCAmelCase						:   Tuple=None    ,  **UpperCAmelCase						:   List[str]			)    ->			Optional[int]:
					lowerCamelCase__					:   Tuple      				=	self.get_vision_text_model(UpperCAmelCase    ,  UpperCAmelCase			)
					lowerCamelCase__					:   Tuple      				=	{'vision_model': vision_model, 'text_model': text_model}
					lowerCamelCase__					:   str      				=	FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCAmelCase			)

					lowerCamelCase__					:   str      				=	model(
					    input_ids=UpperCAmelCase    ,  pixel_values=UpperCAmelCase    ,  attention_mask=UpperCAmelCase    ,  output_attentions=UpperCAmelCase			)

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

					lowerCamelCase__					:   str      				=	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   A_			(   self						:   str    ,  UpperCAmelCase						:   Optional[Any]    ,  UpperCAmelCase						:   List[Any]    ,  UpperCAmelCase						:   str			)    ->			List[Any]:
					pt_model.to(UpperCAmelCase			)
					pt_model.eval()

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

					with torch.no_grad():
									lowerCamelCase__					:   Tuple      				=	pt_model(**UpperCAmelCase			).to_tuple()

					lowerCamelCase__					:   List[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			)
									lowerCamelCase__					:   Optional[int]      				=	FlaxVisionTextDualEncoderModel.from_pretrained(UpperCAmelCase    ,  from_pt=UpperCAmelCase			)

					lowerCamelCase__					:   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			)
									lowerCamelCase__					:   Any      				=	VisionTextDualEncoderModel.from_pretrained(UpperCAmelCase    ,  from_flax=UpperCAmelCase			)

					pt_model_loaded.to(UpperCAmelCase			)
					pt_model_loaded.eval()

					with torch.no_grad():
									lowerCamelCase__					:   int      				=	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   A_			(   self						:   List[str]    ,  UpperCAmelCase						:   Optional[Any]    ,  UpperCAmelCase						:   str    ,  UpperCAmelCase						:   str			)    ->			List[Any]:
					lowerCamelCase__					:   List[str]      				=	VisionTextDualEncoderConfig.from_vision_text_configs(UpperCAmelCase    ,  UpperCAmelCase			)

					lowerCamelCase__					:   List[str]      				=	VisionTextDualEncoderModel(UpperCAmelCase			)
					lowerCamelCase__					:   Tuple      				=	FlaxVisionTextDualEncoderModel(UpperCAmelCase			)

					lowerCamelCase__					:   Union[str, Any]      				=	convert_pytorch_state_dict_to_flax(pt_model.state_dict()    ,  UpperCAmelCase			)
					lowerCamelCase__					:   Optional[Any]      				=	fx_state

					self.check_pt_flax_equivalence(UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase			)
	def   A_			(   self						:   Any    ,  UpperCAmelCase						:   Optional[int]    ,  UpperCAmelCase						:   Tuple    ,  UpperCAmelCase						:   Union[str, Any]			)    ->			str:
					lowerCamelCase__					:   Optional[Any]      				=	VisionTextDualEncoderConfig.from_vision_text_configs(UpperCAmelCase    ,  UpperCAmelCase			)

					lowerCamelCase__					:   Optional[Any]      				=	VisionTextDualEncoderModel(UpperCAmelCase			)
					lowerCamelCase__					:   str      				=	FlaxVisionTextDualEncoderModel(UpperCAmelCase			)

					lowerCamelCase__					:   str      				=	load_flax_weights_in_pytorch_model(UpperCAmelCase    ,  fx_model.params			)

					self.check_pt_flax_equivalence(UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase			)
	def   A_			(   self						:   Union[str, Any]			)    ->			Union[str, Any]:
					lowerCamelCase__					:   Tuple      				=	self.prepare_config_and_inputs()
					self.check_model_from_pretrained_configs(**UpperCAmelCase			)
	def   A_			(   self						:   Any			)    ->			List[str]:
					lowerCamelCase__					:   List[Any]      				=	self.prepare_config_and_inputs()
					self.check_vision_text_dual_encoder_from_pretrained(**UpperCAmelCase			)
	def   A_			(   self						:   Union[str, Any]			)    ->			Dict:
					lowerCamelCase__					:   Union[str, Any]      				=	self.prepare_config_and_inputs()
					self.check_save_load(**UpperCAmelCase			)
	def   A_			(   self						:   str			)    ->			int:
					lowerCamelCase__					:   List[Any]      				=	self.prepare_config_and_inputs()
					self.check_vision_text_output_attention(**UpperCAmelCase			)
	@is_pt_flax_cross_test
	def   A_			(   self						:   List[Any]			)    ->			Union[str, Any]:
					lowerCamelCase__					:   int      				=	self.prepare_config_and_inputs()
					lowerCamelCase__					:   int      				=	config_inputs_dict.pop('vision_config'			)
					lowerCamelCase__					:   Any      				=	config_inputs_dict.pop('text_config'			)

					lowerCamelCase__					:   Union[str, Any]      				=	config_inputs_dict

					self.check_equivalence_pt_to_flax(UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase			)
					self.check_equivalence_flax_to_pt(UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase			)







	@slow
	def   A_			(   self						:   Tuple			)    ->			Optional[int]:
					lowerCamelCase__					:   Dict      				=	self.get_pretrained_model_and_inputs()

					lowerCamelCase__					:   Tuple      				=	model_a(**UpperCAmelCase			)
					lowerCamelCase__					:   Optional[Any]      				=	outputs[0]

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

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


@require_flax
class      lowerCAmelCase							(      __UpperCamelCase,						unittest.TestCase    ):
	def   A_			(   self						:   Any			)    ->			Dict:
					lowerCamelCase__					:   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    ,  )
					lowerCamelCase__					:   Dict      				=	13
					lowerCamelCase__					:   Optional[Any]      				=	floats_tensor(
					    [
					        batch_size,
					        model.config.vision_config.num_channels,
					        model.config.vision_config.image_size,
					        model.config.vision_config.image_size,
					    ]			)
					lowerCamelCase__					:   Dict      				=	ids_tensor([batch_size, 4]    ,  model.config.text_config.vocab_size			)
					lowerCamelCase__					:   str      				=	random_attention_mask([batch_size, 4]			)
					lowerCamelCase__					:   Union[str, Any]      				=	{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

					return model, inputs
	def   A_			(   self						:   Dict    ,  UpperCAmelCase						:   int    ,  UpperCAmelCase						:   Tuple			)    ->			List[str]:
					lowerCamelCase__					:   Tuple      				=	FlaxViTModel(UpperCAmelCase			)
					lowerCamelCase__					:   List[Any]      				=	FlaxBertModel(UpperCAmelCase			)
					return vision_model, text_model







	def   A_			(   self						:   Any			)    ->			str:
					lowerCamelCase__					:   str      				=	FlaxViTModelTester(self			)
					lowerCamelCase__					:   int      				=	FlaxBertModelTester(self			)
					lowerCamelCase__					:   Any      				=	vit_model_tester.prepare_config_and_inputs()
					lowerCamelCase__					:   Tuple      				=	bert_model_tester.prepare_config_and_inputs()

					lowerCamelCase__					:   Dict      				=	vision_config_and_inputs

					lowerCamelCase__					:   List[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_torch
class      lowerCAmelCase							(      __UpperCamelCase,						unittest.TestCase    ):
	def   A_			(   self						:   Optional[Any]			)    ->			List[Any]:
					lowerCamelCase__					:   Optional[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    ,  )
					lowerCamelCase__					:   List[Any]      				=	13
					lowerCamelCase__					:   Optional[int]      				=	floats_tensor(
					    [
					        batch_size,
					        model.config.vision_config.num_channels,
					        model.config.vision_config.image_size,
					        model.config.vision_config.image_size,
					    ]			)
					lowerCamelCase__					:   Dict      				=	ids_tensor([batch_size, 4]    ,  model.config.text_config.vocab_size			)
					lowerCamelCase__					:   Optional[int]      				=	random_attention_mask([batch_size, 4]			)
					lowerCamelCase__					:   List[Any]      				=	{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

					return model, inputs
	def   A_			(   self						:   Optional[Any]    ,  UpperCAmelCase						:   List[Any]    ,  UpperCAmelCase						:   List[str]			)    ->			str:
					lowerCamelCase__					:   Tuple      				=	FlaxCLIPVisionModel(UpperCAmelCase			)
					lowerCamelCase__					:   str      				=	FlaxBertModel(UpperCAmelCase			)
					return vision_model, text_model







	def   A_			(   self						:   List[Any]			)    ->			Any:
					lowerCamelCase__					:   Dict      				=	FlaxCLIPVisionModelTester(self			)
					lowerCamelCase__					:   Tuple      				=	FlaxBertModelTester(self			)
					lowerCamelCase__					:   str      				=	clip_model_tester.prepare_config_and_inputs()
					lowerCamelCase__					:   List[str]      				=	bert_model_tester.prepare_config_and_inputs()

					lowerCamelCase__					:   Optional[int]      				=	vision_config_and_inputs

					lowerCamelCase__					:   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      lowerCAmelCase							(      unittest.TestCase    ):
	@slow
	def   A_			(   self						:   Optional[int]			)    ->			List[str]:
					lowerCamelCase__					:   Optional[int]      				=	FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian'    ,  logit_scale_init_value=1.0			)
					lowerCamelCase__					:   List[str]      				=	VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian'			)

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

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

					lowerCamelCase__					:   Dict      				=	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    ,  UpperCAmelCase    ,  atol=1e-3			)			)












import socket


def  SCREAMING_SNAKE_CASE   ( )    ->  Any:
    lowerCamelCase__					:   int      				=	socket.socket(socket.AF_INET		,			socket.SOCK_STREAM				)
    lowerCamelCase__					:   Optional[int]      				=	socket.gethostname()
    lowerCamelCase__					:   Optional[int]      				=	1_2312

    sock.connect((host, port)				)
    sock.send(b'Hello server!'				)

    with open('Received_file'		,			'wb'				) as out_file:
        print('File opened'				)
        print('Receiving data...'				)
        while True:
            lowerCamelCase__					:   str      				=	sock.recv(1024				)
            if not data:
                break
            out_file.write(_UpperCAmelCase				)

    print('Successfully received the file'				)
    sock.close()
    print('Connection closed'				)


if __name__ == "__main__":
    main()





