




"""simple docstring"""







import copy
from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto.configuration_auto import AutoConfig


if TYPE_CHECKING:
						from ... import PreTrainedTokenizerBase, TensorType

__A   :  Union[str, Any]		=      logging.get_logger(__name__)




class       lowerCAmelCase__       (			UpperCAmelCase__    ):


				"""simple docstring"""





				__UpperCAmelCase :     str       =      'vision-encoder-decoder'
				__UpperCAmelCase :     Union[str, Any]       =      True



				def __init__(     self					:	Optional[Any]    ,   **lowercase__					:	int						):
						super().__init__(**lowercase__						)
						if "encoder" not in kwargs or "decoder" not in kwargs:
								raise ValueError(
								    f'A configuraton of type {self.model_type} cannot be instantiated because '
								    f'not both `encoder` and `decoder` sub-configurations are passed, but only {kwargs}'						)

						__lowercase				:		int												=				kwargs.pop("encoder"						)
						__lowercase				:		Optional[int]												=				encoder_config.pop("model_type"						)
						__lowercase				:		Union[str, Any]												=				kwargs.pop("decoder"						)
						__lowercase				:		str												=				decoder_config.pop("model_type"						)

						__lowercase				:		List[str]												=				AutoConfig.for_model(lowercase__    ,   **lowercase__						)
						__lowercase				:		Tuple												=				AutoConfig.for_model(lowercase__    ,   **lowercase__						)
						__lowercase				:		Optional[Any]												=				True



				@classmethod
				def       snake_case    (     cls					:	Tuple    ,   lowercase__					:	PretrainedConfig    ,   lowercase__					:	PretrainedConfig    ,   **lowercase__					:	Any						):
						logger.info("Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config"						)
						__lowercase				:		Any												=				True
						__lowercase				:		Optional[Any]												=				True

						return cls(encoder=encoder_config.to_dict()    ,   decoder=decoder_config.to_dict()    ,   **lowercase__						)



				def       snake_case    (     self					:	Optional[Any]						):
						__lowercase				:		Tuple												=				copy.deepcopy(self.__dict__						)
						__lowercase				:		List[Any]												=				self.encoder.to_dict()
						__lowercase				:		Tuple												=				self.decoder.to_dict()
						__lowercase				:		Union[str, Any]												=				self.__class__.model_type
						return output





class       lowerCAmelCase__       (			UpperCAmelCase__    ):


				"""simple docstring"""





				__UpperCAmelCase :     Any       =      version.parse("1.11"    )



				@property
				def       snake_case    (     self					:	Dict						):
						return OrderedDict(
						    [
						        ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
						    ]						)



				@property
				def       snake_case    (     self					:	int						):
						return 1e-4



				@property
				def       snake_case    (     self					:	List[Any]						):
						return OrderedDict({"last_hidden_state": {0: "batch", 1: "encoder_sequence"}}						)





class       lowerCAmelCase__       (			UpperCAmelCase__    ):


				"""simple docstring"""





				@property
				def       snake_case    (     self					:	Union[str, Any]						):
						__lowercase				:		Any												=				OrderedDict()
						__lowercase				:		Optional[Any]												=				{0: """batch""", 1: """past_decoder_sequence + sequence"""}
						__lowercase				:		Dict												=				{0: """batch""", 1: """past_decoder_sequence + sequence"""}
						__lowercase				:		int												=				{0: """batch""", 1: """encoder_sequence"""}

						return common_inputs



				def       snake_case    (     self					:	List[Any]    ,   lowercase__					:	"PreTrainedTokenizerBase"    ,   lowercase__					:	int = -1    ,   lowercase__					:	int = -1    ,   lowercase__					:	bool = False    ,   lowercase__					:	Optional["TensorType"] = None    ,   ):
						import torch

						__lowercase				:		Optional[Any]												=				OrderedDict()

						__lowercase				:		Dict												=				super().generate_dummy_inputs(
						    lowercase__    ,   batch_size=lowercase__    ,   seq_length=lowercase__    ,   is_pair=lowercase__    ,   framework=lowercase__						)

						__lowercase				:		int												=				dummy_input["""input_ids"""].shape
						__lowercase				:		Any												=				(batch, encoder_sequence, self._config.encoder_hidden_size)
						__lowercase				:		List[str]												=				dummy_input.pop("input_ids"						)
						__lowercase				:		Tuple												=				dummy_input.pop("attention_mask"						)
						__lowercase				:		Tuple												=				torch.zeros(lowercase__						)

						return common_inputs





