usrbinenv python codingutf8 2022 the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache orglicenseslicense2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and finetuning a transformers ctc model for automatic speech recognition in streaming mode import logging import os import re import sys import warnings from dataclasses import dataclass field from typing import dict list optional union import datasets import numpy as np import torch from datasets import iterabledatasetdict interleavedatasets loaddataset loadmetric from torch utils data import iterabledataset import transformers from transformers import autoconfig autofeatureextractor automodelforctc autoprocessor autotokenizer hfargumentparser trainer trainercallback trainingarguments wav2vec2processor setseed from transformers trainerptutils import iterabledatasetshard from transformers trainerutils import getlastcheckpoint ismainprocess from transformers utils import checkminversion from transformers utils versions import requireversion will error if the minimal version of transformers is not installed remove at your own risk checkminversion4 17 0 dev0 requireversiondatasets1 18 2 to fix pip install datasets1 18 2 logger logging getloggername def listfielddefaultnone metadatanone return fielddefaultfactorylambda default metadatametadata dataclass class modelarguments modelnameorpath str field metadatahelp path to pretrained model or model identifier from huggingface comodels tokenizernameorpath optionalstr field defaultnone metadatahelp path to pretrained tokenizer or tokenizer identifier from huggingface comodels cachedir optionalstr field defaultnone metadatahelp where do you want to store the pretrained models downloaded from huggingface co freezefeatureencoder bool field defaulttrue metadatahelp whether to freeze the feature encoder layers of the model attentiondropout float field default0 0 metadatahelp the dropout ratio for the attention probabilities activationdropout float field default0 0 metadatahelp the dropout ratio for activations inside the fully connected layer featprojdropout float fielddefault0 0 metadatahelp the dropout ratio for the projected features hiddendropout float field default0 0 metadata help the dropout probability for all fully connected layers in the embeddings encoder and pooler finaldropout float field default0 0 metadatahelp the dropout probability for the final projection layer masktimeprob float field default0 05 metadata help probability of each feature vector along the time axis to be chosen as the start of the vector span to be masked approximately masktimeprob sequencelength masktimelength feature vectors will be masked along the time axis masktimelength int field default10 metadatahelp length of vector span to mask along the time axis maskfeatureprob float field default0 0 metadata help probability of each feature vector along the feature axis to be chosen as the start of the vectorspan to be masked approximately maskfeatureprob sequencelength maskfeaturelength feature bins will be masked along the time axis maskfeaturelength int field default10 metadatahelp length of vector span to mask along the feature axis layerdrop float fielddefault0 0 metadatahelp the layerdrop probability ctclossreduction optionalstr field defaultmean metadatahelp the way the ctc loss should be reduced should be one of mean or sum dataclass class datatrainingarguments datasetname str field metadatahelp the configuration name of the dataset to use via the datasets library datasetconfigname str field defaultnone metadatahelp the configuration name of the dataset to use via the datasets library trainsplitname str field defaulttrainvalidation metadata help the name of the training data set split to use via the datasets library defaults to trainvalidation evalsplitname str field defaulttest metadata help the name of the training data set split to use via the datasets library defaults to test audiocolumnname str field defaultaudio metadatahelp the name of the dataset column containing the audio data defaults to audio textcolumnname str field defaulttext metadatahelp the name of the dataset column containing the text data defaults to text overwritecache bool field defaultfalse metadatahelp overwrite the cached preprocessed datasets or not preprocessingnumworkers optionalint field defaultnone metadatahelp the number of processes to use for the preprocessing maxtrainsamples optionalint field defaultnone metadata help for debugging purposes or quicker training truncate the number of training examples to this value if set maxevalsamples optionalint field defaultnone metadata help for debugging purposes or quicker training truncate the number of validation examples to this value if set shufflebuffersize optionalint field default500 metadata help the number of streamed examples to download before shuffling them the large the buffer the closer it is to real offline shuffling charstoignore optionalliststr listfield defaultnone metadatahelp a list of characters to remove from the transcripts evalmetrics liststr listfield defaultwer metadatahelp a list of metrics the model should be evaluated on e g wer cer maxdurationinseconds float field default20 0 metadatahelp filter audio files that are longer than maxdurationinseconds seconds preprocessingonly bool field defaultfalse metadata help whether to only do data preprocessing and skip training this is especially useful when data preprocessing errors out in distributed training due to timeout in this case one should run the preprocessing in a nondistributed setup with preprocessingonlytrue so that the cached datasets can consequently be loaded in distributed training useauthtoken bool field defaultfalse metadata help if obj true will use the token generated when running obj huggingfacecli login as http bearer ization for remote files phonemelanguage optionalstr field defaultnone metadata help the target language that should be used be passed to the tokenizer for tokenization note that this is only relevant if the model classifies the input audio to a sequence of phoneme sequences dataclass class datacollatorctcwithpadding processor autoprocessor padding unionbool str longest maxlength optionalint none padtomultipleof optionalint none padtomultipleoflabels optionalint none def callself features listdictstr unionlistint torch tensor dictstr torch tensor split inputs and labels since they have to be of different lengths and need different padding methods inputfeatures labelfeatures for feature in features if self maxlength and featureinputvalues shape1 self maxlength continue inputfeatures appendinputvalues featureinputvalues labelfeatures appendinputids featurelabels batch self processor pad inputfeatures paddingself padding padtomultipleofself padtomultipleof returntensorspt labelsbatch self processor pad labelslabelfeatures paddingself padding padtomultipleofself padtomultipleoflabels returntensorspt replace padding with 100 to ignore loss correctly labels labelsbatchinputids maskedfilllabelsbatch attentionmask ne1 100 batchlabels labels return batch def main see all possible arguments in srctransformerstrainingargs py or by passing the help flag to this script we now keep distinct sets of args for a cleaner separation of concerns parser hfargumentparsermodelarguments datatrainingarguments trainingarguments if lensys argv 2 and sys argv1 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 modelargs dataargs trainingargs parser parsejsonfilejsonfileos path abspathsys argv1 else modelargs dataargs trainingargs parser parseargsintodataclasses detecting last checkpoint lastcheckpoint none if os path isdirtrainingargs outputdir and trainingargs dotrain and not trainingargs overwriteoutputdir lastcheckpoint getlastcheckpointtrainingargs outputdir if lastcheckpoint is none and lenos listdirtrainingargs outputdir 0 raise valueerror foutput directory trainingargs outputdir already exists and is not empty use overwriteoutputdir to overcome elif lastcheckpoint is not none logger info fcheckpoint detected resuming training at lastcheckpoint to avoid this behavior change the outputdir or add overwriteoutputdir to train from scratch setup logging logging basicconfig formatasctimes levelnames names messages datefmtmdy h m s handlerslogging streamhandlersys stdout logger setlevellogging info if ismainprocesstrainingargs localrank else logging warn log on each process the small summary logger warning fprocess rank trainingargs localrank device trainingargs device ngpu trainingargs ngpu fdistributed training booltrainingargs localrank 1 16bits training trainingargs fp16 set the verbosity to info of the transformers logger on main process only if ismainprocesstrainingargs localrank transformers utils logging setverbosityinfo logger infotrainingevaluation parameters s trainingargs set seed before initializing model setseedtrainingargs seed 1 first let s load the dataset rawdatasets iterabledatasetdict rawcolumnnames def loadstreamingdatasetsplit samplingrate kwargs if in split datasetsplits loaddatasetsplitsplitname kwargs for splitname in split split features and castcolumn won t be available after interleaving so we ll use them here features datasetsplits0 features make sure that the dataset decodes audio with a correct sampling rate datasetsplits dataset castcolumndataargs audiocolumnname datasets features audiosamplingratesamplingrate for dataset in datasetsplits interleaveddataset interleavedatasetsdatasetsplits return interleaveddataset features else dataset loaddatasetsplitsplit kwargs features dataset features make sure that the dataset decodes audio with a correct sampling rate dataset dataset castcolumn dataargs audiocolumnname datasets features audiosamplingratesamplingrate return dataset features datasets takes care of automatically loading and resampling the audio so we just need to set the correct target sampling rate and normalize the input via the featureextractor featureextractor autofeatureextractor frompretrained modelargs modelnameorpath cachedirmodelargs cachedir tokendataargs useauthtoken if trainingargs dotrain rawdatasetstrain trainfeatures loadstreamingdataset pathdataargs datasetname namedataargs datasetconfigname splitdataargs trainsplitname tokendataargs useauthtoken streamingtrue samplingratefeatureextractor samplingrate rawcolumnnamestrain listtrainfeatures keys if dataargs audiocolumnname not in rawcolumnnamestrain raise valueerror faudiocolumnname dataargs audiocolumnname not found in dataset dataargs datasetname make sure to set audiocolumnname to the correct audio column one of f joinrawcolumnnames train if dataargs textcolumnname not in rawcolumnnamestrain raise valueerror ftextcolumnname dataargs textcolumnname not found in dataset dataargs datasetname make sure to set textcolumnname to the correct text column one of f joinrawcolumnnames train if dataargs maxtrainsamples is not none rawdatasetstrain rawdatasetstrain takerangedataargs maxtrainsamples if trainingargs doeval rawdatasetseval evalfeatures loadstreamingdataset pathdataargs datasetname namedataargs datasetconfigname splitdataargs evalsplitname tokendataargs useauthtoken streamingtrue samplingratefeatureextractor samplingrate rawcolumnnameseval listevalfeatures keys if dataargs maxevalsamples is not none rawdatasetseval rawdatasetseval takerangedataargs maxevalsamples 2 we remove some special characters from the datasets that make training complicated and do not help in transcribing the speech e g characters such as and do not really have an acoustic characteristic that could be easily picked up by the model charstoignoreregex f joindataargs charstoignore if dataargs charstoignore is not none else none textcolumnname dataargs textcolumnname def removespecialcharactersbatch if charstoignoreregex is not none batchtargettext re subcharstoignoreregex batchtextcolumnname lower else batchtargettext batchtextcolumnname lower return batch with trainingargs mainprocessfirstdescdataset map special characters removal for split dataset in rawdatasets items rawdatasetssplit dataset map removespecialcharacters removecolumnstextcolumnname 3 next let s load the config as we might need it to create the tokenizer config autoconfig frompretrained modelargs modelnameorpath cachedirmodelargs cachedir tokendataargs useauthtoken 4 now we can instantiate the tokenizer and model note for distributed training the frompretrained methods guarantee that only one local process can concurrently download model vocab tokenizernameorpath modelargs tokenizernameorpath if tokenizernameorpath is none raise valueerror tokenizer has to be created before training in streaming mode please specify tokenizernameorpath load featureextractor and tokenizer tokenizer autotokenizer frompretrained tokenizernameorpath configconfig tokendataargs useauthtoken adapt config config update featprojdropout modelargs featprojdropout attentiondropout modelargs attentiondropout hiddendropout modelargs hiddendropout finaldropout modelargs finaldropout masktimeprob modelargs masktimeprob masktimelength modelargs masktimelength maskfeatureprob modelargs maskfeatureprob maskfeaturelength modelargs maskfeaturelength gradientcheckpointing trainingargs gradientcheckpointing layerdrop modelargs layerdrop ctclossreduction modelargs ctclossreduction padtokenid tokenizer padtokenid vocabsize lentokenizer activationdropout modelargs activationdropout create model model automodelforctc frompretrained modelargs modelnameorpath cachedirmodelargs cachedir configconfig tokendataargs useauthtoken freeze encoder if modelargs freezefeatureencoder model freezefeatureencoder 5 now we preprocess the datasets including loading the audio resampling and normalization audiocolumnname dataargs audiocolumnname phonemelanguage is only relevant if the model is finetuned on phoneme classification phonemelanguage dataargs phonemelanguage preprocessing the datasets we need to read the audio files as arrays and tokenize the targets def preparedatasetbatch load audio sample batchaudiocolumnname inputs featureextractorsamplearray samplingratesamplesamplingrate batchinputvalues inputs inputvalues0 batchinputlength lenbatchinputvalues encode targets additionalkwargs if phonemelanguage is not none additionalkwargsphonemizerlang phonemelanguage batchlabels tokenizerbatchtargettext additionalkwargs inputids return batch vectorizeddatasets iterabledatasetdict with trainingargs mainprocessfirstdescdataset map preprocessing for split dataset in rawdatasets items vectorizeddatasetssplit dataset mappreparedataset removecolumnsrawcolumnnamessplit targettext withformattorch if split train vectorizeddatasetssplit vectorizeddatasetssplit shuffle buffersizedataargs shufflebuffersize seedtrainingargs seed 6 next we can prepare the training let s use word error rate wer as our evaluation metric instantiate a data collator and the trainer define evaluation metrics during training i e word error rate character error rate evalmetrics metric loadmetricmetric for metric in dataargs evalmetrics def computemetricspred predlogits pred predictions predids np argmaxpredlogits axis1 pred labelidspred labelids 100 tokenizer padtokenid predstr tokenizer batchdecodepredids we do not want to group tokens when computing the metrics labelstr tokenizer batchdecodepred labelids grouptokensfalse metrics k v computepredictionspredstr referenceslabelstr for k v in evalmetrics items return metrics now save everything to be able to create a single processor later if ismainprocesstrainingargs localrank save feature extractor tokenizer and config featureextractor savepretrainedtrainingargs outputdir tokenizer savepretrainedtrainingargs outputdir config savepretrainedtrainingargs outputdir try processor autoprocessor frompretrainedtrainingargs outputdir except oserror keyerror warnings warn loading a processor from a feature extractor config that does not include a processorclass attribute is deprecated and will be removed in v5 please add the following attribute to your preprocessorconfig json file to suppress this warning processorclass wav2vec2processor futurewarning processor wav2vec2processor frompretrainedtrainingargs outputdir instantiate custom data collator maxinputlength dataargs maxdurationinseconds featureextractor samplingrate datacollator datacollatorctcwithpaddingprocessorprocessor maxlengthmaxinputlength trainer callback to reinitialize and reshuffle the streamable datasets at the beginning of each epoch class shufflecallbacktrainercallback def onepochbeginself args state control traindataloader kwargs if isinstancetraindataloader dataset iterabledatasetshard pass setepoch is handled by the trainer elif isinstancetraindataloader dataset iterabledataset traindataloader dataset setepochtraindataloader dataset epoch 1 initialize trainer trainer trainer modelmodel datacollatordatacollator argstrainingargs computemetricscomputemetrics traindatasetvectorizeddatasetstrain if trainingargs dotrain else none evaldatasetvectorizeddatasetseval if trainingargs doeval else none tokenizerprocessor callbacksshufflecallback 7 finally we can start training training if trainingargs dotrain use last checkpoint if exist if lastcheckpoint is not none checkpoint lastcheckpoint elif os path isdirmodelargs modelnameorpath checkpoint modelargs modelnameorpath else checkpoint none trainresult trainer trainresumefromcheckpointcheckpoint trainer savemodel metrics trainresult metrics if dataargs maxtrainsamples metricstrainsamples dataargs maxtrainsamples trainer logmetricstrain metrics trainer savemetricstrain metrics trainer savestate evaluation results if trainingargs doeval logger info evaluate metrics trainer evaluate if dataargs maxevalsamples metricsevalsamples dataargs maxevalsamples trainer logmetricseval metrics trainer savemetricseval metrics write model card and optionally push to hub configname dataargs datasetconfigname if dataargs datasetconfigname is not none else na kwargs finetunedfrom modelargs modelnameorpath tasks automaticspeechrecognition tags automaticspeechrecognition dataargs datasetname datasetargs fconfig configname training split dataargs trainsplitname eval split f dataargs evalsplitname dataset fdataargs datasetname upper configname upper if commonvoice in dataargs datasetname kwargslanguage configname if trainingargs pushtohub trainer pushtohubkwargs else trainer createmodelcardkwargs return results if name main main usr bin env python coding utf 8 2022 the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license 2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and fine tuning a transformers ctc model for automatic speech recognition in streaming mode will error if the minimal version of transformers is not installed remove at your own risk arguments pertaining to which model config tokenizer we are going to fine tune from arguments pertaining to what data we are going to input our model for training and eval using hfargumentparser we can turn this class into argparse arguments to be able to specify them on the command line data collator that will dynamically pad the inputs received args processor class transformers autoprocessor the processor used for proccessing the data padding obj bool obj str or class transformers tokenization_utils_base paddingstrategy optional defaults to obj true select a strategy to pad the returned sequences according to the model s padding side and padding index among obj true or obj longest pad to the longest sequence in the batch or no padding if only a single sequence if provided obj max_length pad to a maximum length specified with the argument obj max_length or to the maximum acceptable input length for the model if that argument is not provided obj false or obj do_not_pad default no padding i e can output a batch with sequences of different lengths max_length obj int optional maximum length of the input_values of the returned list and optionally padding length see above max_length_labels obj int optional maximum length of the labels returned list and optionally padding length see above pad_to_multiple_of obj int optional if set will pad the sequence to a multiple of the provided value this is especially useful to enable the use of tensor cores on nvidia hardware with compute capability 7 5 volta split inputs and labels since they have to be of different lengths and need different padding methods replace padding with 100 to ignore loss correctly see all possible arguments in src transformers training_args py or by passing the help flag to this script we now keep distinct sets of args for a cleaner separation of concerns 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 detecting last checkpoint setup logging log on each process the small summary set the verbosity to info of the transformers logger on main process only set seed before initializing model 1 first let s load the dataset features and cast_column won t be available after interleaving so we ll use them here make sure that the dataset decodes audio with a correct sampling rate make sure that the dataset decodes audio with a correct sampling rate datasets takes care of automatically loading and resampling the audio so we just need to set the correct target sampling rate and normalize the input via the feature_extractor 2 we remove some special characters from the datasets that make training complicated and do not help in transcribing the speech e g characters such as and do not really have an acoustic characteristic that could be easily picked up by the model 3 next let s load the config as we might need it to create the tokenizer 4 now we can instantiate the tokenizer and model note for distributed training the from_pretrained methods guarantee that only one local process can concurrently download model vocab load feature_extractor and tokenizer adapt config create model freeze encoder 5 now we preprocess the datasets including loading the audio resampling and normalization phoneme_language is only relevant if the model is fine tuned on phoneme classification preprocessing the datasets we need to read the audio files as arrays and tokenize the targets load audio encode targets 6 next we can prepare the training let s use word error rate wer as our evaluation metric instantiate a data collator and the trainer define evaluation metrics during training i e word error rate character error rate we do not want to group tokens when computing the metrics now save everything to be able to create a single processor later save feature extractor tokenizer and config instantiate custom data collator trainer callback to reinitialize and reshuffle the streamable datasets at the beginning of each epoch set_epoch is handled by the trainer initialize trainer 7 finally we can start training training use last checkpoint if exist evaluation write model card and optionally push to hub
import logging
import os
import re
import sys
import warnings
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Union

