


"""simple docstring"""






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

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

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


if is_apex_available():
					from apex import amp


if version.parse(version.parse(torch.__version__).base_version) >= version.parse("""1.6"""):
					UpperCamelCase__				:Union[str, Any]			   =	True
					from torch.cuda.amp import autocast

UpperCamelCase__				:Optional[Any]			   =	logging.getLogger(__name__)





def 				A_       ( snake_case__=None       ,					snake_case__=None		)					->  str:
			return field(default_factory=lambda: default       ,					metadata=snake_case__		)






@dataclass
class      A:

		"""simple docstring"""





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






@dataclass
class      A:

		"""simple docstring"""





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






@dataclass
class      A:

		"""simple docstring"""





		A    =							42
		A    =							True
		A    =							None
		A    =							None
		A    =							None
		A    =							None
		def __call__( self					,				SCREAMING_SNAKE_CASE__   )      ->	Dict[str, torch.Tensor]:

					"""simple docstring"""



					_UpperCamelCase					:int					     =	[{'''input_values''': feature['''input_values''']} for feature in features]
					_UpperCamelCase					:List[str]					     =	[{'''input_ids''': feature['''labels''']} for feature in features]

					_UpperCamelCase					:List[Any]					     =	self.processor.pad(
					    SCREAMING_SNAKE_CASE__					,				padding=self.padding					,				max_length=self.max_length					,				pad_to_multiple_of=self.pad_to_multiple_of					,				return_tensors='''pt'''					,				)
					_UpperCamelCase					:List[str]					     =	self.processor.pad(
					    labels=SCREAMING_SNAKE_CASE__					,				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
					_UpperCamelCase					:str					     =	labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1   )					,				-1_00   )

					_UpperCamelCase					:List[Any]					     =	labels

					return batch






class      A(  lowerCamelCase__		):

		"""simple docstring"""





		def   _UpperCamelCase( self					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__   )      ->	torch.Tensor:

					"""simple docstring"""



					model.train()
					_UpperCamelCase					:str					     =	self._prepare_inputs(SCREAMING_SNAKE_CASE__   )

					if self.use_amp:
								with autocast():
											_UpperCamelCase					:int					     =	self.compute_loss(SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__   )
					else:
								_UpperCamelCase					:List[Any]					     =	self.compute_loss(SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__   )

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

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

					return loss.detach()





