

import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union

import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


if is_apex_available():
       from apex import amp


if version.parse(version.parse(torch.__version__).base_version) >= version.parse('''1.6'''):
       snake_case_			  = True
       from torch.cuda.amp import autocast

snake_case_			  = logging.getLogger(__name__)

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Any=None	,     SCREAMING_SNAKE_CASE_		:    Tuple=None			):



     '''simple docstring'''





     return field(default_factory=lambda: default	,     metadata=SCREAMING_SNAKE_CASE_			)


@dataclass
class       SCREAMING_SNAKE_CASE__					:
    __lowerCamelCase						:       str														=     field(
        metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}     )
    __lowerCamelCase						:       Optional[str]														=     field(
        default=__snake_case		,       metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}		,       )
    __lowerCamelCase						:       Optional[bool]														=     field(
        default=__snake_case		,       metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""}     )
    __lowerCamelCase						:       Optional[float]														=     field(
        default=0.1		,       metadata={"""help""": """The dropout ratio for the attention probabilities."""}     )
    __lowerCamelCase						:       Optional[float]														=     field(
        default=0.1		,       metadata={"""help""": """The dropout ratio for activations inside the fully connected layer."""}     )
    __lowerCamelCase						:       Optional[float]														=     field(
        default=0.1		,       metadata={
            """help""": """The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler."""
        }		,       )
    __lowerCamelCase						:       Optional[float]														=     field(
        default=0.1		,       metadata={"""help""": """The dropout probabilitiy for all 1D convolutional layers in feature extractor."""}		,       )
    __lowerCamelCase						:       Optional[float]														=     field(
        default=0.05		,       metadata={
            """help""": (
                """Propability of each feature vector along the time axis to be chosen as the start of the vector"""
                """span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature"""
                """vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``."""
            )
        }		,       )
    __lowerCamelCase						:       Optional[float]														=     field(default=0.0		,       metadata={"""help""": """The LayerDrop probability."""}     )



@dataclass
class       SCREAMING_SNAKE_CASE__					:
    __lowerCamelCase						:       Optional[str]														=     field(
        default=__snake_case		,       metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}     )
    __lowerCamelCase						:       Optional[str]														=     field(
        default="""train+validation"""		,       metadata={
            """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'"""
        }		,       )
    __lowerCamelCase						:       bool														=     field(
        default=__snake_case		,       metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}     )
    __lowerCamelCase						:       Optional[int]														=     field(
        default=__snake_case		,       metadata={"""help""": """The number of processes to use for the preprocessing."""}		,       )
    __lowerCamelCase						:       Optional[int]														=     field(
        default=__snake_case		,       metadata={
            """help""": (
                """For debugging purposes or quicker training, truncate the number of training examples to this """
                """value if set."""
            )
        }		,       )
    __lowerCamelCase						:       Optional[int]														=     field(
        default=__snake_case		,       metadata={
            """help""": (
                """For debugging purposes or quicker training, truncate the number of validation examples to this """
                """value if set."""
            )
        }		,       )
    __lowerCamelCase						:       List[str]														=     list_field(
        default=[""",""", """?""", """.""", """!""", """-""", """;""", """:""", """\"\"""", """%""", """'""", """\"""", """�"""]		,       metadata={"""help""": """A list of characters to remove from the transcripts."""}		,       )



@dataclass
class       SCREAMING_SNAKE_CASE__					:
    __lowerCamelCase						:       WavaVecaProcessor
    __lowerCamelCase						:       Union[bool, str]														=     True
    __lowerCamelCase						:       Optional[int]														=     None
    __lowerCamelCase						:       Optional[int]														=     None
    __lowerCamelCase						:       Optional[int]														=     None
    __lowerCamelCase						:       Optional[int]														=     None





    def __call__(      self						,   a):
         # split inputs and labels since they have to be of different lenghts and need
         # different padding methods
         lowercase__    :   List[str]      =       [{'input_values': feature['input_values']} for feature in features]
         lowercase__    :   Any      =       [{'input_ids': feature['labels']} for feature in features]

         lowercase__    :   Tuple      =       self.processor.pad(
             a						,   padding=self.padding						,   max_length=self.max_length						,   pad_to_multiple_of=self.pad_to_multiple_of						,   return_tensors='pt'						,   )
         lowercase__    :   List[str]      =       self.processor.pad(
             labels=a						,   padding=self.padding						,   max_length=self.max_length_labels						,   pad_to_multiple_of=self.pad_to_multiple_of_labels						,   return_tensors='pt'						,   )

         # replace padding with -100 to ignore loss correctly
         lowercase__    :   Optional[int]      =       labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1)						,   -100)

         lowercase__    :   List[str]      =       labels

         return batch



