'''simple docstring'''




import logging
import os
import time
from argparse import Namespace
from pathlib import Path

import datasets
import torch
from accelerate import Accelerator, DistributedType
from accelerate.utils import ProjectConfiguration
from arguments import TrainingArguments
from datasets import load_dataset
from huggingface_hub import Repository
from torch.optim import AdamW
from torch.utils.data import IterableDataset
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.datapipes.iter.combinatorics import ShufflerIterDataPipe

import transformers
from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, get_scheduler, set_seed

class 			lowerCamelCase_			(snake_case__					):
						'''simple docstring'''

						def __init__( self		:       str		,      A		:       Optional[Any]		,      A		:       Optional[int]		,      A		:       int=False		,      A		:       Dict=1024		,      A		:       List[Any]=1024		,      A		:       Tuple=3.6		,      A		:       Any=False		,      ):
													_UpperCAmelCase  :						List[str]							   =					tokenizer
													_UpperCAmelCase  :						str							   =					tokenizer.bos_token_id
													_UpperCAmelCase  :						Union[str, Any]							   =					dataset
													_UpperCAmelCase  :						Dict							   =					seq_length
													_UpperCAmelCase  :						Optional[int]							   =					0
													_UpperCAmelCase  :						str							   =					infinite
													_UpperCAmelCase  :						List[str]							   =					0
													_UpperCAmelCase  :						Optional[int]							   =					tokenized

													if self.tokenized:
																				_UpperCAmelCase  :						Optional[int]							   =					seq_length * num_of_sequences
																				_UpperCAmelCase  :						Tuple							   =					"input_ids"
													else:
																				_UpperCAmelCase  :						Any							   =					seq_length * chars_per_token * num_of_sequences
																				_UpperCAmelCase  :						Tuple							   =					"content"




						def __iter__( self		:       List[str] ):
													_UpperCAmelCase  :						int							   =					iter(self.dataset )
													_UpperCAmelCase  :						int							   =					True
													while more_examples:
																				_UpperCAmelCase  :						Tuple							   =					[], 0
																				while True:
																											if buffer_len >= self.max_buffer_size:
																																		break
																											try:
																																		buffer.append(next(A )[self.content_field] )
																																		buffer_len += len(buffer[-1] )
																											except StopIteration:
																																		if self.infinite:
																																									_UpperCAmelCase  :						Any							   =					iter(self.dataset )
																																									self.epoch += 1
																																									logger.info(F"""Dataset epoch: {self.epoch}""" )
																																		else:
																																									_UpperCAmelCase  :						Optional[Any]							   =					False
																																									break
																				if self.tokenized:
																											_UpperCAmelCase  :						List[Any]							   =					buffer
																				else:
																											_UpperCAmelCase  :						Tuple							   =					self.tokenizer(A		,      truncation=A )["input_ids"]
																				_UpperCAmelCase  :						Optional[Any]							   =					[]
																				for tokenized_input in tokenized_inputs:
																											all_token_ids.extend(tokenized_input + [self.concat_token_id] )
																				for i in range(0		,      len(A )		,      self.seq_length ):
																											_UpperCAmelCase  :						Any							   =					all_token_ids[i : i + self.seq_length]
																											if len(A ) == self.seq_length:
																																		self.current_size += 1
																																		yield torch.tensor(A )





						def   _A			( self		:       Tuple		,      A		:       int=1000 ):
													return ShufflerIterDataPipe(self		,      buffer_size=A )

