


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







class _lowerCAmelCase				:







   def __init__(	self						,	UpperCamelCase__						,	UpperCamelCase__=13						,	UpperCamelCase__=7						,	UpperCamelCase__=False						,	UpperCamelCase__=True						,	UpperCamelCase__=False						,	UpperCamelCase__=False						,	UpperCamelCase__=19						,	UpperCamelCase__=32						,	UpperCamelCase__=5						,	UpperCamelCase__=4						,	UpperCamelCase__=37						,	UpperCamelCase__="gelu"						,	UpperCamelCase__=0.1						,	UpperCamelCase__=0.1						,	UpperCamelCase__=512						,	UpperCamelCase__=16						,	UpperCamelCase__=2						,	UpperCamelCase__=0.02						,	UpperCamelCase__=3						,	UpperCamelCase__=4						,	UpperCamelCase__=None						,	)	->		Any:

       '''simple docstring'''




       snake_case    :      Dict      					=    parent
       snake_case    :      List[str]      					=    batch_size
       snake_case    :      str      					=    seq_length
       snake_case    :      Tuple      					=    is_training
       snake_case    :      Tuple      					=    use_input_mask
       snake_case    :      int      					=    use_token_type_ids
       snake_case    :      str      					=    use_labels
       snake_case    :      Optional[int]      					=    vocab_size
       snake_case    :      Union[str, Any]      					=    hidden_size
       snake_case    :      Optional[int]      					=    num_hidden_layers
       snake_case    :      int      					=    num_attention_heads
       snake_case    :      Optional[int]      					=    intermediate_size
       snake_case    :      Any      					=    hidden_act
       snake_case    :      Dict      					=    hidden_dropout_prob
       snake_case    :      Any      					=    attention_probs_dropout_prob
       snake_case    :      Optional[Any]      					=    max_position_embeddings
       snake_case    :      List[Any]      					=    type_vocab_size
       snake_case    :      Dict      					=    type_sequence_label_size
       snake_case    :      int      					=    initializer_range
       snake_case    :      int      					=    num_labels
       snake_case    :      Any      					=    num_choices
       snake_case    :      Any      					=    scope







   def  lowerCamelCase		(	self						)	->		int:

       '''simple docstring'''




       snake_case    :      Tuple      					=    ids_tensor([self.batch_size, self.seq_length]						,	self.vocab_size						)

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

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

       snake_case    :      Tuple      					=    self.get_config()

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







   def  lowerCamelCase		(	self						)	->		Optional[int]:

       '''simple docstring'''




       snake_case    :      List[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=UpperCamelCase__						,	esmfold_config={"trunk": {"num_blocks": 2}, "fp16_esm": False}						,	)
       return config







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

       '''simple docstring'''




       snake_case    :      Any      					=    EsmForProteinFolding(config=UpperCamelCase__						).float()
       model.to(UpperCamelCase__						)
       model.eval()
       snake_case    :      List[Any]      					=    model(UpperCamelCase__						,	attention_mask=UpperCamelCase__						)
       snake_case    :      List[str]      					=    model(UpperCamelCase__						)
       snake_case    :      Optional[Any]      					=    model(UpperCamelCase__						)

       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  lowerCamelCase		(	self						)	->		Optional[int]:

       '''simple docstring'''




       snake_case    :      Any      					=    self.prepare_config_and_inputs()
       (
           (
           snake_case
       )					,(
           snake_case
       )					,(
           snake_case
       )					,(
           snake_case
       )					,(
           snake_case
       )					,(
           snake_case
       )					,
       )    :      Union[str, Any]      					=    config_and_inputs
       snake_case    :      str      					=    {"input_ids": input_ids, "attention_mask": input_mask}
       return config, inputs_dict







