



'''simple docstring'''





import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union

import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


if is_apex_available():
  from apex import amp


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

lowercase_		       =  logging.getLogger(__name__)




def lowerCAmelCase  (__A=None  ,	__A=None):



     """simple docstring"""



     return field(default_factory=lambda: default  ,	metadata=SCREAMING_SNAKE_CASE_)






@dataclass
class __A			:



 '''simple docstring'''







 __lowerCamelCase    :       str          =       field(
     metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}						)
 __lowerCamelCase    :       Optional[str]          =       field(
     default=__snake_case   ,   metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}   ,   )
 __lowerCamelCase    :       Optional[bool]          =       field(
     default=__snake_case   ,   metadata={'help': 'Whether to freeze the feature extractor layers of the model.'}						)
 __lowerCamelCase    :       Optional[float]          =       field(
     default=0.1   ,   metadata={'help': 'The dropout ratio for the attention probabilities.'}						)
 __lowerCamelCase    :       Optional[float]          =       field(
     default=0.1   ,   metadata={'help': 'The dropout ratio for activations inside the fully connected layer.'}						)
 __lowerCamelCase    :       Optional[float]          =       field(
     default=0.1   ,   metadata={
         'help': 'The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.'
     }   ,   )
 __lowerCamelCase    :       Optional[float]          =       field(
     default=0.1   ,   metadata={'help': 'The dropout probabilitiy for all 1D convolutional layers in feature extractor.'}   ,   )
 __lowerCamelCase    :       Optional[float]          =       field(
     default=0.05   ,   metadata={
         'help': (
             'Propability of each feature vector along the time axis to be chosen as the start of the vector'
             'span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature'
             'vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.'
         )
     }   ,   )
 __lowerCamelCase    :       Optional[float]          =       field(default=0.0   ,   metadata={'help': 'The LayerDrop probability.'}						)






@dataclass
class __A			:



 '''simple docstring'''







 __lowerCamelCase    :       Optional[str]          =       field(
     default=__snake_case   ,   metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}						)
 __lowerCamelCase    :       Optional[str]          =       field(
     default='train+validation'   ,   metadata={
         'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\''
     }   ,   )
 __lowerCamelCase    :       bool          =       field(
     default=__snake_case   ,   metadata={'help': 'Overwrite the cached preprocessed datasets or not.'}						)
 __lowerCamelCase    :       Optional[int]          =       field(
     default=__snake_case   ,   metadata={'help': 'The number of processes to use for the preprocessing.'}   ,   )
 __lowerCamelCase    :       Optional[int]          =       field(
     default=__snake_case   ,   metadata={
         'help': (
             'For debugging purposes or quicker training, truncate the number of training examples to this '
             'value if set.'
         )
     }   ,   )
 __lowerCamelCase    :       Optional[int]          =       field(
     default=__snake_case   ,   metadata={
         'help': (
             'For debugging purposes or quicker training, truncate the number of validation examples to this '
             'value if set.'
         )
     }   ,   )
 __lowerCamelCase    :       List[str]          =       list_field(
     default=[',', '?', '.', '!', '-', ';', ':', '\"\"', '%', '\'', '\"', '�']   ,   metadata={'help': 'A list of characters to remove from the transcripts.'}   ,   )






@dataclass
class __A			:



 '''simple docstring'''







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



 def __call__(self ,   A       )    ->     Union[str, Any]:


      """simple docstring"""



      _a      =  [{'input_values': feature['input_values']} for feature in features]
      _a      =  [{'input_ids': feature['labels']} for feature in features]

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

      _a      =  labels

      return batch






class __A			(  __snake_case						):



 '''simple docstring'''







 def 					a__  (self ,   A ,   A       )    ->     int:


      """simple docstring"""



      model.train()
      _a      =  self._prepare_inputs(A       )

      if self.use_amp:
           with autocast():
                _a      =  self.compute_loss(A ,   A       )
      else:
           _a      =  self.compute_loss(A ,   A       )

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

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

      return loss.detach()





