





from __future__ import annotations

import unittest

from transformers import EsmConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
				import numpy
				import tensorflow as tf

				from transformers.models.esm.modeling_tf_esm import (
				    TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST,
				    TFEsmForMaskedLM,
				    TFEsmForSequenceClassification,
				    TFEsmForTokenClassification,
				    TFEsmModel,
				)





class 						_A:


				"""simple docstring"""


				def __init__(			self     ,					_A     ,					):
									__A	:						Union[str, Any]       =				parent
									__A	:						List[Any]       =				13
									__A	:						Optional[int]       =				7
									__A	:						Tuple       =				True
									__A	:						str       =				True
									__A	:						int       =				True
									__A	:						Any       =				99
									__A	:						Tuple       =				32
									__A	:						Dict       =				2
									__A	:						List[str]       =				4
									__A	:						int       =				37
									__A	:						Union[str, Any]       =				'gelu'
									__A	:						List[Any]       =				0.1
									__A	:						List[str]       =				0.1
									__A	:						Dict       =				512
									__A	:						List[Any]       =				16
									__A	:						int       =				2
									__A	:						Optional[int]       =				0.0_2
									__A	:						str       =				3
									__A	:						Tuple       =				4
									__A	:						Dict       =				None



				def 					UpperCAmelCase_		(			self     ):
									__A	:						Union[str, Any]       =				ids_tensor([self.batch_size, self.seq_length]     ,					self.vocab_size     )

									__A	:						int       =				None
									if self.use_input_mask:
														__A	:						Any       =				random_attention_mask([self.batch_size, self.seq_length]     )

									__A	:						str       =				None
									__A	:						List[str]       =				None
									__A	:						Tuple       =				None
									if self.use_labels:
														__A	:						Tuple       =				ids_tensor([self.batch_size]     ,					self.type_sequence_label_size     )
														__A	:						Optional[Any]       =				ids_tensor([self.batch_size, self.seq_length]     ,					self.num_labels     )
														__A	:						Tuple       =				ids_tensor([self.batch_size]     ,					self.num_choices     )

									__A	:						Tuple       =				EsmConfig(
									    vocab_size=self.vocab_size     ,					hidden_size=self.hidden_size     ,					num_hidden_layers=self.num_hidden_layers     ,					pad_token_id=1     ,					num_attention_heads=self.num_attention_heads     ,					intermediate_size=self.intermediate_size     ,					hidden_act=self.hidden_act     ,					hidden_dropout_prob=self.hidden_dropout_prob     ,					attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,					max_position_embeddings=self.max_position_embeddings     ,					type_vocab_size=self.type_vocab_size     ,					initializer_range=self.initializer_range     ,					)

									return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels



				def 					UpperCAmelCase_		(			self     ):
									(
									    (
									    __A
									)    ,				(
									    __A
									)    ,				(
									    __A
									)    ,				(
									    __A
									)    ,				(
									    __A
									)    ,				(
									    __A
									)    ,				
									)	:						int       =				self.prepare_config_and_inputs()

									__A	:						Optional[int]       =				True
									__A	:						Any       =				floats_tensor([self.batch_size, self.seq_length, self.hidden_size]     )
									__A	:						Tuple       =				ids_tensor([self.batch_size, self.seq_length]     ,					vocab_size=2     )

									return (
									    config,
									    input_ids,
									    input_mask,
									    sequence_labels,
									    token_labels,
									    choice_labels,
									    encoder_hidden_states,
									    encoder_attention_mask,
									)



				def 					UpperCAmelCase_		(			self     ,					_A     ,					_A     ,					_A     ,					_A     ,					_A     ,					_A     ):
									__A	:						str       =				TFEsmModel(config=_A     )
									__A	:						str       =				{'input_ids': input_ids, 'attention_mask': input_mask}
									__A	:						Dict       =				model(_A     )

									__A	:						List[str]       =				[input_ids, input_mask]
									__A	:						str       =				model(_A     )

									__A	:						Dict       =				model(_A     )

									self.parent.assertEqual(result.last_hidden_state.shape     ,					(self.batch_size, self.seq_length, self.hidden_size)     )



				def 					UpperCAmelCase_		(			self     ,					_A     ,					_A     ,					_A     ,					_A     ,					_A     ,					_A     ,					_A     ,					_A     ,					):
									__A	:						int       =				True

									__A	:						List[str]       =				TFEsmModel(config=_A     )
									__A	:						Dict       =				{
									    'input_ids': input_ids,
									    'attention_mask': input_mask,
									    'encoder_hidden_states': encoder_hidden_states,
									    'encoder_attention_mask': encoder_attention_mask,
									}
									__A	:						Optional[Any]       =				model(_A     )

									__A	:						Optional[int]       =				[input_ids, input_mask]
									__A	:						int       =				model(_A     ,					encoder_hidden_states=_A     )

									# Also check the case where encoder outputs are not passed
									__A	:						Union[str, Any]       =				model(_A     ,					attention_mask=_A     )

									self.parent.assertEqual(result.last_hidden_state.shape     ,					(self.batch_size, self.seq_length, self.hidden_size)     )



				def 					UpperCAmelCase_		(			self     ,					_A     ,					_A     ,					_A     ,					_A     ,					_A     ,					_A     ):
									__A	:						Optional[Any]       =				TFEsmForMaskedLM(config=_A     )
									__A	:						List[Any]       =				model([input_ids, input_mask]     )
									self.parent.assertEqual(result.logits.shape     ,					(self.batch_size, self.seq_length, self.vocab_size)     )



				def 					UpperCAmelCase_		(			self     ,					_A     ,					_A     ,					_A     ,					_A     ,					_A     ,					_A     ):
									__A	:						str       =				self.num_labels
									__A	:						Dict       =				TFEsmForTokenClassification(config=_A     )
									__A	:						List[str]       =				{'input_ids': input_ids, 'attention_mask': input_mask}
									__A	:						Tuple       =				model(_A     )
									self.parent.assertEqual(result.logits.shape     ,					(self.batch_size, self.seq_length, self.num_labels)     )





				def 					UpperCAmelCase_		(			self     ):
									__A	:						List[Any]       =				self.prepare_config_and_inputs()
									(
									    (
									    __A
									)    ,				(
									    __A
									)    ,				(
									    __A
									)    ,				(
									    __A
									)    ,				(
									    __A
									)    ,				(
									    __A
									)    ,				
									)	:						Dict       =				config_and_inputs
									__A	:						int       =				{'input_ids': input_ids, 'attention_mask': input_mask}
									return config, inputs_dict





