




"""simple docstring"""




import copy
import logging
import random

import joblib
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from tqdm import tqdm

from transformers import AdamW, GPTaLMHeadModel, get_linear_schedule_with_warmup


lowercase__    :					Dict					=						logging.getLogger(__name__)


def 						lowerCamelCase__   (		_A							):







	'''simple docstring'''





	random.seed(_A							)
	np.random.seed(_A							)
	torch.manual_seed(_A							)
	torch.cuda.manual_seed_all(_A							)


def 						lowerCamelCase__   (		_A					,     _A					,     _A							):







	'''simple docstring'''





	model.eval()
	snake_case_		   =					next(model.parameters()							).device
	snake_case_		   =					1
	snake_case_		   =					torch.zeros((eval_batch_size, context_len)					,     dtype=torch.long					,     device=_A							)
	snake_case_		   =					DataLoader(_A					,     shuffle=_A					,     batch_size=_A							)
	snake_case_		   =					torch.zeros(1					,     device=_A							)
	snake_case_		   =					0
	for batch in eval_dataloader:
		batch.to(_A							)
		# pad
		context.zero_()
		for i in range(_A							):
			snake_case_		   =					batch[i]
		snake_case_		   =					model(_A					,     labels=_A							)
		eval_loss += outputs[0].sum().item()
		nb_eval_examples += batch.size(0							)
	snake_case_		   =					eval_loss / nb_eval_examples
	snake_case_		   =					torch.exp(_A							)
	model.train()
	return perplexity


def 						lowerCamelCase__   (		_A="gpt2"							):







	'''simple docstring'''





	snake_case_		   =					GPTaLMHeadModel.from_pretrained(_A					,     output_hidden_states=_A							)
	torch.save(model.state_dict()					,     model_name + "local.pt"							)
	return model


def 						lowerCamelCase__   (		_A					,     _A					,     _A							):







	'''simple docstring'''





	snake_case_		   =					copy.deepcopy(_A							)
	model.to(_A							)

	snake_case_		   =					["bias", "LayerNorm.weight"]
	snake_case_		   =					[
	    {
	        "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay							)],
	        "weight_decay": 0.0,
	    },
	    {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay							)], "weight_decay": 0.0},
	]
	snake_case_		   =					AdamW(_A					,     lr=5E-5					,     eps=1E-8							)
	snake_case_		   =					get_linear_schedule_with_warmup(_A					,     0					,     _A							)
	torch.cuda.empty_cache()
	return model, lm_optimizer, lm_scheduler


def 						lowerCamelCase__   (		_A					,     _A					,     _A					,     _A							):







	'''simple docstring'''





	snake_case_		   =					np.array(_A							).mean()
	snake_case_		   =					np.array(_A							).std()
	snake_case_		   =					(real_perps - avg) / std
	snake_case_		   =					list(zip(_A					,     _A					,     _A							)							)
	joblib.dump(_A					,     _A							)


def 						lowerCamelCase__   (		_A					,     _A					,     _A					,     _A					,     _A					,     _A					,     _A					,     _A="dev.jbl"					,     _A=recopy_gpta					,     ):







	'''simple docstring'''





	snake_case_		   =					[]
	snake_case_		   =					[]
	snake_case_		   =					[]

	# Initialize the transformer model
	snake_case_		   =					copy.deepcopy(_A							)
	orig_model.to(device="cpu"							)
	torch.cuda.empty_cache()

	# Compute perplexity of initial transformer model for comparison
	model.train()
	snake_case_   ,				snake_case_   ,				snake_case_		   =					recopy_model(_A					,     _A					,     _A							)

	for step in tqdm(range(_A							)							):
		snake_case_		   =					torch.zeros((1, context_len)					,     dtype=torch.long					,     device=_A							)
		snake_case_		   =					random.choice(_A							)
		snake_case_		   =					random.randint(0					,     len(story[0]							) - context_len - 1							)
		snake_case_		   =					story[0][start : start + context_len]
		lm_optimizer.zero_grad()
		snake_case_		   =					model(_A					,     labels=_A							)
		snake_case_		   =					outputs[0]
		snake_case_		   =					compute_perplexity(_A					,     _A					,     _A							)
		model.train()
		lm_loss.backward()
		# Do LM backprop
		torch.nn.utils.clip_grad_norm_(model.parameters()					,     3.0							)
		lm_optimizer.step()
		lm_scheduler.step()  # Update learning rate schedule

		# Compute perplexity after back-propagating on the selected context
		snake_case_		   =					compute_perplexity(_A					,     _A					,     _A							)

		# Periodically save the stored (X, IG(X)) pairs
		if step % 1000 == 0 and step > 1:
			intermittent_save(_A					,     _A					,     _A					,     _A							)

		# Reset the pretrained model to the original pretrained GPT-2 weights after each iteration
		snake_case_   ,				snake_case_   ,				snake_case_		   =					recopy_model(_A					,     _A					,     _A							)

		past_perps.append(past_perp.item()							)
		real_perps.append(orig_perp - real_perp.item()							)
		contexts.append(np.array(context.cpu()							)							)

	intermittent_save(_A					,     _A					,     _A					,     _A							)


