
import unittest

from transformers import EsmConfig, is_torch_available
from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device

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


if is_torch_available():
				import torch

				from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel
				from transformers.models.esm.modeling_esm import (
				    ESM_PRETRAINED_MODEL_ARCHIVE_LIST,
				    EsmEmbeddings,
				    create_position_ids_from_input_ids,
				)






class        SCREAMING_SNAKE_CASE__    :

							"""simple docstring"""






							def __init__(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_=13     ,	SCREAMING_SNAKE_CASE_=7     ,	SCREAMING_SNAKE_CASE_=False     ,	SCREAMING_SNAKE_CASE_=True     ,	SCREAMING_SNAKE_CASE_=False     ,	SCREAMING_SNAKE_CASE_=True     ,	SCREAMING_SNAKE_CASE_=33     ,	SCREAMING_SNAKE_CASE_=32     ,	SCREAMING_SNAKE_CASE_=5     ,	SCREAMING_SNAKE_CASE_=4     ,	SCREAMING_SNAKE_CASE_=37     ,	SCREAMING_SNAKE_CASE_="gelu"     ,	SCREAMING_SNAKE_CASE_=0.1     ,	SCREAMING_SNAKE_CASE_=0.1     ,	SCREAMING_SNAKE_CASE_=512     ,	SCREAMING_SNAKE_CASE_=16     ,	SCREAMING_SNAKE_CASE_=2     ,	SCREAMING_SNAKE_CASE_=0.0_2     ,	SCREAMING_SNAKE_CASE_=3     ,	SCREAMING_SNAKE_CASE_=4     ,	SCREAMING_SNAKE_CASE_=None     ,	)->   Optional[Any]:





													'''simple docstring'''






													__UpperCamelCase       =			parent
													__UpperCamelCase       =			batch_size
													__UpperCamelCase       =			seq_length
													__UpperCamelCase       =			is_training
													__UpperCamelCase       =			use_input_mask
													__UpperCamelCase       =			use_token_type_ids
													__UpperCamelCase       =			use_labels
													__UpperCamelCase       =			vocab_size
													__UpperCamelCase       =			hidden_size
													__UpperCamelCase       =			num_hidden_layers
													__UpperCamelCase       =			num_attention_heads
													__UpperCamelCase       =			intermediate_size
													__UpperCamelCase       =			hidden_act
													__UpperCamelCase       =			hidden_dropout_prob
													__UpperCamelCase       =			attention_probs_dropout_prob
													__UpperCamelCase       =			max_position_embeddings
													__UpperCamelCase       =			type_vocab_size
													__UpperCamelCase       =			type_sequence_label_size
													__UpperCamelCase       =			initializer_range
													__UpperCamelCase       =			num_labels
													__UpperCamelCase       =			num_choices
													__UpperCamelCase       =			scope



							def     A__		(  self			)->   Union[str, Any]:





													'''simple docstring'''






													__UpperCamelCase       =			ids_tensor([self.batch_size, self.seq_length]     ,	self.vocab_size			)

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

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

													__UpperCamelCase       =			self.get_config()

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



							def     A__		(  self			)->   Union[str, Any]:





													'''simple docstring'''






													return EsmConfig(
													    vocab_size=self.vocab_size     ,	hidden_size=self.hidden_size     ,	pad_token_id=1     ,	num_hidden_layers=self.num_hidden_layers     ,	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     ,	)



							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)->   int:





													'''simple docstring'''






													__UpperCamelCase       =			EsmModel(config=SCREAMING_SNAKE_CASE_			)
													model.to(SCREAMING_SNAKE_CASE_			)
													model.eval()
													__UpperCamelCase       =			model(SCREAMING_SNAKE_CASE_     ,	attention_mask=SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			model(SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			model(SCREAMING_SNAKE_CASE_			)

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



							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)->   List[str]:





													'''simple docstring'''






													__UpperCamelCase       =			EsmForMaskedLM(config=SCREAMING_SNAKE_CASE_			)
													model.to(SCREAMING_SNAKE_CASE_			)
													model.eval()
													__UpperCamelCase       =			model(SCREAMING_SNAKE_CASE_     ,	attention_mask=SCREAMING_SNAKE_CASE_     ,	labels=SCREAMING_SNAKE_CASE_			)
													self.parent.assertEqual(result.logits.shape     ,	(self.batch_size, self.seq_length, self.vocab_size)			)



							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)->   List[str]:





													'''simple docstring'''






													__UpperCamelCase       =			self.num_labels
													__UpperCamelCase       =			EsmForTokenClassification(config=SCREAMING_SNAKE_CASE_			)
													model.to(SCREAMING_SNAKE_CASE_			)
													model.eval()
													__UpperCamelCase       =			model(SCREAMING_SNAKE_CASE_     ,	attention_mask=SCREAMING_SNAKE_CASE_     ,	labels=SCREAMING_SNAKE_CASE_			)
													self.parent.assertEqual(result.logits.shape     ,	(self.batch_size, self.seq_length, self.num_labels)			)



							def     A__		(  self			)->   Any:





													'''simple docstring'''






													__UpperCamelCase       =			self.prepare_config_and_inputs()
													(
													    (
													    __UpperCamelCase							
													)  ,							(
													    __UpperCamelCase							
													)  ,							(
													    __UpperCamelCase							
													)  ,							(
													    __UpperCamelCase							
													)  ,							(
													    __UpperCamelCase							
													)  ,							(
													    __UpperCamelCase							
													)  ,														
													)       =			config_and_inputs
													__UpperCamelCase       =			{'''input_ids''': input_ids, '''attention_mask''': input_mask}
													return config, inputs_dict