class       SCREAMING_SNAKE_CASE__					(__snake_case     ):





    def       snake_case_				(      self						,   a						,   a):
         model.train()
         lowercase__    :   List[Any]      =       self._prepare_inputs(a)

         if self.use_amp:
              with autocast():
                   lowercase__    :   Any      =       self.compute_loss(a						,   a)
         else:
              lowercase__    :   Union[str, Any]      =       self.compute_loss(a						,   a)

         if self.args.n_gpu > 1:
              if model.module.config.ctc_loss_reduction == "mean":
                   lowercase__    :   Union[str, Any]      =       loss.mean()
              elif model.module.config.ctc_loss_reduction == "sum":
                   lowercase__    :   List[Any]      =       loss.sum() / (inputs['labels'] >= 0).sum()
              else:
                   raise ValueError(f"""{model.config.ctc_loss_reduction} is not valid. Choose one of ['mean', 'sum']""")

         if self.args.gradient_accumulation_steps > 1:
              lowercase__    :   Optional[int]      =       loss / self.args.gradient_accumulation_steps

         if self.use_amp:
              self.scaler.scale(a).backward()
         elif self.use_apex:
              with amp.scale_loss(a						,   self.optimizer) as scaled_loss:
                   scaled_loss.backward()
         elif self.deepspeed:
              self.deepspeed.backward(a)
         else:
              loss.backward()

         return loss.detach()



