


'''simple docstring'''

import logging
import os
import sys
import warnings
from dataclasses import dataclass, field
from random import randint
from typing import Optional

import datasets
import evaluate
import numpy as np
from datasets import DatasetDict, load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoFeatureExtractor,
    AutoModelForAudioClassification,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version


lowerCamelCase				:  List[str]    		=      logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('4.31.0')

require_version('datasets>=1.14.0', 'To fix: pip install -r examples/pytorch/audio-classification/requirements.txt')

def _SCREAMING_SNAKE_CASE (A    ,					A    ,					A = 16_000			)			->			Optional[int]:






       """simple docstring"""







       lowercase__      =					int(round(sample_rate * max_length			)			)
       if len(A			) <= sample_length:
              return wav
       lowercase__      =					randint(0    ,					len(A			) - sample_length - 1			)
       return wav[random_offset : random_offset + sample_length]
@dataclass
class     __lowerCAmelCase		:





      '''simple docstring'''






      lowerCAmelCase__   :	Optional[str]       =				field(default=lowercase_    ,	metadata={"""help""": """Name of a dataset from the datasets package"""}	)
      lowerCAmelCase__   :	Optional[str]       =				field(
          default=lowercase_    ,	metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}	)
      lowerCAmelCase__   :	Optional[str]       =				field(
          default=lowercase_    ,	metadata={"""help""": """A file containing the training audio paths and labels."""}	)
      lowerCAmelCase__   :	Optional[str]       =				field(
          default=lowercase_    ,	metadata={"""help""": """A file containing the validation audio paths and labels."""}	)
      lowerCAmelCase__   :	str       =				field(
          default="""train"""    ,	metadata={
              """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'"""
          }    ,	)
      lowerCAmelCase__   :	str       =				field(
          default="""validation"""    ,	metadata={
              """help""": (
                  """The name of the training data set split to use (via the datasets library). Defaults to 'validation'"""
              )
          }    ,	)
      lowerCAmelCase__   :	str       =				field(
          default="""audio"""    ,	metadata={"""help""": """The name of the dataset column containing the audio data. Defaults to 'audio'"""}    ,	)
      lowerCAmelCase__   :	str       =				field(
          default="""label"""    ,	metadata={"""help""": """The name of the dataset column containing the labels. Defaults to 'label'"""}	)
      lowerCAmelCase__   :	Optional[int]       =				field(
          default=lowercase_    ,	metadata={
              """help""": (
                  """For debugging purposes or quicker training, truncate the number of training examples to this """
                  """value if set."""
              )
          }    ,	)
      lowerCAmelCase__   :	Optional[int]       =				field(
          default=lowercase_    ,	metadata={
              """help""": (
                  """For debugging purposes or quicker training, truncate the number of evaluation examples to this """
                  """value if set."""
              )
          }    ,	)
      lowerCAmelCase__   :	float       =				field(
          default=20    ,	metadata={"""help""": """Audio clips will be randomly cut to this length during training if the value is set."""}    ,	)






@dataclass
class     __lowerCAmelCase		:





      '''simple docstring'''






      lowerCAmelCase__   :	str       =				field(
          default="""facebook/wav2vec2-base"""    ,	metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}    ,	)
      lowerCAmelCase__   :	Optional[str]       =				field(
          default=lowercase_    ,	metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}	)
      lowerCAmelCase__   :	Optional[str]       =				field(
          default=lowercase_    ,	metadata={"""help""": """Where do you want to store the pretrained models downloaded from the Hub"""}	)
      lowerCAmelCase__   :	str       =				field(
          default="""main"""    ,	metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""}    ,	)
      lowerCAmelCase__   :	Optional[str]       =				field(
          default=lowercase_    ,	metadata={"""help""": """Name or path of preprocessor config."""}	)
      lowerCAmelCase__   :	bool       =				field(
          default=lowercase_    ,	metadata={"""help""": """Whether to freeze the feature encoder layers of the model."""}	)
      lowerCAmelCase__   :	bool       =				field(
          default=lowercase_    ,	metadata={"""help""": """Whether to generate an attention mask in the feature extractor."""}	)
      lowerCAmelCase__   :	bool       =				field(
          default=lowercase_    ,	metadata={
              """help""": (
                  """Will use the token generated when running `huggingface-cli login` (necessary to use this script """
                  """with private models)."""
              )
          }    ,	)
      lowerCAmelCase__   :	Optional[bool]       =				field(
          default=lowercase_    ,	metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""}	)
      lowerCAmelCase__   :	bool       =				field(
          default=lowercase_    ,	metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""}    ,	)



      def  UpperCamelCase__						(self       :       int					):

             '''simple docstring'''







             if not self.freeze_feature_extractor and self.freeze_feature_encoder:
                    warnings.warn(
                        '''The argument `--freeze_feature_extractor` is deprecated and '''
                        '''will be removed in a future version. Use `--freeze_feature_encoder`'''
                        '''instead. Setting `freeze_feature_encoder==True`.'''  ,		UpperCamelCase  ,		)
             if self.freeze_feature_extractor and not self.freeze_feature_encoder:
                    raise ValueError(
                        '''The argument `--freeze_feature_extractor` is deprecated and '''
                        '''should not be used in combination with `--freeze_feature_encoder`.'''
                        '''Only make use of `--freeze_feature_encoder`.'''					)






