



'''simple docstring'''






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







    def __init__(				self			:  Any						,      __snake_case			:  Any						,      __snake_case			:  Union[str, Any]=13						,      __snake_case			:  Tuple=7						,      __snake_case			:  List[str]=False						,      __snake_case			:  Optional[int]=True						,      __snake_case			:  Optional[int]=False						,      __snake_case			:  Any=True						,      __snake_case			:  Any=33						,      __snake_case			:  List[str]=32						,      __snake_case			:  Dict=5						,      __snake_case			:  Any=4						,      __snake_case			:  Union[str, Any]=37						,      __snake_case			:  str="gelu"						,      __snake_case			:  str=0.1						,      __snake_case			:  Union[str, Any]=0.1						,      __snake_case			:  Optional[Any]=5_12						,      __snake_case			:  Optional[int]=16						,      __snake_case			:  Optional[int]=2						,      __snake_case			:  Tuple=0.02						,      __snake_case			:  Any=3						,      __snake_case			:  Dict=4						,      __snake_case			:  int=None						,      ):
      a						: Optional[Any]					       =					parent
      a						: str					       =					batch_size
      a						: str					       =					seq_length
      a						: List[str]					       =					is_training
      a						: List[str]					       =					use_input_mask
      a						: Tuple					       =					use_token_type_ids
      a						: str					       =					use_labels
      a						: List[Any]					       =					vocab_size
      a						: Any					       =					hidden_size
      a						: List[str]					       =					num_hidden_layers
      a						: Optional[int]					       =					num_attention_heads
      a						: Union[str, Any]					       =					intermediate_size
      a						: Optional[int]					       =					hidden_act
      a						: List[Any]					       =					hidden_dropout_prob
      a						: str					       =					attention_probs_dropout_prob
      a						: Tuple					       =					max_position_embeddings
      a						: Union[str, Any]					       =					type_vocab_size
      a						: List[str]					       =					type_sequence_label_size
      a						: List[Any]					       =					initializer_range
      a						: str					       =					num_labels
      a						: Dict					       =					num_choices
      a						: str					       =					scope







    def       lowercase_	(				self			:  Union[str, Any]     ):
      a						: Dict					       =					ids_tensor([self.batch_size, self.seq_length]						,      self.vocab_size     )

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

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

      a						: List[str]					       =					self.get_config()

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







    def       lowercase_	(				self			:  Dict     ):
      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       lowercase_	(				self			:  str						,      __snake_case			:  List[Any]						,      __snake_case			:  Dict						,      __snake_case			:  int						,      __snake_case			:  Optional[int]						,      __snake_case			:  List[Any]						,      __snake_case			:  Union[str, Any]     ):
      a						: Optional[Any]					       =					EsmModel(config=UpperCamelCase__     )
      model.to(UpperCamelCase__     )
      model.eval()
      a						: Optional[int]					       =					model(UpperCamelCase__						,      attention_mask=UpperCamelCase__     )
      a						: List[str]					       =					model(UpperCamelCase__     )
      a						: Dict					       =					model(UpperCamelCase__     )

      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       lowercase_	(				self			:  int						,      __snake_case			:  Dict						,      __snake_case			:  List[str]						,      __snake_case			:  Optional[Any]						,      __snake_case			:  int						,      __snake_case			:  Any						,      __snake_case			:  Union[str, Any]     ):
      a						: Tuple					       =					EsmForMaskedLM(config=UpperCamelCase__     )
      model.to(UpperCamelCase__     )
      model.eval()
      a						: Optional[int]					       =					model(UpperCamelCase__						,      attention_mask=UpperCamelCase__						,      labels=UpperCamelCase__     )
      self.parent.assertEqual(result.logits.shape						,      (self.batch_size, self.seq_length, self.vocab_size)     )







    def       lowercase_	(				self			:  str						,      __snake_case			:  Optional[Any]						,      __snake_case			:  List[str]						,      __snake_case			:  int						,      __snake_case			:  Any						,      __snake_case			:  List[Any]						,      __snake_case			:  List[Any]     ):
      a						: Optional[int]					       =					self.num_labels
      a						: Tuple					       =					EsmForTokenClassification(config=UpperCamelCase__     )
      model.to(UpperCamelCase__     )
      model.eval()
      a						: int					       =					model(UpperCamelCase__						,      attention_mask=UpperCamelCase__						,      labels=UpperCamelCase__     )
      self.parent.assertEqual(result.logits.shape						,      (self.batch_size, self.seq_length, self.num_labels)     )







    def       lowercase_	(				self			:  List[str]     ):
      a						: Tuple					       =					self.prepare_config_and_inputs()
      (
          a			
      )						: int					       =					config_and_inputs
      a						: Dict					       =					{"input_ids": input_ids, "attention_mask": input_mask}
      return config, inputs_dict