@require_torch
class        SCREAMING_SNAKE_CASE__    (							SCREAMING_SNAKE_CASE_   ,		SCREAMING_SNAKE_CASE_   ,		unittest.TestCase    ):

							"""simple docstring"""






							_snake_case     		=  False

							_snake_case     		=  (
							    (
							        EsmForMaskedLM,
							        EsmModel,
							        EsmForSequenceClassification,
							        EsmForTokenClassification,
							    )
							    if is_torch_available()
							    else ()
							)
							_snake_case     		=  ()
							_snake_case     		=  (
							    {
							        'feature-extraction': EsmModel,
							        'fill-mask': EsmForMaskedLM,
							        'text-classification': EsmForSequenceClassification,
							        'token-classification': EsmForTokenClassification,
							        'zero-shot': EsmForSequenceClassification,
							    }
							    if is_torch_available()
							    else {}
							)
							_snake_case     		=  True



							def     A__		(  self			)->   List[str]:





													'''simple docstring'''






													__UpperCamelCase       =			EsmModelTester(self			)
													__UpperCamelCase       =			ConfigTester(self     ,	config_class=SCREAMING_SNAKE_CASE_     ,	hidden_size=37			)



							def     A__		(  self			)->   Tuple:





													'''simple docstring'''






													self.config_tester.run_common_tests()



							def     A__		(  self			)->   Union[str, Any]:





													'''simple docstring'''






													__UpperCamelCase       =			self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_			)



							def     A__		(  self			)->   List[str]:





													'''simple docstring'''






													__UpperCamelCase       =			self.model_tester.prepare_config_and_inputs()
													for type in ["absolute", "relative_key", "relative_key_query"]:
																			__UpperCamelCase       =			type
																			self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_			)



							def     A__		(  self			)->   str:





													'''simple docstring'''






													__UpperCamelCase       =			self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE_			)



							def     A__		(  self			)->   Optional[int]:





													'''simple docstring'''






													__UpperCamelCase       =			self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE_			)



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





													'''simple docstring'''






													for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			__UpperCamelCase       =			EsmModel.from_pretrained(SCREAMING_SNAKE_CASE_			)
																			self.assertIsNotNone(SCREAMING_SNAKE_CASE_			)



							def     A__		(  self			)->   Union[str, Any]:





													'''simple docstring'''






													__UpperCamelCase       =			self.model_tester.prepare_config_and_inputs()[0]
													__UpperCamelCase       =			EsmEmbeddings(config=SCREAMING_SNAKE_CASE_			)

													__UpperCamelCase       =			torch.as_tensor([[12, 31, 13, model.padding_idx]]			)
													__UpperCamelCase       =			torch.as_tensor(
													    [
													        [
													            0 + model.padding_idx + 1,
													            1 + model.padding_idx + 1,
													            2 + model.padding_idx + 1,
													            model.padding_idx,
													        ]
													    ]			)
													__UpperCamelCase       =			create_position_ids_from_input_ids(SCREAMING_SNAKE_CASE_     ,	model.padding_idx			)
													self.assertEqual(position_ids.shape     ,	expected_positions.shape			)
													self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)			)			)



							def     A__		(  self			)->   str:





													'''simple docstring'''






													__UpperCamelCase       =			self.model_tester.prepare_config_and_inputs()[0]
													__UpperCamelCase       =			EsmEmbeddings(config=SCREAMING_SNAKE_CASE_			)

													__UpperCamelCase       =			torch.empty(2     ,	4     ,	30			)
													__UpperCamelCase       =			[
													    0 + embeddings.padding_idx + 1,
													    1 + embeddings.padding_idx + 1,
													    2 + embeddings.padding_idx + 1,
													    3 + embeddings.padding_idx + 1,
													]
													__UpperCamelCase       =			torch.as_tensor([expected_single_positions, expected_single_positions]			)
													__UpperCamelCase       =			embeddings.create_position_ids_from_inputs_embeds(SCREAMING_SNAKE_CASE_			)
													self.assertEqual(position_ids.shape     ,	expected_positions.shape			)
													self.assertTrue(torch.all(torch.eq(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)			)			)



							@unittest.skip('''Esm does not support embedding resizing'''			)
							def     A__		(  self			)->   int:





													'''simple docstring'''






													pass



							@unittest.skip('''Esm does not support embedding resizing'''			)
							def     A__		(  self			)->   Dict:





													'''simple docstring'''






													pass



							@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''			)
							def     A__		(  self			)->   Optional[int]:





													'''simple docstring'''






													pass