def 						lowerCamelCase__   (		_A					,     _A="data/tokenized_stories_train_wikitext103.jbl"					,     _A=100					,     _A=1026					,     _A=True							):







	'''simple docstring'''





	snake_case_		   =					joblib.load(_A							)
	print("data loaded"							)
	snake_case_		   =					[]
	if trim:
		for i, example in enumerate(_A							):
			if len(example[0]							) > min_len:
				snake_case_		   =					random.randint(0					,     len(example[0]							) - context_len - 1							)
				objective_set.append(example[0, start : start + context_len]							)
			if len(_A							) >= number:
				break
		snake_case_		   =					[]
		for j in range(i + 1					,     len(_A							)							):
			if len(data[j][0]							) > min_len:
				train_data.append(data[j]							)
	else:
		snake_case_		   =					data[0:number]
		snake_case_		   =					data[number:]

	joblib.dump(_A					,     "objective_set.jbl"							)
	print("objective set saved"							)
	return train_data, objective_set


def 						lowerCamelCase__   (		_A					,     _A					,     _A					,     _A					,     _A=50					,     _A="secondary_learner.pt"							):







	'''simple docstring'''





	snake_case_		   =					torch.device("cuda:0" if torch.cuda.is_available() else "cpu"							)
	# We will use the first 512 pairs from our dataset as a test set for
	# our secondary learner and the rest to train
	snake_case_		   =					train_dataset[:512]
	snake_case_		   =					train_dataset[512:]
	snake_case_		   =					DataLoader(_A					,     shuffle=_A					,     batch_size=_A							)
	snake_case_		   =					DataLoader(_A					,     shuffle=_A					,     batch_size=_A							)

	# secondary learner model set up
	snake_case_		   =					nn.MSELoss()
	snake_case_		   =					nn.MSELoss(reduction="sum"							)
	secondary_learner.to(_A							)
	snake_case_		   =					torch.optim.Adam(secondary_learner.parameters()					,     lr=0.0_00_01							)
	secondary_learner.train()

	# TODO in original code this is written as number of actual batches seen
	# not number of items seen but other places it is number of items instead.
	# improve consistency! changed this to epochs for clarity
	snake_case_		   =					float("inf"							)
	# Iterate through batches until we've used max_steps batches
	for epoch in range(int(_A							)							):
		snake_case_		   =					0.0
		secondary_learner.train()
		for step, batch in enumerate(_A							):
			snake_case_		   =					batch[0].to(_A							)
			snake_case_		   =					batch[1].to(_A							)
			snake_case_		   =					secondary_learner(_A							)
			q_optimizer.zero_grad()
			snake_case_		   =					loss(_A					,     real_q.float()							)
			q_loss.backward()
			q_optimizer.step()
			tr_q_loss += q_loss.item()

			# model trains fairly quickly so we won't wait for a full epoch
			# eval is triggered at eval_freq and end of epochs
			if (step % eval_freq == 0 and step > 0) or ((step + 1) == len(_A							)):
				snake_case_		   =					tr_q_loss / (step + 1)

				secondary_learner.eval()
				snake_case_		   =					0.0
				snake_case_		   =					0.0
				snake_case_		   =					[]
				snake_case_		   =					[]
				# Compute performance of the secondary learner after this batch
				for stepa, batcha in enumerate(_A							):
					snake_case_		   =					batcha[0].to(_A							)
					snake_case_		   =					batcha[1].to(_A							)
					snake_case_		   =					secondary_learner(_A							)
					q_lossa += test_loss(_A					,     _A							).item()
					sum_qa += torch.sum(_A							).item()
					for ei, i in enumerate(predicted_qa.cpu().detach().numpy()							):
						predicted.append(i.item()							)
					for ei, i in enumerate(real_qa.cpu().detach().numpy()							):
						actual.append(i.item()							)

				q_lossa /= len(_A							)
				print(
				    "Epoch: "					,     _A					,     "step: "					,     _A					,     "Avg. q:"					,     sum_qa / len(_A							)					,     "Train Loss: "					,     _A					,     "Test Loss: "					,     _A					,     )
				if q_lossa < best_test_loss:
					joblib.dump((predicted, actual)					,     "pred_vs_actual.jbl"							)
					torch.save(secondary_learner.state_dict()					,     _A							)
					snake_case_		   =					q_lossa

			secondary_learner.train()
	return secondary_learner