import datasets
import numpy as np
import torch
from datasets import IterableDatasetDict, interleave_datasets, load_dataset, load_metric
from torch.utils.data import IterableDataset

import transformers
from transformers import (
    AutoConfig,
    AutoFeatureExtractor,
    AutoModelForCTC,
    AutoProcessor,
    AutoTokenizer,
    HfArgumentParser,
    Trainer,
    TrainerCallback,
    TrainingArguments,
    Wav2Vec2Processor,
    set_seed,
)
from transformers.trainer_pt_utils import IterableDatasetShard
from transformers.trainer_utils import get_last_checkpoint, is_main_process
from transformers.utils import check_min_version
from transformers.utils.versions import require_version



check_min_version("4.17.0.dev0")

require_version("datasets>=1.18.2", "To fix: pip install 'datasets>=1.18.2'")


logger = logging.getLogger(__name__)


def list_field(default=None, metadata=None):
    return field(default_factory=lambda: default, metadata=metadata)


@dataclass
class ModelArguments:
    

    model_name_or_path: str = field(
        metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
    )
    tokenizer_name_or_path: Optional[str] = field(
        default=None,
        metadata={"help": "Path to pretrained tokenizer or tokenizer identifier from huggingface.co/models"},
    )
    cache_dir: Optional[str] = field(
        default=None,
        metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
    )
    freeze_feature_encoder: bool = field(
        default=True, metadata={"help": "Whether to freeze the feature encoder layers of the model."}
    )
    attention_dropout: float = field(
        default=0.0, metadata={"help": "The dropout ratio for the attention probabilities."}
    )
    activation_dropout: float = field(
        default=0.0, metadata={"help": "The dropout ratio for activations inside the fully connected layer."}
    )
    feat_proj_dropout: float = field(default=0.0, metadata={"help": "The dropout ratio for the projected features."})
    hidden_dropout: float = field(
        default=0.0,
        metadata={
            "help": "The dropout probability for all fully connected layers in the embeddings, encoder, and pooler."
        },
    )
    final_dropout: float = field(
        default=0.0,
        metadata={"help": "The dropout probability for the final projection layer."},
    )
    mask_time_prob: float = field(
        default=0.05,
        metadata={
            "help": (
                "Probability 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."
            )
        },
    )
    mask_time_length: int = field(
        default=10,
        metadata={"help": "Length of vector span to mask along the time axis."},
    )
    mask_feature_prob: float = field(
        default=0.0,
        metadata={
            "help": (
                "Probability of each feature vector along the feature axis to be chosen as the start of the vectorspan"
                " to be masked. Approximately ``mask_feature_prob * sequence_length // mask_feature_length`` feature"
                " bins will be masked along the time axis."
            )
        },
    )
    mask_feature_length: int = field(
        default=10,
        metadata={"help": "Length of vector span to mask along the feature axis."},
    )
    layerdrop: float = field(default=0.0, metadata={"help": "The LayerDrop probability."})
    ctc_loss_reduction: Optional[str] = field(
        default="mean", metadata={"help": "The way the ctc loss should be reduced. Should be one of 'mean' or 'sum'."}
    )


