





import argparse
import json
import os
import re

import torch

from transformers import BloomConfig, BloomModel
from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME
from transformers.utils import logging


logging.set_verbosity_info()

SCREAMING_SNAKE_CASE_		     = [
    """word_embeddings_layernorm.weight""",
    """word_embeddings_layernorm.bias""",
    """input_layernorm.weight""",
    """input_layernorm.bias""",
    """post_attention_layernorm.weight""",
    """post_attention_layernorm.bias""",
    """self_attention.dense.bias""",
    """mlp.dense_4h_to_h.bias""",
    """ln_f.weight""",
    """ln_f.bias""",
]

SCREAMING_SNAKE_CASE_		     = [
    """mlp.dense_4h_to_h.weight""",
    """self_attention.dense.weight""",
]



def      __lowercase     (   _SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE			)				->     Optional[int]:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE	=		{
          """word_embeddings.weight""": """word_embeddings.weight""",
          """word_embeddings.norm.weight""": """word_embeddings_layernorm.weight""",
          """word_embeddings.norm.bias""": """word_embeddings_layernorm.bias""",
          """weight""": """ln_f.weight""",
          """bias""": """ln_f.bias""",
      }

      if key in layer_rename_map:
            return layer_rename_map[key]

      # Handle transformer blocks
      SCREAMING_SNAKE_CASE	=		int(re.match(r""".*layer_(\d*).*"""				,		_SCREAMING_SNAKE_CASE			)[1]			)
      layer_number -= 3
      return F"""h.{layer_number}.""" + key



def      __lowercase     (   _SCREAMING_SNAKE_CASE			)				->     str:


      '''simple docstring'''


      if dtype == torch.bool:
            return 1 / 8
      SCREAMING_SNAKE_CASE	=		re.search(r"""[^\d](\d+)$"""				,		str(_SCREAMING_SNAKE_CASE			)			)
      if bit_search is None:
            raise ValueError(F"""`dtype` is not a valid dtype: {dtype}."""			)
      SCREAMING_SNAKE_CASE	=		int(bit_search.groups()[0]			)
      return bit_size // 8