def 			UpperCamelCase_							(      _UpperCAmelCase						:   Dict					)					->					Tuple:


							"""simple docstring"""







							_UpperCAmelCase  :						Any							   =					args.model_ckpt.split("/"					)[-1]
							_UpperCAmelCase  :						Dict							   =					logging.getLogger(__name__					)
							_UpperCAmelCase  :						List[str]							   =					Path(args.save_dir					) / "log/"
							log_dir.mkdir(exist_ok=_UpperCAmelCase					)
							_UpperCAmelCase  :						Any							   =					F"""debug_{accelerator.process_index}.log"""
							logging.basicConfig(
							    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"    ,			datefmt="%m/%d/%Y %H:%M:%S"    ,			level=logging.INFO    ,			handlers=[logging.FileHandler(log_dir / filename					), logging.StreamHandler()]    ,			)
							if accelerator.is_main_process:  # we only want to setup logging once
														accelerator.init_trackers(_UpperCAmelCase    ,			vars(_UpperCAmelCase					)					)
														_UpperCAmelCase  :						Dict							   =					accelerator.trackers[0].run.name
														logger.setLevel(logging.INFO					)
														datasets.utils.logging.set_verbosity_info()
														transformers.utils.logging.set_verbosity_info()
							else:
														_UpperCAmelCase  :						int							   =					""
														logger.setLevel(logging.ERROR					)
														datasets.utils.logging.set_verbosity_error()
														transformers.utils.logging.set_verbosity_error()
							return logger, run_name

def 			UpperCamelCase_							(      _UpperCAmelCase						:   Dict					)					->					Dict:


							"""simple docstring"""







							_UpperCAmelCase  :						Dict							   =					{"streaming": True}
							_UpperCAmelCase  :						Optional[int]							   =					load_dataset(args.dataset_name_train    ,			split="train"    ,			**_UpperCAmelCase					)
							_UpperCAmelCase  :						List[str]							   =					train_data.shuffle(buffer_size=args.shuffle_buffer    ,			seed=args.seed					)
							_UpperCAmelCase  :						str							   =					load_dataset(args.dataset_name_valid    ,			split="train"    ,			**_UpperCAmelCase					)
							_UpperCAmelCase  :						Union[str, Any]							   =					ConstantLengthDataset(
							    _UpperCAmelCase    ,			_UpperCAmelCase    ,			infinite=_UpperCAmelCase    ,			seq_length=args.seq_length    ,			tokenized=args.tokenized					)
							_UpperCAmelCase  :						Union[str, Any]							   =					ConstantLengthDataset(
							    _UpperCAmelCase    ,			_UpperCAmelCase    ,			infinite=_UpperCAmelCase    ,			seq_length=args.seq_length    ,			tokenized=args.tokenized					)
							_UpperCAmelCase  :						Optional[int]							   =					train_dataset.shuffle(buffer_size=args.shuffle_buffer					)
							_UpperCAmelCase  :						Dict							   =					DataLoader(_UpperCAmelCase    ,			batch_size=args.train_batch_size    ,			shuffle=_UpperCAmelCase					)
							_UpperCAmelCase  :						str							   =					DataLoader(_UpperCAmelCase    ,			batch_size=args.valid_batch_size					)
							return train_dataloader, eval_dataloader

def 			UpperCamelCase_							(      _UpperCAmelCase						:   str    ,			_UpperCAmelCase						:   Any    ,			_UpperCAmelCase						:   Tuple=["bias", "ln_1.weight", "ln_2.weight", "ln_f.weight"]					)					->					List[str]:


							"""simple docstring"""







							_UpperCAmelCase  :						List[str]							   =					[], []
							for n, p in model.named_parameters():
														if any(nd in n for nd in no_decay					):
																					params_without_wd.append(_UpperCAmelCase					)
														else:
																					params_with_wd.append(_UpperCAmelCase					)
							return [
							    {"params": params_with_wd, "weight_decay": args.weight_decay},
							    {"params": params_without_wd, "weight_decay": 0.0},
							]

def 			UpperCamelCase_							(      _UpperCAmelCase						:   Any    ,			_UpperCAmelCase						:   Tuple					)					->					Tuple:


							"""simple docstring"""







							logger.info(F"""Step {step}: {metrics}"""					)
							if accelerator.is_main_process:
														accelerator.log(_UpperCAmelCase    ,			_UpperCAmelCase					)

def 			UpperCamelCase_							(      _UpperCAmelCase						:   Optional[Any]    ,			_UpperCAmelCase						:   Optional[int]    ,			_UpperCAmelCase						:   Any					)					->					Optional[Any]:


							"""simple docstring"""







							_UpperCAmelCase  :						Any							   =					accelerator.unwrap_model(_UpperCAmelCase					).config
							_UpperCAmelCase  :						Any							   =					4 if args.gradient_checkpointing else 3
							_UpperCAmelCase  :						str							   =					args.train_batch_size * accelerator.state.num_processes * args.gradient_accumulation_steps
							_UpperCAmelCase  :						int							   =					24 * checkpoint_factor * batch_size * args.seq_length * config_model.n_layer * (config_model.n_embd**2)
							_UpperCAmelCase  :						Dict							   =					factor * (
							    1.0
							    + (args.seq_length / (6.0 * config_model.n_embd))
							    + (tokenizer.vocab_size / (16.0 * config_model.n_layer * config_model.n_embd))
							)
							_UpperCAmelCase  :						Tuple							   =					flops_per_iteration / (elapsed_time * accelerator.state.num_processes * (10**12))
							return tflops

def 			UpperCamelCase_							(      _UpperCAmelCase						:   Dict					)					->					Dict:


							"""simple docstring"""







							model.eval()
							_UpperCAmelCase  :						Union[str, Any]							   =					[]
							for step, batch in enumerate(_UpperCAmelCase					):
														with torch.no_grad():
																					_UpperCAmelCase  :						int							   =					model(_UpperCAmelCase    ,			labels=_UpperCAmelCase					)
														_UpperCAmelCase  :						Optional[int]							   =					outputs.loss.repeat(args.valid_batch_size					)
														losses.append(accelerator.gather(_UpperCAmelCase					)					)
														if args.max_eval_steps > 0 and step >= args.max_eval_steps:
																					break
							_UpperCAmelCase  :						str							   =					torch.cat(_UpperCAmelCase					)
							_UpperCAmelCase  :						Dict							   =					losses[: eval_dataloader.dataset.current_size].mean()
							try:
														_UpperCAmelCase  :						int							   =					torch.exp(_UpperCAmelCase					)
							except OverflowError:
														_UpperCAmelCase  :						Dict							   =					float("inf"					)
							return loss.item(), perplexity.item()


# Settings
__SCREAMING_SNAKE_CASE :  int  =						HfArgumentParser(TrainingArguments)
__SCREAMING_SNAKE_CASE :  Optional[Any]  =						parser.parse_args()

# Accelerator
__SCREAMING_SNAKE_CASE :  Any  =						ProjectConfiguration(project_dir=args.save_dir, logging_dir="""log""")
__SCREAMING_SNAKE_CASE :  Optional[int]  =						Accelerator(log_with=["""wandb""", """tensorboard"""], project_config=config)
__SCREAMING_SNAKE_CASE :  List[Any]  =						{str(k): str(v) for k, v in accelerator.state.__dict__.items()}

__SCREAMING_SNAKE_CASE :  int  =						Namespace(**vars(args), **acc_state)
__SCREAMING_SNAKE_CASE :  int  =						accelerator.state.num_processes * args.train_batch_size
set_seed(args.seed)

# Clone model repository
if accelerator.is_main_process:
		__SCREAMING_SNAKE_CASE :  Tuple  =						Repository(args.save_dir, clone_from=args.model_ckpt)

# Logging
__SCREAMING_SNAKE_CASE :  str  =						setup_logging(args)
logger.info(accelerator.state)

# Checkout new branch on repo
if accelerator.is_main_process:
		hf_repo.git_checkout(run_name, create_branch_ok=True)

# Load model and tokenizer
__SCREAMING_SNAKE_CASE :  str  =						AutoModelForCausalLM.from_pretrained(args.save_dir)
if args.gradient_checkpointing:
		model.gradient_checkpointing_enable()
__SCREAMING_SNAKE_CASE :  int  =						AutoTokenizer.from_pretrained(args.save_dir)

# Load dataset and dataloader
__SCREAMING_SNAKE_CASE :  int  =						create_dataloaders(args)

# Prepare the optimizer and learning rate scheduler
__SCREAMING_SNAKE_CASE :  Dict  =						AdamW(get_grouped_params(model, args), lr=args.learning_rate)
__SCREAMING_SNAKE_CASE :  Tuple  =						get_scheduler(
    name=args.lr_scheduler_type,
    optimizer=optimizer,
    num_warmup_steps=args.num_warmup_steps,
    num_training_steps=args.max_train_steps,
)
accelerator.register_for_checkpointing(lr_scheduler)

def 			UpperCamelCase_							(      )					->					Union[str, Any]:


							"""simple docstring"""







							return optimizer.param_groups[0]["lr"]


# Prepare everything with our `accelerator`.
__SCREAMING_SNAKE_CASE :  Optional[int]  =						accelerator.prepare(
    model, optimizer, train_dataloader, eval_dataloader
)

# load in the weights and states from a previous save
if args.resume_from_checkpoint:
		if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
				accelerator.print(F'Resumed from checkpoint: {args.resume_from_checkpoint}')
				accelerator.load_state(args.resume_from_checkpoint)
				__SCREAMING_SNAKE_CASE :  List[Any]  =						os.path.basename(args.resume_from_checkpoint)
		else:
				# Get the most recent checkpoint
				__SCREAMING_SNAKE_CASE :  str  =						[f.name for f in os.scandir(args.save_dir) if f.is_dir() and """step""" in str(f)]
				dirs.sort(key=os.path.getctime)
				__SCREAMING_SNAKE_CASE :  Tuple  =						dirs[-1]  # Sorts folders by date modified, most recent checkpoint is the last
		# Extract the step of the checkpoint to continue from there
		__SCREAMING_SNAKE_CASE :  str  =						os.path.splitext(path)[0]
		__SCREAMING_SNAKE_CASE :  str  =						int(training_difference.replace("""step_""", """"""))

# Train model
model.train()
__SCREAMING_SNAKE_CASE :  Optional[Any]  =						0
__SCREAMING_SNAKE_CASE :  Optional[Any]  =						time.time()
__SCREAMING_SNAKE_CASE :  Optional[int]  =						0
for step, batch in enumerate(train_dataloader, start=1):
		if args.resume_from_checkpoint and step < resume_step:
				continue  # we need to skip steps until we reach the resumed step
		__SCREAMING_SNAKE_CASE :  Optional[Any]  =						model(batch, labels=batch, use_cache=False).loss
		__SCREAMING_SNAKE_CASE :  List[str]  =						accelerator.gather(loss.repeat(args.train_batch_size)).mean()
		loss_tracking += avg_loss.item() / args.gradient_accumulation_steps
		log_metrics(step, {"""samples""": step * samples_per_step, """loss_per_step/train""": loss.item()})
		__SCREAMING_SNAKE_CASE :  List[str]  =						loss / args.gradient_accumulation_steps
		if step % args.gradient_accumulation_steps != 0:
				# Prevent backward from doing gradient all_reduce in every step
				if accelerator.distributed_type == DistributedType.MULTI_GPU:
						with model.no_sync():
								accelerator.backward(loss)
				else:
						accelerator.backward(loss)
		else:
				__SCREAMING_SNAKE_CASE :  str  =						get_lr()
				accelerator.backward(loss)
				accelerator.clip_grad_norm_(model.parameters(), 1.0)
				optimizer.step()
				lr_scheduler.step()
				optimizer.zero_grad()
				__SCREAMING_SNAKE_CASE :  Optional[Any]  =						time.time() - t_start
				__SCREAMING_SNAKE_CASE :  int  =						compute_tflops(elapsed_time, accelerator, args)
				log_metrics(
				    step,
				    {
				        """steps""": completed_steps,
				        """loss/train""": loss_tracking,
				        """lr""": lr,
				        """tflops""": tflops,
				        """time_per_iteration""": elapsed_time,
				    },
				)
				__SCREAMING_SNAKE_CASE :  str  =						time.time()
				__SCREAMING_SNAKE_CASE :  Any  =						0
				completed_steps += 1
		if step % args.save_checkpoint_steps == 0:
				logger.info("""Evaluating and saving model checkpoint""")
				__SCREAMING_SNAKE_CASE :  int  =						evaluate(args)
				log_metrics(step, {"""loss/eval""": eval_loss, """perplexity""": perplexity})
				accelerator.wait_for_everyone()
				__SCREAMING_SNAKE_CASE :  str  =						os.path.join(args.save_dir, F'step_{step}')
				accelerator.save_state(save_dir)
				if accelerator.is_main_process:
						hf_repo.push_to_hub(commit_message=F'step {step}')
				model.train()
		if completed_steps >= args.max_train_steps:
				break

# Evaluate and save the last checkpoint
logger.info("""Evaluating and saving model after training""")
__SCREAMING_SNAKE_CASE :  List[Any]  =						evaluate(args)
log_metrics(step, {"""loss/eval""": eval_loss, """perplexity""": perplexity})
accelerator.wait_for_everyone()
__SCREAMING_SNAKE_CASE :  Dict  =						accelerator.unwrap_model(model)
unwrapped_model.save_pretrained(args.save_dir, save_function=accelerator.save)
__SCREAMING_SNAKE_CASE :  Dict  =						os.path.join(args.save_dir, F'step_{step}')
accelerator.save_state(save_dir)
if accelerator.is_main_process:
		hf_repo.push_to_hub(commit_message="""final model""")


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

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




      def   _A			( self		:       Any ):
             _UpperCAmelCase  :						Union[str, Any]							   =					ids_tensor([self.batch_size, self.seq_length]		,      self.vocab_size )

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

             _UpperCAmelCase  :						List[str]							   =					None
             if self.use_token_type_ids:
                    _UpperCAmelCase  :						Optional[Any]							   =					ids_tensor([self.batch_size, self.seq_length]		,      self.type_vocab_size )

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

             _UpperCAmelCase  :						Any							   =					self.get_config()

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




      def   _A			( self		:       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=A		,      initializer_range=self.initializer_range		,      )




      def   _A			( self		:       Union[str, Any] ):
             (
                 (
                 _UpperCAmelCase
             )   ,						(
                 _UpperCAmelCase
             )   ,						(
                 _UpperCAmelCase
             )   ,						(
                 _UpperCAmelCase
             )   ,						(
                 _UpperCAmelCase
             )   ,						(
                 _UpperCAmelCase
             )   ,						(
                 _UpperCAmelCase
             )   ,						(
                 _UpperCAmelCase
             )   ,						
             )  :						Dict							   =					self.prepare_config_and_inputs()

             _UpperCAmelCase  :						int							   =					True
             _UpperCAmelCase  :						Any							   =					floats_tensor([self.batch_size, self.seq_length, self.hidden_size] )
             _UpperCAmelCase  :						List[Any]							   =					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   _A			( self		:       Union[str, Any]		,      A		:       Dict		,      A		:       int		,      A		:       Any		,      A		:       Tuple		,      A		:       Union[str, Any]		,      A		:       int		,      A		:       str		,      A		:       Union[str, Any]		,      ):
             _UpperCAmelCase  :						Any							   =					ElectraModel(config=A )
             model.to(A )
             model.eval()
             _UpperCAmelCase  :						Optional[int]							   =					model(A		,      attention_mask=A		,      token_type_ids=A )
             _UpperCAmelCase  :						Tuple							   =					model(A		,      token_type_ids=A )
             _UpperCAmelCase  :						List[str]							   =					model(A )
             self.parent.assertEqual(result.last_hidden_state.shape		,      (self.batch_size, self.seq_length, self.hidden_size) )




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




      def   _A			( self		:       Optional[int]		,      A		:       int		,      A		:       Optional[Any]		,      A		:       int		,      A		:       Tuple		,      A		:       List[str]		,      A		:       Optional[Any]		,      A		:       str		,      A		:       Dict		,      ):
             _UpperCAmelCase  :						Optional[Any]							   =					ElectraForMaskedLM(config=A )
             model.to(A )
             model.eval()
             _UpperCAmelCase  :						int							   =					model(A		,      attention_mask=A		,      token_type_ids=A		,      labels=A )
             self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.seq_length, self.vocab_size) )




      def   _A			( self		:       Optional[Any]		,      A		:       Optional[int]		,      A		:       Optional[int]		,      A		:       Any		,      A		:       str		,      A		:       Optional[int]		,      A		:       Any		,      A		:       str		,      A		:       int		,      A		:       Dict		,      ):
             _UpperCAmelCase  :						Tuple							   =					ElectraForCausalLM(config=A )
             model.to(A )
             model.eval()
             _UpperCAmelCase  :						List[Any]							   =					model(A		,      attention_mask=A		,      token_type_ids=A		,      labels=A )
             self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.seq_length, self.vocab_size) )




      def   _A			( self		:       List[str]		,      A		:       Tuple		,      A		:       Dict		,      A		:       Tuple		,      A		:       List[str]		,      A		:       List[Any]		,      A		:       Optional[Any]		,      A		:       str		,      A		:       Dict		,      ):
             _UpperCAmelCase  :						Any							   =					self.num_labels
             _UpperCAmelCase  :						Tuple							   =					ElectraForTokenClassification(config=A )
             model.to(A )
             model.eval()
             _UpperCAmelCase  :						Union[str, Any]							   =					model(A		,      attention_mask=A		,      token_type_ids=A		,      labels=A )
             self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.seq_length, self.num_labels) )




      def   _A			( self		:       Union[str, Any]		,      A		:       Optional[Any]		,      A		:       Optional[int]		,      A		:       Union[str, Any]		,      A		:       str		,      A		:       Union[str, Any]		,      A		:       Tuple		,      A		:       Optional[int]		,      A		:       Optional[int]		,      ):
             _UpperCAmelCase  :						Union[str, Any]							   =					self.num_labels
             _UpperCAmelCase  :						int							   =					ElectraForPreTraining(config=A )
             model.to(A )
             model.eval()
             _UpperCAmelCase  :						Dict							   =					model(A		,      attention_mask=A		,      token_type_ids=A		,      labels=A )
             self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.seq_length) )




      def   _A			( self		:       Union[str, Any]		,      A		:       List[Any]		,      A		:       int		,      A		:       int		,      A		:       Optional[int]		,      A		:       Optional[Any]		,      A		:       Dict		,      A		:       str		,      A		:       Any		,      ):
             _UpperCAmelCase  :						Union[str, Any]							   =					self.num_labels
             _UpperCAmelCase  :						List[str]							   =					ElectraForSequenceClassification(A )
             model.to(A )
             model.eval()
             _UpperCAmelCase  :						str							   =					model(A		,      attention_mask=A		,      token_type_ids=A		,      labels=A )
             self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.num_labels) )




      def   _A			( self		:       List[str]		,      A		:       Optional[Any]		,      A		:       Optional[int]		,      A		:       Tuple		,      A		:       Optional[Any]		,      A		:       int		,      A		:       List[str]		,      A		:       Tuple		,      A		:       Optional[int]		,      ):
             _UpperCAmelCase  :						List[str]							   =					ElectraForQuestionAnswering(config=A )
             model.to(A )
             model.eval()
             _UpperCAmelCase  :						Any							   =					model(
                 A		,      attention_mask=A		,      token_type_ids=A		,      start_positions=A		,      end_positions=A		,      )
             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   _A			( self		:       int		,      A		:       Optional[Any]		,      A		:       Optional[Any]		,      A		:       Tuple		,      A		:       Dict		,      A		:       Optional[Any]		,      A		:       Union[str, Any]		,      A		:       Optional[Any]		,      A		:       str		,      ):
             _UpperCAmelCase  :						Tuple							   =					self.num_choices
             _UpperCAmelCase  :						int							   =					ElectraForMultipleChoice(config=A )
             model.to(A )
             model.eval()
             _UpperCAmelCase  :						str							   =					input_ids.unsqueeze(1 ).expand(-1		,      self.num_choices		,      -1 ).contiguous()
             _UpperCAmelCase  :						Dict							   =					token_type_ids.unsqueeze(1 ).expand(-1		,      self.num_choices		,      -1 ).contiguous()
             _UpperCAmelCase  :						Union[str, Any]							   =					input_mask.unsqueeze(1 ).expand(-1		,      self.num_choices		,      -1 ).contiguous()
             _UpperCAmelCase  :						Union[str, Any]							   =					model(
                 A		,      attention_mask=A		,      token_type_ids=A		,      labels=A		,      )
             self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.num_choices) )





      def   _A			( self		:       Any ):
             _UpperCAmelCase  :						List[Any]							   =					self.prepare_config_and_inputs()
             (
                 (
                 _UpperCAmelCase
             )   ,						(
                 _UpperCAmelCase
             )   ,						(
                 _UpperCAmelCase
             )   ,						(
                 _UpperCAmelCase
             )   ,						(
                 _UpperCAmelCase
             )   ,						(
                 _UpperCAmelCase
             )   ,						(
                 _UpperCAmelCase
             )   ,						(
                 _UpperCAmelCase
             )   ,						
             )  :						Tuple							   =					config_and_inputs
             _UpperCAmelCase  :						List[Any]							   =					{"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
             return config, inputs_dict

@require_torch
class 			lowerCamelCase_			(snake_case__							,				snake_case__							,				unittest.TestCase					):
      '''simple docstring'''

      __UpperCamelCase:						Tuple      			=		(
          (
              ElectraModel,
              ElectraForPreTraining,
              ElectraForMaskedLM,
              ElectraForCausalLM,
              ElectraForMultipleChoice,
              ElectraForTokenClassification,
              ElectraForSequenceClassification,
              ElectraForQuestionAnswering,
          )
          if is_torch_available()
          else ()
      )
      __UpperCamelCase:						Optional[Any]      			=		(
          {
              "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:						str      			=		True




      def   _A			( self		:       Optional[Any]		,      A		:       Tuple		,      A		:       Optional[Any]		,      A		:       List[Any]=False ):
             _UpperCAmelCase  :						int							   =					super()._prepare_for_class(A		,      A		,      return_labels=A )

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




      def   _A			( self		:       Optional[int] ):
             _UpperCAmelCase  :						Any							   =					ElectraModelTester(self )
             _UpperCAmelCase  :						Tuple							   =					ConfigTester(self		,      config_class=A		,      hidden_size=37 )




      def   _A			( self		:       Tuple ):
             self.config_tester.run_common_tests()




      def   _A			( self		:       Dict ):
             _UpperCAmelCase  :						Dict							   =					self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_electra_model(*A )




      def   _A			( self		:       int ):
             _UpperCAmelCase  :						List[Any]							   =					self.model_tester.prepare_config_and_inputs_for_decoder()
             self.model_tester.create_and_check_electra_model_as_decoder(*A )




      def   _A			( self		:       Union[str, Any] ):
             _UpperCAmelCase  :						Optional[Any]							   =					self.model_tester.prepare_config_and_inputs()
             for type in ["absolute", "relative_key", "relative_key_query"]:
                    _UpperCAmelCase  :						Optional[int]							   =					type
                    self.model_tester.create_and_check_electra_model(*A )




      def   _A			( self		:       Optional[Any] ):
             _UpperCAmelCase  :						Optional[Any]							   =					self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_electra_for_masked_lm(*A )




      def   _A			( self		:       Any ):
             _UpperCAmelCase  :						Optional[Any]							   =					self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_electra_for_token_classification(*A )




      def   _A			( self		:       str ):
             _UpperCAmelCase  :						int							   =					self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_electra_for_pretraining(*A )




      def   _A			( self		:       Tuple ):
             _UpperCAmelCase  :						List[str]							   =					self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_electra_for_sequence_classification(*A )




      def   _A			( self		:       Dict ):
             _UpperCAmelCase  :						List[Any]							   =					self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_electra_for_question_answering(*A )




      def   _A			( self		:       Dict ):
             _UpperCAmelCase  :						Optional[int]							   =					self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_electra_for_multiple_choice(*A )




      @slow
      def   _A			( self		:       Union[str, Any] ):
             for model_name in ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    _UpperCAmelCase  :						List[Any]							   =					ElectraModel.from_pretrained(A )
                    self.assertIsNotNone(A )





      def   _A			( self		:       List[Any] ):
             _UpperCAmelCase  :						Union[str, Any]							   =					self.model_tester.prepare_config_and_inputs_for_decoder()
             self.model_tester.create_and_check_electra_for_causal_lm(*A )

@require_torch
class 			lowerCamelCase_			(unittest.TestCase					):
      '''simple docstring'''

      @slow
      def   _A			( self		:       List[Any] ):
             _UpperCAmelCase  :						List[Any]							   =					ElectraModel.from_pretrained("google/electra-small-discriminator" )
             _UpperCAmelCase  :						List[Any]							   =					torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] )
             _UpperCAmelCase  :						List[str]							   =					torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
             _UpperCAmelCase  :						str							   =					model(A		,      attention_mask=A )[0]
             _UpperCAmelCase  :						Union[str, Any]							   =					torch.Size((1, 11, 256) )
             self.assertEqual(output.shape		,      A )
             _UpperCAmelCase  :						Optional[Any]							   =					torch.tensor(
                 [[[0.4_471, 0.6_821, -0.3_265], [0.4_627, 0.5_255, -0.3_668], [0.4_532, 0.3_313, -0.4_344]]] )

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

