
import inspect
import unittest

from transformers import SegformerConfig, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch

		from transformers import (
		    MODEL_MAPPING,
		    SegformerForImageClassification,
		    SegformerForSemanticSegmentation,
		    SegformerModel,
		)
		from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import SegformerImageProcessor







class 				lowerCAmelCase_				(      UpperCamelCase__    ):



						'''simple docstring'''


						def 						_SCREAMING_SNAKE_CASE      ( self     :      List[Any]      )     ->   str:
							A						   =   self.config_class(**self.inputs_dict      )
							self.parent.assertTrue(hasattr(__A  ,'hidden_sizes'      )      )
							self.parent.assertTrue(hasattr(__A  ,'num_attention_heads'      )      )
							self.parent.assertTrue(hasattr(__A  ,'num_encoder_blocks'      )      )







class 				lowerCAmelCase_				:



						'''simple docstring'''


						def __init__( self     :      List[str]  ,A_     :      Optional[Any]  ,A_     :      Tuple=13  ,A_     :      List[Any]=64  ,A_     :      int=3  ,A_     :      Dict=4  ,A_     :      str=[2, 2, 2, 2]  ,A_     :      Optional[Any]=[8, 4, 2, 1]  ,A_     :      str=[16, 32, 64, 128]  ,A_     :      Any=[1, 4, 8, 16]  ,A_     :      Tuple=[1, 2, 4, 8]  ,A_     :      List[Any]=True  ,A_     :      List[str]=True  ,A_     :      str="gelu"  ,A_     :      str=0.1  ,A_     :      Dict=0.1  ,A_     :      Optional[Any]=0.02  ,A_     :      Union[str, Any]=3  ,A_     :      Any=None  ,)     ->   List[Any]:
							A						   =   parent
							A						   =   batch_size
							A						   =   image_size
							A						   =   num_channels
							A						   =   num_encoder_blocks
							A						   =   sr_ratios
							A						   =   depths
							A						   =   hidden_sizes
							A						   =   downsampling_rates
							A						   =   num_attention_heads
							A						   =   is_training
							A						   =   use_labels
							A						   =   hidden_act
							A						   =   hidden_dropout_prob
							A						   =   attention_probs_dropout_prob
							A						   =   initializer_range
							A						   =   num_labels
							A						   =   scope


						def 						_SCREAMING_SNAKE_CASE      ( self     :      str      )     ->   List[Any]:
							A						   =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

							A						   =   None
							if self.use_labels:
								A						   =   ids_tensor([self.batch_size, self.image_size, self.image_size]  ,self.num_labels      )

							A						   =   self.get_config()
							return config, pixel_values, labels


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Dict      )     ->   List[Any]:
							return SegformerConfig(
							    image_size=self.image_size  ,num_channels=self.num_channels  ,num_encoder_blocks=self.num_encoder_blocks  ,depths=self.depths  ,hidden_sizes=self.hidden_sizes  ,num_attention_heads=self.num_attention_heads  ,hidden_act=self.hidden_act  ,hidden_dropout_prob=self.hidden_dropout_prob  ,attention_probs_dropout_prob=self.attention_probs_dropout_prob  ,initializer_range=self.initializer_range  ,)


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[int]  ,A_     :      Tuple  ,A_     :      Optional[int]  ,A_     :      str      )     ->   Tuple:
							A						   =   SegformerModel(config=__A      )
							model.to(__A      )
							model.eval()
							A						   =   model(__A      )
							A						   =   A						   =   self.image_size // (self.downsampling_rates[-1] * 2)
							self.parent.assertEqual(
							    result.last_hidden_state.shape  ,(self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Tuple  ,A_     :      Optional[Any]  ,A_     :      Any  ,A_     :      Union[str, Any]      )     ->   str:
							A						   =   self.num_labels
							A						   =   SegformerForSemanticSegmentation(__A      )
							model.to(__A      )
							model.eval()
							A						   =   model(__A      )
							self.parent.assertEqual(
							    result.logits.shape  ,(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)      )
							A						   =   model(__A  ,labels=__A      )
							self.parent.assertEqual(
							    result.logits.shape  ,(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)      )
							self.parent.assertGreater(result.loss  ,0.0      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[int]  ,A_     :      List[Any]  ,A_     :      int  ,A_     :      List[str]      )     ->   Dict:
							A						   =   1
							A						   =   SegformerForSemanticSegmentation(config=__A      )
							model.to(__A      )
							model.eval()
							A						   =   torch.randint(0  ,1  ,(self.batch_size, self.image_size, self.image_size)      ).to(__A      )
							A						   =   model(__A  ,labels=__A      )
							self.parent.assertGreater(result.loss  ,0.0      )




						def 						_SCREAMING_SNAKE_CASE      ( self     :      List[Any]      )     ->   Optional[Any]:
							A						   =   self.prepare_config_and_inputs()
							A   ,      A   ,      A						   =   config_and_inputs
							A						   =   {'pixel_values': pixel_values}
							return config, inputs_dict







@require_torch
class 				lowerCAmelCase_				(      UpperCamelCase__		,					UpperCamelCase__		,					unittest.TestCase    ):



						'''simple docstring'''


						_lowerCamelCase:    List[Any]      =    (
						    (
						        SegformerModel,
						        SegformerForSemanticSegmentation,
						        SegformerForImageClassification,
						    )
						    if is_torch_available()
						    else ()
						)
						_lowerCamelCase:    List[str]      =    (
						    {
						        '''feature-extraction''': SegformerModel,
						        '''image-classification''': SegformerForImageClassification,
						        '''image-segmentation''': SegformerForSemanticSegmentation,
						    }
						    if is_torch_available()
						    else {}
						)

						_lowerCamelCase:    int      =    True
						_lowerCamelCase:    int      =    False
						_lowerCamelCase:    Union[str, Any]      =    False
						_lowerCamelCase:    Union[str, Any]      =    False


						def 						_SCREAMING_SNAKE_CASE      ( self     :      int      )     ->   Tuple:
							A						   =   SegformerModelTester(self      )
							A						   =   SegformerConfigTester(self  ,config_class=__A      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Any      )     ->   int:
							self.config_tester.run_common_tests()


						def 						_SCREAMING_SNAKE_CASE      ( self     :      List[Any]      )     ->   Union[str, Any]:
							A						   =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__A      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[Any]      )     ->   Dict:
							A						   =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_binary_image_segmentation(*__A      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Union[str, Any]      )     ->   Optional[Any]:
							A						   =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_segmentation(*__A      )


						@unittest.skip('SegFormer does not use inputs_embeds'      )
						def 						_SCREAMING_SNAKE_CASE      ( self     :      List[str]      )     ->   Optional[Any]:
							pass


						@unittest.skip('SegFormer does not have get_input_embeddings method and get_output_embeddings methods'      )
						def 						_SCREAMING_SNAKE_CASE      ( self     :      Union[str, Any]      )     ->   Any:
							pass


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Union[str, Any]      )     ->   Union[str, Any]:
							A   ,      A						   =   self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
								A						   =   model_class(__A      )
								A						   =   inspect.signature(model.forward      )
								# signature.parameters is an OrderedDict => so arg_names order is deterministic
								A						   =   [*signature.parameters.keys()]

								A						   =   ['pixel_values']
								self.assertListEqual(arg_names[:1]  ,__A      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      int      )     ->   Tuple:
							A   ,      A						   =   self.model_tester.prepare_config_and_inputs_for_common()
							A						   =   True

							for model_class in self.all_model_classes:
								A						   =   True
								A						   =   False
								A						   =   True
								A						   =   model_class(__A      )
								model.to(__A      )
								model.eval()
								with torch.no_grad():
									A						   =   model(**self._prepare_for_class(__A  ,__A      )      )
								A						   =   outputs.attentions

								A						   =   sum(self.model_tester.depths      )
								self.assertEqual(len(__A      )  ,__A      )

								# check that output_attentions also work using config
								del inputs_dict["output_attentions"]
								A						   =   True
								A						   =   model_class(__A      )
								model.to(__A      )
								model.eval()
								with torch.no_grad():
									A						   =   model(**self._prepare_for_class(__A  ,__A      )      )
								A						   =   outputs.attentions

								self.assertEqual(len(__A      )  ,__A      )

								# verify the first attentions (first block, first layer)
								A						   =   (self.model_tester.image_size // 4) ** 2
								A						   =   (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
								self.assertListEqual(
								    list(attentions[0].shape[-3:]      )  ,[self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]  ,)

								# verify the last attentions (last block, last layer)
								A						   =   (self.model_tester.image_size // 32) ** 2
								A						   =   (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2
								self.assertListEqual(
								    list(attentions[-1].shape[-3:]      )  ,[self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len]  ,)
								A						   =   len(__A      )

								# Check attention is always last and order is fine
								A						   =   True
								A						   =   True
								A						   =   model_class(__A      )
								model.to(__A      )
								model.eval()
								with torch.no_grad():
									A						   =   model(**self._prepare_for_class(__A  ,__A      )      )

								self.assertEqual(out_len + 1  ,len(__A      )      )

								A						   =   outputs.attentions

								self.assertEqual(len(__A      )  ,__A      )
								# verify the first attentions (first block, first layer)
								A						   =   (self.model_tester.image_size // 4) ** 2
								A						   =   (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
								self.assertListEqual(
								    list(self_attentions[0].shape[-3:]      )  ,[self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]  ,)


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Dict      )     ->   Dict:



							def check_hidden_states_output(A_     :      Optional[Any]  ,A_     :      str  ,A_     :      List[str]      ):
								A						   =   model_class(__A      )
								model.to(__A      )
								model.eval()

								with torch.no_grad():
									A						   =   model(**self._prepare_for_class(__A  ,__A      )      )

								A						   =   outputs.hidden_states

								A						   =   self.model_tester.num_encoder_blocks
								self.assertEqual(len(__A      )  ,__A      )

								# verify the first hidden states (first block)
								self.assertListEqual(
								    list(hidden_states[0].shape[-3:]      )  ,[
								        self.model_tester.hidden_sizes[0],
								        self.model_tester.image_size // 4,
								        self.model_tester.image_size // 4,
								    ]  ,)

							A   ,      A						   =   self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
								A						   =   True
								check_hidden_states_output(__A  ,__A  ,__A      )

								# check that output_hidden_states also work using config
								del inputs_dict["output_hidden_states"]
								A						   =   True

								check_hidden_states_output(__A  ,__A  ,__A      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      str      )     ->   List[Any]:



							if not self.model_tester.is_training:
								return

							A   ,      A						   =   self.model_tester.prepare_config_and_inputs_for_common()
							A						   =   True

							for model_class in self.all_model_classes:
								if model_class in get_values(__A      ):
									continue

								A						   =   model_class(__A      )
								model.to(__A      )
								model.train()
								A						   =   self._prepare_for_class(__A  ,__A  ,return_labels=__A      )
								A						   =   model(**__A      ).loss
								loss.backward()


						@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'      )
						def 						_SCREAMING_SNAKE_CASE      ( self     :      str      )     ->   int:
							pass




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



							for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								A						   =   SegformerModel.from_pretrained(__A      )
								self.assertIsNotNone(__A      )






def       _snake_case				(		):
	A						   =   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
	return image







@require_torch
class 				lowerCAmelCase_				(      unittest.TestCase    ):



						'''simple docstring'''


						@slow
						def 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[int]      )     ->   Tuple:
							A						   =   SegformerImageProcessor(
							    image_scale=(512, 512)  ,keep_ratio=__A  ,align=__A  ,do_random_crop=__A      )
							A						   =   SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'      ).to(
							    __A      )

							A						   =   prepare_img()
							A						   =   image_processor(images=__A  ,return_tensors='pt'      )
							A						   =   encoded_inputs.pixel_values.to(__A      )

							with torch.no_grad():
								A						   =   model(__A      )

							A						   =   torch.Size((1, model.config.num_labels, 128, 128)      )
							self.assertEqual(outputs.logits.shape  ,__A      )

							A						   =   torch.tensor(
							    [
							        [[-4.63_10, -5.52_32, -6.23_56], [-5.19_21, -6.14_44, -6.59_96], [-5.44_24, -6.27_90, -6.75_74]],
							        [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]],
							        [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]],
							    ]      ).to(__A      )
							self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]  ,__A  ,atol=1e-4      )      )


						@slow
						def 						_SCREAMING_SNAKE_CASE      ( self     :      Dict      )     ->   List[Any]:
							A						   =   SegformerImageProcessor(
							    image_scale=(512, 512)  ,keep_ratio=__A  ,align=__A  ,do_random_crop=__A      )
							A						   =   SegformerForSemanticSegmentation.from_pretrained(
							    'nvidia/segformer-b1-finetuned-cityscapes-1024-1024'      ).to(__A      )

							A						   =   prepare_img()
							A						   =   image_processor(images=__A  ,return_tensors='pt'      )
							A						   =   encoded_inputs.pixel_values.to(__A      )

							with torch.no_grad():
								A						   =   model(__A      )

							A						   =   torch.Size((1, model.config.num_labels, 128, 128)      )
							self.assertEqual(outputs.logits.shape  ,__A      )

							A						   =   torch.tensor(
							    [
							        [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]],
							        [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]],
							        [[-3.64_56, -3.02_09, -1.42_03], [-3.07_97, -3.19_59, -2.00_00], [-1.87_57, -1.92_17, -1.69_97]],
							    ]      ).to(__A      )
							self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]  ,__A  ,atol=1e-1      )      )




						@slow
						def 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[int]      )     ->   List[Any]:
							A						   =   SegformerImageProcessor(
							    image_scale=(512, 512)  ,keep_ratio=__A  ,align=__A  ,do_random_crop=__A      )
							A						   =   SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'      ).to(
							    __A      )

							A						   =   prepare_img()
							A						   =   image_processor(images=__A  ,return_tensors='pt'      )
							A						   =   encoded_inputs.pixel_values.to(__A      )

							with torch.no_grad():
								A						   =   model(__A      )

							A						   =   outputs.logits.detach().cpu()

							A						   =   image_processor.post_process_semantic_segmentation(outputs=__A  ,target_sizes=[(500, 300)]      )
							A						   =   torch.Size((500, 300)      )
							self.assertEqual(segmentation[0].shape  ,__A      )

							A						   =   image_processor.post_process_semantic_segmentation(outputs=__A      )
							A						   =   torch.Size((128, 128)      )
							self.assertEqual(segmentation[0].shape  ,__A      )

