
"""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   _UpperCAmelCase				:




      def __init__(				self ,							lowercase_ ,							lowercase_=1_3 ,							lowercase_=7 ,							lowercase_=False ,							lowercase_=True ,							lowercase_=False ,							lowercase_=True ,							lowercase_=3_3 ,							lowercase_=3_2 ,							lowercase_=5 ,							lowercase_=4 ,							lowercase_=3_7 ,							lowercase_="gelu" ,							lowercase_=0.1 ,							lowercase_=0.1 ,							lowercase_=5_1_2 ,							lowercase_=1_6 ,							lowercase_=2 ,							lowercase_=0.0_2 ,							lowercase_=3 ,							lowercase_=4 ,							lowercase_=None ,							)    ->       Union[str, Any]:
          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				)    ->       List[str]:
          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				)    ->       Optional[int]:
          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 ,							lowercase_ ,							lowercase_ ,							lowercase_ ,							lowercase_ ,							lowercase_ ,							lowercase_				)    ->       List[str]:
          UpperCAmelCase          =       EsmModel(config=lowercase_				)
          model.to(lowercase_				)
          model.eval()
          UpperCAmelCase          =       model(lowercase_ ,							attention_mask=lowercase_				)
          UpperCAmelCase          =       model(lowercase_				)
          UpperCAmelCase          =       model(lowercase_				)

          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 ,							lowercase_ ,							lowercase_ ,							lowercase_ ,							lowercase_ ,							lowercase_ ,							lowercase_				)    ->       str:
          UpperCAmelCase          =       EsmForMaskedLM(config=lowercase_				)
          model.to(lowercase_				)
          model.eval()
          UpperCAmelCase          =       model(lowercase_ ,							attention_mask=lowercase_ ,							labels=lowercase_				)
          self.parent.assertEqual(result.logits.shape ,							(self.batch_size, self.seq_length, self.vocab_size)				)




      def      a_   (				self ,							lowercase_ ,							lowercase_ ,							lowercase_ ,							lowercase_ ,							lowercase_ ,							lowercase_				)    ->       str:
          UpperCAmelCase          =       self.num_labels
          UpperCAmelCase          =       EsmForTokenClassification(config=lowercase_				)
          model.to(lowercase_				)
          model.eval()
          UpperCAmelCase          =       model(lowercase_ ,							attention_mask=lowercase_ ,							labels=lowercase_				)
          self.parent.assertEqual(result.logits.shape ,							(self.batch_size, self.seq_length, self.num_labels)				)




      def      a_   (				self				)    ->       str:
          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   _UpperCAmelCase				(		SCREAMING_SNAKE_CASE_  ,      SCREAMING_SNAKE_CASE_  ,      unittest.TestCase				):
      __SCREAMING_SNAKE_CASE :				Dict				   =						False

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




      def      a_   (				self				)    ->       Union[str, Any]:
          UpperCAmelCase          =       EsmModelTester(self				)
          UpperCAmelCase          =       ConfigTester(self ,							config_class=lowercase_ ,							hidden_size=3_7				)




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




      def      a_   (				self				)    ->       Tuple:
          UpperCAmelCase          =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*lowercase_				)




      def      a_   (				self				)    ->       Union[str, Any]:
          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(*lowercase_				)




      def      a_   (				self				)    ->       Tuple:
          UpperCAmelCase          =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_masked_lm(*lowercase_				)




      def      a_   (				self				)    ->       Union[str, Any]:
          UpperCAmelCase          =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_token_classification(*lowercase_				)




      @slow
      def      a_   (				self				)    ->       int:
          for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              UpperCAmelCase          =       EsmModel.from_pretrained(lowercase_				)
              self.assertIsNotNone(lowercase_				)




      def      a_   (				self				)    ->       Any:
          UpperCAmelCase          =       self.model_tester.prepare_config_and_inputs()[0]
          UpperCAmelCase          =       EsmEmbeddings(config=lowercase_				)

          UpperCAmelCase          =       torch.as_tensor([[1_2, 3_1, 1_3, 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(lowercase_ ,							model.padding_idx				)
          self.assertEqual(position_ids.shape ,							expected_positions.shape				)
          self.assertTrue(torch.all(torch.eq(lowercase_ ,							lowercase_				)				)				)




      def      a_   (				self				)    ->       Optional[Any]:
          UpperCAmelCase          =       self.model_tester.prepare_config_and_inputs()[0]
          UpperCAmelCase          =       EsmEmbeddings(config=lowercase_				)

          UpperCAmelCase          =       torch.empty(2 ,							4 ,							3_0				)
          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(lowercase_				)
          self.assertEqual(position_ids.shape ,							expected_positions.shape				)
          self.assertTrue(torch.all(torch.eq(lowercase_ ,							lowercase_				)				)				)




      @unittest.skip('Esm does not support embedding resizing'				)
      def      a_   (				self				)    ->       List[str]:
          pass




      @unittest.skip('Esm does not support embedding resizing'				)
      def      a_   (				self				)    ->       Union[str, Any]:
          pass




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

@require_torch
class   _UpperCAmelCase				(		SCREAMING_SNAKE_CASE_				):




      @slow
      def      a_   (				self				)    ->       List[str]:
          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(lowercase_				)[0]

              UpperCAmelCase          =       3_3

              UpperCAmelCase          =       torch.Size((1, 6, vocab_size)				)
              self.assertEqual(output.shape ,							lowercase_				)

              UpperCAmelCase          =       torch.tensor(
                  [[[8.9_2_1_5, -1_0.5_8_9_8, -6.4_6_7_1], [-6.3_9_6_7, -1_3.9_1_1_4, -1.1_2_1_2], [-7.7_8_1_2, -1_3.9_5_1_6, -3.7_4_0_6]]]				)
              self.assertTrue(torch.allclose(output[:, :3, :3] ,							lowercase_ ,							atol=1E-4				)				)




      @slow
      def      a_   (				self				)    ->       Optional[int]:
          with torch.no_grad():
              UpperCAmelCase          =       EsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D'				)
              model.eval()

              UpperCAmelCase          =       torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]]				)
              UpperCAmelCase          =       model(lowercase_				)[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] ,							lowercase_ ,							atol=1E-4				)				)





"""simple docstring"""

from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_torch_available,
    is_vision_available,
)


SCREAMING_SNAKE_CASE_            =    {'''configuration_beit''': ['''BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BeitConfig''', '''BeitOnnxConfig''']}

try:
   if not is_vision_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   SCREAMING_SNAKE_CASE_            =    ['''BeitFeatureExtractor''']
   SCREAMING_SNAKE_CASE_            =    ['''BeitImageProcessor''']

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   SCREAMING_SNAKE_CASE_            =    [
       '''BEIT_PRETRAINED_MODEL_ARCHIVE_LIST''',
       '''BeitForImageClassification''',
       '''BeitForMaskedImageModeling''',
       '''BeitForSemanticSegmentation''',
       '''BeitModel''',
       '''BeitPreTrainedModel''',
   ]


try:
   if not is_flax_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   SCREAMING_SNAKE_CASE_            =    [
       '''FlaxBeitForImageClassification''',
       '''FlaxBeitForMaskedImageModeling''',
       '''FlaxBeitModel''',
       '''FlaxBeitPreTrainedModel''',
   ]

if TYPE_CHECKING:
   from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig

   try:
      if not is_vision_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .feature_extraction_beit import BeitFeatureExtractor
      from .image_processing_beit import BeitImageProcessor

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_beit import (
          BEIT_PRETRAINED_MODEL_ARCHIVE_LIST,
          BeitForImageClassification,
          BeitForMaskedImageModeling,
          BeitForSemanticSegmentation,
          BeitModel,
          BeitPreTrainedModel,
      )

   try:
      if not is_flax_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_flax_beit import (
          FlaxBeitForImageClassification,
          FlaxBeitForMaskedImageModeling,
          FlaxBeitModel,
          FlaxBeitPreTrainedModel,
      )


else:
   import sys

   SCREAMING_SNAKE_CASE_            =    _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)