@require_torch
class        SCREAMING_SNAKE_CASE__    (							SCREAMING_SNAKE_CASE_    ):

							"""simple docstring"""






							@slow
							def     A__		(  self			)->   Optional[Any]:





													'''simple docstring'''






													with torch.no_grad():
																			__UpperCamelCase       =			EsmForMaskedLM.from_pretrained('''facebook/esm2_t6_8M_UR50D'''			)
																			model.eval()
																			__UpperCamelCase       =			torch.tensor([[0, 1, 2, 3, 4, 5]]			)
																			__UpperCamelCase       =			model(SCREAMING_SNAKE_CASE_			)[0]

																			__UpperCamelCase       =			33

																			__UpperCamelCase       =			torch.Size((1, 6, vocab_size)			)
																			self.assertEqual(output.shape     ,	SCREAMING_SNAKE_CASE_			)

																			__UpperCamelCase       =			torch.tensor(
																			    [[[8.9_2_1_5, -10.5898, -6.4_6_7_1], [-6.3_9_6_7, -13.9114, -1.1_2_1_2], [-7.7_8_1_2, -13.9516, -3.7_4_0_6]]]			)
																			self.assertTrue(torch.allclose(output[:, :3, :3]     ,	SCREAMING_SNAKE_CASE_     ,	atol=1E-4			)			)



							@slow
							def     A__		(  self			)->   Union[str, Any]:





													'''simple docstring'''






													with torch.no_grad():
																			__UpperCamelCase       =			EsmModel.from_pretrained('''facebook/esm2_t6_8M_UR50D'''			)
																			model.eval()

																			__UpperCamelCase       =			torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]			)
																			__UpperCamelCase       =			model(SCREAMING_SNAKE_CASE_			)[0]
																			# compare the actual values for a slice.
																			__UpperCamelCase       =			torch.tensor(
																			    [[[0.1_4_4_4, 0.5_4_1_3, 0.3_2_4_8], [0.3_0_3_4, 0.0_0_5_3, 0.3_1_0_8], [0.3_2_2_8, -0.2_4_9_9, 0.3_4_1_5]]]			)
																			self.assertTrue(torch.allclose(output[:, :3, :3]     ,	SCREAMING_SNAKE_CASE_     ,	atol=1E-4			)			)






from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


lowercase__							:							Tuple									=			logging.get_logger(__name__)

lowercase__							:							int									=			{
    "microsoft/table-transformer-detection": (
        "https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json"
    ),
}






