


from ...configuration_utils import PretrainedConfig
from ...utils import logging


SCREAMING_SNAKE_CASE       :      str												= logging.get_logger(__name__)

SCREAMING_SNAKE_CASE       :      List[str]												= {
    "tiiuae/falcon-40b": "https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json",
    "tiiuae/falcon-7b": "https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json",
}






class _lowerCamelCase(						_a   ):
       lowercase_ :	Optional[int]     =			"""falcon"""
       lowercase_ :	Dict     =			["""past_key_values"""]
       def __init__(					self,      lowerCamelCase=6_50_24,      lowerCamelCase=45_44,      lowerCamelCase=32,      lowerCamelCase=71,      lowerCamelCase=1E-5,      lowerCamelCase=0.0_2,      lowerCamelCase=True,      lowerCamelCase=0.0,      lowerCamelCase=0.0,      lowerCamelCase=None,      lowerCamelCase=False,      lowerCamelCase=False,      lowerCamelCase=True,      lowerCamelCase=True,      lowerCamelCase=False,      lowerCamelCase=11,      lowerCamelCase=11,      **lowerCamelCase,      )       ->   Optional[Any]:




           """simple docstring"""

           _lowercase       :							List[str]      		=		vocab_size
           # Backward compatibility with n_embed kwarg
           _lowercase       :							Tuple      		=		kwargs.pop('n_embed',      lowerCamelCase)
           _lowercase       :							Optional[int]      		=		hidden_size if n_embed is None else n_embed
           _lowercase       :							Optional[Any]      		=		num_hidden_layers
           _lowercase       :							Optional[int]      		=		num_attention_heads
           _lowercase       :							int      		=		layer_norm_epsilon
           _lowercase       :							Any      		=		initializer_range
           _lowercase       :							Tuple      		=		use_cache
           _lowercase       :							List[Any]      		=		hidden_dropout
           _lowercase       :							Tuple      		=		attention_dropout

           _lowercase       :							Optional[int]      		=		bos_token_id
           _lowercase       :							int      		=		eos_token_id
           _lowercase       :							str      		=		num_attention_heads if num_kv_heads is None else num_kv_heads
           _lowercase       :							Optional[Any]      		=		alibi
           _lowercase       :							Dict      		=		new_decoder_architecture
           _lowercase       :							Any      		=		multi_query  # Ignored when new_decoder_architecture is True
           _lowercase       :							Tuple      		=		parallel_attn
           _lowercase       :							List[Any]      		=		bias

           super().__init__(bos_token_id=lowerCamelCase,      eos_token_id=lowerCamelCase,      **lowerCamelCase)
       @property
       def 			UpperCamelCase     (					self)       ->   List[str]:




           """simple docstring"""

           return self.hidden_size // self.num_attention_heads




       @property
       def 			UpperCamelCase     (					self)       ->   int:




           """simple docstring"""

           return not self.alibi






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 				UpperCamelCase_(      lowerCamelCase_ )    ->						Optional[int]:
    if isinstance(lowerCamelCase_							, collections.abc.Iterable ):
        return x
    return (x, x)