def      __lowercase     (   _SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE			)				->     Optional[int]:


      '''simple docstring'''


      if bloom_config_file == "":
            SCREAMING_SNAKE_CASE	=		BloomConfig()
      else:
            SCREAMING_SNAKE_CASE	=		BloomConfig.from_json_file(_SCREAMING_SNAKE_CASE			)

      if shard_model:
            SCREAMING_SNAKE_CASE	=		os.listdir(_SCREAMING_SNAKE_CASE			)
            SCREAMING_SNAKE_CASE	=		sorted(filter(lambda _SCREAMING_SNAKE_CASE			: s.startswith("""layer"""			) and "model_00" in s				,		_SCREAMING_SNAKE_CASE			)			)

            SCREAMING_SNAKE_CASE	=		{"""weight_map""": {}, """metadata""": {}}
            SCREAMING_SNAKE_CASE	=		0

            SCREAMING_SNAKE_CASE	=		None

            SCREAMING_SNAKE_CASE	=		BloomConfig()

            for j, file in enumerate(_SCREAMING_SNAKE_CASE			):
                  print("""Processing file: {}""".format(_SCREAMING_SNAKE_CASE			)			)
                  SCREAMING_SNAKE_CASE	=		None

                  for i in range(_SCREAMING_SNAKE_CASE			):
                        # load all TP files
                        SCREAMING_SNAKE_CASE	=		file.replace("""model_00"""				,		F"""model_0{i}"""			)
                        SCREAMING_SNAKE_CASE	=		torch.load(os.path.join(_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE			)				,		map_location="""cpu"""			)

                        # Rename keys in the transformers names
                        SCREAMING_SNAKE_CASE	=		list(temp.keys()			)
                        for key in keys:
                              SCREAMING_SNAKE_CASE	=		temp.pop(_SCREAMING_SNAKE_CASE			)

                        if tensors is None:
                              SCREAMING_SNAKE_CASE	=		temp
                        else:
                              for key in tensors.keys():
                                    if any(key.endswith(_SCREAMING_SNAKE_CASE			) for end in WEIGHTS_TO_AVERAGE_ENDSWITH			):
                                          # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425)
                                          tensors[key] += temp[key]
                                    else:
                                          # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel
                                          SCREAMING_SNAKE_CASE	=		1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN			) else 0
                                          # We concatenate these weights accross TP ranks
                                          SCREAMING_SNAKE_CASE	=		torch.cat([tensors[key], temp[key]]				,		dim=_SCREAMING_SNAKE_CASE			)

            # Divide by the number of TP the weights we want to average
                  for key in tensors.keys():
                        if any(key.endswith(_SCREAMING_SNAKE_CASE			) for end in WEIGHTS_TO_AVERAGE_ENDSWITH			):
                              SCREAMING_SNAKE_CASE	=		tensors[key] / pretraining_tp
                  torch.save(
                      _SCREAMING_SNAKE_CASE				,		os.path.join(
                          _SCREAMING_SNAKE_CASE				,		"""pytorch_model_{}-of-{}.bin""".format(str(j + 1			).zfill(5			)				,		str(len(_SCREAMING_SNAKE_CASE			)			).zfill(5			)			)				,		)				,		)

                  for key in tensors.keys():
                        SCREAMING_SNAKE_CASE	=		tensors[key]
                        total_size += value.numel() * get_dtype_size(value.dtype			)
                        if key not in index_dict["weight_map"]:
                              SCREAMING_SNAKE_CASE	=		"""pytorch_model_{}-of-{}.bin""".format(
                                  str(j + 1			).zfill(5			)				,		str(len(_SCREAMING_SNAKE_CASE			)			).zfill(5			)			)

            SCREAMING_SNAKE_CASE	=		BloomConfig()
            SCREAMING_SNAKE_CASE	=		pytorch_dump_folder_path + """/""" + CONFIG_NAME
            SCREAMING_SNAKE_CASE	=		total_size
            with open(_SCREAMING_SNAKE_CASE				,		"""w"""				,		encoding="""utf-8"""			) as f:
                  f.write(config.to_json_string()			)
            with open(os.path.join(_SCREAMING_SNAKE_CASE				,		WEIGHTS_NAME + """.index.json"""			)				,		"""w"""				,		encoding="""utf-8"""			) as f:
                  SCREAMING_SNAKE_CASE	=		json.dumps(_SCREAMING_SNAKE_CASE				,		indent=2				,		sort_keys=_SCREAMING_SNAKE_CASE			) + """\n"""
                  f.write(_SCREAMING_SNAKE_CASE			)
      else:
            SCREAMING_SNAKE_CASE	=		BloomModel(_SCREAMING_SNAKE_CASE			)

            SCREAMING_SNAKE_CASE	=		os.listdir(_SCREAMING_SNAKE_CASE			)
            SCREAMING_SNAKE_CASE	=		sorted(filter(lambda _SCREAMING_SNAKE_CASE			: s.startswith("""layer"""			) and "model_00" in s				,		_SCREAMING_SNAKE_CASE			)			)

            SCREAMING_SNAKE_CASE	=		None
            for i, file in enumerate(_SCREAMING_SNAKE_CASE			):
                  SCREAMING_SNAKE_CASE	=		None
                  for i in range(_SCREAMING_SNAKE_CASE			):
                        # load all TP files
                        SCREAMING_SNAKE_CASE	=		file.replace("""model_00"""				,		F"""model_0{i}"""			)
                        SCREAMING_SNAKE_CASE	=		torch.load(os.path.join(_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE			)				,		map_location="""cpu"""			)

                        # Rename keys in the transformers names
                        SCREAMING_SNAKE_CASE	=		list(temp.keys()			)
                        for key in keys:
                              SCREAMING_SNAKE_CASE	=		temp.pop(_SCREAMING_SNAKE_CASE			)

                        if tensors is None:
                              SCREAMING_SNAKE_CASE	=		temp
                        else:
                              for key in tensors.keys():
                                    # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425)
                                    if any(key.endswith(_SCREAMING_SNAKE_CASE			) for end in WEIGHTS_TO_AVERAGE_ENDSWITH			):
                                          tensors[key] += temp[key]
                                    else:
                                          # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel
                                          SCREAMING_SNAKE_CASE	=		1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN			) else 0
                                          # We concatenate these weights accross TP ranks
                                          SCREAMING_SNAKE_CASE	=		torch.cat([tensors[key], temp[key]]				,		dim=_SCREAMING_SNAKE_CASE			)

            # Divide by the number of TP the weights we want to average
                  for key in tensors.keys():
                        if any(key.endswith(_SCREAMING_SNAKE_CASE			) for end in WEIGHTS_TO_AVERAGE_ENDSWITH			):
                              SCREAMING_SNAKE_CASE	=		tensors[key] / pretraining_tp

                  SCREAMING_SNAKE_CASE	=		model.load_state_dict(_SCREAMING_SNAKE_CASE				,		strict=_SCREAMING_SNAKE_CASE			)
                  assert not other_keys.unexpected_keys, F"""The keys {other_keys.unexpected_keys} are unexpected"""
                  if missing_keys is None:
                        SCREAMING_SNAKE_CASE	=		set(other_keys.missing_keys			)
                  else:
                        SCREAMING_SNAKE_CASE	=		missing_keys.intersection(set(other_keys.missing_keys			)			)

            assert not missing_keys, F"""The keys {missing_keys} are missing"""

            # Save pytorch-model
            os.makedirs(_SCREAMING_SNAKE_CASE				,		exist_ok=_SCREAMING_SNAKE_CASE			)
            SCREAMING_SNAKE_CASE	=		pytorch_dump_folder_path + """/""" + WEIGHTS_NAME
            SCREAMING_SNAKE_CASE	=		pytorch_dump_folder_path + """/""" + CONFIG_NAME
            print(F"""Save PyTorch model to {pytorch_weights_dump_path} with dtype {config.torch_dtype}"""			)
            if config.torch_dtype is not None:
                  SCREAMING_SNAKE_CASE	=		model.to(config.torch_dtype			)
            torch.save(model.state_dict()				,		_SCREAMING_SNAKE_CASE			)
            print(F"""Save configuration file to {pytorch_config_dump_path}"""			)
            with open(_SCREAMING_SNAKE_CASE				,		"""w"""				,		encoding="""utf-8"""			) as f:
                  f.write(config.to_json_string()			)


