






"""simple docstring"""



from __future__ import annotations

import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import is_tf_available, is_vision_available

from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_tf_bert import TFBertModelTester
from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester
from ..deit.test_modeling_tf_deit import TFDeiTModelTester
from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester
from ..vit.test_modeling_tf_vit import TFViTModelTester


if is_tf_available():
						from transformers import (
						    TFBertModel,
						    TFCLIPVisionModel,
						    TFDeiTModel,
						    TFRobertaModel,
						    TFVisionTextDualEncoderModel,
						    TFViTModel,
						    VisionTextDualEncoderConfig,
						)

if is_vision_available():
						from PIL import Image

						from transformers import VisionTextDualEncoderProcessor




def      _lowerCAmelCase		(							UpperCAmelCase__       :					Optional[int]      )		->str:
						if isinstance(UpperCAmelCase__,						collections.abc.Iterable      ):
												return x
						return (x, x)






@require_tf
class 							__SCREAMING_SNAKE_CASE						:


							def 						_UpperCamelCase       (			self      :						List[Any]			,    snake_case      :						List[Any]			,    snake_case      :						Any							):
													'''simple docstring'''





													pass


							def 						_UpperCamelCase       (			self      :						Tuple							):
													'''simple docstring'''





													pass


							def 						_UpperCamelCase       (			self      :						str							):
													'''simple docstring'''





													pass


							def 						_UpperCamelCase       (			self      :						Union[str, Any]			,    snake_case      :						str			,    snake_case      :						int			,    snake_case      :						int			,    snake_case      :						List[Any]			,    snake_case      :						str=None			,    **snake_case      :						Union[str, Any]							):
													'''simple docstring'''





													A__						:  Optional[Any]		  =  VisionTextDualEncoderConfig.from_vision_text_configs(snake_case			,    snake_case							)

													A__						:  List[Any]		  =  TFVisionTextDualEncoderModel(snake_case							)

													A__						:  Optional[int]		  =  model(input_ids=snake_case			,    pixel_values=snake_case			,    attention_mask=snake_case							)

													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      :						int			,    snake_case      :						List[str]			,    snake_case      :						Optional[int]			,    snake_case      :						Dict			,    snake_case      :						Optional[int]			,    snake_case      :						Any=None			,    **snake_case      :						Optional[Any]							):
													'''simple docstring'''





													A__  ,  A__						:  Tuple		  =  self.get_vision_text_model(snake_case			,    snake_case							)
													A__						:  Union[str, Any]		  =  TFVisionTextDualEncoderModel(vision_model=snake_case			,    text_model=snake_case							)

													A__						:  Dict		  =  model(input_ids=snake_case			,    pixel_values=snake_case			,    attention_mask=snake_case							)

													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      :						Dict			,    snake_case      :						Dict			,    snake_case      :						Union[str, Any]			,    snake_case      :						Tuple			,    snake_case      :						str			,    snake_case      :						Union[str, Any]=None			,    **snake_case      :						Tuple							):
													'''simple docstring'''





													A__  ,  A__						:  Optional[int]		  =  self.get_vision_text_model(snake_case			,    snake_case							)
													A__						:  Tuple		  =  {"""vision_model""": vision_model, """text_model""": text_model}
													A__						:  Dict		  =  TFVisionTextDualEncoderModel.from_vision_text_pretrained(**snake_case							)

													A__						:  int		  =  model(input_ids=snake_case			,    pixel_values=snake_case			,    attention_mask=snake_case							)

													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      :						List[Any]			,    snake_case      :						Optional[int]			,    snake_case      :						int			,    snake_case      :						Any			,    snake_case      :						List[str]			,    snake_case      :						Optional[int]=None			,    **snake_case      :						Tuple							):
													'''simple docstring'''





													A__  ,  A__						:  Tuple		  =  self.get_vision_text_model(snake_case			,    snake_case							)
													A__						:  Dict		  =  TFVisionTextDualEncoderModel(vision_model=snake_case			,    text_model=snake_case							)

													A__						:  List[Any]		  =  model(input_ids=snake_case			,    pixel_values=snake_case			,    attention_mask=snake_case							)
													A__						:  Union[str, Any]		  =  output[0].numpy()

													with tempfile.TemporaryDirectory() as tmpdirname:
																			model.save_pretrained(snake_case							)
																			A__						:  Any		  =  TFVisionTextDualEncoderModel.from_pretrained(snake_case							)

																			A__						:  int		  =  model(input_ids=snake_case			,    pixel_values=snake_case			,    attention_mask=snake_case							)
																			A__						:  Union[str, Any]		  =  after_output[0].numpy()
																			A__						:  Tuple		  =  np.amax(np.abs(out_a - out_a							)							)
																			self.assertLessEqual(snake_case			,    1e-5							)


							def 						_UpperCamelCase       (			self      :						List[str]			,    snake_case      :						Any			,    snake_case      :						Any			,    snake_case      :						int			,    snake_case      :						Dict			,    snake_case      :						Optional[int]=None			,    **snake_case      :						List[Any]							):
													'''simple docstring'''





													A__  ,  A__						:  List[str]		  =  self.get_vision_text_model(snake_case			,    snake_case							)
													A__						:  Optional[Any]		  =  TFVisionTextDualEncoderModel(vision_model=snake_case			,    text_model=snake_case							)

													A__						:  Tuple		  =  model(
													    input_ids=snake_case			,    pixel_values=snake_case			,    attention_mask=snake_case			,    output_attentions=snake_case							)

													A__						:  Optional[int]		  =  output.vision_model_output.attentions
													self.assertEqual(len(snake_case							)			,    vision_config.num_hidden_layers							)

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

													A__						:  Tuple		  =  output.text_model_output.attentions
													self.assertEqual(len(snake_case							)			,    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      :						str			,    snake_case      :						np.ndarray			,    snake_case      :						np.ndarray			,    snake_case      :						float							):
													'''simple docstring'''





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


							def 						_UpperCamelCase       (			self      :						Optional[int]							):
													'''simple docstring'''





													A__						:  Tuple		  =  self.prepare_config_and_inputs()
													self.check_vision_text_dual_encoder_model(**snake_case							)


							def 						_UpperCamelCase       (			self      :						Any							):
													'''simple docstring'''





													A__						:  List[Any]		  =  self.prepare_config_and_inputs()
													self.check_model_from_pretrained_configs(**snake_case							)


							def 						_UpperCamelCase       (			self      :						List[str]							):
													'''simple docstring'''





													A__						:  Optional[int]		  =  self.prepare_config_and_inputs()
													self.check_vision_text_dual_encoder_from_pretrained(**snake_case							)


							def 						_UpperCamelCase       (			self      :						List[str]							):
													'''simple docstring'''





													A__						:  Tuple		  =  self.prepare_config_and_inputs()
													self.check_save_load(**snake_case							)


							def 						_UpperCamelCase       (			self      :						int							):
													'''simple docstring'''





													A__						:  str		  =  self.prepare_config_and_inputs()
													self.check_vision_text_output_attention(**snake_case							)


							@slow
							def 						_UpperCamelCase       (			self      :						Optional[int]							):
													'''simple docstring'''





													A__  ,  A__						:  Any		  =  self.get_pretrained_model_and_inputs()

													A__						:  int		  =  model_a(**snake_case							)
													A__						:  Dict		  =  outputs[0].numpy()

													with tempfile.TemporaryDirectory() as tmp_dirname:
																			model_a.save_pretrained(snake_case							)
																			A__						:  List[str]		  =  TFVisionTextDualEncoderModel.from_pretrained(snake_case							)

																			A__						:  List[Any]		  =  model_a(**snake_case							)
																			A__						:  List[Any]		  =  after_outputs[0].numpy()
																			A__						:  Optional[Any]		  =  np.amax(np.abs(out_a - out_a							)							)
																			self.assertLessEqual(snake_case			,    1e-5							)