def lowerCAmelCase  ():



     """simple docstring"""



     _a      =  HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
     if len(sys.argv) == 2 and sys.argv[1].endswith('''.json'''):
          # If we pass only one argument to the script and it's the path to a json file,
          # let's parse it to get our arguments.
          _a      =  parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
     else:
          _a      =  parser.parse_args_into_dataclasses()

     # Detecting last checkpoint.
     _a      =  None
     if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
          _a      =  get_last_checkpoint(training_args.output_dir)
          if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
               raise ValueError(
                   F'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
                   '''Use --overwrite_output_dir to overcome.''')
          elif last_checkpoint is not None:
               logger.info(
                   F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
                   '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''')

    # Setup logging
     logging.basicConfig(
         format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''  ,	datefmt='''%m/%d/%Y %H:%M:%S'''  ,	handlers=[logging.StreamHandler(sys.stdout)]  ,	)
     logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)

     # Log on each process the small summary:
     logger.warning(
         F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
         + F'''distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fpaa}''')
     # Set the verbosity to info of the Transformers logger (on main process only):
     if is_main_process(training_args.local_rank):
          transformers.utils.logging.set_verbosity_info()
     logger.info('''Training/evaluation parameters %s'''  ,	SCREAMING_SNAKE_CASE_)

     # Set seed before initializing model.
     set_seed(training_args.seed)

     # Get the datasets:
     _a      =  datasets.load_dataset(
         '''common_voice'''  ,	data_args.dataset_config_name  ,	split=data_args.train_split_name)
     _a      =  datasets.load_dataset('''common_voice'''  ,	data_args.dataset_config_name  ,	split='''test''')

     # Create and save tokenizer
     _a      =  F'''[{''.join(data_args.chars_to_ignore)}]'''

     def remove_special_characters(__A):
          _a      =  re.sub(SCREAMING_SNAKE_CASE_  ,	''''''  ,	batch['''sentence''']).lower() + ' '
          return batch

     _a      =  train_dataset.map(SCREAMING_SNAKE_CASE_  ,	remove_columns=['''sentence'''])
     _a      =  eval_dataset.map(SCREAMING_SNAKE_CASE_  ,	remove_columns=['''sentence'''])

     def extract_all_chars(__A):
          _a      =  ' '.join(batch['''text'''])
          _a      =  list(set(SCREAMING_SNAKE_CASE_))
          return {"vocab": [vocab], "all_text": [all_text]}

     _a      =  train_dataset.map(
         SCREAMING_SNAKE_CASE_  ,	batched=SCREAMING_SNAKE_CASE_  ,	batch_size=-1  ,	keep_in_memory=SCREAMING_SNAKE_CASE_  ,	remove_columns=train_dataset.column_names  ,	)
     _a      =  train_dataset.map(
         SCREAMING_SNAKE_CASE_  ,	batched=SCREAMING_SNAKE_CASE_  ,	batch_size=-1  ,	keep_in_memory=SCREAMING_SNAKE_CASE_  ,	remove_columns=eval_dataset.column_names  ,	)

     _a      =  list(set(vocab_train['''vocab'''][0]) | set(vocab_test['''vocab'''][0]))
     _a      =  {v: k for k, v in enumerate(SCREAMING_SNAKE_CASE_)}
     _a      =  vocab_dict[' ']
     del vocab_dict[" "]
     _a      =  len(SCREAMING_SNAKE_CASE_)
     _a      =  len(SCREAMING_SNAKE_CASE_)

     with open('''vocab.json'''  ,	'''w''') as vocab_file:
          json.dump(SCREAMING_SNAKE_CASE_  ,	SCREAMING_SNAKE_CASE_)

     # Load pretrained model and tokenizer
     #
     # Distributed training:
     # The .from_pretrained methods guarantee that only one local process can concurrently
     # download model & vocab.
     _a      =  WavaVecaCTCTokenizer(
         '''vocab.json'''  ,	unk_token='''[UNK]'''  ,	pad_token='''[PAD]'''  ,	word_delimiter_token='''|'''  ,	)
     _a      =  WavaVecaFeatureExtractor(
         feature_size=1  ,	sampling_rate=16_000  ,	padding_value=0.0  ,	do_normalize=SCREAMING_SNAKE_CASE_  ,	return_attention_mask=SCREAMING_SNAKE_CASE_)
     _a      =  WavaVecaProcessor(feature_extractor=SCREAMING_SNAKE_CASE_  ,	tokenizer=SCREAMING_SNAKE_CASE_)
     _a      =  WavaVecaForCTC.from_pretrained(
         model_args.model_name_or_path  ,	cache_dir=model_args.cache_dir  ,	activation_dropout=model_args.activation_dropout  ,	attention_dropout=model_args.attention_dropout  ,	hidden_dropout=model_args.hidden_dropout  ,	feat_proj_dropout=model_args.feat_proj_dropout  ,	mask_time_prob=model_args.mask_time_prob  ,	gradient_checkpointing=training_args.gradient_checkpointing  ,	layerdrop=model_args.layerdrop  ,	ctc_loss_reduction='''mean'''  ,	pad_token_id=processor.tokenizer.pad_token_id  ,	vocab_size=len(processor.tokenizer)  ,	)

     if data_args.max_train_samples is not None:
          _a      =  min(len(SCREAMING_SNAKE_CASE_)  ,	data_args.max_train_samples)
          _a      =  train_dataset.select(range(SCREAMING_SNAKE_CASE_))

     if data_args.max_val_samples is not None:
          _a      =  eval_dataset.select(range(data_args.max_val_samples))

     _a      =  torchaudio.transforms.Resample(48_000  ,	16_000)

     # Preprocessing the datasets.
     # We need to read the aduio files as arrays and tokenize the targets.
     def speech_file_to_array_fn(__A):
          _a      =  torchaudio.load(batch['''path'''])
          _a      =  resampler(SCREAMING_SNAKE_CASE_).squeeze().numpy()
          _a      =  16_000
          _a      =  batch['text']
          return batch

     _a      =  train_dataset.map(
         SCREAMING_SNAKE_CASE_  ,	remove_columns=train_dataset.column_names  ,	num_proc=data_args.preprocessing_num_workers  ,	)
     _a      =  eval_dataset.map(
         SCREAMING_SNAKE_CASE_  ,	remove_columns=eval_dataset.column_names  ,	num_proc=data_args.preprocessing_num_workers  ,	)

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

          _a      =  processor(
              audio=batch['''speech''']  ,	text=batch['''target_text''']  ,	sampling_rate=batch['''sampling_rate'''][0])
          batch.update(SCREAMING_SNAKE_CASE_)
          return batch

     _a      =  train_dataset.map(
         SCREAMING_SNAKE_CASE_  ,	remove_columns=train_dataset.column_names  ,	batch_size=training_args.per_device_train_batch_size  ,	batched=SCREAMING_SNAKE_CASE_  ,	num_proc=data_args.preprocessing_num_workers  ,	)
     _a      =  eval_dataset.map(
         SCREAMING_SNAKE_CASE_  ,	remove_columns=eval_dataset.column_names  ,	batch_size=training_args.per_device_train_batch_size  ,	batched=SCREAMING_SNAKE_CASE_  ,	num_proc=data_args.preprocessing_num_workers  ,	)

     # Metric
     _a      =  datasets.load_metric('''wer''')

     def compute_metrics(__A):
          _a      =  pred.predictions
          _a      =  np.argmax(SCREAMING_SNAKE_CASE_  ,	axis=-1)

          _a      =  processor.tokenizer.pad_token_id

          _a      =  processor.batch_decode(SCREAMING_SNAKE_CASE_)
          # we do not want to group tokens when computing the metrics
          _a      =  processor.batch_decode(pred.label_ids  ,	group_tokens=SCREAMING_SNAKE_CASE_)

          _a      =  wer_metric.compute(predictions=SCREAMING_SNAKE_CASE_  ,	references=SCREAMING_SNAKE_CASE_)

          return {"wer": wer}

     if model_args.freeze_feature_extractor:
          model.freeze_feature_extractor()

     # Data collator
     _a      =  DataCollatorCTCWithPadding(processor=SCREAMING_SNAKE_CASE_  ,	padding=SCREAMING_SNAKE_CASE_)

     # Initialize our Trainer
     _a      =  CTCTrainer(
         model=SCREAMING_SNAKE_CASE_  ,	data_collator=SCREAMING_SNAKE_CASE_  ,	args=SCREAMING_SNAKE_CASE_  ,	compute_metrics=SCREAMING_SNAKE_CASE_  ,	train_dataset=train_dataset if training_args.do_train else None  ,	eval_dataset=eval_dataset if training_args.do_eval else None  ,	tokenizer=processor.feature_extractor  ,	)

     # Training
     if training_args.do_train:
          if last_checkpoint is not None:
               _a      =  last_checkpoint
          elif os.path.isdir(model_args.model_name_or_path):
               _a      =  model_args.model_name_or_path
          else:
               _a      =  None

          # Save the feature_extractor and the tokenizer
          if is_main_process(training_args.local_rank):
               processor.save_pretrained(training_args.output_dir)

          _a      =  trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE_)
          trainer.save_model()

          _a      =  train_result.metrics
          _a      =  (
              data_args.max_train_samples if data_args.max_train_samples is not None else len(SCREAMING_SNAKE_CASE_)
          )
          _a      =  min(SCREAMING_SNAKE_CASE_  ,	len(SCREAMING_SNAKE_CASE_))

          trainer.log_metrics('''train'''  ,	SCREAMING_SNAKE_CASE_)
          trainer.save_metrics('''train'''  ,	SCREAMING_SNAKE_CASE_)
          trainer.save_state()

     # Evaluation
     _a      =  {}
     if training_args.do_eval:
          logger.info('''*** Evaluate ***''')
          _a      =  trainer.evaluate()
          _a      =  data_args.max_val_samples if data_args.max_val_samples is not None else len(SCREAMING_SNAKE_CASE_)
          _a      =  min(SCREAMING_SNAKE_CASE_  ,	len(SCREAMING_SNAKE_CASE_))

          trainer.log_metrics('''eval'''  ,	SCREAMING_SNAKE_CASE_)
          trainer.save_metrics('''eval'''  ,	SCREAMING_SNAKE_CASE_)

     return results


