






"""simple docstring"""




import unittest

from transformers import ElectraConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import (
     MODEL_FOR_PRETRAINING_MAPPING,
     ElectraForCausalLM,
     ElectraForMaskedLM,
     ElectraForMultipleChoice,
     ElectraForPreTraining,
     ElectraForQuestionAnswering,
     ElectraForSequenceClassification,
     ElectraForTokenClassification,
     ElectraModel,
 )
 from transformers.models.electra.modeling_electra import ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST






class  UpperCamelCase    :


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


 def _lowercase			(  self	:		Optional[Any]							)      -> int:
   _a						: Tuple    =			ids_tensor([self.batch_size, self.seq_length]							,		self.vocab_size							)

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

   _a						: str    =			None
   if self.use_token_type_ids:
     _a						: Optional[int]    =			ids_tensor([self.batch_size, self.seq_length]							,		self.type_vocab_size							)

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

   _a						: Union[str, Any]    =			self.get_config()

   return (
       config,
       input_ids,
       token_type_ids,
       input_mask,
       sequence_labels,
       token_labels,
       choice_labels,
       fake_token_labels,
   )


 def _lowercase			(  self	:		Union[str, Any]							)      -> List[str]:
   return ElectraConfig(
       vocab_size=self.vocab_size							,		hidden_size=self.hidden_size							,		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							,		is_decoder=UpperCAmelCase__							,		initializer_range=self.initializer_range							,		)


 def _lowercase			(  self	:		Any							)      -> int:
   (
       (
       _a
   )   ,						(
       _a
   )   ,						(
       _a
   )   ,						(
       _a
   )   ,						(
       _a
   )   ,						(
       _a
   )   ,						(
       _a
   )   ,						(
       _a
   )   ,						
   )						: Optional[int]    =			self.prepare_config_and_inputs()

   _a						: Union[str, Any]    =			True
   _a						: List[Any]    =			floats_tensor([self.batch_size, self.seq_length, self.hidden_size]							)
   _a						: Tuple    =			ids_tensor([self.batch_size, self.seq_length]							,		vocab_size=2							)

   return (
       config,
       input_ids,
       token_type_ids,
       input_mask,
       sequence_labels,
       token_labels,
       choice_labels,
       encoder_hidden_states,
       encoder_attention_mask,
   )


 def _lowercase			(  self	:		Optional[int]							,		UpperCAmelCase__	:		Optional[Any]							,		UpperCAmelCase__	:		Dict							,		UpperCAmelCase__	:		Tuple							,		UpperCAmelCase__	:		str							,		UpperCAmelCase__	:		Optional[Any]							,		UpperCAmelCase__	:		Union[str, Any]							,		UpperCAmelCase__	:		Union[str, Any]							,		UpperCAmelCase__	:		Any							,		)      -> Any:
   _a						: int    =			ElectraModel(config=UpperCAmelCase__							)
   model.to(UpperCAmelCase__							)
   model.eval()
   _a						: Any    =			model(UpperCAmelCase__							,		attention_mask=UpperCAmelCase__							,		token_type_ids=UpperCAmelCase__							)
   _a						: str    =			model(UpperCAmelCase__							,		token_type_ids=UpperCAmelCase__							)
   _a						: int    =			model(UpperCAmelCase__							)
   self.parent.assertEqual(result.last_hidden_state.shape							,		(self.batch_size, self.seq_length, self.hidden_size)							)


 def _lowercase			(  self	:		Optional[Any]							,		UpperCAmelCase__	:		Tuple							,		UpperCAmelCase__	:		str							,		UpperCAmelCase__	:		Tuple							,		UpperCAmelCase__	:		Optional[int]							,		UpperCAmelCase__	:		List[str]							,		UpperCAmelCase__	:		List[Any]							,		UpperCAmelCase__	:		List[Any]							,		UpperCAmelCase__	:		Optional[int]							,		UpperCAmelCase__	:		List[Any]							,		)      -> List[Any]:
   _a						: Union[str, Any]    =			True
   _a						: Dict    =			ElectraModel(UpperCAmelCase__							)
   model.to(UpperCAmelCase__							)
   model.eval()
   _a						: Optional[Any]    =			model(
       UpperCAmelCase__							,		attention_mask=UpperCAmelCase__							,		token_type_ids=UpperCAmelCase__							,		encoder_hidden_states=UpperCAmelCase__							,		encoder_attention_mask=UpperCAmelCase__							,		)
   _a						: List[str]    =			model(
       UpperCAmelCase__							,		attention_mask=UpperCAmelCase__							,		token_type_ids=UpperCAmelCase__							,		encoder_hidden_states=UpperCAmelCase__							,		)
   _a						: str    =			model(UpperCAmelCase__							,		attention_mask=UpperCAmelCase__							,		token_type_ids=UpperCAmelCase__							)
   self.parent.assertEqual(result.last_hidden_state.shape							,		(self.batch_size, self.seq_length, self.hidden_size)							)


 def _lowercase			(  self	:		Any							,		UpperCAmelCase__	:		int							,		UpperCAmelCase__	:		str							,		UpperCAmelCase__	:		Any							,		UpperCAmelCase__	:		str							,		UpperCAmelCase__	:		str							,		UpperCAmelCase__	:		Tuple							,		UpperCAmelCase__	:		List[Any]							,		UpperCAmelCase__	:		Optional[Any]							,		)      -> Dict:
   _a						: Union[str, Any]    =			ElectraForMaskedLM(config=UpperCAmelCase__							)
   model.to(UpperCAmelCase__							)
   model.eval()
   _a						: str    =			model(UpperCAmelCase__							,		attention_mask=UpperCAmelCase__							,		token_type_ids=UpperCAmelCase__							,		labels=UpperCAmelCase__							)
   self.parent.assertEqual(result.logits.shape							,		(self.batch_size, self.seq_length, self.vocab_size)							)


 def _lowercase			(  self	:		List[str]							,		UpperCAmelCase__	:		Tuple							,		UpperCAmelCase__	:		Any							,		UpperCAmelCase__	:		Union[str, Any]							,		UpperCAmelCase__	:		List[str]							,		UpperCAmelCase__	:		Any							,		UpperCAmelCase__	:		Union[str, Any]							,		UpperCAmelCase__	:		str							,		UpperCAmelCase__	:		Any							,		UpperCAmelCase__	:		Any							,		)      -> str:
   _a						: Union[str, Any]    =			ElectraForCausalLM(config=UpperCAmelCase__							)
   model.to(UpperCAmelCase__							)
   model.eval()
   _a						: Optional[Any]    =			model(UpperCAmelCase__							,		attention_mask=UpperCAmelCase__							,		token_type_ids=UpperCAmelCase__							,		labels=UpperCAmelCase__							)
   self.parent.assertEqual(result.logits.shape							,		(self.batch_size, self.seq_length, self.vocab_size)							)


 def _lowercase			(  self	:		str							,		UpperCAmelCase__	:		Union[str, Any]							,		UpperCAmelCase__	:		Dict							,		UpperCAmelCase__	:		Optional[int]							,		UpperCAmelCase__	:		Optional[int]							,		UpperCAmelCase__	:		int							,		UpperCAmelCase__	:		Optional[Any]							,		UpperCAmelCase__	:		Tuple							,		UpperCAmelCase__	:		str							,		)      -> Any:
   _a						: List[Any]    =			self.num_labels
   _a						: Tuple    =			ElectraForTokenClassification(config=UpperCAmelCase__							)
   model.to(UpperCAmelCase__							)
   model.eval()
   _a						: Union[str, Any]    =			model(UpperCAmelCase__							,		attention_mask=UpperCAmelCase__							,		token_type_ids=UpperCAmelCase__							,		labels=UpperCAmelCase__							)
   self.parent.assertEqual(result.logits.shape							,		(self.batch_size, self.seq_length, self.num_labels)							)


 def _lowercase			(  self	:		Dict							,		UpperCAmelCase__	:		Dict							,		UpperCAmelCase__	:		int							,		UpperCAmelCase__	:		Dict							,		UpperCAmelCase__	:		str							,		UpperCAmelCase__	:		Dict							,		UpperCAmelCase__	:		int							,		UpperCAmelCase__	:		Union[str, Any]							,		UpperCAmelCase__	:		Optional[int]							,		)      -> List[Any]:
   _a						: List[str]    =			self.num_labels
   _a						: Tuple    =			ElectraForPreTraining(config=UpperCAmelCase__							)
   model.to(UpperCAmelCase__							)
   model.eval()
   _a						: List[str]    =			model(UpperCAmelCase__							,		attention_mask=UpperCAmelCase__							,		token_type_ids=UpperCAmelCase__							,		labels=UpperCAmelCase__							)
   self.parent.assertEqual(result.logits.shape							,		(self.batch_size, self.seq_length)							)


 def _lowercase			(  self	:		Tuple							,		UpperCAmelCase__	:		List[str]							,		UpperCAmelCase__	:		Any							,		UpperCAmelCase__	:		List[str]							,		UpperCAmelCase__	:		Optional[int]							,		UpperCAmelCase__	:		Dict							,		UpperCAmelCase__	:		Dict							,		UpperCAmelCase__	:		Dict							,		UpperCAmelCase__	:		Union[str, Any]							,		)      -> List[str]:
   _a						: str    =			self.num_labels
   _a						: List[str]    =			ElectraForSequenceClassification(UpperCAmelCase__							)
   model.to(UpperCAmelCase__							)
   model.eval()
   _a						: Any    =			model(UpperCAmelCase__							,		attention_mask=UpperCAmelCase__							,		token_type_ids=UpperCAmelCase__							,		labels=UpperCAmelCase__							)
   self.parent.assertEqual(result.logits.shape							,		(self.batch_size, self.num_labels)							)


 def _lowercase			(  self	:		Tuple							,		UpperCAmelCase__	:		str							,		UpperCAmelCase__	:		Optional[int]							,		UpperCAmelCase__	:		List[Any]							,		UpperCAmelCase__	:		Union[str, Any]							,		UpperCAmelCase__	:		Optional[int]							,		UpperCAmelCase__	:		Dict							,		UpperCAmelCase__	:		List[Any]							,		UpperCAmelCase__	:		List[Any]							,		)      -> Optional[int]:
   _a						: List[Any]    =			ElectraForQuestionAnswering(config=UpperCAmelCase__							)
   model.to(UpperCAmelCase__							)
   model.eval()
   _a						: str    =			model(
       UpperCAmelCase__							,		attention_mask=UpperCAmelCase__							,		token_type_ids=UpperCAmelCase__							,		start_positions=UpperCAmelCase__							,		end_positions=UpperCAmelCase__							,		)
   self.parent.assertEqual(result.start_logits.shape							,		(self.batch_size, self.seq_length)							)
   self.parent.assertEqual(result.end_logits.shape							,		(self.batch_size, self.seq_length)							)


 def _lowercase			(  self	:		int							,		UpperCAmelCase__	:		Union[str, Any]							,		UpperCAmelCase__	:		Tuple							,		UpperCAmelCase__	:		List[str]							,		UpperCAmelCase__	:		List[Any]							,		UpperCAmelCase__	:		List[Any]							,		UpperCAmelCase__	:		str							,		UpperCAmelCase__	:		int							,		UpperCAmelCase__	:		str							,		)      -> str:
   _a						: int    =			self.num_choices
   _a						: Dict    =			ElectraForMultipleChoice(config=UpperCAmelCase__							)
   model.to(UpperCAmelCase__							)
   model.eval()
   _a						: Dict    =			input_ids.unsqueeze(1							).expand(-1							,		self.num_choices							,		-1							).contiguous()
   _a						: Optional[Any]    =			token_type_ids.unsqueeze(1							).expand(-1							,		self.num_choices							,		-1							).contiguous()
   _a						: str    =			input_mask.unsqueeze(1							).expand(-1							,		self.num_choices							,		-1							).contiguous()
   _a						: str    =			model(
       UpperCAmelCase__							,		attention_mask=UpperCAmelCase__							,		token_type_ids=UpperCAmelCase__							,		labels=UpperCAmelCase__							,		)
   self.parent.assertEqual(result.logits.shape							,		(self.batch_size, self.num_choices)							)







 def _lowercase			(  self	:		Optional[Any]							)      -> Optional[Any]:
   _a						: str    =			self.prepare_config_and_inputs()
   (
       (
       _a
   )   ,						(
       _a
   )   ,						(
       _a
   )   ,						(
       _a
   )   ,						(
       _a
   )   ,						(
       _a
   )   ,						(
       _a
   )   ,						(
       _a
   )   ,						
   )						: Any    =			config_and_inputs
   _a						: Optional[Any]    =			{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
   return config, inputs_dict







@require_torch
class  UpperCamelCase    (			snake_case_	,  snake_case_	,  unittest.TestCase   ):
 UpperCamelCase      : List[Any]    =      (
     (
         ElectraModel,
         ElectraForPreTraining,
         ElectraForMaskedLM,
         ElectraForCausalLM,
         ElectraForMultipleChoice,
         ElectraForTokenClassification,
         ElectraForSequenceClassification,
         ElectraForQuestionAnswering,
     )
     if is_torch_available()
     else ()
 )
 UpperCamelCase      : str    =      (
     {
         '''feature-extraction''': ElectraModel,
         '''fill-mask''': ElectraForMaskedLM,
         '''question-answering''': ElectraForQuestionAnswering,
         '''text-classification''': ElectraForSequenceClassification,
         '''text-generation''': ElectraForCausalLM,
         '''token-classification''': ElectraForTokenClassification,
         '''zero-shot''': ElectraForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )
 UpperCamelCase      : Tuple    =      True


 def _lowercase			(  self	:		int							,		UpperCAmelCase__	:		List[str]							,		UpperCAmelCase__	:		Tuple							,		UpperCAmelCase__	:		int=False							)      -> Union[str, Any]:
   _a						: List[str]    =			super()._prepare_for_class(UpperCAmelCase__							,		UpperCAmelCase__							,		return_labels=UpperCAmelCase__							)

   if return_labels:
     if model_class in get_values(UpperCAmelCase__							):
       _a						: List[Any]    =			torch.zeros(
           (self.model_tester.batch_size, self.model_tester.seq_length)							,		dtype=torch.long							,		device=UpperCAmelCase__							)
   return inputs_dict


 def _lowercase			(  self	:		int							)      -> str:
   _a						: List[str]    =			ElectraModelTester(self							)
   _a						: int    =			ConfigTester(self							,		config_class=UpperCAmelCase__							,		hidden_size=37							)


 def _lowercase			(  self	:		List[str]							)      -> int:
   self.config_tester.run_common_tests()


 def _lowercase			(  self	:		List[Any]							)      -> Optional[int]:
   _a						: Tuple    =			self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_electra_model(*UpperCAmelCase__							)


 def _lowercase			(  self	:		int							)      -> Optional[Any]:
   _a						: Dict    =			self.model_tester.prepare_config_and_inputs_for_decoder()
   self.model_tester.create_and_check_electra_model_as_decoder(*UpperCAmelCase__							)


 def _lowercase			(  self	:		int							)      -> List[str]:
   _a						: str    =			self.model_tester.prepare_config_and_inputs()
   for type in ["absolute", "relative_key", "relative_key_query"]:
     _a						: str    =			type
     self.model_tester.create_and_check_electra_model(*UpperCAmelCase__							)


 def _lowercase			(  self	:		List[Any]							)      -> Tuple:
   _a						: Dict    =			self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_electra_for_masked_lm(*UpperCAmelCase__							)


 def _lowercase			(  self	:		Optional[int]							)      -> List[str]:
   _a						: Union[str, Any]    =			self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_electra_for_token_classification(*UpperCAmelCase__							)


 def _lowercase			(  self	:		List[str]							)      -> Optional[Any]:
   _a						: Optional[int]    =			self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_electra_for_pretraining(*UpperCAmelCase__							)


 def _lowercase			(  self	:		Dict							)      -> Optional[Any]:
   _a						: Dict    =			self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_electra_for_sequence_classification(*UpperCAmelCase__							)


 def _lowercase			(  self	:		Optional[Any]							)      -> int:
   _a						: Optional[int]    =			self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_electra_for_question_answering(*UpperCAmelCase__							)


 def _lowercase			(  self	:		Optional[Any]							)      -> Any:
   _a						: Optional[Any]    =			self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_electra_for_multiple_choice(*UpperCAmelCase__							)


 @slow
 def _lowercase			(  self	:		List[str]							)      -> Optional[Any]:
   for model_name in ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     _a						: List[Any]    =			ElectraModel.from_pretrained(UpperCAmelCase__							)
     self.assertIsNotNone(UpperCAmelCase__							)







 def _lowercase			(  self	:		int							)      -> Any:
   _a						: Any    =			self.model_tester.prepare_config_and_inputs_for_decoder()
   self.model_tester.create_and_check_electra_for_causal_lm(*UpperCAmelCase__							)







@require_torch
class  UpperCamelCase    (			unittest.TestCase   ):


 @slow
 def _lowercase			(  self	:		List[Any]							)      -> Tuple:
   _a						: Tuple    =			ElectraModel.from_pretrained("""google/electra-small-discriminator"""							)
   _a						: Optional[Any]    =			torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]							)
   _a						: Tuple    =			torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]							)
   _a						: Dict    =			model(UpperCAmelCase__							,		attention_mask=UpperCAmelCase__							)[0]
   _a						: List[str]    =			torch.Size((1, 11, 256)							)
   self.assertEqual(output.shape							,		UpperCAmelCase__							)
   _a						: Dict    =			torch.tensor(
       [[[0.4_4_7_1, 0.6_8_2_1, -0.3_2_6_5], [0.4_6_2_7, 0.5_2_5_5, -0.3_6_6_8], [0.4_5_3_2, 0.3_3_1_3, -0.4_3_4_4]]]							)

   self.assertTrue(torch.allclose(output[:, 1:4, 1:4]							,		UpperCAmelCase__							,		atol=1E-4							)							)