class       lowerCAmelCase__       (			UpperCAmelCase__    ):


				"""simple docstring"""





				@property
				def       snake_case    (     self					:	Tuple						):
						pass



				def       snake_case    (     self					:	str    ,   lowercase__					:	PretrainedConfig						):
						return VisionEncoderDecoderEncoderOnnxConfig(lowercase__						)



				def       snake_case    (     self					:	Dict    ,   lowercase__					:	PretrainedConfig    ,   lowercase__					:	PretrainedConfig    ,   lowercase__					:	str = "default"						):
						__lowercase				:		int												=				encoder_config.hidden_size
						return VisionEncoderDecoderDecoderOnnxConfig(lowercase__    ,   lowercase__						)






"""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__       :


				"""simple docstring"""





				def __init__(     self					:	Tuple    ,   lowercase__					:	Tuple    ,   lowercase__					:	Tuple=1_3    ,   lowercase__					:	Optional[int]=7    ,   lowercase__					:	List[str]=False    ,   lowercase__					:	Tuple=True    ,   lowercase__					:	int=False    ,   lowercase__					:	List[str]=False    ,   lowercase__					:	Optional[Any]=1_9    ,   lowercase__					:	int=3_2    ,   lowercase__					:	List[Any]=5    ,   lowercase__					:	Optional[int]=4    ,   lowercase__					:	Any=3_7    ,   lowercase__					:	Tuple="gelu"    ,   lowercase__					:	int=0.1    ,   lowercase__					:	Tuple=0.1    ,   lowercase__					:	List[Any]=5_1_2    ,   lowercase__					:	List[Any]=1_6    ,   lowercase__					:	Union[str, Any]=2    ,   lowercase__					:	List[str]=0.0_2    ,   lowercase__					:	List[Any]=3    ,   lowercase__					:	Any=4    ,   lowercase__					:	Optional[Any]=None    ,   ):
						__lowercase				:		int												=				parent
						__lowercase				:		Tuple												=				batch_size
						__lowercase				:		Optional[int]												=				seq_length
						__lowercase				:		str												=				is_training
						__lowercase				:		List[Any]												=				use_input_mask
						__lowercase				:		Any												=				use_token_type_ids
						__lowercase				:		str												=				use_labels
						__lowercase				:		Dict												=				vocab_size
						__lowercase				:		Optional[int]												=				hidden_size
						__lowercase				:		List[Any]												=				num_hidden_layers
						__lowercase				:		int												=				num_attention_heads
						__lowercase				:		Union[str, Any]												=				intermediate_size
						__lowercase				:		Dict												=				hidden_act
						__lowercase				:		Union[str, Any]												=				hidden_dropout_prob
						__lowercase				:		Optional[int]												=				attention_probs_dropout_prob
						__lowercase				:		Optional[Any]												=				max_position_embeddings
						__lowercase				:		List[str]												=				type_vocab_size
						__lowercase				:		str												=				type_sequence_label_size
						__lowercase				:		List[str]												=				initializer_range
						__lowercase				:		Optional[Any]												=				num_labels
						__lowercase				:		Tuple												=				num_choices
						__lowercase				:		Optional[Any]												=				scope



				def       snake_case    (     self					:	Optional[int]						):
						__lowercase				:		Tuple												=				ids_tensor([self.batch_size, self.seq_length]    ,   self.vocab_size						)

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

						__lowercase				:		Dict												=				None
						__lowercase				:		Any												=				None
						__lowercase				:		Optional[Any]												=				None
						if self.use_labels:
								__lowercase				:		Tuple												=				ids_tensor([self.batch_size]    ,   self.type_sequence_label_size						)
								__lowercase				:		List[str]												=				ids_tensor([self.batch_size, self.seq_length]    ,   self.num_labels						)
								__lowercase				:		Optional[Any]												=				ids_tensor([self.batch_size]    ,   self.num_choices						)

						__lowercase				:		Optional[Any]												=				self.get_config()

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



				def       snake_case    (     self					:	Any						):
						__lowercase				:		Dict												=				EsmConfig(
						    vocab_size=3_3    ,   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=lowercase__    ,   esmfold_config={"trunk": {"num_blocks": 2}, "fp16_esm": False}    ,   )
						return config



				def       snake_case    (     self					:	str    ,   lowercase__					:	List[Any]    ,   lowercase__					:	Optional[int]    ,   lowercase__					:	List[Any]    ,   lowercase__					:	int    ,   lowercase__					:	List[Any]    ,   lowercase__					:	str						):
						__lowercase				:		List[Any]												=				EsmForProteinFolding(config=lowercase__						).float()
						model.to(lowercase__						)
						model.eval()
						__lowercase				:		List[str]												=				model(lowercase__    ,   attention_mask=lowercase__						)
						__lowercase				:		Any												=				model(lowercase__						)
						__lowercase				:		Any												=				model(lowercase__						)

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



				def       snake_case    (     self					:	Tuple						):
						__lowercase				:		List[str]												=				self.prepare_config_and_inputs()
						(
						    (
						    __lowercase
						)						,(
						    __lowercase
						)						,(
						    __lowercase
						)						,(
						    __lowercase
						)						,(
						    __lowercase
						)						,(
						    __lowercase
						)						,
						)				:		Any												=				config_and_inputs
						__lowercase				:		int												=				{"input_ids": input_ids, "attention_mask": input_mask}
						return config, inputs_dict





@require_torch
class       lowerCAmelCase__       (			lowerCAmelCase_  ,			lowerCAmelCase_  ,			unittest.TestCase    ):


				"""simple docstring"""





				__UpperCAmelCase :     Union[str, Any]       =      False

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



				def       snake_case    (     self					:	Tuple						):
						__lowercase				:		Tuple												=				EsmFoldModelTester(self						)
						__lowercase				:		Dict												=				ConfigTester(self    ,   config_class=lowercase__    ,   hidden_size=3_7						)



				def       snake_case    (     self					:	Dict						):
						self.config_tester.run_common_tests()



				def       snake_case    (     self					:	Optional[int]						):
						__lowercase				:		Tuple												=				self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*lowercase__						)



				@unittest.skip("Does not support attention outputs"						)
				def       snake_case    (     self					:	Union[str, Any]						):
						pass



				@unittest.skip
				def       snake_case    (     self					:	Tuple						):
						pass



				@unittest.skip("Esm does not support embedding resizing"						)
				def       snake_case    (     self					:	Optional[int]						):
						pass



				@unittest.skip("Esm does not support embedding resizing"						)
				def       snake_case    (     self					:	List[str]						):
						pass



				@unittest.skip("ESMFold does not support passing input embeds!"						)
				def       snake_case    (     self					:	int						):
						pass



				@unittest.skip("ESMFold does not support head pruning."						)
				def       snake_case    (     self					:	List[Any]						):
						pass



				@unittest.skip("ESMFold does not support head pruning."						)
				def       snake_case    (     self					:	Any						):
						pass



				@unittest.skip("ESMFold does not support head pruning."						)
				def       snake_case    (     self					:	Optional[Any]						):
						pass



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



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



				@unittest.skip("ESMFold does not output hidden states in the normal way."						)
				def       snake_case    (     self					:	Optional[Any]						):
						pass



				@unittest.skip("ESMfold does not output hidden states in the normal way."						)
				def       snake_case    (     self					:	Optional[Any]						):
						pass



				@unittest.skip("ESMFold only has one output format."						)
				def       snake_case    (     self					:	Tuple						):
						pass



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



				@unittest.skip("ESMFold does not support input chunking."						)
				def       snake_case    (     self					:	str						):
						pass



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



				@unittest.skip("ESMFold doesn't support torchscript compilation."						)
				def       snake_case    (     self					:	Any						):
						pass



				@unittest.skip("ESMFold doesn't support torchscript compilation."						)
				def       snake_case    (     self					:	Tuple						):
						pass



				@unittest.skip("ESMFold doesn't support torchscript compilation."						)
				def       snake_case    (     self					:	List[str]						):
						pass



				@unittest.skip("ESMFold doesn't support data parallel."						)
				def       snake_case    (     self					:	Optional[Any]						):
						pass



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





@require_torch
class       lowerCAmelCase__       (			lowerCAmelCase_    ):


				"""simple docstring"""





				@slow
				def       snake_case    (     self					:	Union[str, Any]						):
						__lowercase				:		Tuple												=				EsmForProteinFolding.from_pretrained("facebook/esmfold_v1"						).float()
						model.eval()
						__lowercase				:		Optional[int]												=				torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]]						)
						__lowercase				:		str												=				model(lowercase__						)["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]    ,   lowercase__    ,   atol=1e-4						)						)