if __name__ == "__main__":
  main()






from ...configuration_utils import PretrainedConfig
from ...utils import logging


snake_case_			  = logging.get_logger(__name__)

snake_case_			  = {
    '''google/switch-base-8''': '''https://huggingface.co/google/switch-base-8/blob/main/config.json''',
}


class       SCREAMING_SNAKE_CASE__					(__snake_case     ):
    __lowerCamelCase						:       int														=     """switch_transformers"""
    __lowerCamelCase						:       Optional[Any]														=     ["""past_key_values"""]
    __lowerCamelCase						:       Any														=     {"""hidden_size""": """d_model""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""}





    def __init__(      self						,   a=3_2128						,   a=768						,   a=64						,   a=2048						,   a=64						,   a=12						,   a=3						,   a=12						,   a=3						,   a=12						,   a=8						,   a=False						,   a=0.01						,   a="float32"						,   a=False						,   a=32						,   a=128						,   a=0.1						,   a=1e-6						,   a=0.001						,   a=0.001						,   a=1.0						,   a="relu"						,   a=True						,   a=False						,   a=True						,   a=0						,   a=1						,   **a						,   ):
         lowercase__    :   Optional[int]      =       vocab_size
         lowercase__    :   List[Any]      =       d_model
         lowercase__    :   List[Any]      =       d_kv
         lowercase__    :   Any      =       d_ff

         lowercase__    :   Optional[int]      =       num_sparse_encoder_layers

         lowercase__    :   Tuple      =       num_layers
         lowercase__    :   Optional[Any]      =       (
             num_decoder_layers if num_decoder_layers is not None else self.num_layers
         )  # default = symmetry
         lowercase__    :   str      =       num_sparse_decoder_layers

         # This tells us, each how many encoder layer we'll have to set a sparse layer.
         if self.num_sparse_encoder_layers > 0:
              lowercase__    :   Optional[Any]      =       self.num_layers // self.num_sparse_encoder_layers
         else:
              lowercase__    :   Optional[int]      =       self.num_layers  # HACK: this will create 0 sparse layers

         # This tells us, each how many encoder layer we'll have to set a sparse layer.
         if self.num_sparse_decoder_layers > 0:
              lowercase__    :   Union[str, Any]      =       self.num_decoder_layers // self.num_sparse_decoder_layers
         else:
              lowercase__    :   int      =       self.num_decoder_layers  # HACK: this will create 0 sparse layers

         lowercase__    :   List[Any]      =       num_heads
         lowercase__    :   Union[str, Any]      =       num_experts
         lowercase__    :   str      =       expert_capacity
         lowercase__    :   List[Any]      =       router_bias
         lowercase__    :   Optional[int]      =       router_jitter_noise
         if router_dtype not in ["float32", "float16", "bfloat16"]:
              raise ValueError(f"""`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}""")
         lowercase__    :   str      =       router_dtype

         lowercase__    :   Optional[int]      =       router_ignore_padding_tokens
         lowercase__    :   int      =       relative_attention_num_buckets
         lowercase__    :   Optional[Any]      =       relative_attention_max_distance

         lowercase__    :   List[str]      =       dropout_rate
         lowercase__    :   str      =       layer_norm_epsilon
         lowercase__    :   int      =       initializer_factor
         lowercase__    :   int      =       feed_forward_proj
         lowercase__    :   Dict      =       use_cache
         lowercase__    :   int      =       add_router_probs

         lowercase__    :   int      =       router_z_loss_coef
         lowercase__    :   List[Any]      =       router_aux_loss_coef

         lowercase__    :   int      =       self.feed_forward_proj.split('-')
         lowercase__    :   Optional[int]      =       act_info[-1]
         lowercase__    :   Dict      =       act_info[0] == 'gated'

         if len(a) > 1 and act_info[0] != "gated" or len(a) > 2:
              raise ValueError(
                  f"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer."""
                  'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. '
                  '\'gated-gelu\' or \'relu\'')

         # for backwards compatibility
         if feed_forward_proj == "gated-gelu":
              lowercase__    :   Optional[int]      =       'gelu_new'

         super().__init__(
             pad_token_id=a						,   eos_token_id=a						,   is_encoder_decoder=a						,   **a						,   )