"""simple docstring"""




import json
import logging
import os
import subprocess
from argparse import ArgumentParser


_snake_case					   =     logging.getLogger(__name__)

def     lowerCAmelCase__  (  ):



  '''simple docstring'''
  _a						: Any    =			ArgumentParser()
  _a   ,						_a						: str    =			parser.parse_known_args()
  for arg in unknown:
    if arg.startswith(("""-""", """--""")       ):
      parser.add_argument(arg.split("""="""       )[0]       )

  return parser.parse_args()

def     lowerCAmelCase__  (  ):



  '''simple docstring'''
  _a						: Optional[Any]    =			parse_args()
  _a						: Any    =			8_8_8_8
  _a						: List[str]    =			int(os.environ["""SM_NUM_GPUS"""]       )
  _a						: Union[str, Any]    =			json.loads(os.environ["""SM_HOSTS"""]       )
  _a						: Tuple    =			len(UpperCamelCase__       )
  _a						: Optional[int]    =			os.environ["""SM_CURRENT_HOST"""]
  _a						: Optional[Any]    =			hosts.index(UpperCamelCase__       )
  _a						: List[str]    =			"""INFO"""

  if num_nodes > 1:
    _a						: int    =			F"""python -m torch.distributed.launch \
                --nnodes={num_nodes}  \
                --node_rank={rank}  \
                --nproc_per_node={num_gpus}  \
                --master_addr={hosts[0]}  \
                --master_port={port} \
                ./run_glue.py \
                {''.join(['nested fstring' for parameter,value in args.__dict__.items()]       )}"""
  else:
    _a						: Any    =			F"""python -m torch.distributed.launch \
            --nproc_per_node={num_gpus}  \
            ./run_glue.py \
            {''.join(['nested fstring' for parameter,value in args.__dict__.items()]       )}"""
  try:
    subprocess.run(UpperCamelCase__  ,     shell=UpperCamelCase__       )
  except Exception as e:
    logger.info(UpperCamelCase__       )


if __name__ == "__main__":
 main()