def 				A_       ( )					->  List[str]:
			# 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.

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

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

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

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

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

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

			# Create and save tokenizer
			_UpperCamelCase					:Optional[Any]					     =	f"[{''.join(data_args.chars_to_ignore		)}]"

			def remove_special_characters(snake_case__		):
						_UpperCamelCase					:Union[str, Any]					     =	re.sub(snake_case__       ,					''''''       ,					batch['''sentence''']		).lower() + ''' '''
						return batch

			_UpperCamelCase					:Dict					     =	train_dataset.map(snake_case__       ,					remove_columns=['''sentence''']		)
			_UpperCamelCase					:str					     =	eval_dataset.map(snake_case__       ,					remove_columns=['''sentence''']		)

			def extract_all_chars(snake_case__		):
						_UpperCamelCase					:Any					     =	''' '''.join(batch['''text''']		)
						_UpperCamelCase					:int					     =	list(set(snake_case__		)		)
						return {"vocab": [vocab], "all_text": [all_text]}

			_UpperCamelCase					:List[str]					     =	train_dataset.map(
			    snake_case__       ,					batched=snake_case__       ,					batch_size=-1       ,					keep_in_memory=snake_case__       ,					remove_columns=train_dataset.column_names       ,					)
			_UpperCamelCase					:List[str]					     =	train_dataset.map(
			    snake_case__       ,					batched=snake_case__       ,					batch_size=-1       ,					keep_in_memory=snake_case__       ,					remove_columns=eval_dataset.column_names       ,					)

			_UpperCamelCase					:Any					     =	list(set(vocab_train['''vocab'''][0]		) | set(vocab_test['''vocab'''][0]		)		)
			_UpperCamelCase					:Optional[int]					     =	{v: k for k, v in enumerate(snake_case__		)}
			_UpperCamelCase					:Optional[Any]					     =	vocab_dict[''' ''']
			del vocab_dict[" "]
			_UpperCamelCase					:str					     =	len(snake_case__		)
			_UpperCamelCase					:str					     =	len(snake_case__		)

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

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

			if data_args.max_train_samples is not None:
						_UpperCamelCase					:Dict					     =	min(len(snake_case__		)       ,					data_args.max_train_samples		)
						_UpperCamelCase					:Union[str, Any]					     =	train_dataset.select(range(snake_case__		)		)

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

			_UpperCamelCase					:Optional[Any]					     =	torchaudio.transforms.Resample(4_80_00       ,					1_60_00		)

			# Preprocessing the datasets.
			# We need to read the aduio files as arrays and tokenize the targets.
			def speech_file_to_array_fn(snake_case__		):
						_UpperCamelCase     ,      _UpperCamelCase					:int					     =	torchaudio.load(batch['''path''']		)
						_UpperCamelCase					:List[Any]					     =	resampler(snake_case__		).squeeze().numpy()
						_UpperCamelCase					:Union[str, Any]					     =	1_60_00
						_UpperCamelCase					:str					     =	batch['''text''']
						return batch

			_UpperCamelCase					:Any					     =	train_dataset.map(
			    snake_case__       ,					remove_columns=train_dataset.column_names       ,					num_proc=data_args.preprocessing_num_workers       ,					)
			_UpperCamelCase					:Any					     =	eval_dataset.map(
			    snake_case__       ,					remove_columns=eval_dataset.column_names       ,					num_proc=data_args.preprocessing_num_workers       ,					)

			def prepare_dataset(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}."

						_UpperCamelCase					:Union[str, Any]					     =	processor(
						    audio=batch['''speech''']       ,					text=batch['''target_text''']       ,					sampling_rate=batch['''sampling_rate'''][0]		)
						batch.update(snake_case__		)
						return batch

			_UpperCamelCase					:str					     =	train_dataset.map(
			    snake_case__       ,					remove_columns=train_dataset.column_names       ,					batch_size=training_args.per_device_train_batch_size       ,					batched=snake_case__       ,					num_proc=data_args.preprocessing_num_workers       ,					)
			_UpperCamelCase					:List[Any]					     =	eval_dataset.map(
			    snake_case__       ,					remove_columns=eval_dataset.column_names       ,					batch_size=training_args.per_device_train_batch_size       ,					batched=snake_case__       ,					num_proc=data_args.preprocessing_num_workers       ,					)

			# Metric
			_UpperCamelCase					:Any					     =	datasets.load_metric('''wer'''		)

			def compute_metrics(snake_case__		):
						_UpperCamelCase					:Union[str, Any]					     =	pred.predictions
						_UpperCamelCase					:str					     =	np.argmax(snake_case__       ,					axis=-1		)

						_UpperCamelCase					:str					     =	processor.tokenizer.pad_token_id

						_UpperCamelCase					:List[str]					     =	processor.batch_decode(snake_case__		)
						# we do not want to group tokens when computing the metrics
						_UpperCamelCase					:List[Any]					     =	processor.batch_decode(pred.label_ids       ,					group_tokens=snake_case__		)

						_UpperCamelCase					:List[Any]					     =	wer_metric.compute(predictions=snake_case__       ,					references=snake_case__		)

						return {"wer": wer}

			if model_args.freeze_feature_extractor:
						model.freeze_feature_extractor()

			# Data collator
			_UpperCamelCase					:Union[str, Any]					     =	DataCollatorCTCWithPadding(processor=snake_case__       ,					padding=snake_case__		)

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

			# Training
			if training_args.do_train:
						if last_checkpoint is not None:
									_UpperCamelCase					:List[str]					     =	last_checkpoint
						elif os.path.isdir(model_args.model_name_or_path		):
									_UpperCamelCase					:str					     =	model_args.model_name_or_path
						else:
									_UpperCamelCase					:int					     =	None

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

						_UpperCamelCase					:Any					     =	trainer.train(resume_from_checkpoint=snake_case__		)
						trainer.save_model()

						_UpperCamelCase					:Optional[Any]					     =	train_result.metrics
						_UpperCamelCase					:int					     =	(
						    data_args.max_train_samples if data_args.max_train_samples is not None else len(snake_case__		)
						)
						_UpperCamelCase					:Optional[int]					     =	min(snake_case__       ,					len(snake_case__		)		)

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

			# Evaluation
			_UpperCamelCase					:Tuple					     =	{}
			if training_args.do_eval:
						logger.info('''*** Evaluate ***'''		)
						_UpperCamelCase					:List[str]					     =	trainer.evaluate()
						_UpperCamelCase					:List[Any]					     =	data_args.max_val_samples if data_args.max_val_samples is not None else len(snake_case__		)
						_UpperCamelCase					:Dict					     =	min(snake_case__       ,					len(snake_case__		)		)

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

			return results