"""simple docstring"""


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 				lowerCAmelCase_				:



						'''simple docstring'''


						def __init__( self     :      List[Any]  ,A_     :      Optional[Any]  ,)     ->   Optional[int]:
							A						   =   parent
							A						   =   13
							A						   =   7
							A						   =   True
							A						   =   True
							A						   =   True
							A						   =   99
							A						   =   32
							A						   =   2
							A						   =   4
							A						   =   37
							A						   =   'gelu'
							A						   =   0.1
							A						   =   0.1
							A						   =   512
							A						   =   16
							A						   =   2
							A						   =   0.02
							A						   =   3
							A						   =   4
							A						   =   None


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Union[str, Any]      )     ->   Union[str, Any]:
							A						   =   ids_tensor([self.batch_size, self.seq_length]  ,self.vocab_size      )

							A						   =   None
							if self.use_input_mask:
								A						   =   random_attention_mask([self.batch_size, self.seq_length]      )

							A						   =   None
							A						   =   None
							A						   =   None
							if self.use_labels:
								A						   =   ids_tensor([self.batch_size]  ,self.type_sequence_label_size      )
								A						   =   ids_tensor([self.batch_size, self.seq_length]  ,self.num_labels      )
								A						   =   ids_tensor([self.batch_size]  ,self.num_choices      )

							A						   =   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 						_SCREAMING_SNAKE_CASE      ( self     :      Union[str, Any]      )     ->   Dict:
							(
							    (
							    A
							)   ,      (
							    A
							)   ,      (
							    A
							)   ,      (
							    A
							)   ,      (
							    A
							)   ,      (
							    A
							)   ,      
							)						   =   self.prepare_config_and_inputs()

							A						   =   True
							A						   =   floats_tensor([self.batch_size, self.seq_length, self.hidden_size]      )
							A						   =   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 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[int]  ,A_     :      int  ,A_     :      List[str]  ,A_     :      Optional[int]  ,A_     :      List[Any]  ,A_     :      Any  ,A_     :      Any      )     ->   Dict:
							A						   =   TFEsmModel(config=A_      )
							A						   =   {'input_ids': input_ids, 'attention_mask': input_mask}
							A						   =   model(A_      )

							A						   =   [input_ids, input_mask]
							A						   =   model(A_      )

							A						   =   model(A_      )

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


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Union[str, Any]  ,A_     :      Any  ,A_     :      Union[str, Any]  ,A_     :      Tuple  ,A_     :      int  ,A_     :      List[Any]  ,A_     :      Optional[int]  ,A_     :      Optional[Any]  ,A_     :      List[str]  ,)     ->   Optional[int]:
							A						   =   True

							A						   =   TFEsmModel(config=A_      )
							A						   =   {
							    'input_ids': input_ids,
							    'attention_mask': input_mask,
							    'encoder_hidden_states': encoder_hidden_states,
							    'encoder_attention_mask': encoder_attention_mask,
							}
							A						   =   model(A_      )

							A						   =   [input_ids, input_mask]
							A						   =   model(A_  ,encoder_hidden_states=A_      )

							# Also check the case where encoder outputs are not passed
							A						   =   model(A_  ,attention_mask=A_      )

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


						def 						_SCREAMING_SNAKE_CASE      ( self     :      str  ,A_     :      List[Any]  ,A_     :      List[Any]  ,A_     :      Optional[Any]  ,A_     :      Optional[int]  ,A_     :      Optional[Any]  ,A_     :      List[Any]      )     ->   Dict:
							A						   =   TFEsmForMaskedLM(config=A_      )
							A						   =   model([input_ids, input_mask]      )
							self.parent.assertEqual(result.logits.shape  ,(self.batch_size, self.seq_length, self.vocab_size)      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Any  ,A_     :      Optional[Any]  ,A_     :      str  ,A_     :      List[Any]  ,A_     :      int  ,A_     :      Tuple  ,A_     :      Optional[int]      )     ->   Union[str, Any]:
							A						   =   self.num_labels
							A						   =   TFEsmForTokenClassification(config=A_      )
							A						   =   {'input_ids': input_ids, 'attention_mask': input_mask}
							A						   =   model(A_      )
							self.parent.assertEqual(result.logits.shape  ,(self.batch_size, self.seq_length, self.num_labels)      )




						def 						_SCREAMING_SNAKE_CASE      ( self     :      Any      )     ->   List[Any]:
							A						   =   self.prepare_config_and_inputs()
							(
							    (
							    A
							)   ,      (
							    A
							)   ,      (
							    A
							)   ,      (
							    A
							)   ,      (
							    A
							)   ,      (
							    A
							)   ,      
							)						   =   config_and_inputs
							A						   =   {'input_ids': input_ids, 'attention_mask': input_mask}
							return config, inputs_dict







