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


lowerCamelCase__        =						logging.getLogger(__name__)







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






def 					lowerCAmelCase__     (    SCREAMING_SNAKE_CASE_			,				SCREAMING_SNAKE_CASE_	)							->						Any:
			logging.basicConfig(
			    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'			,				datefmt='%m/%d/%Y %H:%M:%S'			,				handlers=[logging.StreamHandler(sys.stdout	)]			,				)
			lowerCAmelCase__ : Union[str, Any]   =						logging.WARNING
			if model_args.verbose_logging:
						lowerCAmelCase__ : List[str]   =						logging.DEBUG
			elif trainer_utils.is_main_process(training_args.local_rank	):
						lowerCAmelCase__ : int   =						logging.INFO
			logger.setLevel(UpperCAmelCase_	)







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







@dataclass
class 	A__				:
				lowercase            =    False
				lowercase            =    None
				lowercase            =    "|"
				lowercase            =    field(default_factory=lowercase__      )
				lowercase            =    field(default_factory=lowercase__      )
				lowercase            =    None






				@classmethod
				def 				_lowerCamelCase						(		cls   : Optional[int]       ,	a   : str  ):






							'''simple docstring'''







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






				def 				_lowerCamelCase						(		self   : int       ,	a   : str  ):






							'''simple docstring'''







							if len(self.translation_table  ) > 0:
										lowerCAmelCase__ : Optional[Any]   =						text.translate(self.translation_table  )
							if len(self.words_to_remove  ) == 0:
										lowerCAmelCase__ : Union[str, Any]   =						' '.join(text.split()  )  # clean up whitespaces
							else:
										lowerCAmelCase__ : Optional[Any]   =						' '.join(w for w in text.split() if w not in self.words_to_remove  )  # and clean up whilespaces
							return text






				def 				_lowerCamelCase						(		self   : str       ,	a   : ModelArguments  ):






							'''simple docstring'''







							lowerCAmelCase__ : str   =						WavaVecaFeatureExtractor.from_pretrained(
							    model_args.model_name_or_path       ,	cache_dir=model_args.cache_dir  )
							if self.vocab_file:
										lowerCAmelCase__ : Any   =						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:
										lowerCAmelCase__ : Union[str, Any]   =						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(a       ,	a  )







@dataclass
class 	A__				:
				lowercase            =    42
				lowercase            =    True
				lowercase            =    None
				lowercase            =    None
				lowercase            =    None
				lowercase            =    None






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






							'''simple docstring'''







							lowerCAmelCase__ : Any   =						[{'input_values': feature['input_values']} for feature in features]
							lowerCAmelCase__ : Optional[int]   =						[{'input_ids': feature['labels']} for feature in features]

							lowerCAmelCase__ : Tuple   =						self.processor.pad(
							    a       ,	padding=self.padding       ,	max_length=self.max_length       ,	pad_to_multiple_of=self.pad_to_multiple_of       ,	return_tensors='pt'       ,	)
							lowerCAmelCase__ : Optional[int]   =						self.processor.pad(
							    labels=a       ,	padding=self.padding       ,	max_length=self.max_length_labels       ,	pad_to_multiple_of=self.pad_to_multiple_of_labels       ,	return_tensors='pt'       ,	)

							# replace padding with -100 to ignore loss correctly
							lowerCAmelCase__ : Optional[Any]   =						labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1  )       ,	-100  )

							lowerCAmelCase__ : Optional[int]   =						labels

							return batch







class 	A__				(	lowercase__      ):






				def 				_lowerCamelCase						(		self   : Tuple       ,	a   : nn.Module       ,	a   : Dict[str, Union[torch.Tensor, Any]]  ):






							'''simple docstring'''







							model.train()
							lowerCAmelCase__ : Any   =						self._prepare_inputs(a  )

							if self.use_amp:
										with autocast():
													lowerCAmelCase__ : Optional[int]   =						self.compute_loss(a       ,	a  )
							else:
										lowerCAmelCase__ : List[str]   =						self.compute_loss(a       ,	a  )

							if self.args.n_gpu > 1:
										if model.module.config.ctc_loss_reduction == "mean":
													lowerCAmelCase__ : Optional[int]   =						loss.mean()
										elif model.module.config.ctc_loss_reduction == "sum":
													lowerCAmelCase__ : Dict   =						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:
										lowerCAmelCase__ : str   =						loss / self.args.gradient_accumulation_steps

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

							return loss.detach()