@require_tf
class 						_A(					snake_case__				, snake_case__				, unittest.TestCase   ):


				"""simple docstring"""


				UpperCamelCase    :  List[str]					    =	(
				    (
				        TFEsmModel,
				        TFEsmForMaskedLM,
				        TFEsmForSequenceClassification,
				        TFEsmForTokenClassification,
				    )
				    if is_tf_available()
				    else ()
				)
				UpperCamelCase    :  str					    =	(
				    {
				        '''feature-extraction''': TFEsmModel,
				        '''fill-mask''': TFEsmForMaskedLM,
				        '''text-classification''': TFEsmForSequenceClassification,
				        '''token-classification''': TFEsmForTokenClassification,
				        '''zero-shot''': TFEsmForSequenceClassification,
				    }
				    if is_tf_available()
				    else {}
				)
				UpperCamelCase    :  Optional[int]					    =	False
				UpperCamelCase    :  int					    =	False



				def 					UpperCAmelCase_		(			self     ):
									__A	:						Optional[Any]       =				TFEsmModelTester(self     )
									__A	:						Dict       =				ConfigTester(self     ,					config_class=_A     ,					hidden_size=37     )



				def 					UpperCAmelCase_		(			self     ):
									self.config_tester.run_common_tests()



				def 					UpperCAmelCase_		(			self     ):
									__A	:						List[Any]       =				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_A     )



				def 					UpperCAmelCase_		(			self     ):
									__A	:						Optional[int]       =				self.model_tester.prepare_config_and_inputs_for_decoder()
									self.model_tester.create_and_check_model_as_decoder(*_A     )



				def 					UpperCAmelCase_		(			self     ):
									__A	:						Tuple       =				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_masked_lm(*_A     )



				def 					UpperCAmelCase_		(			self     ):
									__A	:						int       =				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_token_classification(*_A     )



				@slow
				def 					UpperCAmelCase_		(			self     ):
									for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														__A	:						Union[str, Any]       =				TFEsmModel.from_pretrained(_A     )
														self.assertIsNotNone(_A     )



				@unittest.skip('Protein models do not support embedding resizing.'     )
				def 					UpperCAmelCase_		(			self     ):
									pass



				@unittest.skip('Protein models do not support embedding resizing.'     )
				def 					UpperCAmelCase_		(			self     ):
									pass





				def 					UpperCAmelCase_		(			self     ):
									__A    ,				__A	:						Tuple       =				self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
														__A	:						Union[str, Any]       =				model_class(_A     )
														assert isinstance(model.get_input_embeddings()     ,					tf.keras.layers.Layer     )
														if model_class is TFEsmForMaskedLM:
																			# Output embedding test differs from the main test because they're a matrix, not a layer
																			__A	:						Optional[Any]       =				model.get_bias()
																			assert isinstance(_A     ,					_A     )
																			for k, v in name.items():
																								assert isinstance(_A     ,					tf.Variable     )
														else:
																			__A	:						Any       =				model.get_output_embeddings()
																			assert x is None
																			__A	:						Tuple       =				model.get_bias()
																			assert name is None





