
'''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 		A_       (	_lowerCAmelCase   :    Any							):



      """simple docstring"""




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

@require_tf
class  UpperCAmelCase__						:



    def   lowerCamelCase_  (	self      :       Tuple,__A      :       Union[str, Any],__A      :       Tuple     ):
          pass



    def   lowerCamelCase_  (	self      :       List[Any]     ):
          pass



    def   lowerCamelCase_  (	self      :       Optional[int]     ):
          pass



    def   lowerCamelCase_  (	self      :       str,__A      :       Tuple,__A      :       str,__A      :       Union[str, Any],__A      :       Any,__A      :       Union[str, Any]=None,**__A      :       Union[str, Any]     ):
          _lowerCamelCase				:   Dict								=   VisionTextDualEncoderConfig.from_vision_text_configs(__A,__A     )

          _lowerCamelCase				:   Optional[int]								=   TFVisionTextDualEncoderModel(__A     )

          _lowerCamelCase				:   Union[str, Any]								=   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   lowerCamelCase_  (	self      :       Tuple,__A      :       List[Any],__A      :       Tuple,__A      :       List[Any],__A      :       List[str],__A      :       Union[str, Any]=None,**__A      :       List[Any]     ):
          _lowerCamelCase						,		_lowerCamelCase				:   Optional[int]								=   self.get_vision_text_model(__A,__A     )
          _lowerCamelCase				:   Optional[int]								=   TFVisionTextDualEncoderModel(vision_model=__A,text_model=__A     )

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

          _lowerCamelCase				:   List[str]								=   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   lowerCamelCase_  (	self      :       List[Any],__A      :       List[str],__A      :       List[Any],__A      :       Optional[int],__A      :       Dict,__A      :       Optional[int]=None,**__A      :       Tuple     ):
          _lowerCamelCase						,		_lowerCamelCase				:   List[str]								=   self.get_vision_text_model(__A,__A     )
          _lowerCamelCase				:   List[Any]								=   TFVisionTextDualEncoderModel(vision_model=__A,text_model=__A     )

          _lowerCamelCase				:   Optional[int]								=   model(input_ids=__A,pixel_values=__A,attention_mask=__A     )
          _lowerCamelCase				:   List[str]								=   output[0].numpy()

          with tempfile.TemporaryDirectory() as tmpdirname:
                model.save_pretrained(__A     )
                _lowerCamelCase				:   Union[str, Any]								=   TFVisionTextDualEncoderModel.from_pretrained(__A     )

                _lowerCamelCase				:   Any								=   model(input_ids=__A,pixel_values=__A,attention_mask=__A     )
                _lowerCamelCase				:   Optional[int]								=   after_output[0].numpy()
                _lowerCamelCase				:   Optional[Any]								=   np.amax(np.abs(out_a - out_a     )     )
                self.assertLessEqual(__A,1e-5     )



    def   lowerCamelCase_  (	self      :       Tuple,__A      :       Optional[Any],__A      :       List[str],__A      :       str,__A      :       Dict,__A      :       int=None,**__A      :       Optional[int]     ):
          _lowerCamelCase						,		_lowerCamelCase				:   int								=   self.get_vision_text_model(__A,__A     )
          _lowerCamelCase				:   Any								=   TFVisionTextDualEncoderModel(vision_model=__A,text_model=__A     )

          _lowerCamelCase				:   str								=   model(
              input_ids=__A,pixel_values=__A,attention_mask=__A,output_attentions=__A     )

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

          _lowerCamelCase				:   List[Any]								=   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   lowerCamelCase_  (	self      :       int,__A      :       np.ndarray,__A      :       np.ndarray,__A      :       float     ):
          _lowerCamelCase				:   List[Any]								=   np.abs((a - b)     ).max()
          self.assertLessEqual(__A,__A,f'Difference between torch and flax is {diff} (>= {tol}).'     )



    def   lowerCamelCase_  (	self      :       List[Any]     ):
          _lowerCamelCase				:   Any								=   self.prepare_config_and_inputs()
          self.check_vision_text_dual_encoder_model(**__A     )



    def   lowerCamelCase_  (	self      :       List[Any]     ):
          _lowerCamelCase				:   str								=   self.prepare_config_and_inputs()
          self.check_model_from_pretrained_configs(**__A     )



    def   lowerCamelCase_  (	self      :       Optional[Any]     ):
          _lowerCamelCase				:   Optional[int]								=   self.prepare_config_and_inputs()
          self.check_vision_text_dual_encoder_from_pretrained(**__A     )



    def   lowerCamelCase_  (	self      :       Optional[int]     ):
          _lowerCamelCase				:   Optional[Any]								=   self.prepare_config_and_inputs()
          self.check_save_load(**__A     )



    def   lowerCamelCase_  (	self      :       Any     ):
          _lowerCamelCase				:   Union[str, Any]								=   self.prepare_config_and_inputs()
          self.check_vision_text_output_attention(**__A     )



    @slow
    def   lowerCamelCase_  (	self      :       int     ):
          _lowerCamelCase						,		_lowerCamelCase				:   Any								=   self.get_pretrained_model_and_inputs()

          _lowerCamelCase				:   Tuple								=   model_a(**__A     )
          _lowerCamelCase				:   int								=   outputs[0].numpy()

          with tempfile.TemporaryDirectory() as tmp_dirname:
                model_a.save_pretrained(__A     )
                _lowerCamelCase				:   int								=   TFVisionTextDualEncoderModel.from_pretrained(__A     )

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


@require_tf
class  UpperCAmelCase__						(       A						,	unittest.TestCase ):



    def   lowerCamelCase_  (	self      :       Any     ):
          _lowerCamelCase				:   Any								=   TFVisionTextDualEncoderModel.from_vision_text_pretrained(
              "hf-internal-testing/tiny-random-vit","hf-internal-testing/tiny-random-bert"     )
          _lowerCamelCase				:   List[str]								=   1_3
          _lowerCamelCase				:   List[str]								=   floats_tensor(
              [
                  batch_size,
                  model.vision_model.config.num_channels,
                  model.vision_model.config.image_size,
                  model.vision_model.config.image_size,
              ]     )
          _lowerCamelCase				:   Optional[Any]								=   ids_tensor([batch_size, 4],model.text_model.config.vocab_size     )
          _lowerCamelCase				:   Tuple								=   random_attention_mask([batch_size, 4]     )
          _lowerCamelCase				:   Optional[Any]								=   {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

          return model, inputs



    def   lowerCamelCase_  (	self      :       Optional[Any],__A      :       List[str],__A      :       Optional[Any]     ):
          _lowerCamelCase				:   List[Any]								=   TFViTModel(__A,name="vision_model"     )
          _lowerCamelCase				:   str								=   TFBertModel(__A,name="text_model"     )
          return vision_model, text_model



    def   lowerCamelCase_  (	self      :       Tuple     ):
          _lowerCamelCase				:   Dict								=   TFViTModelTester(self     )
          _lowerCamelCase				:   int								=   TFBertModelTester(self     )
          _lowerCamelCase				:   Tuple								=   vit_model_tester.prepare_config_and_inputs()
          _lowerCamelCase				:   Optional[Any]								=   bert_model_tester.prepare_config_and_inputs()

          _lowerCamelCase						,		_lowerCamelCase						,		_lowerCamelCase				:   str								=   vision_config_and_inputs

          (
              (
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		
          )				:   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  UpperCAmelCase__						(       A						,	unittest.TestCase ):



    def   lowerCamelCase_  (	self      :       Any     ):
          # DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's
          # just reinitialize it.
          _lowerCamelCase				:   List[str]								=   TFVisionTextDualEncoderModel.from_vision_text_pretrained(
              "Rocketknight1/tiny-random-deit-tf","hf-internal-testing/tiny-random-roberta"     )
          _lowerCamelCase				:   int								=   1_3
          _lowerCamelCase				:   Tuple								=   floats_tensor(
              [
                  batch_size,
                  model.vision_model.config.num_channels,
                  model.vision_model.config.image_size,
                  model.vision_model.config.image_size,
              ]     )
          _lowerCamelCase				:   Optional[int]								=   ids_tensor([batch_size, 4],model.text_model.config.vocab_size     )
          _lowerCamelCase				:   Optional[int]								=   random_attention_mask([batch_size, 4]     )
          _lowerCamelCase				:   str								=   {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

          return model, inputs



    def   lowerCamelCase_  (	self      :       Dict,__A      :       Optional[Any],__A      :       str,__A      :       Tuple,__A      :       Optional[Any],__A      :       str=None,**__A      :       List[str]     ):
          _lowerCamelCase						,		_lowerCamelCase				:   Dict								=   self.get_vision_text_model(__A,__A     )
          _lowerCamelCase				:   int								=   TFVisionTextDualEncoderModel(vision_model=__A,text_model=__A     )

          _lowerCamelCase				:   List[Any]								=   model(
              input_ids=__A,pixel_values=__A,attention_mask=__A,output_attentions=__A     )

          _lowerCamelCase				:   int								=   output.vision_model_output.attentions
          self.assertEqual(len(__A     ),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)
          _lowerCamelCase				:   Union[str, Any]								=   to_atuple(vision_model.config.image_size     )
          _lowerCamelCase				:   Tuple								=   to_atuple(vision_model.config.patch_size     )
          _lowerCamelCase				:   Optional[Any]								=   (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
          _lowerCamelCase				:   Dict								=   num_patches + 2
          self.assertEqual(vision_attentions[0].shape[-3:],(vision_config.num_attention_heads, seq_len, seq_len)     )

          _lowerCamelCase				:   Any								=   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   lowerCamelCase_  (	self      :       int,__A      :       List[str],__A      :       Any     ):
          _lowerCamelCase				:   Union[str, Any]								=   TFDeiTModel(__A,name="vision_model"     )
          _lowerCamelCase				:   str								=   TFRobertaModel(__A,name="text_model"     )
          return vision_model, text_model



    def   lowerCamelCase_  (	self      :       int     ):
          _lowerCamelCase				:   Tuple								=   TFDeiTModelTester(self     )
          _lowerCamelCase				:   Union[str, Any]								=   TFRobertaModelTester(self     )
          _lowerCamelCase				:   str								=   vit_model_tester.prepare_config_and_inputs()
          _lowerCamelCase				:   Any								=   bert_model_tester.prepare_config_and_inputs()

          _lowerCamelCase						,		_lowerCamelCase						,		_lowerCamelCase				:   List[Any]								=   vision_config_and_inputs

          (
              (
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		
          )				:   Dict								=   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  UpperCAmelCase__						(       A						,	unittest.TestCase ):



    def   lowerCamelCase_  (	self      :       Dict     ):
          _lowerCamelCase				:   Any								=   TFVisionTextDualEncoderModel.from_vision_text_pretrained(
              "Rocketknight1/tiny-random-clip-tf","hf-internal-testing/tiny-random-bert"     )
          _lowerCamelCase				:   List[Any]								=   1_3
          _lowerCamelCase				:   List[Any]								=   floats_tensor(
              [
                  batch_size,
                  model.vision_model.config.num_channels,
                  model.vision_model.config.image_size,
                  model.vision_model.config.image_size,
              ]     )
          _lowerCamelCase				:   List[str]								=   ids_tensor([batch_size, 4],model.text_model.config.vocab_size     )
          _lowerCamelCase				:   List[Any]								=   random_attention_mask([batch_size, 4]     )
          _lowerCamelCase				:   str								=   {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

          return model, inputs



    def   lowerCamelCase_  (	self      :       Optional[Any],__A      :       List[Any],__A      :       List[str]     ):
          _lowerCamelCase				:   Tuple								=   TFCLIPVisionModel(__A,name="vision_model"     )
          _lowerCamelCase				:   int								=   TFBertModel(__A,name="text_model"     )
          return vision_model, text_model



    def   lowerCamelCase_  (	self      :       List[Any]     ):
          _lowerCamelCase				:   Union[str, Any]								=   TFCLIPVisionModelTester(self     )
          _lowerCamelCase				:   Dict								=   TFBertModelTester(self     )
          _lowerCamelCase				:   List[str]								=   clip_model_tester.prepare_config_and_inputs()
          _lowerCamelCase				:   List[Any]								=   bert_model_tester.prepare_config_and_inputs()

          _lowerCamelCase						,		_lowerCamelCase				:   Optional[Any]								=   vision_config_and_inputs

          (
              (
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		(
              _lowerCamelCase
          )						,		
          )				:   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_vision
@require_tf
class  UpperCAmelCase__						(       unittest.TestCase ):



    @slow
    def   lowerCamelCase_  (	self      :       Dict     ):
          _lowerCamelCase				:   Dict								=   TFVisionTextDualEncoderModel.from_pretrained(
              "clip-italian/clip-italian",logit_scale_init_value=1.0,from_pt=__A     )
          _lowerCamelCase				:   List[Any]								=   VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian"     )

          _lowerCamelCase				:   Any								=   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"     )
          _lowerCamelCase				:   str								=   processor(
              text=["una foto di un gatto", "una foto di un cane"],images=__A,padding=__A,return_tensors="np"     )

          _lowerCamelCase				:   int								=   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]),)

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

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

'''simple docstring'''






import math







def 		A_       (	_lowerCAmelCase   :    int							):



      """simple docstring"""




      _lowerCamelCase				:   Optional[int]								=   math.loga(math.sqrt(4 * positive_integer + 1							) / 2 + 1 / 2							)

      return exponent == int(_lowerCAmelCase							)







def 		A_       (	_lowerCAmelCase   :    float = 1 / 12345							):



      """simple docstring"""




      _lowerCamelCase				:   Optional[int]								=   0
      _lowerCamelCase				:   int								=   0

      _lowerCamelCase				:   List[str]								=   3
      while True:
            _lowerCamelCase				:   List[Any]								=   (integer**2 - 1) / 4
            # if candidate is an integer, then there is a partition for k
            if partition_candidate == int(_lowerCAmelCase							):
                  _lowerCamelCase				:   Any								=   int(_lowerCAmelCase							)
                  total_partitions += 1
                  if check_partition_perfect(_lowerCAmelCase							):
                        perfect_partitions += 1
            if perfect_partitions > 0:
                  if perfect_partitions / total_partitions < max_proportion:
                        return int(_lowerCAmelCase							)
            integer += 1


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