def 					lowerCAmelCase__     (    )							->						Dict:
			# 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.

			lowerCAmelCase__ : int   =						HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)	)

			lowerCAmelCase__ ,							lowerCAmelCase__ ,							lowerCAmelCase__ : Union[str, Any]   =						parser.parse_args_into_dataclasses()
			configure_logger(UpperCAmelCase_			,				UpperCAmelCase_	)

			lowerCAmelCase__ : List[str]   =						Orthography.from_name(data_args.orthography.lower()	)
			lowerCAmelCase__ : List[Any]   =						orthography.create_processor(UpperCAmelCase_	)
			lowerCAmelCase__ : Optional[Any]   =						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	)			,				)

			lowerCAmelCase__ : Dict   =						datasets.load_dataset(
			    data_args.dataset_name			,				data_args.dataset_config_name			,				split=data_args.train_split_name	)
			lowerCAmelCase__ : Optional[Any]   =						datasets.load_dataset(
			    data_args.dataset_name			,				data_args.dataset_config_name			,				split=data_args.validation_split_name	)

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

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

			lowerCAmelCase__ : Any   =						train_dataset.map(UpperCAmelCase_			,				remove_columns=[data_args.speech_file_column]	)
			lowerCAmelCase__ : Optional[Any]   =						val_dataset.map(UpperCAmelCase_			,				remove_columns=[data_args.speech_file_column]	)

			if data_args.max_duration_in_seconds is not None:

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

						lowerCAmelCase__ : int   =						len(UpperCAmelCase_	)
						lowerCAmelCase__ : Optional[Any]   =						len(UpperCAmelCase_	)
						lowerCAmelCase__ : List[Any]   =						train_dataset.filter(UpperCAmelCase_			,				remove_columns=['duration_in_seconds']	)
						lowerCAmelCase__ : Dict   =						val_dataset.filter(UpperCAmelCase_			,				remove_columns=['duration_in_seconds']	)
						if len(UpperCAmelCase_	) > old_train_size:
									logger.warning(
									    F'''Filtered out {len(UpperCAmelCase_	) - old_train_size} train example(s) longer than'''
									    F''' {data_args.max_duration_in_seconds} second(s).'''	)
						if len(UpperCAmelCase_	) > old_val_size:
									logger.warning(
									    F'''Filtered out {len(UpperCAmelCase_	) - old_val_size} validation example(s) longer than'''
									    F''' {data_args.max_duration_in_seconds} second(s).'''	)
			logger.info(F'''Split sizes: {len(UpperCAmelCase_	)} train and {len(UpperCAmelCase_	)} validation.'''	)

			logger.warning(F'''Updated {len(UpperCAmelCase_	)} 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}\"'''	)
			lowerCAmelCase__ : int   =						None

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

						lowerCAmelCase__ : Dict   =						processor(
						    audio=batch['speech']			,				text=batch[data_args.target_text_column]			,				sampling_rate=batch['sampling_rate'][0]	)
						batch.update(UpperCAmelCase_	)
						return batch

			lowerCAmelCase__ : Union[str, Any]   =						train_dataset.map(
			    UpperCAmelCase_			,				batch_size=training_args.per_device_train_batch_size			,				batched=UpperCAmelCase_			,				num_proc=data_args.preprocessing_num_workers			,				)
			lowerCAmelCase__ : Union[str, Any]   =						val_dataset.map(
			    UpperCAmelCase_			,				batch_size=training_args.per_device_train_batch_size			,				batched=UpperCAmelCase_			,				num_proc=data_args.preprocessing_num_workers			,				)

			lowerCAmelCase__ : Any   =						DataCollatorCTCWithPadding(processor=UpperCAmelCase_			,				padding=UpperCAmelCase_	)

			def compute_metrics(SCREAMING_SNAKE_CASE_	):
						lowerCAmelCase__ : Optional[int]   =						pred.predictions
						lowerCAmelCase__ : List[Any]   =						np.argmax(UpperCAmelCase_			,				axis=-1	)

						lowerCAmelCase__ : str   =						processor.tokenizer.pad_token_id

						lowerCAmelCase__ : List[str]   =						processor.batch_decode(UpperCAmelCase_	)
						# we do not want to group tokens when computing the metrics
						lowerCAmelCase__ : Tuple   =						processor.batch_decode(pred.label_ids			,				group_tokens=UpperCAmelCase_	)
						if logger.isEnabledFor(logging.DEBUG	):
									for reference, predicted in zip(UpperCAmelCase_			,				UpperCAmelCase_	):
												logger.debug(F'''reference: \"{reference}\"'''	)
												logger.debug(F'''predicted: \"{predicted}\"'''	)
												if orthography.untransliterator is not None:
															logger.debug(F'''reference (untransliterated): \"{orthography.untransliterator(UpperCAmelCase_	)}\"'''	)
															logger.debug(F'''predicted (untransliterated): \"{orthography.untransliterator(UpperCAmelCase_	)}\"'''	)

						lowerCAmelCase__ : List[str]   =						wer_metric.compute(predictions=UpperCAmelCase_			,				references=UpperCAmelCase_	)

						return {"wer": wer}

			if model_args.freeze_feature_extractor:
						model.freeze_feature_extractor()

			lowerCAmelCase__ : Any   =						CTCTrainer(
			    model=UpperCAmelCase_			,				data_collator=UpperCAmelCase_			,				args=UpperCAmelCase_			,				compute_metrics=UpperCAmelCase_			,				train_dataset=UpperCAmelCase_			,				eval_dataset=UpperCAmelCase_			,				tokenizer=processor.feature_extractor			,				)

			trainer.train()