@require_torch
class _lowerCAmelCase				(      snake_case_    ,							snake_case_    ,							unittest.TestCase	):
   __UpperCAmelCase :       Tuple							  =  False

   __UpperCAmelCase :       List[Any]							  =  (EsmForProteinFolding,) if is_torch_available() else ()
   __UpperCAmelCase :       Optional[Any]							  =  ()
   __UpperCAmelCase :       Dict							  =  {} if is_torch_available() else {}
   __UpperCAmelCase :       Tuple							  =  False







   def  lowerCamelCase		(	self						)	->		Optional[int]:

       '''simple docstring'''




       snake_case    :      Dict      					=    EsmFoldModelTester(self						)
       snake_case    :      str      					=    ConfigTester(self						,	config_class=UpperCamelCase__						,	hidden_size=37						)







   def  lowerCamelCase		(	self						)	->		int:

       '''simple docstring'''




       self.config_tester.run_common_tests()







   def  lowerCamelCase		(	self						)	->		Optional[Any]:

       '''simple docstring'''




       snake_case    :      Any      					=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCamelCase__						)







   @unittest.skip("Does not support attention outputs"						)
   def  lowerCamelCase		(	self						)	->		Tuple:

       '''simple docstring'''




       pass







   @unittest.skip
   def  lowerCamelCase		(	self						)	->		Dict:

       '''simple docstring'''




       pass







   @unittest.skip("Esm does not support embedding resizing"						)
   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       pass







   @unittest.skip("Esm does not support embedding resizing"						)
   def  lowerCamelCase		(	self						)	->		int:

       '''simple docstring'''




       pass







   @unittest.skip("ESMFold does not support passing input embeds!"						)
   def  lowerCamelCase		(	self						)	->		List[str]:

       '''simple docstring'''




       pass







   @unittest.skip("ESMFold does not support head pruning."						)
   def  lowerCamelCase		(	self						)	->		List[str]:

       '''simple docstring'''




       pass







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

       '''simple docstring'''




       pass







   @unittest.skip("ESMFold does not support head pruning."						)
   def  lowerCamelCase		(	self						)	->		Tuple:

       '''simple docstring'''




       pass







   @unittest.skip("ESMFold does not support head pruning."						)
   def  lowerCamelCase		(	self						)	->		List[str]:

       '''simple docstring'''




       pass







   @unittest.skip("ESMFold does not support head pruning."						)
   def  lowerCamelCase		(	self						)	->		int:

       '''simple docstring'''




       pass







   @unittest.skip("ESMFold does not output hidden states in the normal way."						)
   def  lowerCamelCase		(	self						)	->		int:

       '''simple docstring'''




       pass







   @unittest.skip("ESMfold does not output hidden states in the normal way."						)
   def  lowerCamelCase		(	self						)	->		List[Any]:

       '''simple docstring'''




       pass







   @unittest.skip("ESMFold only has one output format."						)
   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       pass







   @unittest.skip("This test doesn't work for ESMFold and doesn't test core functionality"						)
   def  lowerCamelCase		(	self						)	->		Optional[Any]:

       '''simple docstring'''




       pass







   @unittest.skip("ESMFold does not support input chunking."						)
   def  lowerCamelCase		(	self						)	->		Union[str, Any]:

       '''simple docstring'''




       pass







   @unittest.skip("ESMFold doesn't respect you and it certainly doesn't respect your initialization arguments."						)
   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       pass







   @unittest.skip("ESMFold doesn't support torchscript compilation."						)
   def  lowerCamelCase		(	self						)	->		Any:

       '''simple docstring'''




       pass







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

       '''simple docstring'''




       pass







   @unittest.skip("ESMFold doesn't support torchscript compilation."						)
   def  lowerCamelCase		(	self						)	->		Any:

       '''simple docstring'''




       pass







   @unittest.skip("ESMFold doesn't support data parallel."						)
   def  lowerCamelCase		(	self						)	->		Any:

       '''simple docstring'''




       pass







   @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."						)
   def  lowerCamelCase		(	self						)	->		List[str]:

       '''simple docstring'''




       pass







@require_torch
class _lowerCAmelCase				(      snake_case_	):







   @slow
   def  lowerCamelCase		(	self						)	->		Optional[Any]:

       '''simple docstring'''




       snake_case    :      Dict      					=    EsmForProteinFolding.from_pretrained("facebook/esmfold_v1"						).float()
       model.eval()
       snake_case    :      Any      					=    torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]						)
       snake_case    :      Union[str, Any]      					=    model(UpperCamelCase__						)["positions"]
       snake_case    :      Optional[int]      					=    torch.tensor([2.5828, 0.7993, -10.9334]						,	dtype=torch.floataa						)
       self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0]						,	UpperCamelCase__						,	atol=1e-4						)						)









"""simple docstring"""



import importlib.util
import json
import os
import warnings
from dataclasses import dataclass, field