def 	snake_case__			(    ):



     '''simple docstring'''





     lowercase__    :   Optional[int]      =       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__    :   Optional[Any]      =       parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]			)			)
     else:
          lowercase__      , lowercase__      , lowercase__    :   List[Any]      =       parser.parse_args_into_dataclasses()

     # Detecting last checkpoint.
     lowercase__    :   Dict      =       None
     if os.path.isdir(training_args.output_dir			) and training_args.do_train and not training_args.overwrite_output_dir:
          lowercase__    :   Optional[Any]      =       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 overcome.'			)
          elif last_checkpoint is not 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.'			)

    # 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			)]	,     )
     logger.setLevel(logging.INFO if is_main_process(training_args.local_rank			) else logging.WARN			)

     # 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}"""			)
     # Set the verbosity to info of the Transformers logger (on main process only):
     if is_main_process(training_args.local_rank			):
          transformers.utils.logging.set_verbosity_info()
     logger.info('Training/evaluation parameters %s'	,     SCREAMING_SNAKE_CASE_			)

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

     # Get the datasets:
     lowercase__    :   Optional[int]      =       datasets.load_dataset(
         'common_voice'	,     data_args.dataset_config_name	,     split=data_args.train_split_name			)
     lowercase__    :   Optional[Any]      =       datasets.load_dataset('common_voice'	,     data_args.dataset_config_name	,     split='test'			)

     # Create and save tokenizer
     lowercase__    :   Optional[int]      =       f"""[{"".join(data_args.chars_to_ignore			)}]"""

     def remove_special_characters(SCREAMING_SNAKE_CASE_		:    str			):
          lowercase__    :   Union[str, Any]      =       re.sub(SCREAMING_SNAKE_CASE_	,     ''	,     batch['sentence']			).lower() + ' '
          return batch

     lowercase__    :   str      =       train_dataset.map(SCREAMING_SNAKE_CASE_	,     remove_columns=['sentence']			)
     lowercase__    :   Any      =       eval_dataset.map(SCREAMING_SNAKE_CASE_	,     remove_columns=['sentence']			)

     def extract_all_chars(SCREAMING_SNAKE_CASE_		:    Tuple			):
          lowercase__    :   List[Any]      =       ' '.join(batch['text']			)
          lowercase__    :   Optional[int]      =       list(set(SCREAMING_SNAKE_CASE_			)			)
          return {"vocab": [vocab], "all_text": [all_text]}

     lowercase__    :   Union[str, Any]      =       train_dataset.map(
         SCREAMING_SNAKE_CASE_	,     batched=SCREAMING_SNAKE_CASE_	,     batch_size=-1	,     keep_in_memory=SCREAMING_SNAKE_CASE_	,     remove_columns=train_dataset.column_names	,     )
     lowercase__    :   Optional[Any]      =       train_dataset.map(
         SCREAMING_SNAKE_CASE_	,     batched=SCREAMING_SNAKE_CASE_	,     batch_size=-1	,     keep_in_memory=SCREAMING_SNAKE_CASE_	,     remove_columns=eval_dataset.column_names	,     )

     lowercase__    :   Optional[Any]      =       list(set(vocab_train['vocab'][0]			) | set(vocab_test['vocab'][0]			)			)
     lowercase__    :   List[Any]      =       {v: k for k, v in enumerate(SCREAMING_SNAKE_CASE_			)}
     lowercase__    :   List[str]      =       vocab_dict[' ']
     del vocab_dict[" "]
     lowercase__    :   Tuple      =       len(SCREAMING_SNAKE_CASE_			)
     lowercase__    :   Dict      =       len(SCREAMING_SNAKE_CASE_			)

     with open('vocab.json'	,     'w'			) as vocab_file:
          json.dump(SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_			)

     # Load pretrained model and tokenizer
     #
     # Distributed training:
     # The .from_pretrained methods guarantee that only one local process can concurrently
     # download model & vocab.
     lowercase__    :   List[Any]      =       WavaVecaCTCTokenizer(
         'vocab.json'	,     unk_token='[UNK]'	,     pad_token='[PAD]'	,     word_delimiter_token='|'	,     )
     lowercase__    :   int      =       WavaVecaFeatureExtractor(
         feature_size=1	,     sampling_rate=16_000	,     padding_value=0.0	,     do_normalize=SCREAMING_SNAKE_CASE_	,     return_attention_mask=SCREAMING_SNAKE_CASE_			)
     lowercase__    :   int      =       WavaVecaProcessor(feature_extractor=SCREAMING_SNAKE_CASE_	,     tokenizer=SCREAMING_SNAKE_CASE_			)
     lowercase__    :   List[Any]      =       WavaVecaForCTC.from_pretrained(
         model_args.model_name_or_path	,     cache_dir=model_args.cache_dir	,     activation_dropout=model_args.activation_dropout	,     attention_dropout=model_args.attention_dropout	,     hidden_dropout=model_args.hidden_dropout	,     feat_proj_dropout=model_args.feat_proj_dropout	,     mask_time_prob=model_args.mask_time_prob	,     gradient_checkpointing=training_args.gradient_checkpointing	,     layerdrop=model_args.layerdrop	,     ctc_loss_reduction='mean'	,     pad_token_id=processor.tokenizer.pad_token_id	,     vocab_size=len(processor.tokenizer			)	,     )

     if data_args.max_train_samples is not None:
          lowercase__    :   int      =       min(len(SCREAMING_SNAKE_CASE_			)	,     data_args.max_train_samples			)
          lowercase__    :   Optional[int]      =       train_dataset.select(range(SCREAMING_SNAKE_CASE_			)			)

     if data_args.max_val_samples is not None:
          lowercase__    :   List[Any]      =       eval_dataset.select(range(data_args.max_val_samples			)			)

     lowercase__    :   str      =       torchaudio.transforms.Resample(48_000	,     16_000			)

     # Preprocessing the datasets.
     # We need to read the aduio files as arrays and tokenize the targets.
     def speech_file_to_array_fn(SCREAMING_SNAKE_CASE_		:    str			):
          lowercase__      , lowercase__    :   List[str]      =       torchaudio.load(batch['path']			)
          lowercase__    :   Optional[int]      =       resampler(SCREAMING_SNAKE_CASE_			).squeeze().numpy()
          lowercase__    :   Dict      =       16_000
          lowercase__    :   Union[str, Any]      =       batch['text']
          return batch

     lowercase__    :   Optional[int]      =       train_dataset.map(
         SCREAMING_SNAKE_CASE_	,     remove_columns=train_dataset.column_names	,     num_proc=data_args.preprocessing_num_workers	,     )
     lowercase__    :   Union[str, Any]      =       eval_dataset.map(
         SCREAMING_SNAKE_CASE_	,     remove_columns=eval_dataset.column_names	,     num_proc=data_args.preprocessing_num_workers	,     )

     def prepare_dataset(SCREAMING_SNAKE_CASE_		:    Union[str, Any]			):
          # check that all files have the correct sampling rate
          assert (
              len(set(batch['sampling_rate']			)			) == 1
          ), f"""Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}."""

          lowercase__    :   Dict      =       processor(
              audio=batch['speech']	,     text=batch['target_text']	,     sampling_rate=batch['sampling_rate'][0]			)
          batch.update(SCREAMING_SNAKE_CASE_			)
          return batch

     lowercase__    :   int      =       train_dataset.map(
         SCREAMING_SNAKE_CASE_	,     remove_columns=train_dataset.column_names	,     batch_size=training_args.per_device_train_batch_size	,     batched=SCREAMING_SNAKE_CASE_	,     num_proc=data_args.preprocessing_num_workers	,     )
     lowercase__    :   Union[str, Any]      =       eval_dataset.map(
         SCREAMING_SNAKE_CASE_	,     remove_columns=eval_dataset.column_names	,     batch_size=training_args.per_device_train_batch_size	,     batched=SCREAMING_SNAKE_CASE_	,     num_proc=data_args.preprocessing_num_workers	,     )

     # Metric
     lowercase__    :   str      =       datasets.load_metric('wer'			)

     def compute_metrics(SCREAMING_SNAKE_CASE_		:    str			):
          lowercase__    :   List[str]      =       pred.predictions
          lowercase__    :   Tuple      =       np.argmax(SCREAMING_SNAKE_CASE_	,     axis=-1			)

          lowercase__    :   str      =       processor.tokenizer.pad_token_id

          lowercase__    :   Dict      =       processor.batch_decode(SCREAMING_SNAKE_CASE_			)
          # we do not want to group tokens when computing the metrics
          lowercase__    :   Dict      =       processor.batch_decode(pred.label_ids	,     group_tokens=SCREAMING_SNAKE_CASE_			)

          lowercase__    :   Optional[int]      =       wer_metric.compute(predictions=SCREAMING_SNAKE_CASE_	,     references=SCREAMING_SNAKE_CASE_			)

          return {"wer": wer}

     if model_args.freeze_feature_extractor:
          model.freeze_feature_extractor()

     # Data collator
     lowercase__    :   Tuple      =       DataCollatorCTCWithPadding(processor=SCREAMING_SNAKE_CASE_	,     padding=SCREAMING_SNAKE_CASE_			)

     # Initialize our Trainer
     lowercase__    :   Tuple      =       CTCTrainer(
         model=SCREAMING_SNAKE_CASE_	,     data_collator=SCREAMING_SNAKE_CASE_	,     args=SCREAMING_SNAKE_CASE_	,     compute_metrics=SCREAMING_SNAKE_CASE_	,     train_dataset=train_dataset if training_args.do_train else None	,     eval_dataset=eval_dataset if training_args.do_eval else None	,     tokenizer=processor.feature_extractor	,     )

     # Training
     if training_args.do_train:
          if last_checkpoint is not None:
               lowercase__    :   Optional[int]      =       last_checkpoint
          elif os.path.isdir(model_args.model_name_or_path			):
               lowercase__    :   Tuple      =       model_args.model_name_or_path
          else:
               lowercase__    :   Union[str, Any]      =       None

          # Save the feature_extractor and the tokenizer
          if is_main_process(training_args.local_rank			):
               processor.save_pretrained(training_args.output_dir			)

          lowercase__    :   str      =       trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE_			)
          trainer.save_model()

          lowercase__    :   Optional[Any]      =       train_result.metrics
          lowercase__    :   Optional[Any]      =       (
              data_args.max_train_samples if data_args.max_train_samples is not None else len(SCREAMING_SNAKE_CASE_			)
          )
          lowercase__    :   Optional[Any]      =       min(SCREAMING_SNAKE_CASE_	,     len(SCREAMING_SNAKE_CASE_			)			)

          trainer.log_metrics('train'	,     SCREAMING_SNAKE_CASE_			)
          trainer.save_metrics('train'	,     SCREAMING_SNAKE_CASE_			)
          trainer.save_state()

     # Evaluation
     lowercase__    :   List[str]      =       {}
     if training_args.do_eval:
          logger.info('*** Evaluate ***'			)
          lowercase__    :   Any      =       trainer.evaluate()
          lowercase__    :   Union[str, Any]      =       data_args.max_val_samples if data_args.max_val_samples is not None else len(SCREAMING_SNAKE_CASE_			)
          lowercase__    :   Dict      =       min(SCREAMING_SNAKE_CASE_	,     len(SCREAMING_SNAKE_CASE_			)			)

          trainer.log_metrics('eval'	,     SCREAMING_SNAKE_CASE_			)
          trainer.save_metrics('eval'	,     SCREAMING_SNAKE_CASE_			)

     return results