def _SCREAMING_SNAKE_CASE ()			->			str:






       """simple docstring"""







       lowercase__      =					HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)			)
       if len(sys.argv			) == 2 and sys.argv[1].endswith('''.json'''			):
              # If we pass only one argument to the script and it's the path to a json file,
              # let's parse it to get our arguments.
              lowercase__     ,lowercase__     ,lowercase__      =					parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]			)			)
       else:
              lowercase__     ,lowercase__     ,lowercase__      =					parser.parse_args_into_dataclasses()

       # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
       # information sent is the one passed as arguments along with your Python/PyTorch versions.
       send_example_telemetry('''run_audio_classification'''    ,					A    ,					A			)

       # Setup logging
       logging.basicConfig(
           format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''    ,					datefmt='''%m/%d/%Y %H:%M:%S'''    ,					handlers=[logging.StreamHandler(sys.stdout			)]    ,					)

       if training_args.should_log:
              # The default of training_args.log_level is passive, so we set log level at info here to have that default.
              transformers.utils.logging.set_verbosity_info()

       lowercase__      =					training_args.get_process_log_level()
       logger.setLevel(A			)
       transformers.utils.logging.set_verbosity(A			)
       transformers.utils.logging.enable_default_handler()
       transformers.utils.logging.enable_explicit_format()

       # Log on each process the small summary:
       logger.warning(
           f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} "
           + f"distributed training: {bool(training_args.local_rank != -1			)}, 16-bits training: {training_args.fpaa}"			)
       logger.info(f"Training/evaluation parameters {training_args}"			)

       # Set seed before initializing model.
       set_seed(training_args.seed			)

       # Detecting last checkpoint.
       lowercase__      =					None
       if os.path.isdir(training_args.output_dir			) and training_args.do_train and not training_args.overwrite_output_dir:
              lowercase__      =					get_last_checkpoint(training_args.output_dir			)
              if last_checkpoint is None and len(os.listdir(training_args.output_dir			)			) > 0:
                     raise ValueError(
                         f"Output directory ({training_args.output_dir}) already exists and is not empty. "
                         '''Use --overwrite_output_dir to train from scratch.'''			)
              elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
                     logger.info(
                         f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
                         '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'''			)

    # Initialize our dataset and prepare it for the audio classification task.
       lowercase__      =					DatasetDict()
       lowercase__      =					load_dataset(
           data_args.dataset_name    ,					data_args.dataset_config_name    ,					split=data_args.train_split_name    ,					use_auth_token=True if model_args.use_auth_token else None    ,					)
       lowercase__      =					load_dataset(
           data_args.dataset_name    ,					data_args.dataset_config_name    ,					split=data_args.eval_split_name    ,					use_auth_token=True if model_args.use_auth_token else None    ,					)

       if data_args.audio_column_name not in raw_datasets["train"].column_names:
              raise ValueError(
                  f"--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. "
                  '''Make sure to set `--audio_column_name` to the correct audio column - one of '''
                  f"{', '.join(raw_datasets['train'].column_names			)}."			)

       if data_args.label_column_name not in raw_datasets["train"].column_names:
              raise ValueError(
                  f"--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. "
                  '''Make sure to set `--label_column_name` to the correct text column - one of '''
                  f"{', '.join(raw_datasets['train'].column_names			)}."			)

       # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over
       # transformer outputs in the classifier, but it doesn't always lead to better accuracy
       lowercase__      =					AutoFeatureExtractor.from_pretrained(
           model_args.feature_extractor_name or model_args.model_name_or_path    ,					return_attention_mask=model_args.attention_mask    ,					cache_dir=model_args.cache_dir    ,					revision=model_args.model_revision    ,					use_auth_token=True if model_args.use_auth_token else None    ,					)

       # `datasets` takes care of automatically loading and resampling the audio,
       # so we just need to set the correct target sampling rate.
       lowercase__      =					raw_datasets.cast_column(
           data_args.audio_column_name    ,					datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate			)			)

       lowercase__      =					feature_extractor.model_input_names[0]

       def train_transforms(A			):
              lowercase__      =					[]
              for audio in batch[data_args.audio_column_name]:
                     lowercase__      =					random_subsample(
                         audio['''array''']    ,					max_length=data_args.max_length_seconds    ,					sample_rate=feature_extractor.sampling_rate			)
                     subsampled_wavs.append(A			)
              lowercase__      =					feature_extractor(A    ,					sampling_rate=feature_extractor.sampling_rate			)
              lowercase__      =					{model_input_name: inputs.get(A			)}
              lowercase__      =					list(batch[data_args.label_column_name]			)

              return output_batch

       def val_transforms(A			):
              lowercase__      =					[audio['''array'''] for audio in batch[data_args.audio_column_name]]
              lowercase__      =					feature_extractor(A    ,					sampling_rate=feature_extractor.sampling_rate			)
              lowercase__      =					{model_input_name: inputs.get(A			)}
              lowercase__      =					list(batch[data_args.label_column_name]			)

              return output_batch

       # Prepare label mappings.
       # We'll include these in the model's config to get human readable labels in the Inference API.
       lowercase__      =					raw_datasets['''train'''].features[data_args.label_column_name].names
       lowercase__     ,lowercase__      =					{}, {}
       for i, label in enumerate(A			):
              lowercase__      =					str(A			)
              lowercase__      =					label

       # Load the accuracy metric from the datasets package
       lowercase__      =					evaluate.load('''accuracy'''			)

       # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with
       # `predictions` and `label_ids` fields) and has to return a dictionary string to float.
       def compute_metrics(A			):
              lowercase__      =					np.argmax(eval_pred.predictions    ,					axis=1			)
              return metric.compute(predictions=A    ,					references=eval_pred.label_ids			)

       lowercase__      =					AutoConfig.from_pretrained(
           model_args.config_name or model_args.model_name_or_path    ,					num_labels=len(A			)    ,					labelaid=A    ,					idalabel=A    ,					finetuning_task='''audio-classification'''    ,					cache_dir=model_args.cache_dir    ,					revision=model_args.model_revision    ,					use_auth_token=True if model_args.use_auth_token else None    ,					)
       lowercase__      =					AutoModelForAudioClassification.from_pretrained(
           model_args.model_name_or_path    ,					from_tf=bool('''.ckpt''' in model_args.model_name_or_path			)    ,					config=A    ,					cache_dir=model_args.cache_dir    ,					revision=model_args.model_revision    ,					use_auth_token=True if model_args.use_auth_token else None    ,					ignore_mismatched_sizes=model_args.ignore_mismatched_sizes    ,					)

       # freeze the convolutional waveform encoder
       if model_args.freeze_feature_encoder:
              model.freeze_feature_encoder()

       if training_args.do_train:
              if data_args.max_train_samples is not None:
                     lowercase__      =					(
                         raw_datasets['''train'''].shuffle(seed=training_args.seed			).select(range(data_args.max_train_samples			)			)
                     )
              # Set the training transforms
              raw_datasets["train"].set_transform(A    ,					output_all_columns=A			)

       if training_args.do_eval:
              if data_args.max_eval_samples is not None:
                     lowercase__      =					(
                         raw_datasets['''eval'''].shuffle(seed=training_args.seed			).select(range(data_args.max_eval_samples			)			)
                     )
              # Set the validation transforms
              raw_datasets["eval"].set_transform(A    ,					output_all_columns=A			)

       # Initialize our trainer
       lowercase__      =					Trainer(
           model=A    ,					args=A    ,					train_dataset=raw_datasets['''train'''] if training_args.do_train else None    ,					eval_dataset=raw_datasets['''eval'''] if training_args.do_eval else None    ,					compute_metrics=A    ,					tokenizer=A    ,					)

       # Training
       if training_args.do_train:
              lowercase__      =					None
              if training_args.resume_from_checkpoint is not None:
                     lowercase__      =					training_args.resume_from_checkpoint
              elif last_checkpoint is not None:
                     lowercase__      =					last_checkpoint
              lowercase__      =					trainer.train(resume_from_checkpoint=A			)
              trainer.save_model()
              trainer.log_metrics('''train'''    ,					train_result.metrics			)
              trainer.save_metrics('''train'''    ,					train_result.metrics			)
              trainer.save_state()

       # Evaluation
       if training_args.do_eval:
              lowercase__      =					trainer.evaluate()
              trainer.log_metrics('''eval'''    ,					A			)
              trainer.save_metrics('''eval'''    ,					A			)

       # Write model card and (optionally) push to hub
       lowercase__      =					{
           '''finetuned_from''': model_args.model_name_or_path,
           '''tasks''': '''audio-classification''',
           '''dataset''': data_args.dataset_name,
           '''tags''': ['''audio-classification'''],
       }
       if training_args.push_to_hub:
              trainer.push_to_hub(**A			)
       else:
              trainer.create_model_card(**A			)