if __name__ == "__main__":
      SCREAMING_SNAKE_CASE_		     = argparse.ArgumentParser()
      # Required parameters
      parser.add_argument(
          """--bloom_checkpoint_path""",
          default=None,
          type=str,
          required=True,
          help="""Path to the Megatron-LM checkpoint path.""",
      )
      parser.add_argument(
          """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
      )
      parser.add_argument(
          """--bloom_config_file""",
          default="""""",
          type=str,
          help=(
              """An optional config json file corresponding to the pre-trained model. \n"""
              """This specifies the model architecture."""
          ),
      )
      parser.add_argument(
          """--shard_model""",
          action="""store_true""",
          help="""An optional setting to shard the output model \nThis enables sharding the converted checkpoint""",
      )
      parser.add_argument(
          """--pretraining_tp""",
          default=4,
          type=int,
          help="""Pretraining TP rank that has been used when training the model in Megatron-LM \n""",
      )
      SCREAMING_SNAKE_CASE_		     = parser.parse_args()
      convert_bloom_checkpoint_to_pytorch(
          args.bloom_checkpoint_path,
          args.bloom_config_file,
          args.pytorch_dump_folder_path,
          args.shard_model,
          args.pretraining_tp,
      )









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

SCREAMING_SNAKE_CASE_		     = logging.getLogger(__name__)



def      __lowercase     (   _SCREAMING_SNAKE_CASE=None				,		_SCREAMING_SNAKE_CASE=None			)				->     int:


      '''simple docstring'''


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

@dataclass
class 	UpperCamelCase__				:



     '''simple docstring'''

     __snake_case					:			str				=    field(
         metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}     )
     __snake_case					:			Optional[str]				=    field(
         default=lowerCAmelCase_							,   metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}							,   )
     __snake_case					:			Optional[bool]				=    field(
         default=lowerCAmelCase_							,   metadata={"help": "Whether to freeze the feature extractor layers of the model."}     )
     __snake_case					:			Optional[float]				=    field(
         default=0.1							,   metadata={"help": "The dropout ratio for the attention probabilities."}     )
     __snake_case					:			Optional[float]				=    field(
         default=0.1							,   metadata={"help": "The dropout ratio for activations inside the fully connected layer."}     )
     __snake_case					:			Optional[float]				=    field(
         default=0.1							,   metadata={
             "help": "The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler."
         }							,   )
     __snake_case					:			Optional[float]				=    field(
         default=0.1							,   metadata={"help": "The dropout probabilitiy for all 1D convolutional layers in feature extractor."}							,   )
     __snake_case					:			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``."
             )
         }							,   )
     __snake_case					:			Optional[float]				=    field(default=0.0							,   metadata={"help": "The LayerDrop probability."}     )

@dataclass
class 	UpperCamelCase__				:



     '''simple docstring'''

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

@dataclass
class 	UpperCamelCase__				:



     '''simple docstring'''

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






     def __call__(							self		:					Any		,lowerCamelCase__		:					List[Dict[str, Union[List[int], torch.Tensor]]] )  ->	Dict[str, torch.Tensor]:




           '''simple docstring'''


           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(
               lowerCamelCase__		,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=lowerCamelCase__		,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 	UpperCamelCase__				(   lowerCAmelCase_     ):



     '''simple docstring'''

     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str]		,lowerCamelCase__		:					nn.Module		,lowerCamelCase__		:					Dict[str, Union[torch.Tensor, Any]] )  ->	torch.Tensor:




           '''simple docstring'''


           model.train()
           SCREAMING_SNAKE_CASE	=		self._prepare_inputs(lowerCamelCase__ )

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

           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(lowerCamelCase__ ).backward()
           elif self.use_apex:
                 with amp.scale_loss(lowerCamelCase__		,self.optimizer ) as scaled_loss:
                       scaled_loss.backward()
           elif self.deepspeed:
                 self.deepspeed.backward(lowerCamelCase__ )
           else:
                 loss.backward()

           return loss.detach()



def      __lowercase     (   )				->     Tuple:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE	=		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.
            SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]			)			)
      else:
            SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		parser.parse_args_into_dataclasses()

      # Detecting last checkpoint.
      SCREAMING_SNAKE_CASE	=		None
      if os.path.isdir(training_args.output_dir			) and training_args.do_train and not training_args.overwrite_output_dir:
            SCREAMING_SNAKE_CASE	=		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:
      SCREAMING_SNAKE_CASE	=		datasets.load_dataset(
          """common_voice"""				,		data_args.dataset_config_name				,		split=data_args.train_split_name			)
      SCREAMING_SNAKE_CASE	=		datasets.load_dataset("""common_voice"""				,		data_args.dataset_config_name				,		split="""test"""			)

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

      def remove_special_characters(_SCREAMING_SNAKE_CASE			):
            SCREAMING_SNAKE_CASE	=		re.sub(_SCREAMING_SNAKE_CASE				,		""""""				,		batch["""sentence"""]			).lower() + """ """
            return batch

      SCREAMING_SNAKE_CASE	=		train_dataset.map(_SCREAMING_SNAKE_CASE				,		remove_columns=["""sentence"""]			)
      SCREAMING_SNAKE_CASE	=		eval_dataset.map(_SCREAMING_SNAKE_CASE				,		remove_columns=["""sentence"""]			)

      def extract_all_chars(_SCREAMING_SNAKE_CASE			):
            SCREAMING_SNAKE_CASE	=		""" """.join(batch["""text"""]			)
            SCREAMING_SNAKE_CASE	=		list(set(_SCREAMING_SNAKE_CASE			)			)
            return {"vocab": [vocab], "all_text": [all_text]}

      SCREAMING_SNAKE_CASE	=		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				,		)
      SCREAMING_SNAKE_CASE	=		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				,		)

      SCREAMING_SNAKE_CASE	=		list(set(vocab_train["""vocab"""][0]			) | set(vocab_test["""vocab"""][0]			)			)
      SCREAMING_SNAKE_CASE	=		{v: k for k, v in enumerate(_SCREAMING_SNAKE_CASE			)}
      SCREAMING_SNAKE_CASE	=		vocab_dict[""" """]
      del vocab_dict[" "]
      SCREAMING_SNAKE_CASE	=		len(_SCREAMING_SNAKE_CASE			)
      SCREAMING_SNAKE_CASE	=		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.
      SCREAMING_SNAKE_CASE	=		WavaVecaCTCTokenizer(
          """vocab.json"""				,		unk_token="""[UNK]"""				,		pad_token="""[PAD]"""				,		word_delimiter_token="""|"""				,		)
      SCREAMING_SNAKE_CASE	=		WavaVecaFeatureExtractor(
          feature_size=1				,		sampling_rate=1_60_00				,		padding_value=0.0				,		do_normalize=_SCREAMING_SNAKE_CASE				,		return_attention_mask=_SCREAMING_SNAKE_CASE			)
      SCREAMING_SNAKE_CASE	=		WavaVecaProcessor(feature_extractor=_SCREAMING_SNAKE_CASE				,		tokenizer=_SCREAMING_SNAKE_CASE			)
      SCREAMING_SNAKE_CASE	=		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:
            SCREAMING_SNAKE_CASE	=		min(len(_SCREAMING_SNAKE_CASE			)				,		data_args.max_train_samples			)
            SCREAMING_SNAKE_CASE	=		train_dataset.select(range(_SCREAMING_SNAKE_CASE			)			)

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

      SCREAMING_SNAKE_CASE	=		torchaudio.transforms.Resample(4_80_00				,		1_60_00			)

      # Preprocessing the datasets.
      # We need to read the aduio files as arrays and tokenize the targets.
      def speech_file_to_array_fn(_SCREAMING_SNAKE_CASE			):
            SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		torchaudio.load(batch["""path"""]			)
            SCREAMING_SNAKE_CASE	=		resampler(_SCREAMING_SNAKE_CASE			).squeeze().numpy()
            SCREAMING_SNAKE_CASE	=		1_60_00
            SCREAMING_SNAKE_CASE	=		batch["""text"""]
            return batch

      SCREAMING_SNAKE_CASE	=		train_dataset.map(
          _SCREAMING_SNAKE_CASE				,		remove_columns=train_dataset.column_names				,		num_proc=data_args.preprocessing_num_workers				,		)
      SCREAMING_SNAKE_CASE	=		eval_dataset.map(
          _SCREAMING_SNAKE_CASE				,		remove_columns=eval_dataset.column_names				,		num_proc=data_args.preprocessing_num_workers				,		)

      def prepare_dataset(_SCREAMING_SNAKE_CASE			):
            # 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["""target_text"""]				,		sampling_rate=batch["""sampling_rate"""][0]			)
            batch.update(_SCREAMING_SNAKE_CASE			)
            return batch

      SCREAMING_SNAKE_CASE	=		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				,		)
      SCREAMING_SNAKE_CASE	=		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
      SCREAMING_SNAKE_CASE	=		datasets.load_metric("""wer"""			)

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

            SCREAMING_SNAKE_CASE	=		processor.tokenizer.pad_token_id

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

            SCREAMING_SNAKE_CASE	=		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
      SCREAMING_SNAKE_CASE	=		DataCollatorCTCWithPadding(processor=_SCREAMING_SNAKE_CASE				,		padding=_SCREAMING_SNAKE_CASE			)

      # Initialize our Trainer
      SCREAMING_SNAKE_CASE	=		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:
                  SCREAMING_SNAKE_CASE	=		last_checkpoint
            elif os.path.isdir(model_args.model_name_or_path			):
                  SCREAMING_SNAKE_CASE	=		model_args.model_name_or_path
            else:
                  SCREAMING_SNAKE_CASE	=		None

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

            SCREAMING_SNAKE_CASE	=		trainer.train(resume_from_checkpoint=_SCREAMING_SNAKE_CASE			)
            trainer.save_model()

            SCREAMING_SNAKE_CASE	=		train_result.metrics
            SCREAMING_SNAKE_CASE	=		(
                data_args.max_train_samples if data_args.max_train_samples is not None else len(_SCREAMING_SNAKE_CASE			)
            )
            SCREAMING_SNAKE_CASE	=		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
      SCREAMING_SNAKE_CASE	=		{}
      if training_args.do_eval:
            logger.info("""*** Evaluate ***"""			)
            SCREAMING_SNAKE_CASE	=		trainer.evaluate()
            SCREAMING_SNAKE_CASE	=		data_args.max_val_samples if data_args.max_val_samples is not None else len(_SCREAMING_SNAKE_CASE			)
            SCREAMING_SNAKE_CASE	=		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()