class 		UpperCAmelCase       (    nn.Module      ):







						'''simple docstring'''





						def __init__(						self							:					Tuple	,     __lowercase							:					int						):






							"""simple docstring"""






							super(__lowercase	,     self						).__init__()
							snake_case_		   =					model.transformer.wte
							snake_case_		   =					copy.deepcopy(model.transformer.wte.weight						)
							snake_case_		   =					nn.Convad(self.embeddings.weight.size(1						)	,     2_56	,     3	,     padding=1						)
							snake_case_		   =					nn.Sequential(nn.Linear(2_56	,     32						)	,     nn.Dropout(p=0.1						)	,     nn.Linear(32	,     32						)	,     nn.Linear(32	,     1						)						)






						def 	snake_case__						(						self							:					int	,     __lowercase							:					List[Any]						):






							"""simple docstring"""






							snake_case_		   =					torch.max(self.conv(self.embeddings(__lowercase						).squeeze(1						).transpose(1	,     2						)						)	,     2						)[0]
							snake_case_		   =					self.fc(__lowercase						)
							return qs.squeeze(1						)






						@classmethod
						def 	snake_case__						(						cls							:					Tuple	,     __lowercase							:					Any	,     __lowercase							:					Optional[Any]						):






							"""simple docstring"""






							snake_case_		   =					cls(__lowercase						)  # this calls __init__
							snake_case_		   =					torch.load(__lowercase						)
							secondary_learner.load_state_dict(__lowercase						)
							snake_case_		   =					model.transformer.wte
							snake_case_		   =					copy.deepcopy(model.transformer.wte.weight						)
							return secondary_learner






import logging
import pathlib
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Set, Union

import datasets
import librosa
import numpy as np
import torch
from lang_trans import arabic
from packaging import version
from torch import nn

from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    trainer_utils,
)


if is_apex_available():
		from apex import amp

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


lowercase__    :					Tuple					=						logging.getLogger(__name__)
@dataclass
class 		UpperCAmelCase       :







						'''simple docstring'''





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