if __name__ == "__main__":
					main()





import math
from collections import OrderedDict

import torch
from packaging import version
from torch import Tensor, nn

from .utils import logging


SCREAMING_SNAKE_CASE_    :       Tuple       =							logging.get_logger(__name__)







class 		__UpperCAmelCase(		nn.Module			):





     """simple docstring"""



     def __init__(   self			:							int     )      ->      Union[str, Any]:






         """simple docstring"""
         super().__init__()
         if version.parse(torch.__version__     ) < version.parse("""1.12.0"""     ):
             raise ImportError(
                 f"""You are using torch=={torch.__version__}, but torch>=1.12.0 is required to use """
                 """PytorchGELUTanh. Please upgrade torch."""     )






     def 					__SCREAMING_SNAKE_CASE		(   self			:							str    ,					A			:							Tensor     )      ->      Tensor:






         """simple docstring"""
         return nn.functional.gelu(A    ,					approximate="""tanh"""     )







class 		__UpperCAmelCase(		nn.Module			):





     """simple docstring"""



     def 					__SCREAMING_SNAKE_CASE		(   self			:							str    ,					A			:							Tensor     )      ->      Tensor:






         """simple docstring"""
         return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi     ) * (input + 0.0_4_4_7_1_5 * torch.pow(A    ,					3.0     ))     ))







class 		__UpperCAmelCase(		nn.Module			):





     """simple docstring"""



     def __init__(   self			:							Optional[Any]    ,					A			:							bool = False     )      ->      Optional[Any]:






         """simple docstring"""
         super().__init__()
         if use_gelu_python:
             a__  			=							self._gelu_python
         else:
             a__  			=							nn.functional.gelu

     def 					__SCREAMING_SNAKE_CASE		(   self			:							Dict    ,					A			:							Tensor     )      ->      Tensor:






         """simple docstring"""
         return input * 0.5 * (1.0 + torch.erf(input / math.sqrt(2.0     )     ))






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






         """simple docstring"""
         return self.act(A     )







class 		__UpperCAmelCase(		nn.Module			):





     """simple docstring"""



     def 					__SCREAMING_SNAKE_CASE		(   self			:							Any    ,					A			:							Tensor     )      ->      Tensor:






         """simple docstring"""
         return 0.5 * input * (1.0 + torch.tanh(input * 0.7_9_7_8_8_4_5_6_0_8 * (1.0 + 0.0_4_4_7_1_5 * input * input)     ))







class 		__UpperCAmelCase(		nn.Module			):





     """simple docstring"""



     def 					__SCREAMING_SNAKE_CASE		(   self			:							List[Any]    ,					A			:							Tensor     )      ->      Tensor:






         """simple docstring"""
         return input * torch.sigmoid(1.7_0_2 * input     )







class 		__UpperCAmelCase(		nn.Module			):





     """simple docstring"""



     def __init__(   self			:							Tuple    ,					A			:							float    ,					A			:							float     )      ->      Optional[Any]:






         """simple docstring"""
         if min > max:
             raise ValueError(f"""min should be < max (got min: {min}, max: {max})"""     )

         super().__init__()
         a__  			=							min
         a__  			=							max






     def 					__SCREAMING_SNAKE_CASE		(   self			:							Optional[int]    ,					A			:							Tensor     )      ->      Tensor:






         """simple docstring"""
         return torch.clip(gelu(A     )    ,					self.min    ,					self.max     )







class 		__UpperCAmelCase(		nn.Module			):





     """simple docstring"""



     def __init__(   self			:							Tuple     )      ->      List[Any]:






         """simple docstring"""
         super().__init__()
         a__  			=							math.sqrt(2 / math.pi     )






     def 					__SCREAMING_SNAKE_CASE		(   self			:							int    ,					A			:							Tensor     )      ->      Tensor:






         """simple docstring"""
         return 0.5 * input * (1 + torch.tanh(self.precomputed_constant * (input + 0.0_4_4_7_1_5 * torch.pow(A    ,					3     ))     ))