@require_tf
class 				lowerCAmelCase_				(      _lowercase		,					_lowercase		,					unittest.TestCase    ):



						'''simple docstring'''


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


						def 						_SCREAMING_SNAKE_CASE      ( self     :      List[Any]      )     ->   int:
							A						   =   TFEsmModelTester(self      )
							A						   =   ConfigTester(self  ,config_class=A_  ,hidden_size=37      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Any      )     ->   Optional[int]:
							self.config_tester.run_common_tests()


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Union[str, Any]      )     ->   List[str]:
							A						   =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*A_      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      List[Any]      )     ->   List[Any]:
							A						   =   self.model_tester.prepare_config_and_inputs_for_decoder()
							self.model_tester.create_and_check_model_as_decoder(*A_      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      str      )     ->   Dict:
							A						   =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_lm(*A_      )


						def 						_SCREAMING_SNAKE_CASE      ( self     :      List[Any]      )     ->   List[Any]:
							A						   =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_token_classification(*A_      )


						@slow
						def 						_SCREAMING_SNAKE_CASE      ( self     :      Tuple      )     ->   Tuple:
							for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								A						   =   TFEsmModel.from_pretrained(A_      )
								self.assertIsNotNone(A_      )


						@unittest.skip('Protein models do not support embedding resizing.'      )
						def 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[int]      )     ->   Optional[int]:
							pass


						@unittest.skip('Protein models do not support embedding resizing.'      )
						def 						_SCREAMING_SNAKE_CASE      ( self     :      Tuple      )     ->   Any:
							pass




						def 						_SCREAMING_SNAKE_CASE      ( self     :      str      )     ->   Dict:
							A   ,      A						   =   self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
								A						   =   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						   =   model.get_bias()
									assert isinstance(A_  ,A_      )
									for k, v in name.items():
										assert isinstance(A_  ,tf.Variable      )
								else:
									A						   =   model.get_output_embeddings()
									assert x is None
									A						   =   model.get_bias()
									assert name is None