@dataclass
class DataTrainingArguments:
    

    dataset_name: str = field(
        metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
    )
    dataset_config_name: str = field(
        default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}
    )
    train_split_name: str = field(
        default="train+validation",
        metadata={
            "help": (
                "The name of the training data set split to use (via the datasets library). Defaults to "
                "'train+validation'"
            )
        },
    )
    eval_split_name: str = field(
        default="test",
        metadata={
            "help": "The name of the training data set split to use (via the datasets library). Defaults to 'test'"
        },
    )
    audio_column_name: str = field(
        default="audio",
        metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"},
    )
    text_column_name: str = field(
        default="text",
        metadata={"help": "The name of the dataset column containing the text data. Defaults to 'text'"},
    )
    overwrite_cache: bool = field(
        default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."}
    )
    preprocessing_num_workers: Optional[int] = field(
        default=None,
        metadata={"help": "The number of processes to use for the preprocessing."},
    )
    max_train_samples: Optional[int] = field(
        default=None,
        metadata={
            "help": (
                "For debugging purposes or quicker training, truncate the number of training examples to this "
                "value if set."
            )
        },
    )
    max_eval_samples: Optional[int] = field(
        default=None,
        metadata={
            "help": (
                "For debugging purposes or quicker training, truncate the number of validation examples to this "
                "value if set."
            )
        },
    )
    shuffle_buffer_size: Optional[int] = field(
        default=500,
        metadata={
            "help": (
                "The number of streamed examples to download before shuffling them. The large the buffer, "
                "the closer it is to real offline shuffling."
            )
        },
    )
    chars_to_ignore: Optional[List[str]] = list_field(
        default=None,
        metadata={"help": "A list of characters to remove from the transcripts."},
    )
    eval_metrics: List[str] = list_field(
        default=["wer"],
        metadata={"help": "A list of metrics the model should be evaluated on. E.g. `'wer cer'`"},
    )
    max_duration_in_seconds: float = field(
        default=20.0,
        metadata={"help": "Filter audio files that are longer than `max_duration_in_seconds` seconds."},
    )
    preprocessing_only: bool = field(
        default=False,
        metadata={
            "help": (
                "Whether to only do data preprocessing and skip training. This is especially useful when data"
                " preprocessing errors out in distributed training due to timeout. In this case, one should run the"
                " preprocessing in a non-distributed setup with `preprocessing_only=True` so that the cached datasets"
                " can consequently be loaded in distributed training"
            )
        },
    )
    use_auth_token: bool = field(
        default=False,
        metadata={
            "help": (
                "If :obj:`True`, will use the token generated when running"
                ":obj:`huggingface-cli login` as HTTP bearer authorization for remote files."
            )
        },
    )
    phoneme_language: Optional[str] = field(
        default=None,
        metadata={
            "help": (
                "The target language that should be used be"
                " passed to the tokenizer for tokenization. Note that"
                " this is only relevant if the model classifies the"
                " input audio to a sequence of phoneme sequences."
            )
        },
    )