class 		__UpperCAmelCase(		nn.Module			):





     """simple docstring"""



     def 					__SCREAMING_SNAKE_CASE		(   self			:							Optional[int]    ,					A			:							Tensor     )      ->      Tensor:






         """simple docstring"""
         return nn.functional.silu(A     )







class 		__UpperCAmelCase(		nn.Module			):





     """simple docstring"""



     def __init__(   self			:							Optional[Any]     )      ->      List[str]:






         """simple docstring"""
         super().__init__()
         if version.parse(torch.__version__     ) < version.parse("""1.9.0"""     ):
             a__  			=							self._mish_python
         else:
             a__  			=							nn.functional.mish

     def 					__SCREAMING_SNAKE_CASE		(   self			:							Any    ,					A			:							Tensor     )      ->      Tensor:






         """simple docstring"""
         return input * torch.tanh(nn.functional.softplus(A     )     )






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






         """simple docstring"""
         return self.act(A     )







class 		__UpperCAmelCase(		nn.Module			):





     """simple docstring"""



     def 					__SCREAMING_SNAKE_CASE		(   self			:							Optional[Any]    ,					A			:							Tensor     )      ->      Tensor:






         """simple docstring"""
         return input







class 		__UpperCAmelCase(		nn.Module			):





     """simple docstring"""



     def 					__SCREAMING_SNAKE_CASE		(   self			:							List[Any]    ,					A			:							str    ,					A			:							Dict=0.7_0_7_1_0_7    ,					A			:							Union[str, Any]=0.2_8_2_0_9_5     )      ->      int:






         """simple docstring"""
         a__  			=							(input - mu).div(sigma * math.sqrt(2.0     )     )
         return 0.5 * (1.0 + torch.erf(A     ))







class 		__UpperCAmelCase(		nn.Module			):





     """simple docstring"""



     def 					__SCREAMING_SNAKE_CASE		(   self			:							List[str]    ,					A			:							List[Any]     )      ->      Tuple:






         """simple docstring"""
         a__  			=							nn.functional.relu(A     )
         a__  			=							torch.square(A     )
         return squared







class 		__UpperCAmelCase(		lowercase__			):





     """simple docstring"""



     def __getitem__(   self			:							List[str]    ,					A			:							int     )      ->      Any:






         """simple docstring"""
         a__  			=							super().__getitem__(A     )
         a__			,		a__  			=							content if isinstance(A    ,					A     ) else (content, {})
         return cls(**A     )






SCREAMING_SNAKE_CASE_    :       List[Any]       =							{
    '''gelu''': GELUActivation,
    '''gelu_10''': (ClippedGELUActivation, {'''min''': -10, '''max''': 10}),
    '''gelu_fast''': FastGELUActivation,
    '''gelu_new''': NewGELUActivation,
    '''gelu_python''': (GELUActivation, {'''use_gelu_python''': True}),
    '''gelu_pytorch_tanh''': PytorchGELUTanh,
    '''gelu_accurate''': AccurateGELUActivation,
    '''laplace''': LaplaceActivation,
    '''linear''': LinearActivation,
    '''mish''': MishActivation,
    '''quick_gelu''': QuickGELUActivation,
    '''relu''': nn.ReLU,
    '''relu2''': ReLUSquaredActivation,
    '''relu6''': nn.ReLUa,
    '''sigmoid''': nn.Sigmoid,
    '''silu''': SiLUActivation,
    '''swish''': SiLUActivation,
    '''tanh''': nn.Tanh,
}
SCREAMING_SNAKE_CASE_    :       Any       =							ClassInstantier(ACTaCLS)
def 							__lowerCAmelCase			(UpperCAmelCase_		):
    if activation_string in ACTaFN:
        return ACTaFN[activation_string]
    else:
        raise KeyError(F"""function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys()		)}"""		)


# For backwards compatibility with: from activations import gelu_python
SCREAMING_SNAKE_CASE_    :       Optional[int]       =							get_activation('''gelu_python''')
SCREAMING_SNAKE_CASE_    :       Union[str, Any]       =							get_activation('''gelu_new''')
SCREAMING_SNAKE_CASE_    :       str       =							get_activation('''gelu''')
SCREAMING_SNAKE_CASE_    :       Optional[Any]       =							get_activation('''gelu_fast''')
SCREAMING_SNAKE_CASE_    :       Union[str, Any]       =							get_activation('''quick_gelu''')
SCREAMING_SNAKE_CASE_    :       Tuple       =							get_activation('''silu''')
SCREAMING_SNAKE_CASE_    :       Union[str, Any]       =							get_activation('''mish''')







SCREAMING_SNAKE_CASE_    :       Tuple       =							get_activation('''linear''')






