





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





   def __init__(			self       ,      snake_case       ,      snake_case=13       ,      snake_case=7       ,      snake_case=False       ,      snake_case=True       ,      snake_case=False       ,      snake_case=True       ,      snake_case=33       ,      snake_case=32       ,      snake_case=5       ,      snake_case=4       ,      snake_case=37       ,      snake_case="gelu"       ,      snake_case=0.1       ,      snake_case=0.1       ,      snake_case=512       ,      snake_case=16       ,      snake_case=2       ,      snake_case=0.02       ,      snake_case=3       ,      snake_case=4       ,      snake_case=None       ,      )					->	Optional[int]:
      """simple docstring"""





      a__						:    int   		=	parent
      a__						:    Any   		=	batch_size
      a__						:    List[Any]   		=	seq_length
      a__						:    Optional[int]   		=	is_training
      a__						:    Dict   		=	use_input_mask
      a__						:    str   		=	use_token_type_ids
      a__						:    Union[str, Any]   		=	use_labels
      a__						:    List[str]   		=	vocab_size
      a__						:    int   		=	hidden_size
      a__						:    Optional[int]   		=	num_hidden_layers
      a__						:    int   		=	num_attention_heads
      a__						:    List[str]   		=	intermediate_size
      a__						:    Any   		=	hidden_act
      a__						:    str   		=	hidden_dropout_prob
      a__						:    List[str]   		=	attention_probs_dropout_prob
      a__						:    Dict   		=	max_position_embeddings
      a__						:    Tuple   		=	type_vocab_size
      a__						:    Union[str, Any]   		=	type_sequence_label_size
      a__						:    Dict   		=	initializer_range
      a__						:    Dict   		=	num_labels
      a__						:    List[str]   		=	num_choices
      a__						:    Optional[int]   		=	scope





   def 						_snake_case			(			self   )					->	Optional[int]:
      """simple docstring"""





      a__						:    str   		=	ids_tensor([self.batch_size, self.seq_length]       ,      self.vocab_size   )

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

      a__						:    str   		=	None
      a__						:    int   		=	None
      a__						:    Union[str, Any]   		=	None
      if self.use_labels:
         a__						:    Optional[Any]   		=	ids_tensor([self.batch_size]       ,      self.type_sequence_label_size   )
         a__						:    Dict   		=	ids_tensor([self.batch_size, self.seq_length]       ,      self.num_labels   )
         a__						:    str   		=	ids_tensor([self.batch_size]       ,      self.num_choices   )

      a__						:    int   		=	self.get_config()

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





   def 						_snake_case			(			self   )					->	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 						_snake_case			(			self       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case   )					->	str:
      """simple docstring"""





      a__						:    Tuple   		=	EsmModel(config=snake_case   )
      model.to(snake_case   )
      model.eval()
      a__						:    Optional[Any]   		=	model(snake_case       ,      attention_mask=snake_case   )
      a__						:    Union[str, Any]   		=	model(snake_case   )
      a__						:    Optional[Any]   		=	model(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 						_snake_case			(			self       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case   )					->	Optional[Any]:
      """simple docstring"""





      a__						:    str   		=	EsmForMaskedLM(config=snake_case   )
      model.to(snake_case   )
      model.eval()
      a__						:    int   		=	model(snake_case       ,      attention_mask=snake_case       ,      labels=snake_case   )
      self.parent.assertEqual(result.logits.shape       ,      (self.batch_size, self.seq_length, self.vocab_size)   )





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case       ,      snake_case   )					->	str:
      """simple docstring"""





      a__						:    Any   		=	self.num_labels
      a__						:    Any   		=	EsmForTokenClassification(config=snake_case   )
      model.to(snake_case   )
      model.eval()
      a__						:    Any   		=	model(snake_case       ,      attention_mask=snake_case       ,      labels=snake_case   )
      self.parent.assertEqual(result.logits.shape       ,      (self.batch_size, self.seq_length, self.num_labels)   )





   def 						_snake_case			(			self   )					->	Dict:
      """simple docstring"""





      a__						:    Union[str, Any]   		=	self.prepare_config_and_inputs()
      (
          (
          a__
      )		,  (
          a__
      )		,  (
          a__
      )		,  (
          a__
      )		,  (
          a__
      )		,  (
          a__
      )		,  
      )						:    Any   		=	config_and_inputs
      a__						:    Tuple   		=	{"input_ids": input_ids, "attention_mask": input_mask}
      return config, inputs_dict