@require_tf
class 						_A(					unittest.TestCase   ):


				"""simple docstring"""


				@slow
				def 					UpperCAmelCase_		(			self     ):
									__A	:						List[Any]       =				TFEsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D'     )

									__A	:						str       =				tf.constant([[0, 1, 2, 3, 4, 5]]     )
									__A	:						Union[str, Any]       =				model(_A     )[0]
									__A	:						Optional[int]       =				[1, 6, 33]
									self.assertEqual(list(output.numpy().shape     )     ,					_A     )
									# compare the actual values for a slice.
									__A	:						str       =				tf.constant(
									    [
									        [
									            [8.9_2_1_5_1_8, -1_0.5_8_9_8_1_4, -6.4_6_7_1_3_0_7],
									            [-6.3_9_6_7_1_5_6, -1_3.9_1_1_3_7_7, -1.1_2_1_1_9_1_5],
									            [-7.7_8_1_2_4_7, -1_3.9_5_1_5_5_7, -3.7_4_0_5_9_2],
									        ]
									    ]     )
									self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()     ,					expected_slice.numpy()     ,					atol=1e-2     )     )





				@slow
				def 					UpperCAmelCase_		(			self     ):
									__A	:						int       =				TFEsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D'     )

									__A	:						Any       =				tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]     )
									__A	:						List[Any]       =				model(_A     )[0]
									# compare the actual values for a slice.
									__A	:						Dict       =				tf.constant(
									    [
									        [
									            [0.1_4_4_4_3_0_9_2, 0.5_4_1_2_5_3_2_7, 0.3_2_4_7_7_3_9],
									            [0.3_0_3_4_0_4_8_4, 0.0_0_5_2_6_6_7_6, 0.3_1_0_7_7_7_2_2],
									            [0.3_2_2_7_8_0_4_3, -0.2_4_9_8_7_0_9_6, 0.3_4_1_4_6_2_8],
									        ]
									    ]     )
									self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()     ,					expected_slice.numpy()     ,					atol=1e-4     )     )











import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
				from PIL import Image

				from transformers import OwlViTImageProcessor, OwlViTProcessor





