




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:






    """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.02       ,_SCREAMING_SNAKE_CASE=3       ,_SCREAMING_SNAKE_CASE=4       ,_SCREAMING_SNAKE_CASE=None       ,)			->		List[Any]:
         UpperCAmelCase_      :							Optional[Any]       =      parent
         UpperCAmelCase_      :							Union[str, Any]       =      batch_size
         UpperCAmelCase_      :							Optional[int]       =      seq_length
         UpperCAmelCase_      :							Any       =      is_training
         UpperCAmelCase_      :							Optional[Any]       =      use_input_mask
         UpperCAmelCase_      :							Tuple       =      use_token_type_ids
         UpperCAmelCase_      :							Any       =      use_labels
         UpperCAmelCase_      :							Union[str, Any]       =      vocab_size
         UpperCAmelCase_      :							List[Any]       =      hidden_size
         UpperCAmelCase_      :							List[str]       =      num_hidden_layers
         UpperCAmelCase_      :							Optional[Any]       =      num_attention_heads
         UpperCAmelCase_      :							Optional[Any]       =      intermediate_size
         UpperCAmelCase_      :							str       =      hidden_act
         UpperCAmelCase_      :							int       =      hidden_dropout_prob
         UpperCAmelCase_      :							Optional[Any]       =      attention_probs_dropout_prob
         UpperCAmelCase_      :							str       =      max_position_embeddings
         UpperCAmelCase_      :							Optional[Any]       =      type_vocab_size
         UpperCAmelCase_      :							int       =      type_sequence_label_size
         UpperCAmelCase_      :							Optional[Any]       =      initializer_range
         UpperCAmelCase_      :							int       =      num_labels
         UpperCAmelCase_      :							Tuple       =      num_choices
         UpperCAmelCase_      :							Any       =      scope





    def 							a__				(				self  )			->		List[Any]:
         UpperCAmelCase_      :							Dict       =      ids_tensor([self.batch_size, self.seq_length]       ,self.vocab_size  )

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

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

         UpperCAmelCase_      :							List[Any]       =      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       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )			->		str:
         UpperCAmelCase_      :							Tuple       =      EsmModel(config=_SCREAMING_SNAKE_CASE  )
         model.to(_SCREAMING_SNAKE_CASE  )
         model.eval()
         UpperCAmelCase_      :							List[Any]       =      model(_SCREAMING_SNAKE_CASE       ,attention_mask=_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							Dict       =      model(_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							str       =      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  )			->		Any:
         UpperCAmelCase_      :							Any       =      EsmForMaskedLM(config=_SCREAMING_SNAKE_CASE  )
         model.to(_SCREAMING_SNAKE_CASE  )
         model.eval()
         UpperCAmelCase_      :							Tuple       =      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[Any]:
         UpperCAmelCase_      :							Union[str, Any]       =      self.num_labels
         UpperCAmelCase_      :							Tuple       =      EsmForTokenClassification(config=_SCREAMING_SNAKE_CASE  )
         model.to(_SCREAMING_SNAKE_CASE  )
         model.eval()
         UpperCAmelCase_      :							str       =      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  )			->		int:
         UpperCAmelCase_      :							List[Any]       =      self.prepare_config_and_inputs()
         (
             UpperCAmelCase_   
         )      :							Optional[Any]       =      config_and_inputs
         UpperCAmelCase_      :							str       =      {'''input_ids''': input_ids, '''attention_mask''': input_mask}
         return config, inputs_dict


@require_torch
class   __a(					_a    ,						_a    ,						unittest.TestCase       ):






    """simple docstring"""





    lowerCAmelCase			      =				False

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





    def 							a__				(				self  )			->		List[Any]:
         UpperCAmelCase_      :							Optional[int]       =      EsmModelTester(self  )
         UpperCAmelCase_      :							int       =      ConfigTester(self       ,config_class=_SCREAMING_SNAKE_CASE       ,hidden_size=37  )





    def 							a__				(				self  )			->		int:
         self.config_tester.run_common_tests()





    def 							a__				(				self  )			->		Union[str, Any]:
         UpperCAmelCase_      :							List[str]       =      self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self  )			->		Any:
         UpperCAmelCase_      :							Any       =      self.model_tester.prepare_config_and_inputs()
         for type in ["absolute", "relative_key", "relative_key_query"]:
              UpperCAmelCase_      :							List[str]       =      type
              self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self  )			->		Optional[Any]:
         UpperCAmelCase_      :							Tuple       =      self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_masked_lm(*_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self  )			->		List[str]:
         UpperCAmelCase_      :							List[str]       =      self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_token_classification(*_SCREAMING_SNAKE_CASE  )





    @slow
    def 							a__				(				self  )			->		int:
         for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              UpperCAmelCase_      :							Union[str, Any]       =      EsmModel.from_pretrained(_SCREAMING_SNAKE_CASE  )
              self.assertIsNotNone(_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self  )			->		Dict:
         UpperCAmelCase_      :							Tuple       =      self.model_tester.prepare_config_and_inputs()[0]
         UpperCAmelCase_      :							Optional[Any]       =      EsmEmbeddings(config=_SCREAMING_SNAKE_CASE  )

         UpperCAmelCase_      :							Optional[int]       =      torch.as_tensor([[12, 31, 13, model.padding_idx]]  )
         UpperCAmelCase_      :							Optional[int]       =      torch.as_tensor(
             [
                 [
                     0 + model.padding_idx + 1,
                     1 + model.padding_idx + 1,
                     2 + model.padding_idx + 1,
                     model.padding_idx,
                 ]
             ]  )
         UpperCAmelCase_      :							Optional[int]       =      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  )			->		Union[str, Any]:
         UpperCAmelCase_      :							List[Any]       =      self.model_tester.prepare_config_and_inputs()[0]
         UpperCAmelCase_      :							Any       =      EsmEmbeddings(config=_SCREAMING_SNAKE_CASE  )

         UpperCAmelCase_      :							Optional[int]       =      torch.empty(2       ,4       ,30  )
         UpperCAmelCase_      :							Tuple       =      [
             0 + embeddings.padding_idx + 1,
             1 + embeddings.padding_idx + 1,
             2 + embeddings.padding_idx + 1,
             3 + embeddings.padding_idx + 1,
         ]
         UpperCAmelCase_      :							int       =      torch.as_tensor([expected_single_positions, expected_single_positions]  )
         UpperCAmelCase_      :							Union[str, Any]       =      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:
         pass





    @unittest.skip('''Esm does not support embedding resizing'''  )
    def 							a__				(				self  )			->		Tuple:
         pass





    @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''  )
    def 							a__				(				self  )			->		Union[str, Any]:
         pass


@require_torch
class   __a(					_a       ):






    """simple docstring"""





    @slow
    def 							a__				(				self  )			->		Tuple:
         with torch.no_grad():
              UpperCAmelCase_      :							Tuple       =      EsmForMaskedLM.from_pretrained('''facebook/esm2_t6_8M_UR50D'''  )
              model.eval()
              UpperCAmelCase_      :							List[Any]       =      torch.tensor([[0, 1, 2, 3, 4, 5]]  )
              UpperCAmelCase_      :							int       =      model(_SCREAMING_SNAKE_CASE  )[0]

              UpperCAmelCase_      :							Union[str, Any]       =      33

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

              UpperCAmelCase_      :							str       =      torch.tensor(
                  [[[8.92_15, -10.58_98, -6.46_71], [-6.39_67, -13.91_14, -1.12_12], [-7.78_12, -13.95_16, -3.74_06]]]  )
              self.assertTrue(torch.allclose(output[:, :3, :3]       ,_SCREAMING_SNAKE_CASE       ,atol=1e-4  )  )





    @slow
    def 							a__				(				self  )			->		Tuple:
         with torch.no_grad():
              UpperCAmelCase_      :							str       =      EsmModel.from_pretrained('''facebook/esm2_t6_8M_UR50D'''  )
              model.eval()

              UpperCAmelCase_      :							Dict       =      torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]  )
              UpperCAmelCase_      :							Optional[Any]       =      model(_SCREAMING_SNAKE_CASE  )[0]
              # compare the actual values for a slice.
              UpperCAmelCase_      :							Any       =      torch.tensor(
                  [[[0.14_44, 0.54_13, 0.32_48], [0.30_34, 0.00_53, 0.31_08], [0.32_28, -0.24_99, 0.34_15]]]  )
              self.assertTrue(torch.allclose(output[:, :3, :3]       ,_SCREAMING_SNAKE_CASE       ,atol=1e-4  )  )





from ...processing_utils import ProcessorMixin

class   __a(					_a       ):






    """simple docstring"""





    lowerCAmelCase        =				'''SpeechT5FeatureExtractor'''
    lowerCAmelCase        =				'''SpeechT5Tokenizer'''





    def __init__(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )			->		int:
         super().__init__(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )





    def __call__(				self       ,*_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )			->		int:
         UpperCAmelCase_      :							List[str]       =      kwargs.pop('''audio'''       ,_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							str       =      kwargs.pop('''text'''       ,_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							List[str]       =      kwargs.pop('''text_target'''       ,_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							int       =      kwargs.pop('''audio_target'''       ,_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							Tuple       =      kwargs.pop('''sampling_rate'''       ,_SCREAMING_SNAKE_CASE  )

         if audio is not None and text is not None:
              raise ValueError(
                  '''Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?'''  )
         if audio_target is not None and text_target is not None:
              raise ValueError(
                  '''Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?'''  )
         if audio is None and audio_target is None and text is None and text_target is None:
              raise ValueError(
                  '''You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process.'''  )

         if audio is not None:
              UpperCAmelCase_      :							Optional[Any]       =      self.feature_extractor(_SCREAMING_SNAKE_CASE       ,*_SCREAMING_SNAKE_CASE       ,sampling_rate=_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )
         elif text is not None:
              UpperCAmelCase_      :							Dict       =      self.tokenizer(_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )
         else:
              UpperCAmelCase_      :							List[str]       =      None

         if audio_target is not None:
              UpperCAmelCase_      :							List[Any]       =      self.feature_extractor(audio_target=_SCREAMING_SNAKE_CASE       ,*_SCREAMING_SNAKE_CASE       ,sampling_rate=_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )
              UpperCAmelCase_      :							int       =      targets['''input_values''']
         elif text_target is not None:
              UpperCAmelCase_      :							Optional[int]       =      self.tokenizer(_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )
              UpperCAmelCase_      :							Optional[Any]       =      targets['''input_ids''']
         else:
              UpperCAmelCase_      :							Tuple       =      None

         if inputs is None:
              return targets

         if targets is not None:
              UpperCAmelCase_      :							Dict       =      labels

              UpperCAmelCase_      :							Optional[int]       =      targets.get('''attention_mask'''  )
              if decoder_attention_mask is not None:
                   UpperCAmelCase_      :							List[Any]       =      decoder_attention_mask

         return inputs





    def 							a__				(				self       ,*_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )			->		Tuple:
         UpperCAmelCase_      :							Dict       =      kwargs.pop('''input_values'''       ,_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							Union[str, Any]       =      kwargs.pop('''input_ids'''       ,_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							List[str]       =      kwargs.pop('''labels'''       ,_SCREAMING_SNAKE_CASE  )

         if input_values is not None and input_ids is not None:
              raise ValueError('''Cannot process both `input_values` and `input_ids` inputs.'''  )
         if input_values is None and input_ids is None and labels is None:
              raise ValueError(
                  '''You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded.'''  )

         if input_values is not None:
              UpperCAmelCase_      :							Tuple       =      self.feature_extractor.pad(_SCREAMING_SNAKE_CASE       ,*_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )
         elif input_ids is not None:
              UpperCAmelCase_      :							Tuple       =      self.tokenizer.pad(_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )
         else:
              UpperCAmelCase_      :							List[str]       =      None

         if labels is not None:
              if "input_ids" in labels or (isinstance(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  ) and "input_ids" in labels[0]):
                   UpperCAmelCase_      :							Tuple       =      self.tokenizer.pad(_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )
                   UpperCAmelCase_      :							Any       =      targets['''input_ids''']
              else:
                   UpperCAmelCase_      :							int       =      self.feature_extractor.feature_size
                   UpperCAmelCase_      :							List[str]       =      self.feature_extractor.num_mel_bins
                   UpperCAmelCase_      :							Optional[Any]       =      self.feature_extractor.pad(_SCREAMING_SNAKE_CASE       ,*_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )
                   UpperCAmelCase_      :							List[Any]       =      feature_size_hack
                   UpperCAmelCase_      :							List[Any]       =      targets['''input_values''']
         else:
              UpperCAmelCase_      :							Optional[int]       =      None

         if inputs is None:
              return targets

         if targets is not None:
              UpperCAmelCase_      :							Optional[int]       =      labels

              UpperCAmelCase_      :							Union[str, Any]       =      targets.get('''attention_mask'''  )
              if decoder_attention_mask is not None:
                   UpperCAmelCase_      :							List[Any]       =      decoder_attention_mask

         return inputs





    def 							a__				(				self       ,*_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )			->		Optional[Any]:
         return self.tokenizer.batch_decode(*_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self       ,*_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )			->		Union[str, Any]:
         return self.tokenizer.decode(*_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )