



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'''):
 __A       					=		True
 from torch.cuda.amp import autocast


__A       					=		logging.getLogger(__name__)






@dataclass
class 	lowercase		:






 """simple docstring"""


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



def  __a  (					lowerCAmelCase_     :      Optional[int]    ,lowerCAmelCase_     :      Dict       )   ->				Tuple:






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






@dataclass
class 	lowercase		:






 """simple docstring"""


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






@dataclass
class 	lowercase		:






 """simple docstring"""


 a__   :      bool	     =							False
 a__   :      Optional[str]	     =							None
 a__   :      Optional[str]	     =							"|"
 a__   :      Optional[Dict[str, str]]	     =							field(default_factory=__lowerCamelCase)
 a__   :      Optional[Set[str]]	     =							field(default_factory=__lowerCamelCase)
 a__   :      Optional[Callable[[str], str]]	     =							None




 @classmethod
 def 						_SCREAMING_SNAKE_CASE	(			cls			:		Tuple		,						__UpperCAmelCase			:		str  )    ->				int:






       if name == "librispeech":
             return cls()
       if name == "timit":
             return cls(
                 do_lower_case=__UpperCAmelCase		,						translation_table=str.maketrans({"""-""": """ """}  )		,						)
       if name == "buckwalter":
             UpperCAmelCase_=     {
                 """-""": """ """,  # sometimes used to represent pauses
                 """^""": """v""",  # fixing "tha" in arabic_speech_corpus dataset
             }
             return cls(
                 vocab_file=pathlib.Path(__UpperCAmelCase  ).parent.joinpath("""vocab/buckwalter.json"""  )		,						word_delimiter_token="""/"""		,						translation_table=str.maketrans(__UpperCAmelCase  )		,						words_to_remove={"""sil"""}		,						untransliterator=arabic.buckwalter.untransliterate		,						)
       raise ValueError(F"""Unsupported orthography: '{name}'."""  )




 def 						_SCREAMING_SNAKE_CASE	(			self			:		str		,						__UpperCAmelCase			:		str  )    ->				str:






       if len(self.translation_table  ) > 0:
             UpperCAmelCase_=     text.translate(self.translation_table  )
       if len(self.words_to_remove  ) == 0:
             UpperCAmelCase_=     """ """.join(text.split()  )  # clean up whitespaces
       else:
             UpperCAmelCase_=     """ """.join(w for w in text.split() if w not in self.words_to_remove  )  # and clean up whilespaces
       return text




 def 						_SCREAMING_SNAKE_CASE	(			self			:		Any		,						__UpperCAmelCase			:		ModelArguments  )    ->				WavaVecaProcessor:
       UpperCAmelCase_=     WavaVecaFeatureExtractor.from_pretrained(
           model_args.model_name_or_path		,						cache_dir=model_args.cache_dir  )
       if self.vocab_file:
             UpperCAmelCase_=     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_=     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(__UpperCAmelCase		,						__UpperCAmelCase  )






@dataclass
class 	lowercase		:






 """simple docstring"""


 a__   :      WavaVecaProcessor
 a__   :      Union[bool, str]	     =							True
 a__   :      Optional[int]	     =							None
 a__   :      Optional[int]	     =							None
 a__   :      Optional[int]	     =							None
 a__   :      Optional[int]	     =							None




 def __call__(			self			:		Any		,						__UpperCAmelCase			:		List[Dict[str, Union[List[int], torch.Tensor]]]  )    ->				Dict[str, torch.Tensor]:
       UpperCAmelCase_=     [{"""input_values""": feature["""input_values"""]} for feature in features]
       UpperCAmelCase_=     [{"""input_ids""": feature["""labels"""]} for feature in features]

       UpperCAmelCase_=     self.processor.pad(
           __UpperCAmelCase		,						padding=self.padding		,						max_length=self.max_length		,						pad_to_multiple_of=self.pad_to_multiple_of		,						return_tensors="""pt"""		,						)
       UpperCAmelCase_=     self.processor.pad(
           labels=__UpperCAmelCase		,						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_=     labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1  )		,						-100  )

       UpperCAmelCase_=     labels

       return batch






class 	lowercase		(				__lowerCamelCase):






 """simple docstring"""


 def 						_SCREAMING_SNAKE_CASE	(			self			:		Tuple		,						__UpperCAmelCase			:		nn.Module		,						__UpperCAmelCase			:		Dict[str, Union[torch.Tensor, Any]]  )    ->				torch.Tensor:
       model.train()
       UpperCAmelCase_=     self._prepare_inputs(__UpperCAmelCase  )

       if self.use_amp:
             with autocast():
                   UpperCAmelCase_=     self.compute_loss(__UpperCAmelCase		,						__UpperCAmelCase  )
       else:
             UpperCAmelCase_=     self.compute_loss(__UpperCAmelCase		,						__UpperCAmelCase  )

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

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

       return loss.detach()



def  __a  (					)   ->				Tuple:






      '''simple docstring'''



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

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

      UpperCAmelCase_=     Orthography.from_name(data_args.orthography.lower()       )
      UpperCAmelCase_=     orthography.create_processor(lowerCAmelCase_       )
      UpperCAmelCase_=     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_=     datasets.load_dataset(
          data_args.dataset_name    ,data_args.dataset_config_name    ,split=data_args.train_split_name       )
      UpperCAmelCase_=     datasets.load_dataset(
          data_args.dataset_name    ,data_args.dataset_config_name    ,split=data_args.validation_split_name       )

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

      def prepare_example(lowerCAmelCase_     :      List[Any]       ):  # TODO(elgeish) make use of multiprocessing?
            UpperCAmelCase_,     UpperCAmelCase_=     librosa.load(example[data_args.speech_file_column]    ,sr=lowerCAmelCase_       )
            if data_args.max_duration_in_seconds is not None:
                  UpperCAmelCase_=     len(example["""speech"""]       ) / example["""sampling_rate"""]
            # Normalize and clean up text; order matters!
            UpperCAmelCase_=     orthography.preprocess_for_training(example[data_args.target_text_column]       )
            UpperCAmelCase_=     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)       )
                  UpperCAmelCase_=     updated_text
            return example

      UpperCAmelCase_=     train_dataset.map(lowerCAmelCase_    ,remove_columns=[data_args.speech_file_column]       )
      UpperCAmelCase_=     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_     :      Any       ):
                  return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

            UpperCAmelCase_=     len(lowerCAmelCase_       )
            UpperCAmelCase_=     len(lowerCAmelCase_       )
            UpperCAmelCase_=     train_dataset.filter(lowerCAmelCase_    ,remove_columns=["""duration_in_seconds"""]       )
            UpperCAmelCase_=     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}\""""       )
      UpperCAmelCase_=     None

      def prepare_dataset(lowerCAmelCase_     :      str       ):
            # 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_=     processor(
                audio=batch["""speech"""]    ,text=batch[data_args.target_text_column]    ,sampling_rate=batch["""sampling_rate"""][0]       )
            batch.update(lowerCAmelCase_       )
            return batch

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

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

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

            UpperCAmelCase_=     processor.tokenizer.pad_token_id

            UpperCAmelCase_=     processor.batch_decode(lowerCAmelCase_       )
            # we do not want to group tokens when computing the metrics
            UpperCAmelCase_=     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_       )}\""""       )

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

            return {"wer": wer}

      if model_args.freeze_feature_extractor:
            model.freeze_feature_extractor()

      UpperCAmelCase_=     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()









import unittest

from transformers import YosoConfig, is_torch_available
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 (
	    YosoForMaskedLM,
	    YosoForMultipleChoice,
	    YosoForQuestionAnswering,
	    YosoForSequenceClassification,
	    YosoForTokenClassification,
	    YosoModel,
	)
	from transformers.models.yoso.modeling_yoso import YOSO_PRETRAINED_MODEL_ARCHIVE_LIST






class 	lowercase		:






	"""simple docstring"""


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




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

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

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

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

							UpperCAmelCase_=     self.get_config()

							return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels




	def 						_SCREAMING_SNAKE_CASE	(			self			:		Dict  )    ->				List[str]:
							return YosoConfig(
							    vocab_size=self.vocab_size		,						hidden_size=self.hidden_size		,						num_hidden_layers=self.num_hidden_layers		,						num_attention_heads=self.num_attention_heads		,						intermediate_size=self.intermediate_size		,						hidden_act=self.hidden_act		,						hidden_dropout_prob=self.hidden_dropout_prob		,						attention_probs_dropout_prob=self.attention_probs_dropout_prob		,						max_position_embeddings=self.max_position_embeddings		,						type_vocab_size=self.type_vocab_size		,						is_decoder=__UpperCAmelCase		,						initializer_range=self.initializer_range		,						)




	def 						_SCREAMING_SNAKE_CASE	(			self			:		Optional[int]  )    ->				Union[str, Any]:
							UpperCAmelCase_=     self.get_config()
							UpperCAmelCase_=     300
							return config




	def 						_SCREAMING_SNAKE_CASE	(			self			:		List[Any]  )    ->				str:
							(
							    (
							    UpperCAmelCase_
							),     (
							    UpperCAmelCase_
							),     (
							    UpperCAmelCase_
							),     (
							    UpperCAmelCase_
							),     (
							    UpperCAmelCase_
							),     (
							    UpperCAmelCase_
							),     (
							    UpperCAmelCase_
							),     
							)=     self.prepare_config_and_inputs()

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




	def 						_SCREAMING_SNAKE_CASE	(			self			:		List[Any]		,						__UpperCAmelCase			:		List[str]		,						__UpperCAmelCase			:		List[Any]		,						__UpperCAmelCase			:		str		,						__UpperCAmelCase			:		Optional[int]		,						__UpperCAmelCase			:		str		,						__UpperCAmelCase			:		Dict		,						__UpperCAmelCase			:		Dict		,						__UpperCAmelCase			:		Optional[int]		,						__UpperCAmelCase			:		Dict		,						)    ->				List[str]:
							UpperCAmelCase_=     True
							UpperCAmelCase_=     YosoModel(__UpperCAmelCase  )
							model.to(__UpperCAmelCase  )
							model.eval()
							UpperCAmelCase_=     model(
							    __UpperCAmelCase		,						attention_mask=__UpperCAmelCase		,						token_type_ids=__UpperCAmelCase		,						encoder_hidden_states=__UpperCAmelCase		,						encoder_attention_mask=__UpperCAmelCase		,						)
							UpperCAmelCase_=     model(
							    __UpperCAmelCase		,						attention_mask=__UpperCAmelCase		,						token_type_ids=__UpperCAmelCase		,						encoder_hidden_states=__UpperCAmelCase		,						)
							UpperCAmelCase_=     model(__UpperCAmelCase		,						attention_mask=__UpperCAmelCase		,						token_type_ids=__UpperCAmelCase  )
							self.parent.assertEqual(result.last_hidden_state.shape		,						(self.batch_size, self.seq_length, self.hidden_size)  )




	def 						_SCREAMING_SNAKE_CASE	(			self			:		str		,						__UpperCAmelCase			:		str		,						__UpperCAmelCase			:		List[Any]		,						__UpperCAmelCase			:		Optional[int]		,						__UpperCAmelCase			:		str		,						__UpperCAmelCase			:		List[Any]		,						__UpperCAmelCase			:		Any		,						__UpperCAmelCase			:		str  )    ->				List[Any]:
							UpperCAmelCase_=     YosoForMaskedLM(config=__UpperCAmelCase  )
							model.to(__UpperCAmelCase  )
							model.eval()
							UpperCAmelCase_=     model(__UpperCAmelCase		,						attention_mask=__UpperCAmelCase		,						token_type_ids=__UpperCAmelCase		,						labels=__UpperCAmelCase  )
							self.parent.assertEqual(result.logits.shape		,						(self.batch_size, self.seq_length, self.vocab_size)  )




	def 						_SCREAMING_SNAKE_CASE	(			self			:		List[Any]		,						__UpperCAmelCase			:		List[str]		,						__UpperCAmelCase			:		Dict		,						__UpperCAmelCase			:		str		,						__UpperCAmelCase			:		Tuple		,						__UpperCAmelCase			:		Tuple		,						__UpperCAmelCase			:		Optional[int]		,						__UpperCAmelCase			:		Optional[int]  )    ->				List[Any]:
							UpperCAmelCase_=     YosoForQuestionAnswering(config=__UpperCAmelCase  )
							model.to(__UpperCAmelCase  )
							model.eval()
							UpperCAmelCase_=     model(
							    __UpperCAmelCase		,						attention_mask=__UpperCAmelCase		,						token_type_ids=__UpperCAmelCase		,						start_positions=__UpperCAmelCase		,						end_positions=__UpperCAmelCase		,						)
							self.parent.assertEqual(result.start_logits.shape		,						(self.batch_size, self.seq_length)  )
							self.parent.assertEqual(result.end_logits.shape		,						(self.batch_size, self.seq_length)  )




	def 						_SCREAMING_SNAKE_CASE	(			self			:		Any		,						__UpperCAmelCase			:		Dict		,						__UpperCAmelCase			:		Union[str, Any]		,						__UpperCAmelCase			:		Tuple		,						__UpperCAmelCase			:		Optional[Any]		,						__UpperCAmelCase			:		Optional[Any]		,						__UpperCAmelCase			:		List[str]		,						__UpperCAmelCase			:		List[str]  )    ->				str:
							UpperCAmelCase_=     self.num_labels
							UpperCAmelCase_=     YosoForSequenceClassification(__UpperCAmelCase  )
							model.to(__UpperCAmelCase  )
							model.eval()
							UpperCAmelCase_=     model(__UpperCAmelCase		,						attention_mask=__UpperCAmelCase		,						token_type_ids=__UpperCAmelCase		,						labels=__UpperCAmelCase  )
							self.parent.assertEqual(result.logits.shape		,						(self.batch_size, self.num_labels)  )




	def 						_SCREAMING_SNAKE_CASE	(			self			:		Dict		,						__UpperCAmelCase			:		Any		,						__UpperCAmelCase			:		str		,						__UpperCAmelCase			:		Any		,						__UpperCAmelCase			:		int		,						__UpperCAmelCase			:		Union[str, Any]		,						__UpperCAmelCase			:		Optional[Any]		,						__UpperCAmelCase			:		Tuple  )    ->				Union[str, Any]:
							UpperCAmelCase_=     self.num_labels
							UpperCAmelCase_=     YosoForTokenClassification(config=__UpperCAmelCase  )
							model.to(__UpperCAmelCase  )
							model.eval()
							UpperCAmelCase_=     model(__UpperCAmelCase		,						attention_mask=__UpperCAmelCase		,						token_type_ids=__UpperCAmelCase		,						labels=__UpperCAmelCase  )
							self.parent.assertEqual(result.logits.shape		,						(self.batch_size, self.seq_length, self.num_labels)  )




	def 						_SCREAMING_SNAKE_CASE	(			self			:		str		,						__UpperCAmelCase			:		Optional[int]		,						__UpperCAmelCase			:		List[str]		,						__UpperCAmelCase			:		List[Any]		,						__UpperCAmelCase			:		List[Any]		,						__UpperCAmelCase			:		str		,						__UpperCAmelCase			:		Any		,						__UpperCAmelCase			:		Optional[int]  )    ->				Any:
							UpperCAmelCase_=     self.num_choices
							UpperCAmelCase_=     YosoForMultipleChoice(config=__UpperCAmelCase  )
							model.to(__UpperCAmelCase  )
							model.eval()
							UpperCAmelCase_=     input_ids.unsqueeze(1  ).expand(-1		,						self.num_choices		,						-1  ).contiguous()
							UpperCAmelCase_=     token_type_ids.unsqueeze(1  ).expand(-1		,						self.num_choices		,						-1  ).contiguous()
							UpperCAmelCase_=     input_mask.unsqueeze(1  ).expand(-1		,						self.num_choices		,						-1  ).contiguous()
							UpperCAmelCase_=     model(
							    __UpperCAmelCase		,						attention_mask=__UpperCAmelCase		,						token_type_ids=__UpperCAmelCase		,						labels=__UpperCAmelCase		,						)
							self.parent.assertEqual(result.logits.shape		,						(self.batch_size, self.num_choices)  )




	def 						_SCREAMING_SNAKE_CASE	(			self			:		Dict  )    ->				Any:
							UpperCAmelCase_=     self.prepare_config_and_inputs()
							(
							    (
							    UpperCAmelCase_
							),     (
							    UpperCAmelCase_
							),     (
							    UpperCAmelCase_
							),     (
							    UpperCAmelCase_
							),     (
							    UpperCAmelCase_
							),     (
							    UpperCAmelCase_
							),     (
							    UpperCAmelCase_
							),     
							)=     config_and_inputs
							UpperCAmelCase_=     {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
							return config, inputs_dict






@require_torch
class 	lowercase		(				snake_case__				,					snake_case__				,					unittest.TestCase):






	"""simple docstring"""


	a__   :      Any	     =							(
	    (
	        YosoModel,
	        YosoForMaskedLM,
	        YosoForMultipleChoice,
	        YosoForQuestionAnswering,
	        YosoForSequenceClassification,
	        YosoForTokenClassification,
	    )
	    if is_torch_available()
	    else ()
	)
	a__   :      Optional[int]	     =							False
	a__   :      Optional[Any]	     =							False
	a__   :      Dict	     =							False

	a__   :      int	     =							()
	a__   :      int	     =							(
	    {
	        "feature-extraction": YosoModel,
	        "fill-mask": YosoForMaskedLM,
	        "question-answering": YosoForQuestionAnswering,
	        "text-classification": YosoForSequenceClassification,
	        "token-classification": YosoForTokenClassification,
	        "zero-shot": YosoForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)




	def 						_SCREAMING_SNAKE_CASE	(			self			:		Optional[int]  )    ->				Optional[int]:
							UpperCAmelCase_=     YosoModelTester(self  )
							UpperCAmelCase_=     ConfigTester(self		,						config_class=__UpperCAmelCase		,						hidden_size=37  )




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




	def 						_SCREAMING_SNAKE_CASE	(			self			:		List[str]  )    ->				Dict:
							UpperCAmelCase_=     self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__UpperCAmelCase  )




	def 						_SCREAMING_SNAKE_CASE	(			self			:		Optional[int]  )    ->				Any:
							UpperCAmelCase_=     self.model_tester.prepare_config_and_inputs()
							for type in ["absolute", "relative_key", "relative_key_query"]:
													UpperCAmelCase_=     type
													self.model_tester.create_and_check_model(*__UpperCAmelCase  )




	def 						_SCREAMING_SNAKE_CASE	(			self			:		int  )    ->				Any:
							UpperCAmelCase_=     self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_lm(*__UpperCAmelCase  )




	def 						_SCREAMING_SNAKE_CASE	(			self			:		Any  )    ->				Optional[int]:
							UpperCAmelCase_=     self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_multiple_choice(*__UpperCAmelCase  )




	def 						_SCREAMING_SNAKE_CASE	(			self			:		Optional[Any]  )    ->				Dict:
							UpperCAmelCase_=     self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_question_answering(*__UpperCAmelCase  )




	def 						_SCREAMING_SNAKE_CASE	(			self			:		str  )    ->				int:
							UpperCAmelCase_=     self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_sequence_classification(*__UpperCAmelCase  )




	def 						_SCREAMING_SNAKE_CASE	(			self			:		Dict  )    ->				Optional[Any]:
							UpperCAmelCase_=     self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_token_classification(*__UpperCAmelCase  )




	@slow
	def 						_SCREAMING_SNAKE_CASE	(			self			:		Union[str, Any]  )    ->				Optional[Any]:
							for model_name in YOSO_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													UpperCAmelCase_=     YosoModel.from_pretrained(__UpperCAmelCase  )
													self.assertIsNotNone(__UpperCAmelCase  )




	def 						_SCREAMING_SNAKE_CASE	(			self			:		Dict  )    ->				Tuple:
							return






@require_torch
class 	lowercase		(				unittest.TestCase):






	"""simple docstring"""


	@slow
	def 						_SCREAMING_SNAKE_CASE	(			self			:		Dict  )    ->				Optional[int]:
							UpperCAmelCase_=     YosoModel.from_pretrained("""uw-madison/yoso-4096"""  )
							UpperCAmelCase_=     torch.tensor([[0, 1, 2, 3, 4, 5]]  )

							with torch.no_grad():
													UpperCAmelCase_=     model(__UpperCAmelCase  )[0]

							UpperCAmelCase_=     torch.Size((1, 6, 768)  )
							self.assertEqual(output.shape		,						__UpperCAmelCase  )

							UpperCAmelCase_=     torch.tensor(
							    [[[-0.0_611, 0.1_242, 0.0_840], [0.0_280, -0.0_048, 0.1_125], [0.0_106, 0.0_226, 0.0_751]]]  )

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




	@slow
	def 						_SCREAMING_SNAKE_CASE	(			self			:		str  )    ->				List[Any]:
							UpperCAmelCase_=     YosoForMaskedLM.from_pretrained("""uw-madison/yoso-4096"""  )
							UpperCAmelCase_=     torch.tensor([[0, 1, 2, 3, 4, 5]]  )

							with torch.no_grad():
													UpperCAmelCase_=     model(__UpperCAmelCase  )[0]

							UpperCAmelCase_=     50_265

							UpperCAmelCase_=     torch.Size((1, 6, vocab_size)  )
							self.assertEqual(output.shape		,						__UpperCAmelCase  )

							UpperCAmelCase_=     torch.tensor(
							    [[[-2.1_313, -3.7_285, -2.2_407], [-2.7_047, -3.3_314, -2.6_408], [0.0_629, -2.5_166, -0.3_356]]]  )

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




	@slow
	def 						_SCREAMING_SNAKE_CASE	(			self			:		Dict  )    ->				Tuple:
							UpperCAmelCase_=     YosoForMaskedLM.from_pretrained("""uw-madison/yoso-4096"""  )
							UpperCAmelCase_=     torch.arange(4_096  ).unsqueeze(0  )

							with torch.no_grad():
													UpperCAmelCase_=     model(__UpperCAmelCase  )[0]

							UpperCAmelCase_=     50_265

							UpperCAmelCase_=     torch.Size((1, 4_096, vocab_size)  )
							self.assertEqual(output.shape		,						__UpperCAmelCase  )

							UpperCAmelCase_=     torch.tensor(
							    [[[-2.3_914, -4.3_742, -5.0_956], [-4.0_988, -4.2_384, -7.0_406], [-3.1_427, -3.7_192, -6.6_800]]]  )

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




