


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 _lowerCamelCase:
       def __init__(      self,   lowerCamelCase,   lowerCamelCase=13,   lowerCamelCase=7,   lowerCamelCase=False,   lowerCamelCase=True,   lowerCamelCase=False,   lowerCamelCase=False,   lowerCamelCase=19,   lowerCamelCase=32,   lowerCamelCase=5,   lowerCamelCase=4,   lowerCamelCase=37,   lowerCamelCase="gelu",   lowerCamelCase=0.1,   lowerCamelCase=0.1,   lowerCamelCase=5_12,   lowerCamelCase=16,   lowerCamelCase=2,   lowerCamelCase=0.0_2,   lowerCamelCase=3,   lowerCamelCase=4,   lowerCamelCase=None,   ) ->     Optional[Any]:




           """simple docstring"""

           _lowercase :							Tuple   	=	parent
           _lowercase :							Tuple   	=	batch_size
           _lowercase :							List[str]   	=	seq_length
           _lowercase :							int   	=	is_training
           _lowercase :							Union[str, Any]   	=	use_input_mask
           _lowercase :							Union[str, Any]   	=	use_token_type_ids
           _lowercase :							Union[str, Any]   	=	use_labels
           _lowercase :							Tuple   	=	vocab_size
           _lowercase :							Union[str, Any]   	=	hidden_size
           _lowercase :							Dict   	=	num_hidden_layers
           _lowercase :							str   	=	num_attention_heads
           _lowercase :							str   	=	intermediate_size
           _lowercase :							Union[str, Any]   	=	hidden_act
           _lowercase :							str   	=	hidden_dropout_prob
           _lowercase :							Optional[Any]   	=	attention_probs_dropout_prob
           _lowercase :							Any   	=	max_position_embeddings
           _lowercase :							List[str]   	=	type_vocab_size
           _lowercase :							Any   	=	type_sequence_label_size
           _lowercase :							Dict   	=	initializer_range
           _lowercase :							Tuple   	=	num_labels
           _lowercase :							List[str]   	=	num_choices
           _lowercase :							Optional[Any]   	=	scope
       def     UpperCamelCase  (      self) ->     Optional[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 :							Tuple   	=	None
           _lowercase :							List[str]   	=	None
           _lowercase :							Tuple   	=	None
           if self.use_labels:
               _lowercase :							List[Any]   	=	ids_tensor([self.batch_size],   self.type_sequence_label_size)
               _lowercase :							Dict   	=	ids_tensor([self.batch_size, self.seq_length],   self.num_labels)
               _lowercase :							List[str]   	=	ids_tensor([self.batch_size],   self.num_choices)

           _lowercase :							Tuple   	=	self.get_config()

           return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
       def     UpperCamelCase  (      self) ->     str:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	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=lowerCamelCase,   esmfold_config={'trunk': {'num_blocks': 2}, 'fp16_esm': False},   )
           return config
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     Optional[int]:




           """simple docstring"""

           _lowercase :							Tuple   	=	EsmForProteinFolding(config=lowerCamelCase).float()
           model.to(lowerCamelCase)
           model.eval()
           _lowercase :							Optional[int]   	=	model(lowerCamelCase,   attention_mask=lowerCamelCase)
           _lowercase :							str   	=	model(lowerCamelCase)
           _lowercase :							Optional[int]   	=	model(lowerCamelCase)

           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     UpperCamelCase  (      self) ->     Any:




           """simple docstring"""

           _lowercase :							List[Any]   	=	self.prepare_config_and_inputs()
           (
               (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       
           ) :							str   	=	config_and_inputs
           _lowercase :							int   	=	{'input_ids': input_ids, 'attention_mask': input_mask}
           return config, inputs_dict






@require_torch
class _lowerCamelCase(		_a,				_a,				unittest.TestCase     ):
       lowercase_				:			List[Any]									=    False

       lowercase_				:			Union[str, Any]									=    (EsmForProteinFolding,) if is_torch_available() else ()
       lowercase_				:			Dict									=    ()
       lowercase_				:			Dict									=    {} if is_torch_available() else {}
       lowercase_				:			Tuple									=    False
       def     UpperCamelCase  (      self) ->     str:




           """simple docstring"""

           _lowercase :							Any   	=	EsmFoldModelTester(self)
           _lowercase :							Tuple   	=	ConfigTester(self,   config_class=lowerCamelCase,   hidden_size=37)
       def     UpperCamelCase  (      self) ->     str:




           """simple docstring"""

           self.config_tester.run_common_tests()
       def     UpperCamelCase  (      self) ->     Tuple:




           """simple docstring"""

           _lowercase :							Union[str, Any]   	=	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowerCamelCase)
       @unittest.skip('Does not support attention outputs')
       def     UpperCamelCase  (      self) ->     Optional[int]:




           """simple docstring"""

           pass
       @unittest.skip
       def     UpperCamelCase  (      self) ->     List[str]:




           """simple docstring"""

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




           """simple docstring"""

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




           """simple docstring"""

           pass
       @unittest.skip('ESMFold does not support passing input embeds!')
       def     UpperCamelCase  (      self) ->     List[Any]:




           """simple docstring"""

           pass
       @unittest.skip('ESMFold does not support head pruning.')
       def     UpperCamelCase  (      self) ->     Tuple:




           """simple docstring"""

           pass
       @unittest.skip('ESMFold does not support head pruning.')
       def     UpperCamelCase  (      self) ->     List[Any]:




           """simple docstring"""

           pass
       @unittest.skip('ESMFold does not support head pruning.')
       def     UpperCamelCase  (      self) ->     int:




           """simple docstring"""

           pass
       @unittest.skip('ESMFold does not support head pruning.')
       def     UpperCamelCase  (      self) ->     Any:




           """simple docstring"""

           pass
       @unittest.skip('ESMFold does not support head pruning.')
       def     UpperCamelCase  (      self) ->     Optional[int]:




           """simple docstring"""

           pass
       @unittest.skip('ESMFold does not output hidden states in the normal way.')
       def     UpperCamelCase  (      self) ->     List[Any]:




           """simple docstring"""

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




           """simple docstring"""

           pass
       @unittest.skip('ESMFold only has one output format.')
       def     UpperCamelCase  (      self) ->     str:




           """simple docstring"""

           pass
       @unittest.skip('This test doesn\'t work for ESMFold and doesn\'t test core functionality')
       def     UpperCamelCase  (      self) ->     Optional[int]:




           """simple docstring"""

           pass
       @unittest.skip('ESMFold does not support input chunking.')
       def     UpperCamelCase  (      self) ->     Optional[int]:




           """simple docstring"""

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




           """simple docstring"""

           pass
       @unittest.skip('ESMFold doesn\'t support torchscript compilation.')
       def     UpperCamelCase  (      self) ->     int:




           """simple docstring"""

           pass
       @unittest.skip('ESMFold doesn\'t support torchscript compilation.')
       def     UpperCamelCase  (      self) ->     Dict:




           """simple docstring"""

           pass
       @unittest.skip('ESMFold doesn\'t support torchscript compilation.')
       def     UpperCamelCase  (      self) ->     Optional[Any]:




           """simple docstring"""

           pass
       @unittest.skip('ESMFold doesn\'t support data parallel.')
       def     UpperCamelCase  (      self) ->     str:




           """simple docstring"""

           pass




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




           """simple docstring"""

           pass