@require_torch
class 							a__( __snake_case		,			__snake_case		,			unittest.TestCase     ):
    lowercase__			=   False

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







    def       lowercase_	(				self			:  List[str]     ):
      a						: str					       =					EsmModelTester(self     )
      a						: str					       =					ConfigTester(self						,      config_class=UpperCamelCase__						,      hidden_size=37     )







    def       lowercase_	(				self			:  Tuple     ):
      self.config_tester.run_common_tests()







    def       lowercase_	(				self			:  int     ):
      a						: List[Any]					       =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*UpperCamelCase__     )







    def       lowercase_	(				self			:  Optional[int]     ):
      a						: Any					       =					self.model_tester.prepare_config_and_inputs()
      for type in ["absolute", "relative_key", "relative_key_query"]:
        a						: Dict					       =					type
        self.model_tester.create_and_check_model(*UpperCamelCase__     )







    def       lowercase_	(				self			:  str     ):
      a						: Any					       =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__     )







    def       lowercase_	(				self			:  List[Any]     ):
      a						: Tuple					       =					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__     )







    @slow
    def       lowercase_	(				self			:  Optional[int]     ):


      for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a						: List[str]					       =					EsmModel.from_pretrained(UpperCamelCase__     )
        self.assertIsNotNone(UpperCamelCase__     )







    def       lowercase_	(				self			:  Any     ):
      a						: Optional[Any]					       =					self.model_tester.prepare_config_and_inputs()[0]
      a						: str					       =					EsmEmbeddings(config=UpperCamelCase__     )

      a						: Union[str, Any]					       =					torch.as_tensor([[12, 31, 13, model.padding_idx]]     )
      a						: int					       =					torch.as_tensor(
          [
              [
                  0 + model.padding_idx + 1,
                  1 + model.padding_idx + 1,
                  2 + model.padding_idx + 1,
                  model.padding_idx,
              ]
          ]     )
      a						: Tuple					       =					create_position_ids_from_input_ids(UpperCamelCase__						,      model.padding_idx     )
      self.assertEqual(position_ids.shape						,      expected_positions.shape     )
      self.assertTrue(torch.all(torch.eq(UpperCamelCase__						,      UpperCamelCase__     )     )     )







    def       lowercase_	(				self			:  str     ):
      a						: List[str]					       =					self.model_tester.prepare_config_and_inputs()[0]
      a						: str					       =					EsmEmbeddings(config=UpperCamelCase__     )

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







    @unittest.skip('Esm does not support embedding resizing'     )
    def       lowercase_	(				self			:  str     ):
      pass







    @unittest.skip('Esm does not support embedding resizing'     )
    def       lowercase_	(				self			:  Optional[int]     ):
      pass







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

@require_torch
class 							a__( __snake_case     ):







    @slow
    def       lowercase_	(				self			:  str     ):


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

        a						: str					       =					33

        a						: Any					       =					torch.Size((1, 6, vocab_size)     )
        self.assertEqual(output.shape						,      UpperCamelCase__     )

        a						: Optional[int]					       =					torch.tensor(
            [[[8.9215, -10.5898, -6.4671], [-6.3967, -13.9114, -1.1212], [-7.7812, -13.9516, -3.7406]]]     )
        self.assertTrue(torch.allclose(output[:, :3, :3]						,      UpperCamelCase__						,      atol=1e-4     )     )







    @slow
    def       lowercase_	(				self			:  Any     ):


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

        a						: List[str]					       =					torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]     )
        a						: List[Any]					       =					model(UpperCamelCase__     )[0]
        # compare the actual values for a slice.
        a						: Dict					       =					torch.tensor(
            [[[0.1444, 0.5413, 0.3248], [0.3034, 0.0053, 0.3108], [0.3228, -0.2499, 0.3415]]]     )
        self.assertTrue(torch.allclose(output[:, :3, :3]						,      UpperCamelCase__						,      atol=1e-4     )     )




'''simple docstring'''






from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


lowerCAmelCase: Any							=						{
    'configuration_poolformer': [
        'POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'PoolFormerConfig',
        'PoolFormerOnnxConfig',
    ]
}

try:
     if not is_vision_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     lowerCAmelCase: List[str]							=						['PoolFormerFeatureExtractor']
     lowerCAmelCase: Tuple							=						['PoolFormerImageProcessor']

try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     lowerCAmelCase: str							=						[
         'POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
         'PoolFormerForImageClassification',
         'PoolFormerModel',
         'PoolFormerPreTrainedModel',
     ]


if TYPE_CHECKING:
     from .configuration_poolformer import (
         POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
         PoolFormerConfig,
         PoolFormerOnnxConfig,
     )

     try:
          if not is_vision_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .feature_extraction_poolformer import PoolFormerFeatureExtractor
          from .image_processing_poolformer import PoolFormerImageProcessor

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_poolformer import (
              POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
              PoolFormerForImageClassification,
              PoolFormerModel,
              PoolFormerPreTrainedModel,
          )


else:
     import sys

     lowerCAmelCase: Dict							=						_LazyModule(__name__, globals()['__file__'], _import_structure)