@require_tf
class 				lowerCAmelCase_				(      unittest.TestCase    ):



						'''simple docstring'''


						@slow
						def 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[Any]      )     ->   Tuple:
							A						   =   TFEsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D'      )

							A						   =   tf.constant([[0, 1, 2, 3, 4, 5]]      )
							A						   =   model(A_      )[0]
							A						   =   [1, 6, 33]
							self.assertEqual(list(output.numpy().shape      )  ,A_      )
							# compare the actual values for a slice.
							A						   =   tf.constant(
							    [
							        [
							            [8.92_15_18, -10.58_98_14, -6.4_67_13_07],
							            [-6.3_96_71_56, -13.91_13_77, -1.1_21_19_15],
							            [-7.78_12_47, -13.95_15_57, -3.74_05_92],
							        ]
							    ]      )
							self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()  ,expected_slice.numpy()  ,atol=1e-2      )      )




						@slow
						def 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[Any]      )     ->   int:
							A						   =   TFEsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D'      )

							A						   =   tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]      )
							A						   =   model(A_      )[0]
							# compare the actual values for a slice.
							A						   =   tf.constant(
							    [
							        [
							            [0.14_44_30_92, 0.54_12_53_27, 0.3_24_77_39],
							            [0.30_34_04_84, 0.00_52_66_76, 0.31_07_77_22],
							            [0.32_27_80_43, -0.24_98_70_96, 0.3_41_46_28],
							        ]
							    ]      )
							self.assertTrue(numpy.allclose(output[:, :3, :3].numpy()  ,expected_slice.numpy()  ,atol=1e-4      )      )