


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    ,			lowerCAmelCase__    ,			lowerCAmelCase__=13    ,			lowerCAmelCase__=7    ,			lowerCAmelCase__=False    ,			lowerCAmelCase__=True    ,			lowerCAmelCase__=False    ,			lowerCAmelCase__=True    ,			lowerCAmelCase__=33    ,			lowerCAmelCase__=32    ,			lowerCAmelCase__=5    ,			lowerCAmelCase__=4    ,			lowerCAmelCase__=37    ,			lowerCAmelCase__="gelu"    ,			lowerCAmelCase__=0.1    ,			lowerCAmelCase__=0.1    ,			lowerCAmelCase__=512    ,			lowerCAmelCase__=16    ,			lowerCAmelCase__=2    ,			lowerCAmelCase__=0.0_2    ,			lowerCAmelCase__=3    ,			lowerCAmelCase__=4    ,			lowerCAmelCase__=None    ,			) ->    List[Any]:




        '''simple docstring'''
        lowercase__:       str        =       parent
        lowercase__:       List[str]        =       batch_size
        lowercase__:       Dict        =       seq_length
        lowercase__:       int        =       is_training
        lowercase__:       str        =       use_input_mask
        lowercase__:       Optional[int]        =       use_token_type_ids
        lowercase__:       Any        =       use_labels
        lowercase__:       List[str]        =       vocab_size
        lowercase__:       Union[str, Any]        =       hidden_size
        lowercase__:       Optional[int]        =       num_hidden_layers
        lowercase__:       Optional[int]        =       num_attention_heads
        lowercase__:       Dict        =       intermediate_size
        lowercase__:       Union[str, Any]        =       hidden_act
        lowercase__:       List[str]        =       hidden_dropout_prob
        lowercase__:       int        =       attention_probs_dropout_prob
        lowercase__:       str        =       max_position_embeddings
        lowercase__:       List[Any]        =       type_vocab_size
        lowercase__:       Optional[Any]        =       type_sequence_label_size
        lowercase__:       Tuple        =       initializer_range
        lowercase__:       str        =       num_labels
        lowercase__:       Optional[int]        =       num_choices
        lowercase__:       Dict        =       scope
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    int:




        '''simple docstring'''
        lowercase__:       str        =       ids_tensor([self.batch_size, self.seq_length]    ,			self.vocab_size			)

        lowercase__:       List[str]        =       None
        if self.use_input_mask:
               lowercase__:       int        =       random_attention_mask([self.batch_size, self.seq_length]			)

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

        lowercase__:       Union[str, Any]        =       self.get_config()

        return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    List[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 		SCREAMING_SNAKE_CASE__       (       self    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__			) ->    Dict:




        '''simple docstring'''
        lowercase__:       Any        =       EsmModel(config=snake_case__			)
        model.to(snake_case__			)
        model.eval()
        lowercase__:       str        =       model(snake_case__    ,			attention_mask=snake_case__			)
        lowercase__:       Union[str, Any]        =       model(snake_case__			)
        lowercase__:       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 		SCREAMING_SNAKE_CASE__       (       self    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__			) ->    List[Any]:




        '''simple docstring'''
        lowercase__:       int        =       EsmForMaskedLM(config=snake_case__			)
        model.to(snake_case__			)
        model.eval()
        lowercase__:       Dict        =       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 		SCREAMING_SNAKE_CASE__       (       self    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__			) ->    Dict:




        '''simple docstring'''
        lowercase__:       int        =       self.num_labels
        lowercase__:       Dict        =       EsmForTokenClassification(config=snake_case__			)
        model.to(snake_case__			)
        model.eval()
        lowercase__:       List[str]        =       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 		SCREAMING_SNAKE_CASE__       (       self			) ->    Dict:




        '''simple docstring'''
        lowercase__:       Optional[int]        =       self.prepare_config_and_inputs()
        (
            lowercase__       
        ):       Dict        =       config_and_inputs
        lowercase__:       Union[str, Any]        =       {'input_ids': input_ids, 'attention_mask': input_mask}
        return config, inputs_dict





@require_torch
class   __a      (   SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_	,	unittest.TestCase				):
 __lowercase			:							List[Any]       					=			False

 __lowercase			:							Optional[Any]       					=			(
     (
         EsmForMaskedLM,
         EsmModel,
         EsmForSequenceClassification,
         EsmForTokenClassification,
     )
     if is_torch_available()
     else ()
 )
 __lowercase			:							str       					=			()
 __lowercase			:							Dict       					=			(
     {
         'feature-extraction': EsmModel,
         'fill-mask': EsmForMaskedLM,
         'text-classification': EsmForSequenceClassification,
         'token-classification': EsmForTokenClassification,
         'zero-shot': EsmForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )
 __lowercase			:							List[str]       					=			True
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    Tuple:




        '''simple docstring'''
        lowercase__:       Optional[int]        =       EsmModelTester(self			)
        lowercase__:       Tuple        =       ConfigTester(self    ,			config_class=snake_case__    ,			hidden_size=37			)
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    str:




        '''simple docstring'''
        self.config_tester.run_common_tests()
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    List[Any]:




        '''simple docstring'''
        lowercase__:       Optional[Any]        =       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*snake_case__			)
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    Optional[int]:




        '''simple docstring'''
        lowercase__:       Optional[Any]        =       self.model_tester.prepare_config_and_inputs()
        for type in ["absolute", "relative_key", "relative_key_query"]:
               lowercase__:       int        =       type
               self.model_tester.create_and_check_model(*snake_case__			)
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    int:




        '''simple docstring'''
        lowercase__:       int        =       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_lm(*snake_case__			)
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    Union[str, Any]:




        '''simple docstring'''
        lowercase__:       Union[str, Any]        =       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_token_classification(*snake_case__			)
 @slow
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    Optional[int]:




        '''simple docstring'''

        for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               lowercase__:       Dict        =       EsmModel.from_pretrained(snake_case__			)
               self.assertIsNotNone(snake_case__			)
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    Union[str, Any]:




        '''simple docstring'''
        lowercase__:       Any        =       self.model_tester.prepare_config_and_inputs()[0]
        lowercase__:       Dict        =       EsmEmbeddings(config=snake_case__			)

        lowercase__:       List[Any]        =       torch.as_tensor([[12, 31, 13, model.padding_idx]]			)
        lowercase__:       List[str]        =       torch.as_tensor(
            [
                [
                    0 + model.padding_idx + 1,
                    1 + model.padding_idx + 1,
                    2 + model.padding_idx + 1,
                    model.padding_idx,
                ]
            ]			)
        lowercase__:       Optional[Any]        =       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 		SCREAMING_SNAKE_CASE__       (       self			) ->    List[Any]:




        '''simple docstring'''
        lowercase__:       Any        =       self.model_tester.prepare_config_and_inputs()[0]
        lowercase__:       Any        =       EsmEmbeddings(config=snake_case__			)

        lowercase__:       Optional[Any]        =       torch.empty(2    ,			4    ,			30			)
        lowercase__:       Dict        =       [
            0 + embeddings.padding_idx + 1,
            1 + embeddings.padding_idx + 1,
            2 + embeddings.padding_idx + 1,
            3 + embeddings.padding_idx + 1,
        ]
        lowercase__:       List[str]        =       torch.as_tensor([expected_single_positions, expected_single_positions]			)
        lowercase__:       Optional[int]        =       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 		SCREAMING_SNAKE_CASE__       (       self			) ->    List[Any]:




        '''simple docstring'''
        pass
 @unittest.skip('Esm does not support embedding resizing'			)
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    int:




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




        '''simple docstring'''
        pass





@require_torch
class   __a      (   SCREAMING_SNAKE_CASE_				):
 @slow
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    List[Any]:




        '''simple docstring'''

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

               lowercase__:       int        =       33

               lowercase__:       Dict        =       torch.Size((1, 6, vocab_size)			)
               self.assertEqual(output.shape    ,			snake_case__			)

               lowercase__:       Optional[int]        =       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]    ,			snake_case__    ,			atol=1E-4			)			)
 @slow
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    List[str]:




        '''simple docstring'''

        with torch.no_grad():
               lowercase__:       List[str]        =       EsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D'			)
               model.eval()

               lowercase__:       Tuple        =       torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]			)
               lowercase__:       Dict        =       model(snake_case__			)[0]
               # compare the actual values for a slice.
               lowercase__:       str        =       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]    ,			snake_case__    ,			atol=1E-4			)			)