@require_tf
class 							__SCREAMING_SNAKE_CASE						(				UpperCamelCase       ,		unittest.TestCase		):


							def 						_UpperCamelCase       (			self      :						Optional[int]							):
													'''simple docstring'''





													A__						:  List[Any]		  =  TFVisionTextDualEncoderModel.from_vision_text_pretrained(
													    """hf-internal-testing/tiny-random-vit"""			,    """hf-internal-testing/tiny-random-bert"""							)
													A__						:  Optional[int]		  =  13
													A__						:  Any		  =  floats_tensor(
													    [
													        batch_size,
													        model.vision_model.config.num_channels,
													        model.vision_model.config.image_size,
													        model.vision_model.config.image_size,
													    ]							)
													A__						:  Any		  =  ids_tensor([batch_size, 4]			,    model.text_model.config.vocab_size							)
													A__						:  Dict		  =  random_attention_mask([batch_size, 4]							)
													A__						:  str		  =  {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

													return model, inputs


							def 						_UpperCamelCase       (			self      :						Any			,    snake_case      :						Tuple			,    snake_case      :						Union[str, Any]							):
													'''simple docstring'''





													A__						:  Optional[Any]		  =  TFViTModel(snake_case			,    name="""vision_model"""							)
													A__						:  Optional[int]		  =  TFBertModel(snake_case			,    name="""text_model"""							)
													return vision_model, text_model


							def 						_UpperCamelCase       (			self      :						List[Any]							):
													'''simple docstring'''





													A__						:  str		  =  TFViTModelTester(self							)
													A__						:  str		  =  TFBertModelTester(self							)
													A__						:  str		  =  vit_model_tester.prepare_config_and_inputs()
													A__						:  str		  =  bert_model_tester.prepare_config_and_inputs()

													A__  ,  A__  ,  A__						:  Any		  =  vision_config_and_inputs

													(
													    (
													    A__
													)  ,  (
													    A__
													)  ,  (
													    A__
													)  ,  (
													    A__
													)  ,  (
													    A__
													)  ,  (
													    A__
													)  ,  (
													    A__
													)  ,  
													)						:  Optional[Any]		  =  text_config_and_inputs

													return {
													    "text_config": text_config,
													    "vision_config": vision_config,
													    "pixel_values": pixel_values,
													    "attention_mask": input_mask,
													    "input_ids": input_ids,
													    "text_token_type_ids": token_type_ids,
													    "text_sequence_labels": sequence_labels,
													    "text_token_labels": token_labels,
													    "text_choice_labels": choice_labels,
													}






@require_tf
class 							__SCREAMING_SNAKE_CASE						(				UpperCamelCase       ,		unittest.TestCase		):


							def 						_UpperCamelCase       (			self      :						Dict							):
													'''simple docstring'''





													A__						:  Union[str, Any]		  =  TFVisionTextDualEncoderModel.from_vision_text_pretrained(
													    """Rocketknight1/tiny-random-deit-tf"""			,    """hf-internal-testing/tiny-random-roberta"""							)
													A__						:  List[str]		  =  13
													A__						:  Optional[int]		  =  floats_tensor(
													    [
													        batch_size,
													        model.vision_model.config.num_channels,
													        model.vision_model.config.image_size,
													        model.vision_model.config.image_size,
													    ]							)
													A__						:  List[str]		  =  ids_tensor([batch_size, 4]			,    model.text_model.config.vocab_size							)
													A__						:  Dict		  =  random_attention_mask([batch_size, 4]							)
													A__						:  Dict		  =  {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

													return model, inputs


							def 						_UpperCamelCase       (			self      :						Union[str, Any]			,    snake_case      :						List[Any]			,    snake_case      :						Union[str, Any]			,    snake_case      :						List[str]			,    snake_case      :						str			,    snake_case      :						Union[str, Any]=None			,    **snake_case      :						List[Any]							):
													'''simple docstring'''





													A__  ,  A__						:  List[str]		  =  self.get_vision_text_model(snake_case			,    snake_case							)
													A__						:  Optional[Any]		  =  TFVisionTextDualEncoderModel(vision_model=snake_case			,    text_model=snake_case							)

													A__						:  int		  =  model(
													    input_ids=snake_case			,    pixel_values=snake_case			,    attention_mask=snake_case			,    output_attentions=snake_case							)

													A__						:  List[str]		  =  output.vision_model_output.attentions
													self.assertEqual(len(snake_case							)			,    vision_config.num_hidden_layers							)

													# in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
													A__						:  Union[str, Any]		  =  to_atuple(vision_model.config.image_size							)
													A__						:  Any		  =  to_atuple(vision_model.config.patch_size							)
													A__						:  Optional[Any]		  =  (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
													A__						:  Tuple		  =  num_patches + 2
													self.assertEqual(vision_attentions[0].shape[-3:]			,    (vision_config.num_attention_heads, seq_len, seq_len)							)

													A__						:  Dict		  =  output.text_model_output.attentions
													self.assertEqual(len(snake_case							)			,    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      :						Optional[int]			,    snake_case      :						List[Any]			,    snake_case      :						Tuple							):
													'''simple docstring'''





													A__						:  Tuple		  =  TFDeiTModel(snake_case			,    name="""vision_model"""							)
													A__						:  Optional[int]		  =  TFRobertaModel(snake_case			,    name="""text_model"""							)
													return vision_model, text_model


							def 						_UpperCamelCase       (			self      :						Tuple							):
													'''simple docstring'''





													A__						:  Optional[Any]		  =  TFDeiTModelTester(self							)
													A__						:  Optional[int]		  =  TFRobertaModelTester(self							)
													A__						:  Union[str, Any]		  =  vit_model_tester.prepare_config_and_inputs()
													A__						:  Any		  =  bert_model_tester.prepare_config_and_inputs()

													A__  ,  A__  ,  A__						:  Tuple		  =  vision_config_and_inputs

													(
													    (
													    A__
													)  ,  (
													    A__
													)  ,  (
													    A__
													)  ,  (
													    A__
													)  ,  (
													    A__
													)  ,  (
													    A__
													)  ,  (
													    A__
													)  ,  
													)						:  Optional[int]		  =  text_config_and_inputs

													return {
													    "text_config": text_config,
													    "vision_config": vision_config,
													    "pixel_values": pixel_values,
													    "attention_mask": input_mask,
													    "input_ids": input_ids,
													    "text_token_type_ids": token_type_ids,
													    "text_sequence_labels": sequence_labels,
													    "text_token_labels": token_labels,
													    "text_choice_labels": choice_labels,
													}






@require_tf
class 							__SCREAMING_SNAKE_CASE						(				UpperCamelCase       ,		unittest.TestCase		):


							def 						_UpperCamelCase       (			self      :						List[Any]							):
													'''simple docstring'''





													A__						:  Tuple		  =  TFVisionTextDualEncoderModel.from_vision_text_pretrained(
													    """Rocketknight1/tiny-random-clip-tf"""			,    """hf-internal-testing/tiny-random-bert"""							)
													A__						:  Optional[Any]		  =  13
													A__						:  Any		  =  floats_tensor(
													    [
													        batch_size,
													        model.vision_model.config.num_channels,
													        model.vision_model.config.image_size,
													        model.vision_model.config.image_size,
													    ]							)
													A__						:  Optional[Any]		  =  ids_tensor([batch_size, 4]			,    model.text_model.config.vocab_size							)
													A__						:  Union[str, Any]		  =  random_attention_mask([batch_size, 4]							)
													A__						:  Tuple		  =  {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

													return model, inputs


							def 						_UpperCamelCase       (			self      :						Dict			,    snake_case      :						Dict			,    snake_case      :						Any							):
													'''simple docstring'''





													A__						:  Dict		  =  TFCLIPVisionModel(snake_case			,    name="""vision_model"""							)
													A__						:  str		  =  TFBertModel(snake_case			,    name="""text_model"""							)
													return vision_model, text_model


							def 						_UpperCamelCase       (			self      :						List[str]							):
													'''simple docstring'''





													A__						:  Optional[int]		  =  TFCLIPVisionModelTester(self							)
													A__						:  List[str]		  =  TFBertModelTester(self							)
													A__						:  str		  =  clip_model_tester.prepare_config_and_inputs()
													A__						:  Union[str, Any]		  =  bert_model_tester.prepare_config_and_inputs()

													A__  ,  A__						:  Tuple		  =  vision_config_and_inputs

													(
													    (
													    A__
													)  ,  (
													    A__
													)  ,  (
													    A__
													)  ,  (
													    A__
													)  ,  (
													    A__
													)  ,  (
													    A__
													)  ,  (
													    A__
													)  ,  
													)						:  str		  =  text_config_and_inputs

													return {
													    "text_config": text_config,
													    "vision_config": vision_config,
													    "pixel_values": pixel_values,
													    "attention_mask": input_mask,
													    "input_ids": input_ids,
													    "text_token_type_ids": token_type_ids,
													    "text_sequence_labels": sequence_labels,
													    "text_token_labels": token_labels,
													    "text_choice_labels": choice_labels,
													}






@require_vision
@require_tf
class 							__SCREAMING_SNAKE_CASE						(				unittest.TestCase		):


							@slow
							def 						_UpperCamelCase       (			self      :						Union[str, Any]							):
													'''simple docstring'''





													A__						:  str		  =  TFVisionTextDualEncoderModel.from_pretrained(
													    """clip-italian/clip-italian"""			,    logit_scale_init_value=1.0			,    from_pt=snake_case							)
													A__						:  str		  =  VisionTextDualEncoderProcessor.from_pretrained("""clip-italian/clip-italian"""							)

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

													A__						:  Optional[Any]		  =  model(**snake_case							)

													# 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__						:  int		  =  np.array([[1.2284727, 0.3104122]]							)

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














"""simple docstring"""



from timeit import timeit




def      _lowerCAmelCase		(							UpperCAmelCase__       :					int      )		->int:
						if number < 0:
												raise ValueError("""the value of input must not be negative"""      )
						A__						:  Optional[int]		  =  0
						while number:
												number &= number - 1
												result += 1
						return result




def      _lowerCAmelCase		(							UpperCAmelCase__       :					int      )		->int:
						if number < 0:
												raise ValueError("""the value of input must not be negative"""      )
						A__						:  Tuple		  =  0
						while number:
												if number % 2 == 1:
																		result += 1
												number >>= 1
						return result




def      _lowerCAmelCase		(							)		->None:

						def do_benchmark(UpperCAmelCase__       :					int      ) -> None:
												A__						:  Optional[int]		  =  """import __main__ as z"""
												print(f'Benchmark when {number = }:'      )
												print(f'{get_set_bits_count_using_modulo_operator(UpperCAmelCase__      ) = }'      )
												A__						:  Any		  =  timeit("""z.get_set_bits_count_using_modulo_operator(25)""",						setup=UpperCAmelCase__      )
												print(f'timeit() runs in {timing} seconds'      )
												print(f'{get_set_bits_count_using_brian_kernighans_algorithm(UpperCAmelCase__      ) = }'      )
												A__						:  List[str]		  =  timeit(
												    """z.get_set_bits_count_using_brian_kernighans_algorithm(25)""",						setup=UpperCAmelCase__,						)
												print(f'timeit() runs in {timing} seconds'      )

						for number in (2_5, 3_7, 5_8, 0):
												do_benchmark(UpperCAmelCase__      )
												print()


if __name__ == "__main__":
						import doctest

						doctest.testmod()
						benchmark()