class        SCREAMING_SNAKE_CASE__    (							SCREAMING_SNAKE_CASE_    ):

							"""simple docstring"""






							_snake_case     		=  'table-transformer'
							_snake_case     		=  ['past_key_values']
							_snake_case     		=  {
							    'hidden_size': 'd_model',
							    'num_attention_heads': 'encoder_attention_heads',
							}



							def __init__(  self     ,	SCREAMING_SNAKE_CASE_=True     ,	SCREAMING_SNAKE_CASE_=None     ,	SCREAMING_SNAKE_CASE_=3     ,	SCREAMING_SNAKE_CASE_=100     ,	SCREAMING_SNAKE_CASE_=6     ,	SCREAMING_SNAKE_CASE_=2048     ,	SCREAMING_SNAKE_CASE_=8     ,	SCREAMING_SNAKE_CASE_=6     ,	SCREAMING_SNAKE_CASE_=2048     ,	SCREAMING_SNAKE_CASE_=8     ,	SCREAMING_SNAKE_CASE_=0.0     ,	SCREAMING_SNAKE_CASE_=0.0     ,	SCREAMING_SNAKE_CASE_=True     ,	SCREAMING_SNAKE_CASE_="relu"     ,	SCREAMING_SNAKE_CASE_=256     ,	SCREAMING_SNAKE_CASE_=0.1     ,	SCREAMING_SNAKE_CASE_=0.0     ,	SCREAMING_SNAKE_CASE_=0.0     ,	SCREAMING_SNAKE_CASE_=0.0_2     ,	SCREAMING_SNAKE_CASE_=1.0     ,	SCREAMING_SNAKE_CASE_=False     ,	SCREAMING_SNAKE_CASE_="sine"     ,	SCREAMING_SNAKE_CASE_="resnet50"     ,	SCREAMING_SNAKE_CASE_=True     ,	SCREAMING_SNAKE_CASE_=False     ,	SCREAMING_SNAKE_CASE_=1     ,	SCREAMING_SNAKE_CASE_=5     ,	SCREAMING_SNAKE_CASE_=2     ,	SCREAMING_SNAKE_CASE_=1     ,	SCREAMING_SNAKE_CASE_=1     ,	SCREAMING_SNAKE_CASE_=5     ,	SCREAMING_SNAKE_CASE_=2     ,	SCREAMING_SNAKE_CASE_=0.1     ,	**SCREAMING_SNAKE_CASE_     ,	)->   Tuple:





													'''simple docstring'''






													if backbone_config is not None and use_timm_backbone:
																			raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.'''			)

													if not use_timm_backbone:
																			if backbone_config is None:
																									logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.'''			)
																									__UpperCamelCase       =			CONFIG_MAPPING['''resnet'''](out_features=['''stage4''']			)
																			elif isinstance(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			):
																									__UpperCamelCase       =			backbone_config.get('''model_type'''			)
																									__UpperCamelCase       =			CONFIG_MAPPING[backbone_model_type]
																									__UpperCamelCase       =			config_class.from_dict(SCREAMING_SNAKE_CASE_			)
																			# set timm attributes to None
																			__UpperCamelCase  ,							__UpperCamelCase  ,							__UpperCamelCase       =			None, None, None

													__UpperCamelCase       =			use_timm_backbone
													__UpperCamelCase       =			backbone_config
													__UpperCamelCase       =			num_channels
													__UpperCamelCase       =			num_queries
													__UpperCamelCase       =			d_model
													__UpperCamelCase       =			encoder_ffn_dim
													__UpperCamelCase       =			encoder_layers
													__UpperCamelCase       =			encoder_attention_heads
													__UpperCamelCase       =			decoder_ffn_dim
													__UpperCamelCase       =			decoder_layers
													__UpperCamelCase       =			decoder_attention_heads
													__UpperCamelCase       =			dropout
													__UpperCamelCase       =			attention_dropout
													__UpperCamelCase       =			activation_dropout
													__UpperCamelCase       =			activation_function
													__UpperCamelCase       =			init_std
													__UpperCamelCase       =			init_xavier_std
													__UpperCamelCase       =			encoder_layerdrop
													__UpperCamelCase       =			decoder_layerdrop
													__UpperCamelCase       =			encoder_layers
													__UpperCamelCase       =			auxiliary_loss
													__UpperCamelCase       =			position_embedding_type
													__UpperCamelCase       =			backbone
													__UpperCamelCase       =			use_pretrained_backbone
													__UpperCamelCase       =			dilation
													# Hungarian matcher
													__UpperCamelCase       =			class_cost
													__UpperCamelCase       =			bbox_cost
													__UpperCamelCase       =			giou_cost
													# Loss coefficients
													__UpperCamelCase       =			mask_loss_coefficient
													__UpperCamelCase       =			dice_loss_coefficient
													__UpperCamelCase       =			bbox_loss_coefficient
													__UpperCamelCase       =			giou_loss_coefficient
													__UpperCamelCase       =			eos_coefficient
													super().__init__(is_encoder_decoder=SCREAMING_SNAKE_CASE_     ,	**SCREAMING_SNAKE_CASE_			)



							@property
							def     A__		(  self			)->   int:





													'''simple docstring'''






													return self.encoder_attention_heads



							@property
							def     A__		(  self			)->   int:





													'''simple docstring'''






													return self.d_model






class        SCREAMING_SNAKE_CASE__    (							SCREAMING_SNAKE_CASE_    ):

							"""simple docstring"""






							_snake_case     		=  version.parse('1.11'    )



							@property
							def     A__		(  self			)->   Mapping[str, Mapping[int, str]]:





													'''simple docstring'''






													return OrderedDict(
													    [
													        ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
													        ('''pixel_mask''', {0: '''batch'''}),
													    ]			)



							@property
							def     A__		(  self			)->   float:





													'''simple docstring'''






													return 1E-5



							@property
							def     A__		(  self			)->   int:





													'''simple docstring'''






													return 12




