

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 _UpperCamelCase							:
			'''simple docstring'''







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

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Tuple				     =       parent
				SCREAMING_SNAKE_CASE   :      int				     =       batch_size
				SCREAMING_SNAKE_CASE   :      int				     =       seq_length
				SCREAMING_SNAKE_CASE   :      Tuple				     =       is_training
				SCREAMING_SNAKE_CASE   :      Dict				     =       use_input_mask
				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       use_token_type_ids
				SCREAMING_SNAKE_CASE   :      List[str]				     =       use_labels
				SCREAMING_SNAKE_CASE   :      int				     =       vocab_size
				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       hidden_size
				SCREAMING_SNAKE_CASE   :      Any				     =       num_hidden_layers
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       num_attention_heads
				SCREAMING_SNAKE_CASE   :      Dict				     =       intermediate_size
				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       hidden_act
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       hidden_dropout_prob
				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       attention_probs_dropout_prob
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       max_position_embeddings
				SCREAMING_SNAKE_CASE   :      Tuple				     =       type_vocab_size
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       type_sequence_label_size
				SCREAMING_SNAKE_CASE   :      Any				     =       initializer_range
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       num_labels
				SCREAMING_SNAKE_CASE   :      Dict				     =       num_choices
				SCREAMING_SNAKE_CASE   :      int				     =       scope
			def 							__UpperCamelCase (			self							: str	)							->       Optional[int]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      str				     =       ids_tensor([self.batch_size, self.seq_length]      ,      self.vocab_size	)

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

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

				SCREAMING_SNAKE_CASE   :      List[str]				     =       self.get_config()

				return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
			def 							__UpperCamelCase (			self							: List[Any]	)							->       Dict:

				"""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							: Union[str, Any]      ,      a							: Tuple      ,      a							: str      ,      a							: Optional[Any]      ,      a							: Tuple      ,      a							: List[str]      ,      a							: Any	)							->       List[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Any				     =       EsmModel(config=a	)
				model.to(a	)
				model.eval()
				SCREAMING_SNAKE_CASE   :      Dict				     =       model(a      ,      attention_mask=a	)
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       model(a	)
				SCREAMING_SNAKE_CASE   :      str				     =       model(a	)

				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							: Optional[int]      ,      a							: List[str]      ,      a							: str      ,      a							: Tuple      ,      a							: Any      ,      a							: List[Any]      ,      a							: Tuple	)							->       int:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       EsmForMaskedLM(config=a	)
				model.to(a	)
				model.eval()
				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       model(a      ,      attention_mask=a      ,      labels=a	)
				self.parent.assertEqual(result.logits.shape      ,      (self.batch_size, self.seq_length, self.vocab_size)	)
			def 							__UpperCamelCase (			self							: int      ,      a							: List[str]      ,      a							: List[Any]      ,      a							: Optional[Any]      ,      a							: int      ,      a							: Optional[int]      ,      a							: Union[str, Any]	)							->       Optional[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Any				     =       self.num_labels
				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       EsmForTokenClassification(config=a	)
				model.to(a	)
				model.eval()
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       model(a      ,      attention_mask=a      ,      labels=a	)
				self.parent.assertEqual(result.logits.shape      ,      (self.batch_size, self.seq_length, self.num_labels)	)






			def 							__UpperCamelCase (			self							: List[str]	)							->       Dict:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Dict				     =       self.prepare_config_and_inputs()
				(
				    (
				    SCREAMING_SNAKE_CASE
				)     ,(
				    SCREAMING_SNAKE_CASE
				)     ,(
				    SCREAMING_SNAKE_CASE
				)     ,(
				    SCREAMING_SNAKE_CASE
				)     ,(
				    SCREAMING_SNAKE_CASE
				)     ,(
				    SCREAMING_SNAKE_CASE
				)     ,
				)   :      Optional[int]				     =       config_and_inputs
				SCREAMING_SNAKE_CASE   :      Dict				     =       {"input_ids": input_ids, "attention_mask": input_mask}
				return config, inputs_dict






@require_torch
class _UpperCamelCase							(							__A							,	__A							,	unittest.TestCase   ):
			'''simple docstring'''







			lowerCamelCase__           =False

			lowerCamelCase__           =(
			    (
			        EsmForMaskedLM,
			        EsmModel,
			        EsmForSequenceClassification,
			        EsmForTokenClassification,
			    )
			    if is_torch_available()
			    else ()
			)
			lowerCamelCase__           =()
			lowerCamelCase__           =(
			    {
			        'feature-extraction': EsmModel,
			        'fill-mask': EsmForMaskedLM,
			        'text-classification': EsmForSequenceClassification,
			        'token-classification': EsmForTokenClassification,
			        'zero-shot': EsmForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)
			lowerCamelCase__           =True
			def 							__UpperCamelCase (			self							: str	)							->       Optional[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Dict				     =       EsmModelTester(self	)
				SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       ConfigTester(self      ,      config_class=a      ,      hidden_size=37	)
			def 							__UpperCamelCase (			self							: List[Any]	)							->       Dict:

				"""simple docstring"""

				self.config_tester.run_common_tests()
			def 							__UpperCamelCase (			self							: Union[str, Any]	)							->       List[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*a	)
			def 							__UpperCamelCase (			self							: Optional[Any]	)							->       Union[str, Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Any				     =       self.model_tester.prepare_config_and_inputs()
				for type in ["absolute", "relative_key", "relative_key_query"]:
					SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       type
					self.model_tester.create_and_check_model(*a	)
			def 							__UpperCamelCase (			self							: Union[str, Any]	)							->       List[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Tuple				     =       self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_masked_lm(*a	)
			def 							__UpperCamelCase (			self							: Tuple	)							->       Union[str, Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      List[Any]				     =       self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_token_classification(*a	)
			@slow
			def 							__UpperCamelCase (			self							: Any	)							->       Dict:

				"""simple docstring"""

				for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
					SCREAMING_SNAKE_CASE   :      Tuple				     =       EsmModel.from_pretrained(a	)
					self.assertIsNotNone(a	)
			def 							__UpperCamelCase (			self							: List[Any]	)							->       List[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       self.model_tester.prepare_config_and_inputs()[0]
				SCREAMING_SNAKE_CASE   :      List[str]				     =       EsmEmbeddings(config=a	)

				SCREAMING_SNAKE_CASE   :      List[str]				     =       torch.as_tensor([[12, 31, 13, model.padding_idx]]	)
				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       torch.as_tensor(
				    [
				        [
				            0 + model.padding_idx + 1,
				            1 + model.padding_idx + 1,
				            2 + model.padding_idx + 1,
				            model.padding_idx,
				        ]
				    ]	)
				SCREAMING_SNAKE_CASE   :      str				     =       create_position_ids_from_input_ids(a      ,      model.padding_idx	)
				self.assertEqual(position_ids.shape      ,      expected_positions.shape	)
				self.assertTrue(torch.all(torch.eq(a      ,      a	)	)	)
			def 							__UpperCamelCase (			self							: Union[str, Any]	)							->       str:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      List[Any]				     =       self.model_tester.prepare_config_and_inputs()[0]
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       EsmEmbeddings(config=a	)

				SCREAMING_SNAKE_CASE   :      Dict				     =       torch.empty(2      ,      4      ,      30	)
				SCREAMING_SNAKE_CASE   :      Any				     =       [
				    0 + embeddings.padding_idx + 1,
				    1 + embeddings.padding_idx + 1,
				    2 + embeddings.padding_idx + 1,
				    3 + embeddings.padding_idx + 1,
				]
				SCREAMING_SNAKE_CASE   :      str				     =       torch.as_tensor([expected_single_positions, expected_single_positions]	)
				SCREAMING_SNAKE_CASE   :      str				     =       embeddings.create_position_ids_from_inputs_embeds(a	)
				self.assertEqual(position_ids.shape      ,      expected_positions.shape	)
				self.assertTrue(torch.all(torch.eq(a      ,      a	)	)	)
			@unittest.skip("Esm does not support embedding resizing"	)
			def 							__UpperCamelCase (			self							: Any	)							->       Tuple:

				"""simple docstring"""

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

				"""simple docstring"""

				pass






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

				"""simple docstring"""

				pass






@require_torch
class _UpperCamelCase							(							__A   ):
			'''simple docstring'''







			@slow
			def 							__UpperCamelCase (			self							: List[Any]	)							->       List[str]:

				"""simple docstring"""

				with torch.no_grad():
					SCREAMING_SNAKE_CASE   :      Tuple				     =       EsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D"	)
					model.eval()
					SCREAMING_SNAKE_CASE   :      Tuple				     =       torch.tensor([[0, 1, 2, 3, 4, 5]]	)
					SCREAMING_SNAKE_CASE   :      int				     =       model(a	)[0]

					SCREAMING_SNAKE_CASE   :      Any				     =       33

					SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       torch.Size((1, 6, vocab_size)	)
					self.assertEqual(output.shape      ,      a	)

					SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       torch.tensor(
					    [[[8.9215, -10.5898, -6.4671], [-6.3967, -13.9114, -1.1212], [-7.7812, -13.9516, -3.7406]]]	)
					self.assertTrue(torch.allclose(output[:, :3, :3]      ,      a      ,      atol=1e-4	)	)






			@slow
			def 							__UpperCamelCase (			self							: str	)							->       Union[str, Any]:

				"""simple docstring"""

				with torch.no_grad():
					SCREAMING_SNAKE_CASE   :      str				     =       EsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D"	)
					model.eval()

					SCREAMING_SNAKE_CASE   :      Any				     =       torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]]	)
					SCREAMING_SNAKE_CASE   :      Optional[int]				     =       model(a	)[0]
					# compare the actual values for a slice.
					SCREAMING_SNAKE_CASE   :      int				     =       torch.tensor(
					    [[[0.1444, 0.5413, 0.3248], [0.3034, 0.0053, 0.3108], [0.3228, -0.2499, 0.3415]]]	)
					self.assertTrue(torch.allclose(output[:, :3, :3]      ,      a      ,      atol=1e-4	)	)


from collections import OrderedDict
from typing import Any, List, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging


a_						     =    logging.get_logger(__name__)

a_						     =    {
    'EleutherAI/gpt-j-6B': 'https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json',
    # See all GPT-J models at https://huggingface.co/models?filter=gpt_j
}






class _UpperCamelCase							(							__A   ):
			'''simple docstring'''







			lowerCamelCase__           ='gptj'
			lowerCamelCase__           ={
			    'max_position_embeddings': 'n_positions',
			    'hidden_size': 'n_embd',
			    'num_attention_heads': 'n_head',
			    'num_hidden_layers': 'n_layer',
			}
			def __init__(			self							: Dict      ,      a							: Optional[Any]=5_0400      ,      a							: List[str]=2048      ,      a							: List[Any]=4096      ,      a							: int=28      ,      a							: Union[str, Any]=16      ,      a							: List[Any]=64      ,      a							: int=None      ,      a							: Optional[int]="gelu_new"      ,      a							: Optional[Any]=0.0      ,      a							: Any=0.0      ,      a							: Union[str, Any]=0.0      ,      a							: Union[str, Any]=1e-5      ,      a							: Any=0.02      ,      a							: Optional[int]=True      ,      a							: Tuple=5_0256      ,      a							: Union[str, Any]=5_0256      ,      a							: List[Any]=False      ,      **a							: str      ,      )							->       Optional[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      str				     =       vocab_size
				SCREAMING_SNAKE_CASE   :      int				     =       n_positions
				SCREAMING_SNAKE_CASE   :      Tuple				     =       n_embd
				SCREAMING_SNAKE_CASE   :      Tuple				     =       n_layer
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       n_head
				SCREAMING_SNAKE_CASE   :      Tuple				     =       n_inner
				SCREAMING_SNAKE_CASE   :      Any				     =       rotary_dim
				SCREAMING_SNAKE_CASE   :      str				     =       activation_function
				SCREAMING_SNAKE_CASE   :      int				     =       resid_pdrop
				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       embd_pdrop
				SCREAMING_SNAKE_CASE   :      Tuple				     =       attn_pdrop
				SCREAMING_SNAKE_CASE   :      List[str]				     =       layer_norm_epsilon
				SCREAMING_SNAKE_CASE   :      int				     =       initializer_range
				SCREAMING_SNAKE_CASE   :      Tuple				     =       use_cache

				SCREAMING_SNAKE_CASE   :      Union[str, Any]				     =       bos_token_id
				SCREAMING_SNAKE_CASE   :      List[Any]				     =       eos_token_id

				super().__init__(
				    bos_token_id=a      ,      eos_token_id=a      ,      tie_word_embeddings=a      ,      **a	)






class _UpperCamelCase							(							__A   ):
			'''simple docstring'''







			def __init__(			self							: Optional[int]      ,      a							: PretrainedConfig      ,      a							: str = "default"      ,      a							: List[PatchingSpec] = None      ,      a							: bool = False      ,      )							->       Any:

				"""simple docstring"""

				super().__init__(a      ,      task=a      ,      patching_specs=a      ,      use_past=a	)
				if not getattr(self._config      ,      "pad_token_id"      ,      a	):
					# TODO: how to do that better?
					SCREAMING_SNAKE_CASE   :      Dict				     =       0
			@property
			def 							__UpperCamelCase (			self							: Any	)							->       Mapping[str, Mapping[int, str]]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      List[Any]				     =       OrderedDict({"input_ids": {0: "batch", 1: "sequence"}}	)
				if self.use_past:
					self.fill_with_past_key_values_(a      ,      direction="inputs"	)
					SCREAMING_SNAKE_CASE   :      int				     =       {0: "batch", 1: "past_sequence + sequence"}
				else:
					SCREAMING_SNAKE_CASE   :      Any				     =       {0: "batch", 1: "sequence"}

				return common_inputs
			@property
			def 							__UpperCamelCase (			self							: Any	)							->       int:

				"""simple docstring"""

				return self._config.n_layer
			@property
			def 							__UpperCamelCase (			self							: str	)							->       int:

				"""simple docstring"""

				return self._config.n_head
			def 							__UpperCamelCase (			self							: str      ,      a							: PreTrainedTokenizer      ,      a							: int = -1      ,      a							: int = -1      ,      a							: bool = False      ,      a							: Optional[TensorType] = None      ,      )							->       Mapping[str, Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE   :      int				     =       super(a      ,      self	).generate_dummy_inputs(
				    a      ,      batch_size=a      ,      seq_length=a      ,      is_pair=a      ,      framework=a	)

				# We need to order the input in the way they appears in the forward()
				SCREAMING_SNAKE_CASE   :      Tuple				     =       OrderedDict({"input_ids": common_inputs["input_ids"]}	)

				# Need to add the past_keys
				if self.use_past:
					if not is_torch_available():
						raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed."	)
					else:
						import torch

						SCREAMING_SNAKE_CASE     ,SCREAMING_SNAKE_CASE   :      Optional[Any]				     =       common_inputs["input_ids"].shape
						# Not using the same length for past_key_values
						SCREAMING_SNAKE_CASE   :      Any				     =       seqlen + 2
						SCREAMING_SNAKE_CASE   :      Dict				     =       (
						    batch,
						    self.num_attention_heads,
						    past_key_values_length,
						    self._config.hidden_size // self.num_attention_heads,
						)
						SCREAMING_SNAKE_CASE   :      str				     =       [
						    (torch.zeros(a	), torch.zeros(a	)) for _ in range(self.num_layers	)
						]

				SCREAMING_SNAKE_CASE   :      Optional[int]				     =       common_inputs["attention_mask"]
				if self.use_past:
					SCREAMING_SNAKE_CASE   :      List[str]				     =       ordered_inputs["attention_mask"].dtype
					SCREAMING_SNAKE_CASE   :      Any				     =       torch.cat(
					    [ordered_inputs["attention_mask"], torch.ones(a      ,      a      ,      dtype=a	)]      ,      dim=1	)

				return ordered_inputs






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

				"""simple docstring"""

				return 13