@require_vision
class 						_A(					unittest.TestCase   ):


				"""simple docstring"""


				def 					UpperCAmelCase_		(			self     ):
									__A	:						List[Any]       =				tempfile.mkdtemp()

									# fmt: off
									__A	:						List[str]       =				['', 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>']
									# fmt: on
									__A	:						Union[str, Any]       =				dict(zip(_A     ,					range(len(_A     )     )     )     )
									__A	:						Optional[int]       =				['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', '']
									__A	:						int       =				{'unk_token': '<unk>'}

									__A	:						Optional[int]       =				os.path.join(self.tmpdirname     ,					VOCAB_FILES_NAMES['vocab_file']     )
									__A	:						int       =				os.path.join(self.tmpdirname     ,					VOCAB_FILES_NAMES['merges_file']     )
									with open(self.vocab_file     ,					'w'     ,					encoding='utf-8'     ) as fp:
														fp.write(json.dumps(_A     ) + '\n'     )
									with open(self.merges_file     ,					'w'     ,					encoding='utf-8'     ) as fp:
														fp.write('\n'.join(_A     )     )

									__A	:						List[Any]       =				{
									    'do_resize': True,
									    'size': 20,
									    'do_center_crop': True,
									    'crop_size': 18,
									    'do_normalize': True,
									    'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3],
									    'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1],
									}
									__A	:						Optional[int]       =				os.path.join(self.tmpdirname     ,					_A     )
									with open(self.image_processor_file     ,					'w'     ,					encoding='utf-8'     ) as fp:
														json.dump(_A     ,					_A     )



				def 					UpperCAmelCase_		(			self     ,					**_A     ):
									return CLIPTokenizer.from_pretrained(self.tmpdirname     ,					pad_token='!'     ,					**_A     )



				def 					UpperCAmelCase_		(			self     ,					**_A     ):
									return CLIPTokenizerFast.from_pretrained(self.tmpdirname     ,					pad_token='!'     ,					**_A     )



				def 					UpperCAmelCase_		(			self     ,					**_A     ):
									return OwlViTImageProcessor.from_pretrained(self.tmpdirname     ,					**_A     )



				def 					UpperCAmelCase_		(			self     ):
									shutil.rmtree(self.tmpdirname     )



				def 					UpperCAmelCase_		(			self     ):
									__A	:						int       =				[np.random.randint(255     ,					size=(3, 30, 400)     ,					dtype=np.uinta     )]

									__A	:						Optional[int]       =				[Image.fromarray(np.moveaxis(_A     ,					0     ,					-1     )     ) for x in image_inputs]

									return image_inputs



				def 					UpperCAmelCase_		(			self     ):
									__A	:						List[Any]       =				self.get_tokenizer()
									__A	:						str       =				self.get_rust_tokenizer()
									__A	:						List[str]       =				self.get_image_processor()

									__A	:						Optional[int]       =				OwlViTProcessor(tokenizer=_A     ,					image_processor=_A     )
									processor_slow.save_pretrained(self.tmpdirname     )
									__A	:						int       =				OwlViTProcessor.from_pretrained(self.tmpdirname     ,					use_fast=_A     )

									__A	:						Optional[Any]       =				OwlViTProcessor(tokenizer=_A     ,					image_processor=_A     )
									processor_fast.save_pretrained(self.tmpdirname     )
									__A	:						Optional[Any]       =				OwlViTProcessor.from_pretrained(self.tmpdirname     )

									self.assertEqual(processor_slow.tokenizer.get_vocab()     ,					tokenizer_slow.get_vocab()     )
									self.assertEqual(processor_fast.tokenizer.get_vocab()     ,					tokenizer_fast.get_vocab()     )
									self.assertEqual(tokenizer_slow.get_vocab()     ,					tokenizer_fast.get_vocab()     )
									self.assertIsInstance(processor_slow.tokenizer     ,					_A     )
									self.assertIsInstance(processor_fast.tokenizer     ,					_A     )

									self.assertEqual(processor_slow.image_processor.to_json_string()     ,					image_processor.to_json_string()     )
									self.assertEqual(processor_fast.image_processor.to_json_string()     ,					image_processor.to_json_string()     )
									self.assertIsInstance(processor_slow.image_processor     ,					_A     )
									self.assertIsInstance(processor_fast.image_processor     ,					_A     )



				def 					UpperCAmelCase_		(			self     ):
									__A	:						List[str]       =				OwlViTProcessor(tokenizer=self.get_tokenizer()     ,					image_processor=self.get_image_processor()     )
									processor.save_pretrained(self.tmpdirname     )

									__A	:						Optional[int]       =				self.get_tokenizer(bos_token='(BOS)'     ,					eos_token='(EOS)'     )
									__A	:						Optional[int]       =				self.get_image_processor(do_normalize=_A     )

									__A	:						Any       =				OwlViTProcessor.from_pretrained(
									    self.tmpdirname     ,					bos_token='(BOS)'     ,					eos_token='(EOS)'     ,					do_normalize=_A     )

									self.assertEqual(processor.tokenizer.get_vocab()     ,					tokenizer_add_kwargs.get_vocab()     )
									self.assertIsInstance(processor.tokenizer     ,					_A     )

									self.assertEqual(processor.image_processor.to_json_string()     ,					image_processor_add_kwargs.to_json_string()     )
									self.assertIsInstance(processor.image_processor     ,					_A     )



				def 					UpperCAmelCase_		(			self     ):
									__A	:						Optional[Any]       =				self.get_image_processor()
									__A	:						Optional[Any]       =				self.get_tokenizer()

									__A	:						Union[str, Any]       =				OwlViTProcessor(tokenizer=_A     ,					image_processor=_A     )

									__A	:						Union[str, Any]       =				self.prepare_image_inputs()

									__A	:						int       =				image_processor(_A     ,					return_tensors='np'     )
									__A	:						str       =				processor(images=_A     ,					return_tensors='np'     )

									for key in input_image_proc.keys():
														self.assertAlmostEqual(input_image_proc[key].sum()     ,					input_processor[key].sum()     ,					delta=1e-2     )



				def 					UpperCAmelCase_		(			self     ):
									__A	:						str       =				self.get_image_processor()
									__A	:						str       =				self.get_tokenizer()

									__A	:						Tuple       =				OwlViTProcessor(tokenizer=_A     ,					image_processor=_A     )

									__A	:						str       =				'lower newer'

									__A	:						str       =				processor(text=_A     ,					return_tensors='np'     )

									__A	:						List[str]       =				tokenizer(_A     ,					return_tensors='np'     )

									for key in encoded_tok.keys():
														self.assertListEqual(encoded_tok[key][0].tolist()     ,					encoded_processor[key][0].tolist()     )



				def 					UpperCAmelCase_		(			self     ):
									__A	:						int       =				self.get_image_processor()
									__A	:						Optional[int]       =				self.get_tokenizer()

									__A	:						List[str]       =				OwlViTProcessor(tokenizer=_A     ,					image_processor=_A     )

									__A	:						Any       =				'lower newer'
									__A	:						Optional[Any]       =				self.prepare_image_inputs()

									__A	:						List[Any]       =				processor(text=_A     ,					images=_A     )

									self.assertListEqual(list(inputs.keys()     )     ,					['input_ids', 'attention_mask', 'pixel_values']     )

									# test if it raises when no input is passed
									with pytest.raises(_A     ):
														processor()



				def 					UpperCAmelCase_		(			self     ):
									__A	:						Any       =				'google/owlvit-base-patch32'
									__A	:						int       =				OwlViTProcessor.from_pretrained(_A     )

									__A	:						Dict       =				['cat', 'nasa badge']
									__A	:						Optional[Any]       =				processor(text=_A     )

									__A	:						Optional[int]       =				16
									self.assertListEqual(list(inputs.keys()     )     ,					['input_ids', 'attention_mask']     )
									self.assertEqual(inputs['input_ids'].shape     ,					(2, seq_length)     )

									# test if it raises when no input is passed
									with pytest.raises(_A     ):
														processor()



				def 					UpperCAmelCase_		(			self     ):
									__A	:						Tuple       =				'google/owlvit-base-patch32'
									__A	:						Any       =				OwlViTProcessor.from_pretrained(_A     )

									__A	:						Dict       =				[['cat', 'nasa badge'], ['person']]
									__A	:						Dict       =				processor(text=_A     )

									__A	:						Optional[int]       =				16
									__A	:						Any       =				len(_A     )
									__A	:						Union[str, Any]       =				max([len(_A     ) for texts in input_texts]     )

									self.assertListEqual(list(inputs.keys()     )     ,					['input_ids', 'attention_mask']     )
									self.assertEqual(inputs['input_ids'].shape     ,					(batch_size * num_max_text_queries, seq_length)     )

									# test if it raises when no input is passed
									with pytest.raises(_A     ):
														processor()



				def 					UpperCAmelCase_		(			self     ):
									__A	:						List[Any]       =				'google/owlvit-base-patch32'
									__A	:						str       =				OwlViTProcessor.from_pretrained(_A     )

									__A	:						Union[str, Any]       =				['cat', 'nasa badge']
									__A	:						Tuple       =				processor(text=_A     )

									__A	:						str       =				16
									__A	:						int       =				inputs['input_ids']
									__A	:						List[Any]       =				[
									    [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
									    [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
									]

									self.assertListEqual(list(inputs.keys()     )     ,					['input_ids', 'attention_mask']     )
									self.assertEqual(inputs['input_ids'].shape     ,					(2, seq_length)     )
									self.assertListEqual(list(input_ids[0]     )     ,					predicted_ids[0]     )
									self.assertListEqual(list(input_ids[1]     )     ,					predicted_ids[1]     )



				def 					UpperCAmelCase_		(			self     ):
									__A	:						Optional[Any]       =				self.get_image_processor()
									__A	:						List[str]       =				self.get_tokenizer()

									__A	:						Optional[Any]       =				OwlViTProcessor(tokenizer=_A     ,					image_processor=_A     )

									__A	:						Optional[int]       =				self.prepare_image_inputs()
									__A	:						Optional[int]       =				self.prepare_image_inputs()

									__A	:						Optional[int]       =				processor(images=_A     ,					query_images=_A     )

									self.assertListEqual(list(inputs.keys()     )     ,					['query_pixel_values', 'pixel_values']     )

									# test if it raises when no input is passed
									with pytest.raises(_A     ):
														processor()





				def 					UpperCAmelCase_		(			self     ):
									__A	:						Optional[Any]       =				self.get_image_processor()
									__A	:						Union[str, Any]       =				self.get_tokenizer()

									__A	:						str       =				OwlViTProcessor(tokenizer=_A     ,					image_processor=_A     )

									__A	:						Optional[Any]       =				[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

									__A	:						Any       =				processor.batch_decode(_A     )
									__A	:						Tuple       =				tokenizer.batch_decode(_A     )

									self.assertListEqual(_A     ,					_A     )




