

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 		a_	:



      """simple docstring"""







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







def       snake_case__    (       lowerCAmelCase_,   lowerCAmelCase_      ):





     """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      )],   )
     SCREAMING_SNAKE_CASE										=logging.WARNING
     if model_args.verbose_logging:
          SCREAMING_SNAKE_CASE										=logging.DEBUG
     elif trainer_utils.is_main_process(training_args.local_rank      ):
          SCREAMING_SNAKE_CASE										=logging.INFO
     logger.setLevel(lowerCAmelCase_      )



@dataclass
class 		a_	:



      """simple docstring"""







      __UpperCAmelCase      		=				field(
          default=lowerCamelCase_			,      metadata={'help': 'The name of the dataset to use (via the datasets library).'}					)
      __UpperCAmelCase      		=				field(
          default=lowerCamelCase_			,      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=lowerCamelCase_			,      metadata={'help': 'Resample loaded audio to target feature extractor\'s sampling rate or not.'}			,      )
      __UpperCAmelCase      		=				field(
          default=lowerCamelCase_			,      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=lowerCamelCase_			,      metadata={'help': 'Overwrite the cached preprocessed datasets or not.'}					)
      __UpperCAmelCase      		=				field(
          default=lowerCamelCase_			,      metadata={'help': 'The number of processes to use for the preprocessing.'}			,      )







@dataclass
class 		a_	:



      """simple docstring"""







      __UpperCAmelCase      		=				False
      __UpperCAmelCase      		=				None
      __UpperCAmelCase      		=				"|"
      __UpperCAmelCase      		=				field(default_factory=lowerCamelCase_					)
      __UpperCAmelCase      		=				field(default_factory=lowerCamelCase_					)
      __UpperCAmelCase      		=				None
      @classmethod
      def 	_lowerCAmelCase					(				cls					:							List[str]      ,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":
                SCREAMING_SNAKE_CASE										={
                    '-': ' ',  # 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 	_lowerCAmelCase					(				self					:							Tuple      ,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:
                SCREAMING_SNAKE_CASE										=text.translate(self.translation_table    )
           if len(self.words_to_remove    ) == 0:
                SCREAMING_SNAKE_CASE										=' '.join(text.split()    )  # clean up whitespaces
           else:
                SCREAMING_SNAKE_CASE										=' '.join(w for w in text.split() if w not in self.words_to_remove    )  # and clean up whilespaces
           return text


      def 	_lowerCAmelCase					(				self					:							Any      ,snake_case					:							ModelArguments    ):
           SCREAMING_SNAKE_CASE										=WavaVecaFeatureExtractor.from_pretrained(
               model_args.model_name_or_path      ,cache_dir=model_args.cache_dir    )
           if self.vocab_file:
                SCREAMING_SNAKE_CASE										=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:
                SCREAMING_SNAKE_CASE										=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 		a_	:



      """simple docstring"""







      __UpperCAmelCase      		=				42
      __UpperCAmelCase      		=				True
      __UpperCAmelCase      		=				None
      __UpperCAmelCase      		=				None
      __UpperCAmelCase      		=				None
      __UpperCAmelCase      		=				None
      def __call__(				self					:							List[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
           SCREAMING_SNAKE_CASE										=[{'input_values': feature['input_values']} for feature in features]
           SCREAMING_SNAKE_CASE										=[{'input_ids': feature['labels']} for feature in features]

           SCREAMING_SNAKE_CASE										=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'      ,)
           SCREAMING_SNAKE_CASE										=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
           SCREAMING_SNAKE_CASE										=labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1    )      ,-100    )

           SCREAMING_SNAKE_CASE										=labels

           return batch







class 		a_	(							lowerCamelCase_					):



      """simple docstring"""







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

           if self.use_amp:
                with autocast():
                     SCREAMING_SNAKE_CASE										=self.compute_loss(snake_case      ,snake_case    )
           else:
                SCREAMING_SNAKE_CASE										=self.compute_loss(snake_case      ,snake_case    )

           if self.args.n_gpu > 1:
                if model.module.config.ctc_loss_reduction == "mean":
                     SCREAMING_SNAKE_CASE										=loss.mean()
                elif model.module.config.ctc_loss_reduction == "sum":
                     SCREAMING_SNAKE_CASE										=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:
                SCREAMING_SNAKE_CASE										=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       snake_case__    (       ):





     """simple docstring"""







     SCREAMING_SNAKE_CASE										=HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)      )

     SCREAMING_SNAKE_CASE						,  SCREAMING_SNAKE_CASE						,  SCREAMING_SNAKE_CASE										=parser.parse_args_into_dataclasses()
     configure_logger(lowerCAmelCase_,   lowerCAmelCase_      )

     SCREAMING_SNAKE_CASE										=Orthography.from_name(data_args.orthography.lower()      )
     SCREAMING_SNAKE_CASE										=orthography.create_processor(lowerCAmelCase_      )
     SCREAMING_SNAKE_CASE										=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      ),   )

     SCREAMING_SNAKE_CASE										=datasets.load_dataset(
         data_args.dataset_name,   data_args.dataset_config_name,   split=data_args.train_split_name      )
     SCREAMING_SNAKE_CASE										=datasets.load_dataset(
         data_args.dataset_name,   data_args.dataset_config_name,   split=data_args.validation_split_name      )

     SCREAMING_SNAKE_CASE										=datasets.load_metric('wer'      )
     SCREAMING_SNAKE_CASE										=processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
     SCREAMING_SNAKE_CASE										=''.join(t for t in processor.tokenizer.get_vocab().keys() if len(lowerCAmelCase_      ) == 1      )
     SCREAMING_SNAKE_CASE										=re.compile(  # remove characters not in vocabulary
         rF'[^\s{re.escape(lowerCAmelCase_      )}]',   flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0,   )
     SCREAMING_SNAKE_CASE										=[]

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

     SCREAMING_SNAKE_CASE										=train_dataset.map(lowerCAmelCase_,   remove_columns=[data_args.speech_file_column]      )
     SCREAMING_SNAKE_CASE										=val_dataset.map(lowerCAmelCase_,   remove_columns=[data_args.speech_file_column]      )

     if data_args.max_duration_in_seconds is not None:

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

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

     logger.warning(F'Updated {len(lowerCAmelCase_      )} 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}"'      )
     SCREAMING_SNAKE_CASE										=None

     def prepare_dataset(lowerCAmelCase_      ):
          # 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}.'

          SCREAMING_SNAKE_CASE										=processor(
              audio=batch['speech'],   text=batch[data_args.target_text_column],   sampling_rate=batch['sampling_rate'][0]      )
          batch.update(lowerCAmelCase_      )
          return batch

     SCREAMING_SNAKE_CASE										=train_dataset.map(
         lowerCAmelCase_,   batch_size=training_args.per_device_train_batch_size,   batched=lowerCAmelCase_,   num_proc=data_args.preprocessing_num_workers,   )
     SCREAMING_SNAKE_CASE										=val_dataset.map(
         lowerCAmelCase_,   batch_size=training_args.per_device_train_batch_size,   batched=lowerCAmelCase_,   num_proc=data_args.preprocessing_num_workers,   )

     SCREAMING_SNAKE_CASE										=DataCollatorCTCWithPadding(processor=lowerCAmelCase_,   padding=lowerCAmelCase_      )

     def compute_metrics(lowerCAmelCase_      ):
          SCREAMING_SNAKE_CASE										=pred.predictions
          SCREAMING_SNAKE_CASE										=np.argmax(lowerCAmelCase_,   axis=-1      )

          SCREAMING_SNAKE_CASE										=processor.tokenizer.pad_token_id

          SCREAMING_SNAKE_CASE										=processor.batch_decode(lowerCAmelCase_      )
          # we do not want to group tokens when computing the metrics
          SCREAMING_SNAKE_CASE										=processor.batch_decode(pred.label_ids,   group_tokens=lowerCAmelCase_      )
          if logger.isEnabledFor(logging.DEBUG      ):
               for reference, predicted in zip(lowerCAmelCase_,   lowerCAmelCase_      ):
                    logger.debug(F'reference: "{reference}"'      )
                    logger.debug(F'predicted: "{predicted}"'      )
                    if orthography.untransliterator is not None:
                         logger.debug(F'reference (untransliterated): "{orthography.untransliterator(lowerCAmelCase_      )}"'      )
                         logger.debug(F'predicted (untransliterated): "{orthography.untransliterator(lowerCAmelCase_      )}"'      )

          SCREAMING_SNAKE_CASE										=wer_metric.compute(predictions=lowerCAmelCase_,   references=lowerCAmelCase_      )

          return {"wer": wer}

     if model_args.freeze_feature_extractor:
          model.freeze_feature_extractor()

     SCREAMING_SNAKE_CASE										=CTCTrainer(
         model=lowerCAmelCase_,   data_collator=lowerCAmelCase_,   args=lowerCAmelCase_,   compute_metrics=lowerCAmelCase_,   train_dataset=lowerCAmelCase_,   eval_dataset=lowerCAmelCase_,   tokenizer=processor.feature_extractor,   )

     trainer.train()


if __name__ == "__main__":
 main()




from __future__ import annotations

import unittest

from transformers import MPNetConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
 import tensorflow as tf

 from transformers.models.mpnet.modeling_tf_mpnet import (
     TFMPNetForMaskedLM,
     TFMPNetForMultipleChoice,
     TFMPNetForQuestionAnswering,
     TFMPNetForSequenceClassification,
     TFMPNetForTokenClassification,
     TFMPNetModel,
 )



class 		a_	:



      """simple docstring"""







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

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

           SCREAMING_SNAKE_CASE										=None
           SCREAMING_SNAKE_CASE										=None
           SCREAMING_SNAKE_CASE										=None
           if self.use_labels:
                SCREAMING_SNAKE_CASE										=ids_tensor([self.batch_size]      ,self.type_sequence_label_size    )
                SCREAMING_SNAKE_CASE										=ids_tensor([self.batch_size, self.seq_length]      ,self.num_labels    )
                SCREAMING_SNAKE_CASE										=ids_tensor([self.batch_size]      ,self.num_choices    )

           SCREAMING_SNAKE_CASE										=MPNetConfig(
               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      ,initializer_range=self.initializer_range      ,)
           return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
      def 	_lowerCAmelCase					(				self					:							Dict      ,snake_case					:							Any      ,snake_case					:							Optional[int]      ,snake_case					:							str      ,snake_case					:							Union[str, Any]      ,snake_case					:							Optional[Any]      ,snake_case					:							Any    ):
           SCREAMING_SNAKE_CASE										=TFMPNetModel(config=snake_case    )
           SCREAMING_SNAKE_CASE										={'input_ids': input_ids, 'attention_mask': input_mask}
           SCREAMING_SNAKE_CASE										=model(snake_case    )
           SCREAMING_SNAKE_CASE										=[input_ids, input_mask]
           SCREAMING_SNAKE_CASE										=model(snake_case    )
           self.parent.assertEqual(result.last_hidden_state.shape      ,(self.batch_size, self.seq_length, self.hidden_size)    )
      def 	_lowerCAmelCase					(				self					:							List[Any]      ,snake_case					:							List[str]      ,snake_case					:							Tuple      ,snake_case					:							Dict      ,snake_case					:							Optional[Any]      ,snake_case					:							Optional[int]      ,snake_case					:							Dict    ):
           SCREAMING_SNAKE_CASE										=TFMPNetForMaskedLM(config=snake_case    )
           SCREAMING_SNAKE_CASE										={'input_ids': input_ids, 'attention_mask': input_mask}
           SCREAMING_SNAKE_CASE										=model(snake_case    )
           self.parent.assertEqual(result.logits.shape      ,(self.batch_size, self.seq_length, self.vocab_size)    )
      def 	_lowerCAmelCase					(				self					:							int      ,snake_case					:							List[str]      ,snake_case					:							Dict      ,snake_case					:							List[Any]      ,snake_case					:							Optional[int]      ,snake_case					:							Optional[int]      ,snake_case					:							Tuple    ):
           SCREAMING_SNAKE_CASE										=TFMPNetForQuestionAnswering(config=snake_case    )
           SCREAMING_SNAKE_CASE										={
               'input_ids': input_ids,
               'attention_mask': input_mask,
           }
           SCREAMING_SNAKE_CASE										=model(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 	_lowerCAmelCase					(				self					:							List[Any]      ,snake_case					:							Union[str, Any]      ,snake_case					:							str      ,snake_case					:							str      ,snake_case					:							Any      ,snake_case					:							Tuple      ,snake_case					:							Optional[Any]    ):
           SCREAMING_SNAKE_CASE										=self.num_labels
           SCREAMING_SNAKE_CASE										=TFMPNetForSequenceClassification(snake_case    )
           SCREAMING_SNAKE_CASE										={'input_ids': input_ids, 'attention_mask': input_mask}
           SCREAMING_SNAKE_CASE										=model(snake_case    )
           self.parent.assertEqual(result.logits.shape      ,(self.batch_size, self.num_labels)    )
      def 	_lowerCAmelCase					(				self					:							int      ,snake_case					:							Any      ,snake_case					:							Union[str, Any]      ,snake_case					:							int      ,snake_case					:							List[str]      ,snake_case					:							Tuple      ,snake_case					:							Union[str, Any]    ):
           SCREAMING_SNAKE_CASE										=self.num_choices
           SCREAMING_SNAKE_CASE										=TFMPNetForMultipleChoice(snake_case    )
           SCREAMING_SNAKE_CASE										=tf.tile(tf.expand_dims(snake_case      ,1    )      ,(1, self.num_choices, 1)    )
           SCREAMING_SNAKE_CASE										=tf.tile(tf.expand_dims(snake_case      ,1    )      ,(1, self.num_choices, 1)    )
           SCREAMING_SNAKE_CASE										={
               'input_ids': multiple_choice_inputs_ids,
               'attention_mask': multiple_choice_input_mask,
           }
           SCREAMING_SNAKE_CASE										=model(snake_case    )
           self.parent.assertEqual(result.logits.shape      ,(self.batch_size, self.num_choices)    )
      def 	_lowerCAmelCase					(				self					:							Any      ,snake_case					:							Tuple      ,snake_case					:							Dict      ,snake_case					:							Tuple      ,snake_case					:							Union[str, Any]      ,snake_case					:							Optional[int]      ,snake_case					:							Dict    ):
           SCREAMING_SNAKE_CASE										=self.num_labels
           SCREAMING_SNAKE_CASE										=TFMPNetForTokenClassification(snake_case    )
           SCREAMING_SNAKE_CASE										={'input_ids': input_ids, 'attention_mask': input_mask}
           SCREAMING_SNAKE_CASE										=model(snake_case    )
           self.parent.assertEqual(result.logits.shape      ,(self.batch_size, self.seq_length, self.num_labels)    )


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







@require_tf
class 		a_	(							lowerCamelCase_			,      lowerCamelCase_			,      unittest.TestCase					):



      """simple docstring"""







      __UpperCAmelCase      		=				(
          (
              TFMPNetForMaskedLM,
              TFMPNetForMultipleChoice,
              TFMPNetForQuestionAnswering,
              TFMPNetForSequenceClassification,
              TFMPNetForTokenClassification,
              TFMPNetModel,
          )
          if is_tf_available()
          else ()
      )
      __UpperCAmelCase      		=				(
          {
              'feature-extraction': TFMPNetModel,
              'fill-mask': TFMPNetForMaskedLM,
              'question-answering': TFMPNetForQuestionAnswering,
              'text-classification': TFMPNetForSequenceClassification,
              'token-classification': TFMPNetForTokenClassification,
              'zero-shot': TFMPNetForSequenceClassification,
          }
          if is_tf_available()
          else {}
      )
      __UpperCAmelCase      		=				False
      __UpperCAmelCase      		=				False
      def 	_lowerCAmelCase					(				self					:							Dict    ):
           SCREAMING_SNAKE_CASE										=TFMPNetModelTester(self    )
           SCREAMING_SNAKE_CASE										=ConfigTester(self      ,config_class=snake_case      ,hidden_size=37    )
      def 	_lowerCAmelCase					(				self					:							Dict    ):
           self.config_tester.run_common_tests()
      def 	_lowerCAmelCase					(				self					:							Union[str, Any]    ):
           SCREAMING_SNAKE_CASE										=self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_mpnet_model(*snake_case    )
      def 	_lowerCAmelCase					(				self					:							List[Any]    ):
           SCREAMING_SNAKE_CASE										=self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_mpnet_for_masked_lm(*snake_case    )
      def 	_lowerCAmelCase					(				self					:							Dict    ):
           SCREAMING_SNAKE_CASE										=self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_mpnet_for_question_answering(*snake_case    )
      def 	_lowerCAmelCase					(				self					:							str    ):
           SCREAMING_SNAKE_CASE										=self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_mpnet_for_sequence_classification(*snake_case    )
      def 	_lowerCAmelCase					(				self					:							Dict    ):
           SCREAMING_SNAKE_CASE										=self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_mpnet_for_multiple_choice(*snake_case    )
      def 	_lowerCAmelCase					(				self					:							List[str]    ):
           SCREAMING_SNAKE_CASE										=self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_mpnet_for_token_classification(*snake_case    )


      @slow
      def 	_lowerCAmelCase					(				self					:							Optional[Any]    ):
           for model_name in ["microsoft/mpnet-base"]:
                SCREAMING_SNAKE_CASE										=TFMPNetModel.from_pretrained(snake_case    )
                self.assertIsNotNone(snake_case    )







@require_tf
class 		a_	(							unittest.TestCase					):



      """simple docstring"""







      @slow
      def 	_lowerCAmelCase					(				self					:							Optional[Any]    ):
           SCREAMING_SNAKE_CASE										=TFMPNetModel.from_pretrained('microsoft/mpnet-base'    )
           SCREAMING_SNAKE_CASE										=tf.constant([[0, 1, 2, 3, 4, 5]]    )
           SCREAMING_SNAKE_CASE										=model(snake_case    )[0]

           SCREAMING_SNAKE_CASE										=[1, 6, 768]
           self.assertEqual(output.shape      ,snake_case    )

           SCREAMING_SNAKE_CASE										=tf.constant(
               [
                   [
                       [-0.1_067_172, 0.08_216_473, 0.0_024_543],
                       [-0.03_465_879, 0.8_354_118, -0.03_252_288],
                       [-0.06_569_476, -0.12_424_111, -0.0_494_436],
                   ]
               ]    )
           tf.debugging.assert_near(output[:, :3, :3]      ,snake_case      ,atol=1e-4    )