@dataclass
class DataCollatorCTCWithPadding:
    

    processor: AutoProcessor
    padding: Union[bool, str] = "longest"
    max_length: Optional[int] = None
    pad_to_multiple_of: Optional[int] = None
    pad_to_multiple_of_labels: Optional[int] = None

    def __call__(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
        
        
        input_features = []
        label_features = []
        for feature in features:
            if self.max_length and feature["input_values"].shape[-1] > self.max_length:
                continue
            input_features.append({"input_values": feature["input_values"]})
            label_features.append({"input_ids": feature["labels"]})

        batch = self.processor.pad(
            input_features,
            padding=self.padding,
            pad_to_multiple_of=self.pad_to_multiple_of,
            return_tensors="pt",
        )

        labels_batch = self.processor.pad(
            labels=label_features,
            padding=self.padding,
            pad_to_multiple_of=self.pad_to_multiple_of_labels,
            return_tensors="pt",
        )

        
        labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)

        batch["labels"] = labels

        return batch


def main():
    
    
    

    parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
    if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
        
        
        model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
    else:
        model_args, data_args, training_args = parser.parse_args_into_dataclasses()

    
    last_checkpoint = None
    if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
        last_checkpoint = 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."
            )

    
    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)

    
    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.fp16}"
    )
    
    if is_main_process(training_args.local_rank):
        transformers.utils.logging.set_verbosity_info()
    logger.info("Training/evaluation parameters %s", training_args)

    
    set_seed(training_args.seed)

    
    raw_datasets = IterableDatasetDict()
    raw_column_names = {}

    def load_streaming_dataset(split, sampling_rate, **kwargs):
        if "+" in split:
            dataset_splits = [load_dataset(split=split_name, **kwargs) for split_name in split.split("+")]
            
            features = dataset_splits[0].features
            
            dataset_splits = [
                dataset.cast_column(data_args.audio_column_name, datasets.features.Audio(sampling_rate=sampling_rate))
                for dataset in dataset_splits
            ]

            interleaved_dataset = interleave_datasets(dataset_splits)
            return interleaved_dataset, features
        else:
            dataset = load_dataset(split=split, **kwargs)
            features = dataset.features
            
            dataset = dataset.cast_column(
                data_args.audio_column_name, datasets.features.Audio(sampling_rate=sampling_rate)
            )
            return dataset, features

    
    
    
    feature_extractor = AutoFeatureExtractor.from_pretrained(
        model_args.model_name_or_path, cache_dir=model_args.cache_dir, token=data_args.use_auth_token
    )

    if training_args.do_train:
        raw_datasets["train"], train_features = load_streaming_dataset(
            path=data_args.dataset_name,
            name=data_args.dataset_config_name,
            split=data_args.train_split_name,
            token=data_args.use_auth_token,
            streaming=True,
            sampling_rate=feature_extractor.sampling_rate,
        )
        raw_column_names["train"] = list(train_features.keys())

        if data_args.audio_column_name not in raw_column_names["train"]:
            raise ValueError(
                f"--audio_column_name '{data_args.audio_column_name}' not found in dataset '{data_args.dataset_name}'."
                " Make sure to set `--audio_column_name` to the correct audio column - one of"
                f" {', '.join(raw_column_names['train'])}."
            )

        if data_args.text_column_name not in raw_column_names["train"]:
            raise ValueError(
                f"--text_column_name {data_args.text_column_name} not found in dataset '{data_args.dataset_name}'. "
                "Make sure to set `--text_column_name` to the correct text column - one of "
                f"{', '.join(raw_column_names['train'])}."
            )

        if data_args.max_train_samples is not None:
            raw_datasets["train"] = raw_datasets["train"].take(range(data_args.max_train_samples))

    if training_args.do_eval:
        raw_datasets["eval"], eval_features = load_streaming_dataset(
            path=data_args.dataset_name,
            name=data_args.dataset_config_name,
            split=data_args.eval_split_name,
            token=data_args.use_auth_token,
            streaming=True,
            sampling_rate=feature_extractor.sampling_rate,
        )
        raw_column_names["eval"] = list(eval_features.keys())

        if data_args.max_eval_samples is not None:
            raw_datasets["eval"] = raw_datasets["eval"].take(range(data_args.max_eval_samples))

    
    
    
    
    chars_to_ignore_regex = (
        f'[{"".join(data_args.chars_to_ignore)}]' if data_args.chars_to_ignore is not None else None
    )
    text_column_name = data_args.text_column_name

    def remove_special_characters(batch):
        if chars_to_ignore_regex is not None:
            batch["target_text"] = re.sub(chars_to_ignore_regex, "", batch[text_column_name]).lower() + " "
        else:
            batch["target_text"] = batch[text_column_name].lower() + " "
        return batch

    with training_args.main_process_first(desc="dataset map special characters removal"):
        for split, dataset in raw_datasets.items():
            raw_datasets[split] = dataset.map(
                remove_special_characters,
            ).remove_columns([text_column_name])

    
    
    config = AutoConfig.from_pretrained(
        model_args.model_name_or_path, cache_dir=model_args.cache_dir, token=data_args.use_auth_token
    )

    
    
    

    tokenizer_name_or_path = model_args.tokenizer_name_or_path
    if tokenizer_name_or_path is None:
        raise ValueError(
            "Tokenizer has to be created before training in streaming mode. Please specify --tokenizer_name_or_path"
        )
    
    tokenizer = AutoTokenizer.from_pretrained(
        tokenizer_name_or_path,
        config=config,
        token=data_args.use_auth_token,
    )

    
    config.update(
        {
            "feat_proj_dropout": model_args.feat_proj_dropout,
            "attention_dropout": model_args.attention_dropout,
            "hidden_dropout": model_args.hidden_dropout,
            "final_dropout": model_args.final_dropout,
            "mask_time_prob": model_args.mask_time_prob,
            "mask_time_length": model_args.mask_time_length,
            "mask_feature_prob": model_args.mask_feature_prob,
            "mask_feature_length": model_args.mask_feature_length,
            "gradient_checkpointing": training_args.gradient_checkpointing,
            "layerdrop": model_args.layerdrop,
            "ctc_loss_reduction": model_args.ctc_loss_reduction,
            "pad_token_id": tokenizer.pad_token_id,
            "vocab_size": len(tokenizer),
            "activation_dropout": model_args.activation_dropout,
        }
    )

    
    model = AutoModelForCTC.from_pretrained(
        model_args.model_name_or_path,
        cache_dir=model_args.cache_dir,
        config=config,
        token=data_args.use_auth_token,
    )

    
    if model_args.freeze_feature_encoder:
        model.freeze_feature_encoder()

    
    audio_column_name = data_args.audio_column_name

    
    phoneme_language = data_args.phoneme_language

    
    
    def prepare_dataset(batch):
        
        sample = batch[audio_column_name]

        inputs = feature_extractor(sample["array"], sampling_rate=sample["sampling_rate"])
        batch["input_values"] = inputs.input_values[0]
        batch["input_length"] = len(batch["input_values"])

        
        additional_kwargs = {}
        if phoneme_language is not None:
            additional_kwargs["phonemizer_lang"] = phoneme_language

        batch["labels"] = tokenizer(batch["target_text"], **additional_kwargs).input_ids
        return batch

    vectorized_datasets = IterableDatasetDict()
    with training_args.main_process_first(desc="dataset map preprocessing"):
        for split, dataset in raw_datasets.items():
            vectorized_datasets[split] = (
                dataset.map(prepare_dataset)
                .remove_columns(raw_column_names[split] + ["target_text"])
                .with_format("torch")
            )
            if split == "train":
                vectorized_datasets[split] = vectorized_datasets[split].shuffle(
                    buffer_size=data_args.shuffle_buffer_size,
                    seed=training_args.seed,
                )

    
    
    

    
    eval_metrics = {metric: load_metric(metric) for metric in data_args.eval_metrics}

    def compute_metrics(pred):
        pred_logits = pred.predictions
        pred_ids = np.argmax(pred_logits, axis=-1)

        pred.label_ids[pred.label_ids == -100] = tokenizer.pad_token_id

        pred_str = tokenizer.batch_decode(pred_ids)
        
        label_str = tokenizer.batch_decode(pred.label_ids, group_tokens=False)

        metrics = {k: v.compute(predictions=pred_str, references=label_str) for k, v in eval_metrics.items()}

        return metrics

    
    if is_main_process(training_args.local_rank):
        
        feature_extractor.save_pretrained(training_args.output_dir)
        tokenizer.save_pretrained(training_args.output_dir)
        config.save_pretrained(training_args.output_dir)

    try:
        processor = AutoProcessor.from_pretrained(training_args.output_dir)
    except (OSError, KeyError):
        warnings.warn(
            "Loading a processor from a feature extractor config that does not"
            " include a `processor_class` attribute is deprecated and will be removed in v5. Please add the following "
            " attribute to your `preprocessor_config.json` file to suppress this warning: "
            " `'processor_class': 'Wav2Vec2Processor'`",
            FutureWarning,
        )
        processor = Wav2Vec2Processor.from_pretrained(training_args.output_dir)

    
    max_input_length = data_args.max_duration_in_seconds * feature_extractor.sampling_rate
    data_collator = DataCollatorCTCWithPadding(processor=processor, max_length=max_input_length)

    
    class ShuffleCallback(TrainerCallback):
        def on_epoch_begin(self, args, state, control, train_dataloader, **kwargs):
            if isinstance(train_dataloader.dataset, IterableDatasetShard):
                pass  
            elif isinstance(train_dataloader.dataset, IterableDataset):
                train_dataloader.dataset.set_epoch(train_dataloader.dataset._epoch + 1)

    
    trainer = Trainer(
        model=model,
        data_collator=data_collator,
        args=training_args,
        compute_metrics=compute_metrics,
        train_dataset=vectorized_datasets["train"] if training_args.do_train else None,
        eval_dataset=vectorized_datasets["eval"] if training_args.do_eval else None,
        tokenizer=processor,
        callbacks=[ShuffleCallback()],
    )

    

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

        train_result = trainer.train(resume_from_checkpoint=checkpoint)
        trainer.save_model()

        metrics = train_result.metrics
        if data_args.max_train_samples:
            metrics["train_samples"] = data_args.max_train_samples

        trainer.log_metrics("train", metrics)
        trainer.save_metrics("train", metrics)
        trainer.save_state()

    
    results = {}
    if training_args.do_eval:
        logger.info("*** Evaluate ***")
        metrics = trainer.evaluate()
        if data_args.max_eval_samples:
            metrics["eval_samples"] = data_args.max_eval_samples

        trainer.log_metrics("eval", metrics)
        trainer.save_metrics("eval", metrics)

    
    config_name = data_args.dataset_config_name if data_args.dataset_config_name is not None else "na"
    kwargs = {
        "finetuned_from": model_args.model_name_or_path,
        "tasks": "automatic-speech-recognition",
        "tags": ["automatic-speech-recognition", data_args.dataset_name],
        "dataset_args": (
            f"Config: {config_name}, Training split: {data_args.train_split_name}, Eval split:"
            f" {data_args.eval_split_name}"
        ),
        "dataset": f"{data_args.dataset_name.upper()} - {config_name.upper()}",
    }
    if "common_voice" in data_args.dataset_name:
        kwargs["language"] = config_name

    if training_args.push_to_hub:
        trainer.push_to_hub(**kwargs)
    else:
        trainer.create_model_card(**kwargs)

    return results


if __name__ == "__main__":
    main()