if __name__ == "__main__":
 main()








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





      '''simple docstring'''






      def __init__(self       :       Optional[int]  ,		UpperCamelCase       :       Tuple  ,		UpperCamelCase       :       str=13  ,		UpperCamelCase       :       Optional[int]=7  ,		UpperCamelCase       :       Union[str, Any]=False  ,		UpperCamelCase       :       Dict=True  ,		UpperCamelCase       :       Optional[int]=False  ,		UpperCamelCase       :       Optional[Any]=True  ,		UpperCamelCase       :       Union[str, Any]=33  ,		UpperCamelCase       :       List[Any]=32  ,		UpperCamelCase       :       Dict=5  ,		UpperCamelCase       :       str=4  ,		UpperCamelCase       :       str=37  ,		UpperCamelCase       :       List[Any]="gelu"  ,		UpperCamelCase       :       List[str]=0.1  ,		UpperCamelCase       :       Dict=0.1  ,		UpperCamelCase       :       Dict=512  ,		UpperCamelCase       :       Any=16  ,		UpperCamelCase       :       List[Any]=2  ,		UpperCamelCase       :       List[Any]=0.02  ,		UpperCamelCase       :       Tuple=3  ,		UpperCamelCase       :       Optional[Any]=4  ,		UpperCamelCase       :       int=None  ,		):

             '''simple docstring'''







             lowercase__      =					parent
             lowercase__      =					batch_size
             lowercase__      =					seq_length
             lowercase__      =					is_training
             lowercase__      =					use_input_mask
             lowercase__      =					use_token_type_ids
             lowercase__      =					use_labels
             lowercase__      =					vocab_size
             lowercase__      =					hidden_size
             lowercase__      =					num_hidden_layers
             lowercase__      =					num_attention_heads
             lowercase__      =					intermediate_size
             lowercase__      =					hidden_act
             lowercase__      =					hidden_dropout_prob
             lowercase__      =					attention_probs_dropout_prob
             lowercase__      =					max_position_embeddings
             lowercase__      =					type_vocab_size
             lowercase__      =					type_sequence_label_size
             lowercase__      =					initializer_range
             lowercase__      =					num_labels
             lowercase__      =					num_choices
             lowercase__      =					scope



      def  UpperCamelCase__						(self       :       str					):

             '''simple docstring'''







             lowercase__      =					ids_tensor([self.batch_size, self.seq_length]  ,		self.vocab_size					)

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

             lowercase__      =					None
             lowercase__      =					None
             lowercase__      =					None
             if self.use_labels:
                    lowercase__      =					ids_tensor([self.batch_size]  ,		self.type_sequence_label_size					)
                    lowercase__      =					ids_tensor([self.batch_size, self.seq_length]  ,		self.num_labels					)
                    lowercase__      =					ids_tensor([self.batch_size]  ,		self.num_choices					)

             lowercase__      =					self.get_config()

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



      def  UpperCamelCase__						(self       :       Optional[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  UpperCamelCase__						(self       :       Optional[int]  ,		UpperCamelCase       :       Union[str, Any]  ,		UpperCamelCase       :       int  ,		UpperCamelCase       :       List[Any]  ,		UpperCamelCase       :       str  ,		UpperCamelCase       :       str  ,		UpperCamelCase       :       Dict					):

             '''simple docstring'''







             lowercase__      =					EsmModel(config=UpperCamelCase					)
             model.to(UpperCamelCase					)
             model.eval()
             lowercase__      =					model(UpperCamelCase  ,		attention_mask=UpperCamelCase					)
             lowercase__      =					model(UpperCamelCase					)
             lowercase__      =					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  UpperCamelCase__						(self       :       str  ,		UpperCamelCase       :       Any  ,		UpperCamelCase       :       Tuple  ,		UpperCamelCase       :       Any  ,		UpperCamelCase       :       List[Any]  ,		UpperCamelCase       :       Optional[Any]  ,		UpperCamelCase       :       Optional[int]					):

             '''simple docstring'''







             lowercase__      =					EsmForMaskedLM(config=UpperCamelCase					)
             model.to(UpperCamelCase					)
             model.eval()
             lowercase__      =					model(UpperCamelCase  ,		attention_mask=UpperCamelCase  ,		labels=UpperCamelCase					)
             self.parent.assertEqual(result.logits.shape  ,		(self.batch_size, self.seq_length, self.vocab_size)					)



      def  UpperCamelCase__						(self       :       Any  ,		UpperCamelCase       :       str  ,		UpperCamelCase       :       List[Any]  ,		UpperCamelCase       :       Tuple  ,		UpperCamelCase       :       int  ,		UpperCamelCase       :       Union[str, Any]  ,		UpperCamelCase       :       List[Any]					):

             '''simple docstring'''







             lowercase__      =					self.num_labels
             lowercase__      =					EsmForTokenClassification(config=UpperCamelCase					)
             model.to(UpperCamelCase					)
             model.eval()
             lowercase__      =					model(UpperCamelCase  ,		attention_mask=UpperCamelCase  ,		labels=UpperCamelCase					)
             self.parent.assertEqual(result.logits.shape  ,		(self.batch_size, self.seq_length, self.num_labels)					)






      def  UpperCamelCase__						(self       :       Optional[Any]					):

             '''simple docstring'''







             lowercase__      =					self.prepare_config_and_inputs()
             (
                 (
                 lowercase__
             )     ,(
                 lowercase__
             )     ,(
                 lowercase__
             )     ,(
                 lowercase__
             )     ,(
                 lowercase__
             )     ,(
                 lowercase__
             )     ,
             )      =					config_and_inputs
             lowercase__      =					{'''input_ids''': input_ids, '''attention_mask''': input_mask}
             return config, inputs_dict






@require_torch
class     __lowerCAmelCase		(lowercase_    ,	lowercase_    ,	unittest.TestCase	):





      '''simple docstring'''






      lowerCAmelCase__   :	Dict       =				False

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



      def  UpperCamelCase__						(self       :       List[Any]					):

             '''simple docstring'''







             lowercase__      =					EsmModelTester(self					)
             lowercase__      =					ConfigTester(self  ,		config_class=UpperCamelCase  ,		hidden_size=37					)



      def  UpperCamelCase__						(self       :       Union[str, Any]					):

             '''simple docstring'''







             self.config_tester.run_common_tests()



      def  UpperCamelCase__						(self       :       Optional[Any]					):

             '''simple docstring'''







             lowercase__      =					self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*UpperCamelCase					)



      def  UpperCamelCase__						(self       :       Any					):

             '''simple docstring'''







             lowercase__      =					self.model_tester.prepare_config_and_inputs()
             for type in ["absolute", "relative_key", "relative_key_query"]:
                    lowercase__      =					type
                    self.model_tester.create_and_check_model(*UpperCamelCase					)



      def  UpperCamelCase__						(self       :       Optional[int]					):

             '''simple docstring'''







             lowercase__      =					self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase					)



      def  UpperCamelCase__						(self       :       List[Any]					):

             '''simple docstring'''







             lowercase__      =					self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_token_classification(*UpperCamelCase					)



      @slow
      def  UpperCamelCase__						(self       :       Union[str, Any]					):

             '''simple docstring'''







             for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    lowercase__      =					EsmModel.from_pretrained(UpperCamelCase					)
                    self.assertIsNotNone(UpperCamelCase					)



      def  UpperCamelCase__						(self       :       Optional[int]					):

             '''simple docstring'''







             lowercase__      =					self.model_tester.prepare_config_and_inputs()[0]
             lowercase__      =					EsmEmbeddings(config=UpperCamelCase					)

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

             '''simple docstring'''







             lowercase__      =					self.model_tester.prepare_config_and_inputs()[0]
             lowercase__      =					EsmEmbeddings(config=UpperCamelCase					)

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

             '''simple docstring'''







             pass



      @unittest.skip('''Esm does not support embedding resizing'''					)
      def  UpperCamelCase__						(self       :       Optional[Any]					):

             '''simple docstring'''







             pass






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

             '''simple docstring'''







             pass






@require_torch
class     __lowerCAmelCase		(lowercase_	):





      '''simple docstring'''






      @slow
      def  UpperCamelCase__						(self       :       Optional[Any]					):

             '''simple docstring'''







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

                    lowercase__      =					33

                    lowercase__      =					torch.Size((1, 6, vocab_size)					)
                    self.assertEqual(output.shape  ,		UpperCamelCase					)

                    lowercase__      =					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]  ,		UpperCamelCase  ,		atol=1E-4					)					)






      @slow
      def  UpperCamelCase__						(self       :       Optional[Any]					):

             '''simple docstring'''







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

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