from ...configuration_utils import PretrainedConfig
from ...utils import logging


__lowerCAmelCase			=							logging.get_logger(__name__)

__lowerCAmelCase			=							{
    '''google/pegasus-large''': '''https://huggingface.co/google/pegasus-large/resolve/main/config.json''',
    # See all PEGASUS models at https://huggingface.co/models?filter=pegasus
}





class   __a      (   __UpperCamelCase				):
 __lowercase			:							Any       					=			'pegasus'
 __lowercase			:							Union[str, Any]       					=			['past_key_values']
 __lowercase			:							Any       					=			{'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}
 def __init__(       self    ,			lowerCAmelCase__=50_265    ,			lowerCAmelCase__=1_024    ,			lowerCAmelCase__=12    ,			lowerCAmelCase__=4_096    ,			lowerCAmelCase__=16    ,			lowerCAmelCase__=12    ,			lowerCAmelCase__=4_096    ,			lowerCAmelCase__=16    ,			lowerCAmelCase__=0.0    ,			lowerCAmelCase__=0.0    ,			lowerCAmelCase__=True    ,			lowerCAmelCase__=True    ,			lowerCAmelCase__="gelu"    ,			lowerCAmelCase__=1_024    ,			lowerCAmelCase__=0.1    ,			lowerCAmelCase__=0.0    ,			lowerCAmelCase__=0.0    ,			lowerCAmelCase__=0.0_2    ,			lowerCAmelCase__=0    ,			lowerCAmelCase__=False    ,			lowerCAmelCase__=0    ,			lowerCAmelCase__=1    ,			lowerCAmelCase__=1    ,			**lowerCAmelCase__    ,			) ->    Union[str, Any]:




        '''simple docstring'''
        lowercase__:       int        =       vocab_size
        lowercase__:       Optional[int]        =       max_position_embeddings
        lowercase__:       List[str]        =       d_model
        lowercase__:       Optional[Any]        =       encoder_ffn_dim
        lowercase__:       Optional[Any]        =       encoder_layers
        lowercase__:       Union[str, Any]        =       encoder_attention_heads
        lowercase__:       Optional[int]        =       decoder_ffn_dim
        lowercase__:       Tuple        =       decoder_layers
        lowercase__:       Union[str, Any]        =       decoder_attention_heads
        lowercase__:       Dict        =       dropout
        lowercase__:       List[str]        =       attention_dropout
        lowercase__:       List[str]        =       activation_dropout
        lowercase__:       Optional[int]        =       activation_function
        lowercase__:       Dict        =       init_std
        lowercase__:       Optional[Any]        =       encoder_layerdrop
        lowercase__:       List[str]        =       decoder_layerdrop
        lowercase__:       Union[str, Any]        =       use_cache
        lowercase__:       Any        =       encoder_layers
        lowercase__:       List[str]        =       scale_embedding  # scale factor will be sqrt(d_model) if True
        super().__init__(
            pad_token_id=lowerCAmelCase__    ,			eos_token_id=lowerCAmelCase__    ,			is_encoder_decoder=lowerCAmelCase__    ,			decoder_start_token_id=lowerCAmelCase__    ,			forced_eos_token_id=lowerCAmelCase__    ,			**lowerCAmelCase__    ,			)
 @property
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    int:




        '''simple docstring'''
        return self.encoder_attention_heads
 @property
 def 		SCREAMING_SNAKE_CASE__       (       self			) ->    int:




        '''simple docstring'''
        return self.d_model