if __name__ == "__main__":
					main()





"""simple docstring"""






import unittest

import numpy as np

from transformers.testing_utils import require_flax, require_tf, require_torch
from transformers.utils import (
    expand_dims,
    flatten_dict,
    is_flax_available,
    is_tf_available,
    is_torch_available,
    reshape,
    squeeze,
    transpose,
)


if is_flax_available():
					import jax.numpy as jnp

if is_tf_available():
					import tensorflow as tf

if is_torch_available():
					import torch






class      A(  unittest.TestCase		):

		"""simple docstring"""





		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:List[str]					     =	{
					    '''task_specific_params''': {
					        '''summarization''': {'''length_penalty''': 1.0, '''max_length''': 1_28, '''min_length''': 12, '''num_beams''': 4},
					        '''summarization_cnn''': {'''length_penalty''': 2.0, '''max_length''': 1_42, '''min_length''': 56, '''num_beams''': 4},
					        '''summarization_xsum''': {'''length_penalty''': 1.0, '''max_length''': 62, '''min_length''': 11, '''num_beams''': 6},
					    }
					}
					_UpperCamelCase					:Union[str, Any]					     =	{
					    '''task_specific_params.summarization.length_penalty''': 1.0,
					    '''task_specific_params.summarization.max_length''': 1_28,
					    '''task_specific_params.summarization.min_length''': 12,
					    '''task_specific_params.summarization.num_beams''': 4,
					    '''task_specific_params.summarization_cnn.length_penalty''': 2.0,
					    '''task_specific_params.summarization_cnn.max_length''': 1_42,
					    '''task_specific_params.summarization_cnn.min_length''': 56,
					    '''task_specific_params.summarization_cnn.num_beams''': 4,
					    '''task_specific_params.summarization_xsum.length_penalty''': 1.0,
					    '''task_specific_params.summarization_xsum.max_length''': 62,
					    '''task_specific_params.summarization_xsum.min_length''': 11,
					    '''task_specific_params.summarization_xsum.num_beams''': 6,
					}

					self.assertEqual(flatten_dict(SCREAMING_SNAKE_CASE__   )					,				SCREAMING_SNAKE_CASE__   )
		def   _UpperCamelCase( self   )      ->	Any:

					"""simple docstring"""



					_UpperCamelCase					:Optional[int]					     =	np.random.randn(3					,				4   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__   )					,				x.transpose()   )   )

					_UpperCamelCase					:Tuple					     =	np.random.randn(3					,				4					,				5   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   )					,				x.transpose((1, 2, 0)   )   )   )
		@require_torch
		def   _UpperCamelCase( self   )      ->	str:

					"""simple docstring"""



					_UpperCamelCase					:Union[str, Any]					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:Any					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__   )					,				transpose(SCREAMING_SNAKE_CASE__   ).numpy()   )   )

					_UpperCamelCase					:int					     =	np.random.randn(3					,				4					,				5   )
					_UpperCamelCase					:Any					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   )					,				transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   ).numpy()   )   )
		@require_tf
		def   _UpperCamelCase( self   )      ->	Dict:

					"""simple docstring"""



					_UpperCamelCase					:Dict					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:List[str]					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__   )					,				transpose(SCREAMING_SNAKE_CASE__   ).numpy()   )   )

					_UpperCamelCase					:int					     =	np.random.randn(3					,				4					,				5   )
					_UpperCamelCase					:Dict					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   )					,				transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   ).numpy()   )   )
		@require_flax
		def   _UpperCamelCase( self   )      ->	str:

					"""simple docstring"""



					_UpperCamelCase					:int					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:Optional[Any]					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__   )					,				np.asarray(transpose(SCREAMING_SNAKE_CASE__   )   )   )   )

					_UpperCamelCase					:Dict					     =	np.random.randn(3					,				4					,				5   )
					_UpperCamelCase					:Dict					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   )					,				np.asarray(transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   )   )   )   )
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:int					     =	np.random.randn(3					,				4   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   )					,				np.reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   )   )   )

					_UpperCamelCase					:Dict					     =	np.random.randn(3					,				4					,				5   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   )					,				np.reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   )   )   )
		@require_torch
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:Union[str, Any]					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:Optional[Any]					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   )					,				reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   ).numpy()   )   )

					_UpperCamelCase					:str					     =	np.random.randn(3					,				4					,				5   )
					_UpperCamelCase					:str					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   )					,				reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   ).numpy()   )   )
		@require_tf
		def   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					_UpperCamelCase					:Optional[int]					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:Dict					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   )					,				reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   ).numpy()   )   )

					_UpperCamelCase					:Union[str, Any]					     =	np.random.randn(3					,				4					,				5   )
					_UpperCamelCase					:Optional[int]					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   )					,				reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   ).numpy()   )   )
		@require_flax
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:List[str]					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:str					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   )					,				np.asarray(reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   )   )   )   )

					_UpperCamelCase					:Dict					     =	np.random.randn(3					,				4					,				5   )
					_UpperCamelCase					:Union[str, Any]					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   )					,				np.asarray(reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   )   )   )   )
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:Dict					     =	np.random.randn(1					,				3					,				4   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__   )					,				np.squeeze(SCREAMING_SNAKE_CASE__   )   )   )

					_UpperCamelCase					:List[Any]					     =	np.random.randn(1					,				4					,				1					,				5   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   )					,				np.squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   )   )   )
		@require_torch
		def   _UpperCamelCase( self   )      ->	Union[str, Any]:

					"""simple docstring"""



					_UpperCamelCase					:str					     =	np.random.randn(1					,				3					,				4   )
					_UpperCamelCase					:Any					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__   )					,				squeeze(SCREAMING_SNAKE_CASE__   ).numpy()   )   )

					_UpperCamelCase					:List[str]					     =	np.random.randn(1					,				4					,				1					,				5   )
					_UpperCamelCase					:List[Any]					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   )					,				squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   ).numpy()   )   )
		@require_tf
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:str					     =	np.random.randn(1					,				3					,				4   )
					_UpperCamelCase					:str					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__   )					,				squeeze(SCREAMING_SNAKE_CASE__   ).numpy()   )   )

					_UpperCamelCase					:str					     =	np.random.randn(1					,				4					,				1					,				5   )
					_UpperCamelCase					:str					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   )					,				squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   ).numpy()   )   )
		@require_flax
		def   _UpperCamelCase( self   )      ->	Optional[Any]:

					"""simple docstring"""



					_UpperCamelCase					:Union[str, Any]					     =	np.random.randn(1					,				3					,				4   )
					_UpperCamelCase					:Optional[Any]					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__   )					,				np.asarray(squeeze(SCREAMING_SNAKE_CASE__   )   )   )   )

					_UpperCamelCase					:Dict					     =	np.random.randn(1					,				4					,				1					,				5   )
					_UpperCamelCase					:int					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   )					,				np.asarray(squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   )   )   )   )
		def   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					_UpperCamelCase					:Dict					     =	np.random.randn(3					,				4   )
					self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   )					,				np.expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   )   )   )
		@require_torch
		def   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					_UpperCamelCase					:List[str]					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:Union[str, Any]					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   )					,				expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   ).numpy()   )   )
		@require_tf
		def   _UpperCamelCase( self   )      ->	Optional[int]:

					"""simple docstring"""



					_UpperCamelCase					:str					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:int					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   )					,				expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   ).numpy()   )   )





		@require_flax
		def   _UpperCamelCase( self   )      ->	List[Any]:

					"""simple docstring"""



					_UpperCamelCase					:Tuple					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:str					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   )					,				np.asarray(expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   )   )   )   )

