




"""simple docstring"""

import logging
import pathlib
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Set, Union

import datasets
import librosa
import numpy as np
import torch
from lang_trans import arabic
from packaging import version
from torch import nn

from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    trainer_utils,
)


if is_apex_available():
						from apex import amp

if version.parse(version.parse(torch.__version__).base_version) >= version.parse("1.6"):
						__lowerCamelCase								=						True
						from torch.cuda.amp import autocast


__lowerCamelCase								=						logging.getLogger(__name__)



@dataclass
class  _snake_case				:

				'''simple docstring'''




				UpperCamelCase__		     =field(
				    metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}       )
				UpperCamelCase__		     =field(
				    default=A__							,						metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}							,						)
				UpperCamelCase__		     =field(
				    default=A__							,						metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""}       )
				UpperCamelCase__		     =field(
				    default=A__							,						metadata={"""help""": """Whether to log verbose messages or not."""}							,						)



def 				a (						__snake_case     :				ModelArguments,    __snake_case     :				TrainingArguments  ):



				'''simple docstring'''





				logging.basicConfig(
				    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''',    datefmt='''%m/%d/%Y %H:%M:%S''',    handlers=[logging.StreamHandler(sys.stdout  )],    )
				UpperCAmelCase_					:List[Any]      			=      logging.WARNING
				if model_args.verbose_logging:
								UpperCAmelCase_					:List[Any]      			=      logging.DEBUG
				elif trainer_utils.is_main_process(training_args.local_rank  ):
								UpperCAmelCase_					:str      			=      logging.INFO
				logger.setLevel(__snake_case  )



@dataclass
class  _snake_case				:

				'''simple docstring'''




				UpperCamelCase__		     =field(
				    default=A__							,						metadata={"""help""": """The name of the dataset to use (via the datasets library)."""}       )
				UpperCamelCase__		     =field(
				    default=A__							,						metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}       )
				UpperCamelCase__		     =field(
				    default="""train"""							,						metadata={
				        """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'"""
				    }							,						)
				UpperCamelCase__		     =field(
				    default="""validation"""							,						metadata={
				        """help""": (
				            """The name of the validation data set split to use (via the datasets library). Defaults to 'validation'"""
				        )
				    }							,						)
				UpperCamelCase__		     =field(
				    default="""text"""							,						metadata={"""help""": """Column in the dataset that contains label (target text). Defaults to 'text'"""}							,						)
				UpperCamelCase__		     =field(
				    default="""file"""							,						metadata={"""help""": """Column in the dataset that contains speech file path. Defaults to 'file'"""}							,						)
				UpperCamelCase__		     =field(
				    default=A__							,						metadata={"""help""": """Resample loaded audio to target feature extractor's sampling rate or not."""}							,						)
				UpperCamelCase__		     =field(
				    default=A__							,						metadata={"""help""": """Filters out examples longer than specified. Defaults to no filtering."""}							,						)
				UpperCamelCase__		     =field(
				    default="""librispeech"""							,						metadata={
				        """help""": (
				            """Orthography used for normalization and tokenization: 'librispeech' (default), 'timit', or"""
				            """ 'buckwalter'."""
				        )
				    }							,						)
				UpperCamelCase__		     =field(
				    default=A__							,						metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}       )
				UpperCamelCase__		     =field(
				    default=A__							,						metadata={"""help""": """The number of processes to use for the preprocessing."""}							,						)



@dataclass
class  _snake_case				:

				'''simple docstring'''




				UpperCamelCase__		     =False
				UpperCamelCase__		     =None
				UpperCamelCase__		     ="|"
				UpperCamelCase__		     =field(default_factory=A__       )
				UpperCamelCase__		     =field(default_factory=A__       )
				UpperCamelCase__		     =None





				@classmethod
				def 				snake_case_ (							cls      :  Optional[Any]					,							snake_case      :  str     ):
								if name == "librispeech":
												return cls()
								if name == "timit":
												return cls(
												    do_lower_case=snake_case					,							translation_table=str.maketrans({'''-''': ''' '''}     )					,							)
								if name == "buckwalter":
												UpperCAmelCase_					:int      			=      {
												    '''-''': ''' ''',  # sometimes used to represent pauses
												    '''^''': '''v''',  # fixing "tha" in arabic_speech_corpus dataset
												}
												return cls(
												    vocab_file=pathlib.Path(snake_case     ).parent.joinpath('''vocab/buckwalter.json'''     )					,							word_delimiter_token='''/'''					,							translation_table=str.maketrans(snake_case     )					,							words_to_remove={'''sil'''}					,							untransliterator=arabic.buckwalter.untransliterate					,							)
								raise ValueError(f'Unsupported orthography: \'{name}\'.'     )





				def 				snake_case_ (							self      :  List[str]					,							snake_case      :  str     ):
								# TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
								if len(self.translation_table     ) > 0:
												UpperCAmelCase_					:str      			=      text.translate(self.translation_table     )
								if len(self.words_to_remove     ) == 0:
												UpperCAmelCase_					:List[Any]      			=      ''' '''.join(text.split()     )  # clean up whitespaces
								else:
												UpperCAmelCase_					:Union[str, Any]      			=      ''' '''.join(w for w in text.split() if w not in self.words_to_remove     )  # and clean up whilespaces
								return text





				def 				snake_case_ (							self      :  Tuple					,							snake_case      :  ModelArguments     ):
								UpperCAmelCase_					:Dict      			=      WavaVecaFeatureExtractor.from_pretrained(
								    model_args.model_name_or_path					,							cache_dir=model_args.cache_dir     )
								if self.vocab_file:
												UpperCAmelCase_					:Tuple      			=      WavaVecaCTCTokenizer(
												    self.vocab_file					,							cache_dir=model_args.cache_dir					,							do_lower_case=self.do_lower_case					,							word_delimiter_token=self.word_delimiter_token					,							)
								else:
												UpperCAmelCase_					:Optional[Any]      			=      WavaVecaCTCTokenizer.from_pretrained(
												    model_args.model_name_or_path					,							cache_dir=model_args.cache_dir					,							do_lower_case=self.do_lower_case					,							word_delimiter_token=self.word_delimiter_token					,							)
								return WavaVecaProcessor(snake_case					,							snake_case     )



@dataclass
class  _snake_case				:

				'''simple docstring'''




				UpperCamelCase__		     =42
				UpperCamelCase__		     =True
				UpperCamelCase__		     =None
				UpperCamelCase__		     =None
				UpperCamelCase__		     =None
				UpperCamelCase__		     =None





				def __call__(							self      :  Union[str, Any]					,							snake_case      :  List[Dict[str, Union[List[int], torch.Tensor]]]     ):
								# split inputs and labels since they have to be of different lenghts and need
								# different padding methods
								UpperCAmelCase_					:List[str]      			=      [{'''input_values''': feature['''input_values''']} for feature in features]
								UpperCAmelCase_					:List[Any]      			=      [{'''input_ids''': feature['''labels''']} for feature in features]

								UpperCAmelCase_					:Any      			=      self.processor.pad(
								    snake_case					,							padding=self.padding					,							max_length=self.max_length					,							pad_to_multiple_of=self.pad_to_multiple_of					,							return_tensors='''pt'''					,							)
								UpperCAmelCase_					:List[Any]      			=      self.processor.pad(
								    labels=snake_case					,							padding=self.padding					,							max_length=self.max_length_labels					,							pad_to_multiple_of=self.pad_to_multiple_of_labels					,							return_tensors='''pt'''					,							)

								# replace padding with -100 to ignore loss correctly
								UpperCAmelCase_					:Optional[Any]      			=      labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1     )					,							-100     )

								UpperCAmelCase_					:Union[str, Any]      			=      labels

								return batch



class  _snake_case				(							A__       ):

				'''simple docstring'''




				def 				snake_case_ (							self      :  str					,							snake_case      :  nn.Module					,							snake_case      :  Dict[str, Union[torch.Tensor, Any]]     ):
								model.train()
								UpperCAmelCase_					:Any      			=      self._prepare_inputs(snake_case     )

								if self.use_amp:
												with autocast():
																UpperCAmelCase_					:Tuple      			=      self.compute_loss(snake_case					,							snake_case     )
								else:
												UpperCAmelCase_					:Any      			=      self.compute_loss(snake_case					,							snake_case     )

								if self.args.n_gpu > 1:
												if model.module.config.ctc_loss_reduction == "mean":
																UpperCAmelCase_					:int      			=      loss.mean()
												elif model.module.config.ctc_loss_reduction == "sum":
																UpperCAmelCase_					:Union[str, Any]      			=      loss.sum() / (inputs['''labels'''] >= 0).sum()
												else:
																raise ValueError(f'{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']'     )

								if self.args.gradient_accumulation_steps > 1:
												UpperCAmelCase_					:Tuple      			=      loss / self.args.gradient_accumulation_steps

								if self.use_amp:
												self.scaler.scale(snake_case     ).backward()
								elif self.use_apex:
												with amp.scale_loss(snake_case					,							self.optimizer     ) as scaled_loss:
																scaled_loss.backward()
								elif self.deepspeed:
												self.deepspeed.backward(snake_case     )
								else:
												loss.backward()

								return loss.detach()



def 				a (						):



				'''simple docstring'''





				UpperCAmelCase_					:Union[str, Any]      			=      HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)  )

				UpperCAmelCase_			,UpperCAmelCase_			,UpperCAmelCase_					:Optional[Any]      			=      parser.parse_args_into_dataclasses()
				configure_logger(__snake_case,    __snake_case  )

				UpperCAmelCase_					:List[str]      			=      Orthography.from_name(data_args.orthography.lower()  )
				UpperCAmelCase_					:Tuple      			=      orthography.create_processor(__snake_case  )
				UpperCAmelCase_					:Union[str, Any]      			=      WavaVecaForCTC.from_pretrained(
				    model_args.model_name_or_path,    cache_dir=model_args.cache_dir,    gradient_checkpointing=training_args.gradient_checkpointing,    vocab_size=len(processor.tokenizer  ),    )

				UpperCAmelCase_					:Any      			=      datasets.load_dataset(
				    data_args.dataset_name,    data_args.dataset_config_name,    split=data_args.train_split_name  )
				UpperCAmelCase_					:Tuple      			=      datasets.load_dataset(
				    data_args.dataset_name,    data_args.dataset_config_name,    split=data_args.validation_split_name  )

				UpperCAmelCase_					:Dict      			=      datasets.load_metric('''wer'''  )
				UpperCAmelCase_					:int      			=      processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
				UpperCAmelCase_					:Optional[Any]      			=      ''''''.join(t for t in processor.tokenizer.get_vocab().keys() if len(__snake_case  ) == 1  )
				UpperCAmelCase_					:List[str]      			=      re.compile(  # remove characters not in vocabulary
				    rf'[^\s{re.escape(__snake_case  )}]',    flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0,    )
				UpperCAmelCase_					:str      			=      []

				def prepare_example(__snake_case     :				str  ):  # TODO(elgeish) make use of multiprocessing?
								UpperCAmelCase_			,UpperCAmelCase_					:Dict      			=      librosa.load(example[data_args.speech_file_column],    sr=__snake_case  )
								if data_args.max_duration_in_seconds is not None:
												UpperCAmelCase_					:List[Any]      			=      len(example['''speech''']  ) / example['''sampling_rate''']
								# Normalize and clean up text; order matters!
								UpperCAmelCase_					:str      			=      orthography.preprocess_for_training(example[data_args.target_text_column]  )
								UpperCAmelCase_					:Tuple      			=      vocabulary_text_cleaner.sub('''''',    __snake_case  )
								if updated_text != example[data_args.target_text_column]:
												text_updates.append((example[data_args.target_text_column], updated_text)  )
												UpperCAmelCase_					:Tuple      			=      updated_text
								return example

				UpperCAmelCase_					:Dict      			=      train_dataset.map(__snake_case,    remove_columns=[data_args.speech_file_column]  )
				UpperCAmelCase_					:Union[str, Any]      			=      val_dataset.map(__snake_case,    remove_columns=[data_args.speech_file_column]  )

				if data_args.max_duration_in_seconds is not None:

								def filter_by_max_duration(__snake_case     :				Any  ):
												return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

								UpperCAmelCase_					:str      			=      len(__snake_case  )
								UpperCAmelCase_					:Any      			=      len(__snake_case  )
								UpperCAmelCase_					:int      			=      train_dataset.filter(__snake_case,    remove_columns=['''duration_in_seconds''']  )
								UpperCAmelCase_					:int      			=      val_dataset.filter(__snake_case,    remove_columns=['''duration_in_seconds''']  )
								if len(__snake_case  ) > old_train_size:
												logger.warning(
												    f'Filtered out {len(__snake_case  ) - old_train_size} train example(s) longer than'
												    f' {data_args.max_duration_in_seconds} second(s).'  )
								if len(__snake_case  ) > old_val_size:
												logger.warning(
												    f'Filtered out {len(__snake_case  ) - old_val_size} validation example(s) longer than'
												    f' {data_args.max_duration_in_seconds} second(s).'  )
				logger.info(f'Split sizes: {len(__snake_case  )} train and {len(__snake_case  )} validation.'  )

				logger.warning(f'Updated {len(__snake_case  )} transcript(s) using \'{data_args.orthography}\' orthography rules.'  )
				if logger.isEnabledFor(logging.DEBUG  ):
								for original_text, updated_text in text_updates:
												logger.debug(f'Updated text: "{original_text}" -> "{updated_text}"'  )
				UpperCAmelCase_					:Tuple      			=      None

				def prepare_dataset(__snake_case     :				Dict  ):
								# check that all files have the correct sampling rate
								assert (
								    len(set(batch['''sampling_rate''']  )  ) == 1
								), f'Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.'

								UpperCAmelCase_					:str      			=      processor(
								    audio=batch['''speech'''],    text=batch[data_args.target_text_column],    sampling_rate=batch['''sampling_rate'''][0]  )
								batch.update(__snake_case  )
								return batch

				UpperCAmelCase_					:List[Any]      			=      train_dataset.map(
				    __snake_case,    batch_size=training_args.per_device_train_batch_size,    batched=__snake_case,    num_proc=data_args.preprocessing_num_workers,    )
				UpperCAmelCase_					:Tuple      			=      val_dataset.map(
				    __snake_case,    batch_size=training_args.per_device_train_batch_size,    batched=__snake_case,    num_proc=data_args.preprocessing_num_workers,    )

				UpperCAmelCase_					:str      			=      DataCollatorCTCWithPadding(processor=__snake_case,    padding=__snake_case  )

				def compute_metrics(__snake_case     :				List[Any]  ):
								UpperCAmelCase_					:int      			=      pred.predictions
								UpperCAmelCase_					:int      			=      np.argmax(__snake_case,    axis=-1  )

								UpperCAmelCase_					:Union[str, Any]      			=      processor.tokenizer.pad_token_id

								UpperCAmelCase_					:Any      			=      processor.batch_decode(__snake_case  )
								# we do not want to group tokens when computing the metrics
								UpperCAmelCase_					:List[str]      			=      processor.batch_decode(pred.label_ids,    group_tokens=__snake_case  )
								if logger.isEnabledFor(logging.DEBUG  ):
												for reference, predicted in zip(__snake_case,    __snake_case  ):
																logger.debug(f'reference: "{reference}"'  )
																logger.debug(f'predicted: "{predicted}"'  )
																if orthography.untransliterator is not None:
																				logger.debug(f'reference (untransliterated): "{orthography.untransliterator(__snake_case  )}"'  )
																				logger.debug(f'predicted (untransliterated): "{orthography.untransliterator(__snake_case  )}"'  )

								UpperCAmelCase_					:Any      			=      wer_metric.compute(predictions=__snake_case,    references=__snake_case  )

								return {"wer": wer}

				if model_args.freeze_feature_extractor:
								model.freeze_feature_extractor()

				UpperCAmelCase_					:Tuple      			=      CTCTrainer(
				    model=__snake_case,    data_collator=__snake_case,    args=__snake_case,    compute_metrics=__snake_case,    train_dataset=__snake_case,    eval_dataset=__snake_case,    tokenizer=processor.feature_extractor,    )

				trainer.train()


if __name__ == "__main__":
						main()








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

				'''simple docstring'''




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





				def 				snake_case_ (							self      :  Tuple     ):
								UpperCAmelCase_					:str      			=      ids_tensor([self.batch_size, self.seq_length]					,							self.vocab_size     )

								UpperCAmelCase_					:Optional[int]      			=      None
								if self.use_input_mask:
												UpperCAmelCase_					:Any      			=      random_attention_mask([self.batch_size, self.seq_length]     )

								UpperCAmelCase_					:Optional[Any]      			=      None
								if self.use_token_type_ids:
												UpperCAmelCase_					:Dict      			=      ids_tensor([self.batch_size, self.seq_length]					,							self.type_vocab_size     )

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

								UpperCAmelCase_					:Dict      			=      self.get_config()

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





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





				def 				snake_case_ (							self      :  List[Any]     ):
								(
								    (
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,
								)					:str      			=      self.prepare_config_and_inputs()

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





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





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





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





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





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





				def 				snake_case_ (							self      :  Dict					,							snake_case      :  Any					,							snake_case      :  List[Any]					,							snake_case      :  Optional[int]					,							snake_case      :  Optional[Any]					,							snake_case      :  Optional[int]					,							snake_case      :  Dict					,							snake_case      :  int					,							snake_case      :  int					,							):
								UpperCAmelCase_					:Optional[Any]      			=      self.num_labels
								UpperCAmelCase_					:Optional[int]      			=      ElectraForSequenceClassification(snake_case     )
								model.to(snake_case     )
								model.eval()
								UpperCAmelCase_					:Any      			=      model(snake_case					,							attention_mask=snake_case					,							token_type_ids=snake_case					,							labels=snake_case     )
								self.parent.assertEqual(result.logits.shape					,							(self.batch_size, self.num_labels)     )





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





				def 				snake_case_ (							self      :  Any     ):
								UpperCAmelCase_					:List[Any]      			=      self.prepare_config_and_inputs()
								(
								    (
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,(
								    UpperCAmelCase_
								)			,
								)					:List[str]      			=      config_and_inputs
								UpperCAmelCase_					:Dict      			=      {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
								return config, inputs_dict



@require_torch
class  _snake_case				(							A__							,						A__							,						unittest.TestCase       ):

				'''simple docstring'''




				UpperCamelCase__		     =(
				    (
				        ElectraModel,
				        ElectraForPreTraining,
				        ElectraForMaskedLM,
				        ElectraForCausalLM,
				        ElectraForMultipleChoice,
				        ElectraForTokenClassification,
				        ElectraForSequenceClassification,
				        ElectraForQuestionAnswering,
				    )
				    if is_torch_available()
				    else ()
				)
				UpperCamelCase__		     =(
				    {
				        """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__		     =True





				def 				snake_case_ (							self      :  List[str]					,							snake_case      :  List[str]					,							snake_case      :  Tuple					,							snake_case      :  List[Any]=False     ):
								UpperCAmelCase_					:Optional[int]      			=      super()._prepare_for_class(snake_case					,							snake_case					,							return_labels=snake_case     )

								if return_labels:
												if model_class in get_values(snake_case     ):
																UpperCAmelCase_					:Dict      			=      torch.zeros(
																    (self.model_tester.batch_size, self.model_tester.seq_length)					,							dtype=torch.long					,							device=snake_case     )
								return inputs_dict





				def 				snake_case_ (							self      :  Optional[int]     ):
								UpperCAmelCase_					:int      			=      ElectraModelTester(self     )
								UpperCAmelCase_					:List[str]      			=      ConfigTester(self					,							config_class=snake_case					,							hidden_size=37     )





				def 				snake_case_ (							self      :  List[Any]     ):
								self.config_tester.run_common_tests()





				def 				snake_case_ (							self      :  List[Any]     ):
								UpperCAmelCase_					:Union[str, Any]      			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_electra_model(*snake_case     )





				def 				snake_case_ (							self      :  List[str]     ):
								UpperCAmelCase_					:str      			=      self.model_tester.prepare_config_and_inputs_for_decoder()
								self.model_tester.create_and_check_electra_model_as_decoder(*snake_case     )





				def 				snake_case_ (							self      :  Union[str, Any]     ):
								UpperCAmelCase_					:Dict      			=      self.model_tester.prepare_config_and_inputs()
								for type in ["absolute", "relative_key", "relative_key_query"]:
												UpperCAmelCase_					:Dict      			=      type
												self.model_tester.create_and_check_electra_model(*snake_case     )





				def 				snake_case_ (							self      :  str     ):
								UpperCAmelCase_					:Dict      			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_electra_for_masked_lm(*snake_case     )





				def 				snake_case_ (							self      :  Tuple     ):
								UpperCAmelCase_					:Dict      			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_electra_for_token_classification(*snake_case     )





				def 				snake_case_ (							self      :  Optional[int]     ):
								UpperCAmelCase_					:Optional[int]      			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_electra_for_pretraining(*snake_case     )





				def 				snake_case_ (							self      :  Dict     ):
								UpperCAmelCase_					:Any      			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_electra_for_sequence_classification(*snake_case     )





				def 				snake_case_ (							self      :  List[Any]     ):
								UpperCAmelCase_					:Union[str, Any]      			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_electra_for_question_answering(*snake_case     )





				def 				snake_case_ (							self      :  Any     ):
								UpperCAmelCase_					:int      			=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_electra_for_multiple_choice(*snake_case     )





				@slow
				def 				snake_case_ (							self      :  Dict     ):
								for model_name in ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												UpperCAmelCase_					:Optional[int]      			=      ElectraModel.from_pretrained(snake_case     )
												self.assertIsNotNone(snake_case     )





				def 				snake_case_ (							self      :  Any     ):
								UpperCAmelCase_					:Any      			=      self.model_tester.prepare_config_and_inputs_for_decoder()
								self.model_tester.create_and_check_electra_for_causal_lm(*snake_case     )



@require_torch
class  _snake_case				(							unittest.TestCase       ):

				'''simple docstring'''




				@slow
				def 				snake_case_ (							self      :  List[Any]     ):
								UpperCAmelCase_					:Optional[int]      			=      ElectraModel.from_pretrained('''google/electra-small-discriminator'''     )
								UpperCAmelCase_					:Dict      			=      torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]]     )
								UpperCAmelCase_					:int      			=      torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]     )
								UpperCAmelCase_					:Optional[int]      			=      model(snake_case					,							attention_mask=snake_case     )[0]
								UpperCAmelCase_					:Optional[Any]      			=      torch.Size((1, 11, 256)     )
								self.assertEqual(output.shape					,							snake_case     )
								UpperCAmelCase_					:Optional[int]      			=      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]					,							snake_case					,							atol=1e-4     )     )