if __name__ == "__main__":
       main()




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.models.esm.modeling_esmfold import EsmForProteinFolding


class       SCREAMING_SNAKE_CASE__					:





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





    def       snake_case_				(      self):
         lowercase__    :   List[Any]      =       ids_tensor([self.batch_size, self.seq_length]						,   self.vocab_size)

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

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

         lowercase__    :   int      =       self.get_config()

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





    def       snake_case_				(      self):
         lowercase__    :   str      =       EsmConfig(
             vocab_size=33						,   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						,   is_folding_model=a						,   esmfold_config={'trunk': {'num_blocks': 2}, 'fp16_esm': False}						,   )
         return config





    def       snake_case_				(      self						,   a						,   a						,   a						,   a						,   a						,   a):
         lowercase__    :   Dict      =       EsmForProteinFolding(config=a).float()
         model.to(a)
         model.eval()
         lowercase__    :   Union[str, Any]      =       model(a						,   attention_mask=a)
         lowercase__    :   Dict      =       model(a)
         lowercase__    :   int      =       model(a)

         self.parent.assertEqual(result.positions.shape						,   (8, self.batch_size, self.seq_length, 14, 3))
         self.parent.assertEqual(result.angles.shape						,   (8, self.batch_size, self.seq_length, 7, 2))





    def       snake_case_				(      self):
         lowercase__    :   List[str]      =       self.prepare_config_and_inputs()
         (
             (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , 
         )    :   int      =       config_and_inputs
         lowercase__    :   Optional[int]      =       {'input_ids': input_ids, 'attention_mask': input_mask}
         return config, inputs_dict



@require_torch
class       SCREAMING_SNAKE_CASE__					(__snake_case		,       __snake_case		,       unittest.TestCase     ):
    __lowerCamelCase						:       Dict														=     False

    __lowerCamelCase						:       Dict														=     (EsmForProteinFolding,) if is_torch_available() else ()
    __lowerCamelCase						:       Union[str, Any]														=     ()
    __lowerCamelCase						:       List[Any]														=     {} if is_torch_available() else {}
    __lowerCamelCase						:       Optional[Any]														=     False





    def       snake_case_				(      self):
         lowercase__    :   Tuple      =       EsmFoldModelTester(self)
         lowercase__    :   List[Any]      =       ConfigTester(self						,   config_class=a						,   hidden_size=37)





    def       snake_case_				(      self):
         self.config_tester.run_common_tests()





    def       snake_case_				(      self):
         lowercase__    :   Optional[int]      =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*a)





    @unittest.skip('Does not support attention outputs')
    def       snake_case_				(      self):
         pass





    @unittest.skip
    def       snake_case_				(      self):
         pass





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





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





    @unittest.skip('ESMFold does not support passing input embeds!')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold does not support head pruning.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold does not support head pruning.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold does not support head pruning.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold does not support head pruning.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold does not support head pruning.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold does not output hidden states in the normal way.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMfold does not output hidden states in the normal way.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold only has one output format.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('This test doesn\'t work for ESMFold and doesn\'t test core functionality')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold does not support input chunking.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold doesn\'t respect you and it certainly doesn\'t respect your initialization arguments.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold doesn\'t support torchscript compilation.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold doesn\'t support torchscript compilation.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold doesn\'t support torchscript compilation.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold doesn\'t support data parallel.')
    def       snake_case_				(      self):
         pass





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



@require_torch
class       SCREAMING_SNAKE_CASE__					(__snake_case     ):





    @slow
    def       snake_case_				(      self):
         lowercase__    :   Dict      =       EsmForProteinFolding.from_pretrained('facebook/esmfold_v1').float()
         model.eval()
         lowercase__    :   Optional[Any]      =       torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]])
         lowercase__    :   Optional[int]      =       model(a)['positions']
         lowercase__    :   Dict      =       torch.tensor([2.5_828, 0.7_993, -10.9_334]						,   dtype=torch.floataa)
         self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0]						,   a						,   atol=1e-4))