@require_flax
class _lowerCamelCase:
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase)       ->   Union[str, Any]:




           """simple docstring"""

           pass
       def 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

           pass
       def 			UpperCamelCase     (					self)       ->   Optional[int]:




           """simple docstring"""

           pass
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase)       ->   Any:




           """simple docstring"""

           _lowercase       :							str      		=		np.abs((a - b)).max()
           self.assertLessEqual(lowerCamelCase,      lowerCamelCase,      F'''Difference between torch and flax is {diff} (>= {tol}).''')
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase=None,      **lowerCamelCase)       ->   Union[str, Any]:




           """simple docstring"""

           _lowercase       :							Any      		=		VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase,      lowerCamelCase)

           _lowercase       :							Optional[int]      		=		FlaxVisionTextDualEncoderModel(lowerCamelCase)

           _lowercase       :							Any      		=		model(input_ids=lowerCamelCase,      pixel_values=lowerCamelCase,      attention_mask=lowerCamelCase)

           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,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase=None,      **lowerCamelCase)       ->   Any:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Union[str, Any]      		=		self.get_vision_text_model(lowerCamelCase,      lowerCamelCase)
           _lowercase       :							str      		=		{'vision_model': vision_model, 'text_model': text_model}
           _lowercase       :							Dict      		=		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase)

           _lowercase       :							List[str]      		=		model(input_ids=lowerCamelCase,      pixel_values=lowerCamelCase,      attention_mask=lowerCamelCase)

           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,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase=None,      **lowerCamelCase)       ->   Union[str, Any]:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Tuple      		=		self.get_vision_text_model(lowerCamelCase,      lowerCamelCase)
           _lowercase       :							List[str]      		=		{'vision_model': vision_model, 'text_model': text_model}
           _lowercase       :							Dict      		=		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase)

           _lowercase       :							List[str]      		=		model(input_ids=lowerCamelCase,      pixel_values=lowerCamelCase,      attention_mask=lowerCamelCase)
           _lowercase       :							Tuple      		=		output[0]

           with tempfile.TemporaryDirectory() as tmpdirname:
               model.save_pretrained(lowerCamelCase)
               _lowercase       :							Any      		=		FlaxVisionTextDualEncoderModel.from_pretrained(lowerCamelCase)

               _lowercase       :							Tuple      		=		model(input_ids=lowerCamelCase,      pixel_values=lowerCamelCase,      attention_mask=lowerCamelCase)
               _lowercase       :							str      		=		after_output[0]
               _lowercase       :							Optional[Any]      		=		np.amax(np.abs(out_a - out_a))
               self.assertLessEqual(lowerCamelCase,      1E-3)
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase=None,      **lowerCamelCase)       ->   str:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Any      		=		self.get_vision_text_model(lowerCamelCase,      lowerCamelCase)
           _lowercase       :							Optional[int]      		=		{'vision_model': vision_model, 'text_model': text_model}
           _lowercase       :							Dict      		=		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase)

           _lowercase       :							Tuple      		=		model(
               input_ids=lowerCamelCase,      pixel_values=lowerCamelCase,      attention_mask=lowerCamelCase,      output_attentions=lowerCamelCase)

           _lowercase       :							int      		=		output.vision_model_output.attentions
           self.assertEqual(len(lowerCamelCase),      vision_config.num_hidden_layers)

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

           _lowercase       :							List[str]      		=		output.text_model_output.attentions
           self.assertEqual(len(lowerCamelCase),      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,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase)       ->   Optional[int]:




           """simple docstring"""

           pt_model.to(lowerCamelCase)
           pt_model.eval()

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

           with torch.no_grad():
               _lowercase       :							Tuple      		=		pt_model(**lowerCamelCase).to_tuple()

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

           # PT -> Flax
           with tempfile.TemporaryDirectory() as tmpdirname:
               pt_model.save_pretrained(lowerCamelCase)
               _lowercase       :							int      		=		FlaxVisionTextDualEncoderModel.from_pretrained(lowerCamelCase,      from_pt=lowerCamelCase)

           _lowercase       :							List[Any]      		=		fx_model_loaded(**lowerCamelCase).to_tuple()
           self.assertEqual(len(lowerCamelCase),      len(lowerCamelCase),      '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(lowerCamelCase,      pt_output.numpy(),      4E-2)

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

           pt_model_loaded.to(lowerCamelCase)
           pt_model_loaded.eval()

           with torch.no_grad():
               _lowercase       :							Optional[Any]      		=		pt_model_loaded(**lowerCamelCase).to_tuple()

           self.assertEqual(len(lowerCamelCase),      len(lowerCamelCase),      '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(lowerCamelCase,      pt_output_loaded.numpy(),      4E-2)
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase)       ->   Tuple:




           """simple docstring"""

           _lowercase       :							Dict      		=		VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase,      lowerCamelCase)

           _lowercase       :							Optional[Any]      		=		VisionTextDualEncoderModel(lowerCamelCase)
           _lowercase       :							str      		=		FlaxVisionTextDualEncoderModel(lowerCamelCase)

           _lowercase       :							Tuple      		=		convert_pytorch_state_dict_to_flax(pt_model.state_dict(),      lowerCamelCase)
           _lowercase       :							List[Any]      		=		fx_state

           self.check_pt_flax_equivalence(lowerCamelCase,      lowerCamelCase,      lowerCamelCase)
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase)       ->   Dict:




           """simple docstring"""

           _lowercase       :							str      		=		VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase,      lowerCamelCase)

           _lowercase       :							Tuple      		=		VisionTextDualEncoderModel(lowerCamelCase)
           _lowercase       :							Optional[int]      		=		FlaxVisionTextDualEncoderModel(lowerCamelCase)

           _lowercase       :							List[str]      		=		load_flax_weights_in_pytorch_model(lowerCamelCase,      fx_model.params)

           self.check_pt_flax_equivalence(lowerCamelCase,      lowerCamelCase,      lowerCamelCase)
       def 			UpperCamelCase     (					self)       ->   List[Any]:




           """simple docstring"""

           _lowercase       :							int      		=		self.prepare_config_and_inputs()
           self.check_model_from_pretrained_configs(**lowerCamelCase)
       def 			UpperCamelCase     (					self)       ->   Tuple:




           """simple docstring"""

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




           """simple docstring"""

           _lowercase       :							Optional[int]      		=		self.prepare_config_and_inputs()
           self.check_save_load(**lowerCamelCase)
       def 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

           _lowercase       :							str      		=		self.prepare_config_and_inputs()
           self.check_vision_text_output_attention(**lowerCamelCase)
       @is_pt_flax_cross_test
       def 			UpperCamelCase     (					self)       ->   Tuple:




           """simple docstring"""

           _lowercase       :							List[Any]      		=		self.prepare_config_and_inputs()
           _lowercase       :							List[str]      		=		config_inputs_dict.pop('vision_config')
           _lowercase       :							str      		=		config_inputs_dict.pop('text_config')

           _lowercase       :							int      		=		config_inputs_dict

           self.check_equivalence_pt_to_flax(lowerCamelCase,      lowerCamelCase,      lowerCamelCase)
           self.check_equivalence_flax_to_pt(lowerCamelCase,      lowerCamelCase,      lowerCamelCase)




       @slow
       def 			UpperCamelCase     (					self)       ->   List[str]:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Optional[Any]      		=		self.get_pretrained_model_and_inputs()

           _lowercase       :							Optional[int]      		=		model_a(**lowerCamelCase)
           _lowercase       :							Tuple      		=		outputs[0]

           with tempfile.TemporaryDirectory() as tmp_dirname:
               model_a.save_pretrained(lowerCamelCase)
               _lowercase       :							int      		=		FlaxVisionTextDualEncoderModel.from_pretrained(lowerCamelCase)

               _lowercase       :							List[Any]      		=		model_a(**lowerCamelCase)
               _lowercase       :							Tuple      		=		after_outputs[0]
               _lowercase       :							Dict      		=		np.amax(np.abs(out_a - out_a))
               self.assertLessEqual(lowerCamelCase,      1E-5)