import torch

from ..training_args import TrainingArguments
from ..utils import cached_property, is_sagemaker_dp_enabled, logging


__snake_case   			=    logging.get_logger(__name__)







def   __lowerCAmelCase						(						)	->						str:


    """simple docstring"""





    snake_case    :      Dict      					=    os.getenv("SM_HP_MP_PARAMETERS"						,							"{}" )
    try:
        # Parse it and check the field "partitions" is included, it is required for model parallel.
        snake_case    :      Optional[int]      					=    json.loads(lowercase )
        if "partitions" not in smp_options:
            return False
    except json.JSONDecodeError:
        return False

    # Get the sagemaker specific framework parameters from mpi_options variable.
    snake_case    :      Optional[int]      					=    os.getenv("SM_FRAMEWORK_PARAMS"						,							"{}" )
    try:
        # Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
        snake_case    :      Any      					=    json.loads(lowercase )
        if not mpi_options.get("sagemaker_mpi_enabled"						,							lowercase ):
            return False
    except json.JSONDecodeError:
        return False
    # Lastly, check if the `smdistributed` module is present.
    return importlib.util.find_spec("smdistributed" ) is not None


if is_sagemaker_model_parallel_available():
  import smdistributed.modelparallel.torch as smp

  smp.init()







@dataclass
class _lowerCAmelCase				(      snake_case_	):
   __UpperCAmelCase :       str							  =  field(
       default=''''''    ,							metadata={'''help''': '''Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer'''}    ,							)







   def  lowerCamelCase		(	self						)	->		List[Any]:

       '''simple docstring'''




       super().__post_init__()
       warnings.warn(
           "`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use "
           "`TrainingArguments` instead."						,	UpperCamelCase__						,	)







   @cached_property
   def  lowerCamelCase		(	self						)	->		"torch.device":

       '''simple docstring'''




       logger.info("PyTorch: setting up devices"						)
       if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1:
           logger.warning(
               "torch.distributed process group is initialized, but local_rank == -1. "
               "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch"						)
       if self.no_cuda:
           snake_case    :      Optional[Any]      					=    torch.device("cpu"						)
           snake_case    :      List[Any]      					=    0
       elif is_sagemaker_model_parallel_available():
           snake_case    :      Tuple      					=    smp.local_rank()
           snake_case    :      int      					=    torch.device("cuda"						,	UpperCamelCase__						)
           snake_case    :      Dict      					=    1
       elif is_sagemaker_dp_enabled():
           import smdistributed.dataparallel.torch.torch_smddp  # noqa: F401

           torch.distributed.init_process_group(backend="smddp"						,	timeout=self.ddp_timeout_delta						)
           snake_case    :      Any      					=    int(os.getenv("SMDATAPARALLEL_LOCAL_RANK"						)						)
           snake_case    :      Optional[Any]      					=    torch.device("cuda"						,	self.local_rank						)
           snake_case    :      str      					=    1
       elif self.local_rank == -1:
           # if n_gpu is > 1 we'll use nn.DataParallel.
           # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
           # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will
           # trigger an error that a device index is missing. Index 0 takes into account the
           # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0`
           # will use the first GPU in that env, i.e. GPU#1
           snake_case    :      List[str]      					=    torch.device("cuda:0" if torch.cuda.is_available() else "cpu"						)
           # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at
           # the default value.
           snake_case    :      Optional[Any]      					=    torch.cuda.device_count()
       else:
           # Here, we'll use torch.distributed.
           # Initializes the distributed backend which will take care of synchronizing nodes/GPUs
           if not torch.distributed.is_initialized():
               torch.distributed.init_process_group(backend="nccl"						,	timeout=self.ddp_timeout_delta						)
           snake_case    :      Any      					=    torch.device("cuda"						,	self.local_rank						)
           snake_case    :      Dict      					=    1

       if device.type == "cuda":
           torch.cuda.set_device(UpperCamelCase__						)

       return device







   @property
   def  lowerCamelCase		(	self						)	->		Optional[int]:

       '''simple docstring'''




       if is_sagemaker_model_parallel_available():
           return smp.dp_size()

       return super().world_size







   @property
   def  lowerCamelCase		(	self						)	->		List[str]:

       '''simple docstring'''




       return not is_sagemaker_model_parallel_available()







   @property
   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       return False





