


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       (			__lowerCAmelCase							:    Tuple       ):
							if isinstance(UpperCAmelCase__ ,   collections.abc.Iterable       ):
														return x
							return (x, x)







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

												a__					=					FlaxVisionTextDualEncoderModel(UpperCamelCase__				)

												a__					=					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       :str      ,__snake_case       :int      ,__snake_case       :List[Any]      ,__snake_case       :str      ,__snake_case       :str      ,__snake_case       :Any=None      ,**__snake_case       :str				) ->   str:
												a__				, a__					=					self.get_vision_text_model(UpperCamelCase__      ,UpperCamelCase__				)
												a__					=					{'vision_model': vision_model, 'text_model': text_model}
												a__					=					FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCamelCase__				)

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

												a__					=					model(input_ids=UpperCamelCase__      ,pixel_values=UpperCamelCase__      ,attention_mask=UpperCamelCase__				)
												a__					=					output[0]

												with tempfile.TemporaryDirectory() as tmpdirname:
																			model.save_pretrained(UpperCamelCase__				)
																			a__					=					FlaxVisionTextDualEncoderModel.from_pretrained(UpperCamelCase__				)

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

												a__					=					model(
												    input_ids=UpperCamelCase__      ,pixel_values=UpperCamelCase__      ,attention_mask=UpperCamelCase__      ,output_attentions=UpperCamelCase__				)

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

												a__					=					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       :Any      ,__snake_case       :str      ,__snake_case       :Union[str, Any]      ,__snake_case       :int				) ->   str:
												pt_model.to(UpperCamelCase__				)
												pt_model.eval()

												# prepare inputs
												a__					=					inputs_dict
												a__					=					{k: torch.tensor(v.tolist()				) for k, v in flax_inputs.items()}

												with torch.no_grad():
																			a__					=					pt_model(**UpperCamelCase__				).to_tuple()

												a__					=					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__				)
																			a__					=					FlaxVisionTextDualEncoderModel.from_pretrained(UpperCamelCase__      ,from_pt=UpperCamelCase__				)

												a__					=					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__				)
																			a__					=					VisionTextDualEncoderModel.from_pretrained(UpperCamelCase__      ,from_flax=UpperCamelCase__				)

												pt_model_loaded.to(UpperCamelCase__				)
												pt_model_loaded.eval()

												with torch.no_grad():
																			a__					=					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       :List[str]      ,__snake_case       :List[Any]      ,__snake_case       :str      ,__snake_case       :int				) ->   int:
												a__					=					VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase__      ,UpperCamelCase__				)

												a__					=					VisionTextDualEncoderModel(UpperCamelCase__				)
												a__					=					FlaxVisionTextDualEncoderModel(UpperCamelCase__				)

												a__					=					convert_pytorch_state_dict_to_flax(pt_model.state_dict()      ,UpperCamelCase__				)
												a__					=					fx_state

												self.check_pt_flax_equivalence(UpperCamelCase__      ,UpperCamelCase__      ,UpperCamelCase__				)
					def 			lowerCamelCase__(				self       :Optional[int]      ,__snake_case       :Optional[int]      ,__snake_case       :int      ,__snake_case       :Any				) ->   int:
												a__					=					VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase__      ,UpperCamelCase__				)

												a__					=					VisionTextDualEncoderModel(UpperCamelCase__				)
												a__					=					FlaxVisionTextDualEncoderModel(UpperCamelCase__				)

												a__					=					load_flax_weights_in_pytorch_model(UpperCamelCase__      ,fx_model.params				)

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

												a__					=					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       :Union[str, Any]				) ->   Optional[int]:
												a__				, a__					=					self.get_pretrained_model_and_inputs()

												a__					=					model_a(**UpperCamelCase__				)
												a__					=					outputs[0]

												with tempfile.TemporaryDirectory() as tmp_dirname:
																			model_a.save_pretrained(UpperCamelCase__				)
																			a__					=					FlaxVisionTextDualEncoderModel.from_pretrained(UpperCamelCase__				)

																			a__					=					model_a(**UpperCamelCase__				)
																			a__					=					after_outputs[0]
																			a__					=					np.amax(np.abs(out_a - out_a				)				)
																			self.assertLessEqual(UpperCamelCase__      ,1E-5				)