def 						lowerCamelCase__   (		_A					,     _A							):







	'''simple docstring'''





	logging.basicConfig(
	    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"					,     datefmt="%m/%d/%Y %H:%M:%S"					,     handlers=[logging.StreamHandler(sys.stdout							)]					,     )
	snake_case_		   =					logging.WARNING
	if model_args.verbose_logging:
		snake_case_		   =					logging.DEBUG
	elif trainer_utils.is_main_process(training_args.local_rank							):
		snake_case_		   =					logging.INFO
	logger.setLevel(_A							)
@dataclass
class 		UpperCAmelCase       :







						'''simple docstring'''





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







@dataclass
class 		UpperCAmelCase       :







						'''simple docstring'''





						lowerCAmelCase_							=       False
						lowerCAmelCase_							=       None
						lowerCAmelCase_							=       "|"
						lowerCAmelCase_							=       field(default_factory=UpperCAmelCase__      )
						lowerCAmelCase_							=       field(default_factory=UpperCAmelCase__      )
						lowerCAmelCase_							=       None






						@classmethod
						def 	snake_case__						(						cls							:					Optional[int]	,     __lowercase							:					str						):






							"""simple docstring"""






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






						def 	snake_case__						(						self							:					str	,     __lowercase							:					str						):






							"""simple docstring"""






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






						def 	snake_case__						(						self							:					Dict	,     __lowercase							:					ModelArguments						):






							"""simple docstring"""






							snake_case_		   =					WavaVecaFeatureExtractor.from_pretrained(
							    model_args.model_name_or_path	,     cache_dir=model_args.cache_dir						)
							if self.vocab_file:
								snake_case_		   =					WavaVecaCTCTokenizer(
								    self.vocab_file	,     cache_dir=model_args.cache_dir	,     do_lower_case=self.do_lower_case	,     word_delimiter_token=self.word_delimiter_token	,     )
							else:
								snake_case_		   =					WavaVecaCTCTokenizer.from_pretrained(
								    model_args.model_name_or_path	,     cache_dir=model_args.cache_dir	,     do_lower_case=self.do_lower_case	,     word_delimiter_token=self.word_delimiter_token	,     )
							return WavaVecaProcessor(__lowercase	,     __lowercase						)







@dataclass
class 		UpperCAmelCase       :







						'''simple docstring'''





						lowerCAmelCase_							=       42
						lowerCAmelCase_							=       True
						lowerCAmelCase_							=       None
						lowerCAmelCase_							=       None
						lowerCAmelCase_							=       None
						lowerCAmelCase_							=       None






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






							"""simple docstring"""






							snake_case_		   =					[{"input_values": feature["input_values"]} for feature in features]
							snake_case_		   =					[{"input_ids": feature["labels"]} for feature in features]

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

							snake_case_		   =					labels

							return batch







class 		UpperCAmelCase       (    UpperCAmelCase__      ):







						'''simple docstring'''





						def 	snake_case__						(						self							:					Dict	,     __lowercase							:					nn.Module	,     __lowercase							:					Dict[str, Union[torch.Tensor, Any]]						):






							"""simple docstring"""






							model.train()
							snake_case_		   =					self._prepare_inputs(__lowercase						)

							if self.use_amp:
								with autocast():
									snake_case_		   =					self.compute_loss(__lowercase	,     __lowercase						)
							else:
								snake_case_		   =					self.compute_loss(__lowercase	,     __lowercase						)

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

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

							return loss.detach()







def 						lowerCamelCase__   (		):







	'''simple docstring'''





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

	snake_case_   ,				snake_case_   ,				snake_case_		   =					parser.parse_args_into_dataclasses()
	configure_logger(_A					,     _A							)

	snake_case_		   =					Orthography.from_name(data_args.orthography.lower()							)
	snake_case_		   =					orthography.create_processor(_A							)
	snake_case_		   =					WavaVecaForCTC.from_pretrained(
	    model_args.model_name_or_path					,     cache_dir=model_args.cache_dir					,     gradient_checkpointing=training_args.gradient_checkpointing					,     vocab_size=len(processor.tokenizer							)					,     )

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

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

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

	snake_case_		   =					train_dataset.map(_A					,     remove_columns=[data_args.speech_file_column]							)
	snake_case_		   =					val_dataset.map(_A					,     remove_columns=[data_args.speech_file_column]							)

	if data_args.max_duration_in_seconds is not None:

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

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

	logger.warning(f"Updated {len(_A							)} transcript(s) using '{data_args.orthography}' orthography rules."							)
	if logger.isEnabledFor(logging.DEBUG							):
		for original_text, updated_text in text_updates:
			logger.debug(f"Updated text: \"{original_text}\" -> \"{updated_text}\""							)
	snake_case_		   =					None

	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}."

		snake_case_		   =					processor(
		    audio=batch["speech"]					,     text=batch[data_args.target_text_column]					,     sampling_rate=batch["sampling_rate"][0]							)
		batch.update(_A							)
		return batch

	snake_case_		   =					train_dataset.map(
	    _A					,     batch_size=training_args.per_device_train_batch_size					,     batched=_A					,     num_proc=data_args.preprocessing_num_workers					,     )
	snake_case_		   =					val_dataset.map(
	    _A					,     batch_size=training_args.per_device_train_batch_size					,     batched=_A					,     num_proc=data_args.preprocessing_num_workers					,     )

	snake_case_		   =					DataCollatorCTCWithPadding(processor=_A					,     padding=_A							)

	def compute_metrics(_A							):
		snake_case_		   =					pred.predictions
		snake_case_		   =					np.argmax(_A					,     axis=-1							)

		snake_case_		   =					processor.tokenizer.pad_token_id

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

		snake_case_		   =					wer_metric.compute(predictions=_A					,     references=_A							)

		return {"wer": wer}

	if model_args.freeze_feature_extractor:
		model.freeze_feature_extractor()

	snake_case_		   =					CTCTrainer(
	    model=_A					,     data_collator=_A					,     args=_A					,     compute_metrics=_A					,     train_dataset=_A					,     eval_dataset=_A					,     tokenizer=processor.feature_extractor					,     )

	trainer.train()


if __name__ == "__main__":
		main()