@require_flax
class _lowerCamelCase(						_a, unittest.TestCase   ):
       def 			UpperCamelCase     (					self)       ->   List[str]:




           """simple docstring"""

           _lowercase       :							Union[str, Any]      		=		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
               'hf-internal-testing/tiny-random-vit',      'hf-internal-testing/tiny-bert',      vision_from_pt=lowerCamelCase,      text_from_pt=lowerCamelCase,      )
           _lowercase       :							List[Any]      		=		13
           _lowercase       :							str      		=		floats_tensor(
               [
                   batch_size,
                   model.config.vision_config.num_channels,
                   model.config.vision_config.image_size,
                   model.config.vision_config.image_size,
               ])
           _lowercase       :							Tuple      		=		ids_tensor([batch_size, 4],      model.config.text_config.vocab_size)
           _lowercase       :							Union[str, Any]      		=		random_attention_mask([batch_size, 4])
           _lowercase       :							int      		=		{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

           return model, inputs
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase)       ->   Any:




           """simple docstring"""

           _lowercase       :							List[Any]      		=		FlaxViTModel(lowerCamelCase)
           _lowercase       :							Optional[Any]      		=		FlaxBertModel(lowerCamelCase)
           return vision_model, text_model




       def 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

           _lowercase       :							List[Any]      		=		FlaxViTModelTester(self)
           _lowercase       :							Any      		=		FlaxBertModelTester(self)
           _lowercase       :							Dict      		=		vit_model_tester.prepare_config_and_inputs()
           _lowercase       :							Any      		=		bert_model_tester.prepare_config_and_inputs()

           _lowercase		,				_lowercase       :							List[str]      		=		vision_config_and_inputs

           _lowercase		,				_lowercase		,				_lowercase		,				_lowercase       :							Tuple      		=		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(						_a, unittest.TestCase   ):
       def 			UpperCamelCase     (					self)       ->   Tuple:




           """simple docstring"""

           _lowercase       :							str      		=		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
               'hf-internal-testing/tiny-random-clip',      'hf-internal-testing/tiny-bert',      vision_from_pt=lowerCamelCase,      text_from_pt=lowerCamelCase,      )
           _lowercase       :							Tuple      		=		13
           _lowercase       :							Any      		=		floats_tensor(
               [
                   batch_size,
                   model.config.vision_config.num_channels,
                   model.config.vision_config.image_size,
                   model.config.vision_config.image_size,
               ])
           _lowercase       :							Union[str, Any]      		=		ids_tensor([batch_size, 4],      model.config.text_config.vocab_size)
           _lowercase       :							Any      		=		random_attention_mask([batch_size, 4])
           _lowercase       :							Dict      		=		{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

           return model, inputs
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase)       ->   Optional[int]:




           """simple docstring"""

           _lowercase       :							Any      		=		FlaxCLIPVisionModel(lowerCamelCase)
           _lowercase       :							Optional[Any]      		=		FlaxBertModel(lowerCamelCase)
           return vision_model, text_model




       def 			UpperCamelCase     (					self)       ->   Dict:




           """simple docstring"""

           _lowercase       :							Tuple      		=		FlaxCLIPVisionModelTester(self)
           _lowercase       :							Union[str, Any]      		=		FlaxBertModelTester(self)
           _lowercase       :							Tuple      		=		clip_model_tester.prepare_config_and_inputs()
           _lowercase       :							str      		=		bert_model_tester.prepare_config_and_inputs()

           _lowercase		,				_lowercase       :							Dict      		=		vision_config_and_inputs

           _lowercase		,				_lowercase		,				_lowercase		,				_lowercase       :							Optional[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_flax
@require_vision
class _lowerCamelCase(						unittest.TestCase   ):
       @slow
       def 			UpperCamelCase     (					self)       ->   Optional[int]:




           """simple docstring"""

           _lowercase       :							List[str]      		=		FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian',      logit_scale_init_value=1.0)
           _lowercase       :							List[str]      		=		VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian')

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

           _lowercase       :							List[Any]      		=		model(**lowerCamelCase)

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

           _lowercase       :							Optional[int]      		=		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,      lowerCamelCase,      atol=1E-3))