@require_flax
class 	snake_case_       (_snake_case     ,						unittest.TestCase				):
					def 			lowerCamelCase__(				self       :List[str]				) ->   Union[str, Any]:
												a__					=					FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
												    'hf-internal-testing/tiny-random-vit'      ,'hf-internal-testing/tiny-bert'      ,vision_from_pt=UpperCamelCase__      ,text_from_pt=UpperCamelCase__      ,)
												a__					=					13
												a__					=					floats_tensor(
												    [
												        batch_size,
												        model.config.vision_config.num_channels,
												        model.config.vision_config.image_size,
												        model.config.vision_config.image_size,
												    ]				)
												a__					=					ids_tensor([batch_size, 4]      ,model.config.text_config.vocab_size				)
												a__					=					random_attention_mask([batch_size, 4]				)
												a__					=					{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

												return model, inputs
					def 			lowerCamelCase__(				self       :Tuple      ,__snake_case       :List[Any]      ,__snake_case       :Tuple				) ->   Optional[Any]:
												a__					=					FlaxViTModel(UpperCamelCase__				)
												a__					=					FlaxBertModel(UpperCamelCase__				)
												return vision_model, text_model



					def 			lowerCamelCase__(				self       :Union[str, Any]				) ->   str:
												a__					=					FlaxViTModelTester(self				)
												a__					=					FlaxBertModelTester(self				)
												a__					=					vit_model_tester.prepare_config_and_inputs()
												a__					=					bert_model_tester.prepare_config_and_inputs()

												a__				, a__					=					vision_config_and_inputs

												a__				, a__				, a__				, a__					=					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_       (_snake_case     ,						unittest.TestCase				):
					def 			lowerCamelCase__(				self       :Tuple				) ->   Any:
												a__					=					FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
												    'hf-internal-testing/tiny-random-clip'      ,'hf-internal-testing/tiny-bert'      ,vision_from_pt=UpperCamelCase__      ,text_from_pt=UpperCamelCase__      ,)
												a__					=					13
												a__					=					floats_tensor(
												    [
												        batch_size,
												        model.config.vision_config.num_channels,
												        model.config.vision_config.image_size,
												        model.config.vision_config.image_size,
												    ]				)
												a__					=					ids_tensor([batch_size, 4]      ,model.config.text_config.vocab_size				)
												a__					=					random_attention_mask([batch_size, 4]				)
												a__					=					{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

												return model, inputs
					def 			lowerCamelCase__(				self       :str      ,__snake_case       :int      ,__snake_case       :Dict				) ->   Union[str, Any]:
												a__					=					FlaxCLIPVisionModel(UpperCamelCase__				)
												a__					=					FlaxBertModel(UpperCamelCase__				)
												return vision_model, text_model



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

												a__				, a__					=					vision_config_and_inputs

												a__				, a__				, a__				, a__					=					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       :Tuple				) ->   Dict:
												a__					=					FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian'      ,logit_scale_init_value=1.0				)
												a__					=					VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian'				)

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

												a__					=					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])      ,)

												a__					=					np.array([[1.2_28_47_27, 0.3_10_41_22]]				)

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








from math import ceil, sqrt






def 							__lowercase       (			__lowerCAmelCase							:    int = 1_0_0_0_0_0_0       ):
							a__					=					0

							for outer_width in range(3 ,   (limit // 4) + 2       ):
														if outer_width**2 > limit:
																					a__					=					max(ceil(sqrt(outer_width**2 - limit       )       ) ,   1       )
														else:
																					a__					=					1
														if (outer_width - hole_width_lower_bound) % 2:
																					hole_width_lower_bound += 1

														answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1

							return answer


if __name__ == "__main__":
						print(f"""{solution() = }""")