@require_torch
class 	__lowerCAmelCase      (       _UpperCamelCase		,_UpperCamelCase		,unittest.TestCase	):
   _UpperCamelCase			:    Optional[int]  		=					False

   _UpperCamelCase			:    Optional[int]  		=					(
       (
           EsmForMaskedLM,
           EsmModel,
           EsmForSequenceClassification,
           EsmForTokenClassification,
       )
       if is_torch_available()
       else ()
   )
   _UpperCamelCase			:    int  		=					()
   _UpperCamelCase			:    Union[str, Any]  		=					(
       {
           """feature-extraction""": EsmModel,
           """fill-mask""": EsmForMaskedLM,
           """text-classification""": EsmForSequenceClassification,
           """token-classification""": EsmForTokenClassification,
           """zero-shot""": EsmForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   _UpperCamelCase			:    Optional[Any]  		=					True





   def 						_snake_case			(			self   )					->	int:
      """simple docstring"""





      a__						:    Any   		=	EsmModelTester(self   )
      a__						:    Any   		=	ConfigTester(self       ,      config_class=snake_case       ,      hidden_size=37   )





   def 						_snake_case			(			self   )					->	List[Any]:
      """simple docstring"""





      self.config_tester.run_common_tests()





   def 						_snake_case			(			self   )					->	Any:
      """simple docstring"""





      a__						:    Optional[int]   		=	self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*snake_case   )





   def 						_snake_case			(			self   )					->	Dict:
      """simple docstring"""





      a__						:    Tuple   		=	self.model_tester.prepare_config_and_inputs()
      for type in ["absolute", "relative_key", "relative_key_query"]:
         a__						:    Optional[Any]   		=	type
         self.model_tester.create_and_check_model(*snake_case   )





   def 						_snake_case			(			self   )					->	Union[str, Any]:
      """simple docstring"""





      a__						:    int   		=	self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_masked_lm(*snake_case   )





   def 						_snake_case			(			self   )					->	List[str]:
      """simple docstring"""





      a__						:    Optional[int]   		=	self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_token_classification(*snake_case   )





   @slow
   def 						_snake_case			(			self   )					->	List[Any]:
      """simple docstring"""





      for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         a__						:    str   		=	EsmModel.from_pretrained(snake_case   )
         self.assertIsNotNone(snake_case   )





   def 						_snake_case			(			self   )					->	Optional[int]:
      """simple docstring"""





      a__						:    Optional[int]   		=	self.model_tester.prepare_config_and_inputs()[0]
      a__						:    str   		=	EsmEmbeddings(config=snake_case   )

      a__						:    Dict   		=	torch.as_tensor([[12, 31, 13, model.padding_idx]]   )
      a__						:    List[Any]   		=	torch.as_tensor(
          [
              [
                  0 + model.padding_idx + 1,
                  1 + model.padding_idx + 1,
                  2 + model.padding_idx + 1,
                  model.padding_idx,
              ]
          ]   )
      a__						:    int   		=	create_position_ids_from_input_ids(snake_case       ,      model.padding_idx   )
      self.assertEqual(position_ids.shape       ,      expected_positions.shape   )
      self.assertTrue(torch.all(torch.eq(snake_case       ,      snake_case   )   )   )





   def 						_snake_case			(			self   )					->	Union[str, Any]:
      """simple docstring"""





      a__						:    List[Any]   		=	self.model_tester.prepare_config_and_inputs()[0]
      a__						:    Union[str, Any]   		=	EsmEmbeddings(config=snake_case   )

      a__						:    Any   		=	torch.empty(2       ,      4       ,      30   )
      a__						:    Dict   		=	[
          0 + embeddings.padding_idx + 1,
          1 + embeddings.padding_idx + 1,
          2 + embeddings.padding_idx + 1,
          3 + embeddings.padding_idx + 1,
      ]
      a__						:    int   		=	torch.as_tensor([expected_single_positions, expected_single_positions]   )
      a__						:    Any   		=	embeddings.create_position_ids_from_inputs_embeds(snake_case   )
      self.assertEqual(position_ids.shape       ,      expected_positions.shape   )
      self.assertTrue(torch.all(torch.eq(snake_case       ,      snake_case   )   )   )





   @unittest.skip("Esm does not support embedding resizing"   )
   def 						_snake_case			(			self   )					->	str:
      """simple docstring"""





      pass





   @unittest.skip("Esm does not support embedding resizing"   )
   def 						_snake_case			(			self   )					->	List[Any]:
      """simple docstring"""





      pass





   @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."   )
   def 						_snake_case			(			self   )					->	Any:
      """simple docstring"""





      pass







@require_torch
class 	__lowerCAmelCase      (       _UpperCamelCase	):





   @slow
   def 						_snake_case			(			self   )					->	Union[str, Any]:
      """simple docstring"""





      with torch.no_grad():
         a__						:    List[Any]   		=	EsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D"   )
         model.eval()
         a__						:    Optional[int]   		=	torch.tensor([[0, 1, 2, 3, 4, 5]]   )
         a__						:    int   		=	model(snake_case   )[0]

         a__						:    List[Any]   		=	33

         a__						:    int   		=	torch.Size((1, 6, vocab_size)   )
         self.assertEqual(output.shape       ,      snake_case   )

         a__						:    Tuple   		=	torch.tensor(
             [[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]]   )
         self.assertTrue(torch.allclose(output[:, :3, :3]       ,      snake_case       ,      atol=1E-4   )   )





   @slow
   def 						_snake_case			(			self   )					->	Optional[Any]:
      """simple docstring"""





      with torch.no_grad():
         a__						:    str   		=	EsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D"   )
         model.eval()

         a__						:    Tuple   		=	torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]   )
         a__						:    Dict   		=	model(snake_case   )[0]
         # compare the actual values for a slice.
         a__						:    Tuple   		=	torch.tensor(
             [[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]]   )
         self.assertTrue(torch.allclose(output[:, :3, :3]       ,      snake_case       ,      atol=1E-4   )   )








from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


SCREAMING_SNAKE_CASE__							:      Union[str, Any]         =    {
    """configuration_autoformer""": [
        """AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """AutoformerConfig""",
    ],
}

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  SCREAMING_SNAKE_CASE__							:      Tuple         =    [
      """AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """AutoformerForPrediction""",
      """AutoformerModel""",
      """AutoformerPreTrainedModel""",
  ]


if TYPE_CHECKING:
  from .configuration_autoformer import (
      AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
      AutoformerConfig,
  )

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_autoformer import (
        AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
        AutoformerForPrediction,
        AutoformerModel,
        AutoformerPreTrainedModel,
    )

else:
  import sys

  SCREAMING_SNAKE_CASE__							:      Any         =    _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