@require_torch
class _lowerCamelCase(		_a     ):
       @slow
       def     UpperCamelCase  (      self) ->     Tuple:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	EsmForProteinFolding.from_pretrained('facebook/esmfold_v1').float()
           model.eval()
           _lowercase :							Union[str, Any]   	=	torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]])
           _lowercase :							Any   	=	model(lowerCamelCase)['positions']
           _lowercase :							Union[str, Any]   	=	torch.tensor([2.5_8_2_8, 0.7_9_9_3, -1_0.9_3_3_4],   dtype=torch.floataa)
           self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0],   lowerCamelCase,   atol=1E-4))






import dataclasses
import json
import warnings
from dataclasses import dataclass, field
from time import time
from typing import List

from ..utils import logging


SCREAMING_SNAKE_CASE :   Dict							      =				logging.get_logger(__name__)



def        UpperCamelCase_(   lowerCamelCase_=None							,				lowerCamelCase_=None				)					->		Tuple:
    return field(default_factory=lambda: default							,				metadata=lowerCamelCase_				)






@dataclass
class _lowerCamelCase:
       lowercase_				:			List[str]									=    list_field(
           default=[],				metadata={
               """help""": (
                   """Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version"""
                   """ of all available models"""
               )
           },				)

       lowercase_				:			List[int]									=    list_field(
           default=[8],				metadata={"""help""": """List of batch sizes for which memory and time performance will be evaluated"""}     )

       lowercase_				:			List[int]									=    list_field(
           default=[8, 32, 1_28, 5_12],				metadata={"""help""": """List of sequence lengths for which memory and time performance will be evaluated"""},				)

       lowercase_				:			bool									=    field(
           default=_a,				metadata={"""help""": """Whether to benchmark inference of model. Inference can be disabled via --no-inference."""},				)
       lowercase_				:			bool									=    field(
           default=_a,				metadata={"""help""": """Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."""},				)
       lowercase_				:			bool									=    field(
           default=_a,				metadata={"""help""": """Whether to run on available tpu devices. TPU can be disabled via --no-tpu."""}     )
       lowercase_				:			bool									=    field(default=_a,				metadata={"""help""": """Use FP16 to accelerate inference."""}     )
       lowercase_				:			bool									=    field(default=_a,				metadata={"""help""": """Benchmark training of model"""}     )
       lowercase_				:			bool									=    field(default=_a,				metadata={"""help""": """Verbose memory tracing"""}     )
       lowercase_				:			bool									=    field(
           default=_a,				metadata={"""help""": """Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."""},				)
       lowercase_				:			bool									=    field(
           default=_a,				metadata={
               """help""": """Whether to perform memory measurements. Memory measurements can be disabled via --no-memory"""
           },				)
       lowercase_				:			bool									=    field(default=_a,				metadata={"""help""": """Trace memory line by line"""}     )
       lowercase_				:			bool									=    field(default=_a,				metadata={"""help""": """Save result to a CSV file"""}     )
       lowercase_				:			bool									=    field(default=_a,				metadata={"""help""": """Save all print statements in a log file"""}     )
       lowercase_				:			bool									=    field(default=_a,				metadata={"""help""": """Whether to print environment information"""}     )
       lowercase_				:			bool									=    field(
           default=_a,				metadata={
               """help""": (
                   """Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use"""
                   """ multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled"""
                   """ for debugging / testing and on TPU."""
               )
           },				)
       lowercase_				:			str									=    field(
           default=F'''inference_time_{round(time()     )}.csv''',				metadata={"""help""": """CSV filename used if saving time results to csv."""},				)
       lowercase_				:			str									=    field(
           default=F'''inference_memory_{round(time()     )}.csv''',				metadata={"""help""": """CSV filename used if saving memory results to csv."""},				)
       lowercase_				:			str									=    field(
           default=F'''train_time_{round(time()     )}.csv''',				metadata={"""help""": """CSV filename used if saving time results to csv for training."""},				)
       lowercase_				:			str									=    field(
           default=F'''train_memory_{round(time()     )}.csv''',				metadata={"""help""": """CSV filename used if saving memory results to csv for training."""},				)
       lowercase_				:			str									=    field(
           default=F'''env_info_{round(time()     )}.csv''',				metadata={"""help""": """CSV filename used if saving environment information."""},				)
       lowercase_				:			str									=    field(
           default=F'''log_{round(time()     )}.csv''',				metadata={"""help""": """Log filename used if print statements are saved in log."""},				)
       lowercase_				:			int									=    field(default=3,				metadata={"""help""": """Times an experiment will be run."""}     )
       lowercase_				:			bool									=    field(
           default=_a,				metadata={
               """help""": (
                   """Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain"""
                   """ model weights."""
               )
           },				)
       def     UpperCamelCase  (      self) ->     Union[str, Any]:




           """simple docstring"""

           warnings.warn(
               F'''The class {self.__class__} is deprecated. Hugging Face Benchmarking utils'''
               ' are deprecated in general and it is advised to use external Benchmarking libraries '
               ' to benchmark Transformer models.',   lowerCamelCase,   )
       def     UpperCamelCase  (      self) ->     Optional[Any]:




           """simple docstring"""

           return json.dumps(dataclasses.asdict(self),   indent=2)
       @property
       def     UpperCamelCase  (      self) ->     List[str]:




           """simple docstring"""

           if len(self.models) <= 0:
               raise ValueError(
                   'Please make sure you provide at least one model name / model identifier, *e.g.* `--models'
                   ' bert-base-cased` or `args.models = [\'bert-base-cased\'].')
           return self.models




       @property
       def     UpperCamelCase  (      self) ->     Dict:




           """simple docstring"""

           if not self.multi_process:
               return False
           elif self.is_tpu:
               logger.info('Multiprocessing is currently not possible on TPU.')
               return False
           else:
               return True


