


"""simple docstring"""







from __future__ import annotations

import unittest

import numpy as np

from transformers import OPTConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
		import tensorflow as tf

		from transformers import GPTaTokenizer, TFOPTForCausalLM, TFOPTModel




def    UpperCAmelCase__       (lowerCAmelCase_  ,						lowerCAmelCase_  ,						lowerCAmelCase_=None  ,						lowerCAmelCase_=None   ):




					'''simple docstring'''


					if attention_mask is None:
										__SCREAMING_SNAKE_CASE						   =				tf.cast(tf.math.not_equal(lowerCAmelCase_  ,						config.pad_token_id   )  ,						tf.inta   )
					return {"input_ids": input_ids, "attention_mask": attention_mask}




@require_tf
class  UpperCamelCase_	:

	"""simple docstring"""





	snake_case__				:  Dict    					=			OPTConfig
	snake_case__				:  List[Any]    					=			{}
	snake_case__				:  List[str]    					=			"gelu"




	def __init__( self			:				Union[str, Any]			,			UpperCAmelCase__			:				int			,			UpperCAmelCase__			:				List[str]=1_3			,			UpperCAmelCase__			:				Optional[int]=7			,			UpperCAmelCase__			:				Tuple=True			,			UpperCAmelCase__			:				Optional[Any]=False			,			UpperCAmelCase__			:				str=9_9			,			UpperCAmelCase__			:				Dict=1_6			,			UpperCAmelCase__			:				Tuple=2			,			UpperCAmelCase__			:				int=4			,			UpperCAmelCase__			:				Tuple=4			,			UpperCAmelCase__			:				str="gelu"			,			UpperCAmelCase__			:				Optional[int]=0.1			,			UpperCAmelCase__			:				Any=0.1			,			UpperCAmelCase__			:				List[str]=2_0			,			UpperCAmelCase__			:				Any=2			,			UpperCAmelCase__			:				str=1			,			UpperCAmelCase__			:				Optional[Any]=0			,			UpperCAmelCase__			:				Optional[Any]=1_6			,			UpperCAmelCase__			:				List[str]=1_6			,			)       ->	List[str]:
						__SCREAMING_SNAKE_CASE						   =				parent
						__SCREAMING_SNAKE_CASE						   =				batch_size
						__SCREAMING_SNAKE_CASE						   =				seq_length
						__SCREAMING_SNAKE_CASE						   =				is_training
						__SCREAMING_SNAKE_CASE						   =				use_labels
						__SCREAMING_SNAKE_CASE						   =				vocab_size
						__SCREAMING_SNAKE_CASE						   =				hidden_size
						__SCREAMING_SNAKE_CASE						   =				num_hidden_layers
						__SCREAMING_SNAKE_CASE						   =				num_attention_heads
						__SCREAMING_SNAKE_CASE						   =				intermediate_size
						__SCREAMING_SNAKE_CASE						   =				hidden_act
						__SCREAMING_SNAKE_CASE						   =				hidden_dropout_prob
						__SCREAMING_SNAKE_CASE						   =				attention_probs_dropout_prob
						__SCREAMING_SNAKE_CASE						   =				max_position_embeddings
						__SCREAMING_SNAKE_CASE						   =				eos_token_id
						__SCREAMING_SNAKE_CASE						   =				pad_token_id
						__SCREAMING_SNAKE_CASE						   =				bos_token_id
						__SCREAMING_SNAKE_CASE						   =				embed_dim
						__SCREAMING_SNAKE_CASE						   =				word_embed_proj_dim
						__SCREAMING_SNAKE_CASE						   =				False




	def   UpperCAmelCase_      ( self			:				Optional[Any]   )       ->	Dict:
						__SCREAMING_SNAKE_CASE						   =				ids_tensor([self.batch_size, self.seq_length - 1]			,			self.vocab_size   )
						__SCREAMING_SNAKE_CASE						   =				tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size   )			,			1   )
						__SCREAMING_SNAKE_CASE						   =				tf.concat([input_ids, eos_tensor]			,			axis=1   )

						__SCREAMING_SNAKE_CASE						   =				self.config_cls(
						    vocab_size=self.vocab_size			,			hidden_size=self.hidden_size			,			num_hidden_layers=self.num_hidden_layers			,			num_attention_heads=self.num_attention_heads			,			ffn_dim=self.intermediate_size			,			dropout=self.hidden_dropout_prob			,			attention_dropout=self.attention_probs_dropout_prob			,			max_position_embeddings=self.max_position_embeddings			,			eos_token_id=self.eos_token_id			,			bos_token_id=self.bos_token_id			,			pad_token_id=self.pad_token_id			,			embed_dim=self.embed_dim			,			word_embed_proj_dim=self.word_embed_proj_dim			,			is_encoder_decoder=UpperCAmelCase__			,			**self.config_updates			,			)
						__SCREAMING_SNAKE_CASE						   =				prepare_opt_inputs_dict(UpperCAmelCase__			,			UpperCAmelCase__   )
						return config, inputs_dict




	def   UpperCAmelCase_      ( self			:				Optional[Any]			,			UpperCAmelCase__			:				Union[str, Any]			,			UpperCAmelCase__			:				List[Any]   )       ->	str:
						__SCREAMING_SNAKE_CASE						   =				TFOPTModel(config=UpperCAmelCase__   )
						__SCREAMING_SNAKE_CASE						   =				inputs_dict["input_ids"]

						__SCREAMING_SNAKE_CASE						   =				input_ids[:1, :]
						__SCREAMING_SNAKE_CASE						   =				inputs_dict["attention_mask"][:1, :]
						__SCREAMING_SNAKE_CASE						   =				1

						# first forward pass
						__SCREAMING_SNAKE_CASE						   =				model(UpperCAmelCase__			,			attention_mask=UpperCAmelCase__			,			use_cache=UpperCAmelCase__   )

						__SCREAMING_SNAKE_CASE   ,  __SCREAMING_SNAKE_CASE						   =				outputs.to_tuple()

						# create hypothetical next token and extent to next_input_ids
						__SCREAMING_SNAKE_CASE						   =				ids_tensor((self.batch_size, 3)			,			config.vocab_size   )
						__SCREAMING_SNAKE_CASE						   =				tf.cast(ids_tensor((self.batch_size, 3)			,			2   )			,			tf.inta   )

						# append to next input_ids and
						__SCREAMING_SNAKE_CASE						   =				tf.concat([input_ids, next_tokens]			,			axis=-1   )
						__SCREAMING_SNAKE_CASE						   =				tf.concat([attention_mask, next_attn_mask]			,			axis=-1   )

						__SCREAMING_SNAKE_CASE						   =				model(UpperCAmelCase__			,			attention_mask=UpperCAmelCase__   )[0]
						__SCREAMING_SNAKE_CASE						   =				model(UpperCAmelCase__			,			attention_mask=UpperCAmelCase__			,			past_key_values=UpperCAmelCase__   )[0]

						self.parent.assertEqual(next_tokens.shape[1]			,			output_from_past.shape[1]   )

						# select random slice
						__SCREAMING_SNAKE_CASE						   =				int(ids_tensor((1,)			,			output_from_past.shape[-1]   )   )
						__SCREAMING_SNAKE_CASE						   =				output_from_no_past[:, -3:, random_slice_idx]
						__SCREAMING_SNAKE_CASE						   =				output_from_past[:, :, random_slice_idx]

						# test that outputs are equal for slice
						tf.debugging.assert_near(UpperCAmelCase__			,			UpperCAmelCase__			,			rtol=1E-3   )




@require_tf
class  UpperCamelCase_	( UpperCamelCase			,  UpperCamelCase			,  unittest.TestCase):

	"""simple docstring"""





	snake_case__				:  str    					=			(TFOPTModel, TFOPTForCausalLM) if is_tf_available() else ()
	snake_case__				:  Optional[Any]    					=			(TFOPTForCausalLM,) if is_tf_available() else ()
	snake_case__				:  Tuple    					=			(
	    {"feature-extraction": TFOPTModel, "text-generation": TFOPTForCausalLM} if is_tf_available() else {}
	)
	snake_case__				:  Any    					=			False
	snake_case__				:  Union[str, Any]    					=			False
	snake_case__				:  List[str]    					=			False
	snake_case__				:  Tuple    					=			10




	def   UpperCAmelCase_      ( self			:				Union[str, Any]   )       ->	Dict:
						__SCREAMING_SNAKE_CASE						   =				TFOPTModelTester(self   )
						__SCREAMING_SNAKE_CASE						   =				ConfigTester(self			,			config_class=UpperCAmelCase__   )




	def   UpperCAmelCase_      ( self			:				List[str]   )       ->	List[Any]:
						self.config_tester.run_common_tests()




	def   UpperCAmelCase_      ( self			:				Optional[int]   )       ->	Union[str, Any]:
						__SCREAMING_SNAKE_CASE						   =				self.model_tester.prepare_config_and_inputs_for_common()
						self.model_tester.check_decoder_model_past_large_inputs(*UpperCAmelCase__   )




	def   UpperCAmelCase_      ( self			:				Dict   )       ->	str:
						__SCREAMING_SNAKE_CASE   ,  __SCREAMING_SNAKE_CASE						   =				self.model_tester.prepare_config_and_inputs_for_common()

						def _get_word_embedding_weight(UpperCAmelCase__			:				Dict			,			UpperCAmelCase__			:				str   ):
											if hasattr(UpperCAmelCase__			,			"weight"   ):
																return embedding_layer.weight
											else:
																# Here we build the word embeddings weights if not exists.
																# And then we retry to get the attribute once built.
																model.build()
																if hasattr(UpperCAmelCase__			,			"weight"   ):
																					return embedding_layer.weight
																else:
																					return None

						for model_class in self.all_model_classes:
											for size in [config.vocab_size - 1_0, config.vocab_size + 1_0]:
																# build the embeddings
																__SCREAMING_SNAKE_CASE						   =				model_class(config=UpperCAmelCase__   )
																__SCREAMING_SNAKE_CASE						   =				_get_word_embedding_weight(UpperCAmelCase__			,			model.get_input_embeddings()   )
																__SCREAMING_SNAKE_CASE						   =				_get_word_embedding_weight(UpperCAmelCase__			,			model.get_output_embeddings()   )

																# reshape the embeddings
																model.resize_token_embeddings(UpperCAmelCase__   )
																__SCREAMING_SNAKE_CASE						   =				_get_word_embedding_weight(UpperCAmelCase__			,			model.get_input_embeddings()   )
																__SCREAMING_SNAKE_CASE						   =				_get_word_embedding_weight(UpperCAmelCase__			,			model.get_output_embeddings()   )

																# check that the resized embeddings size matches the desired size.
																__SCREAMING_SNAKE_CASE						   =				size if size is not None else config.vocab_size

																self.assertEqual(new_input_embeddings.shape[0]			,			UpperCAmelCase__   )

																# check that weights remain the same after resizing
																__SCREAMING_SNAKE_CASE						   =				True
																for pa, pa in zip(old_input_embeddings.value()			,			new_input_embeddings.value()   ):
																					if tf.math.reduce_sum(tf.math.abs(pa - pa   )   ) > 0:
																										__SCREAMING_SNAKE_CASE						   =				False
																self.assertTrue(UpperCAmelCase__   )

																if old_output_embeddings is not None and new_output_embeddings is not None:
																					self.assertEqual(new_output_embeddings.shape[0]			,			UpperCAmelCase__   )

																					__SCREAMING_SNAKE_CASE						   =				True
																					for pa, pa in zip(old_output_embeddings.value()			,			new_output_embeddings.value()   ):
																										if tf.math.reduce_sum(tf.math.abs(pa - pa   )   ) > 0:
																															__SCREAMING_SNAKE_CASE						   =				False
																					self.assertTrue(UpperCAmelCase__   )




def    UpperCAmelCase__       (lowerCAmelCase_   ):




					'''simple docstring'''


					return tf.constant(lowerCAmelCase_  ,						dtype=tf.intaa   )




@require_tf
class  UpperCamelCase_	( unittest.TestCase):

	"""simple docstring"""





	snake_case__				:  int    					=			99




	def   UpperCAmelCase_      ( self			:				Optional[Any]   )       ->	Optional[int]:
						__SCREAMING_SNAKE_CASE						   =				tf.ones((4, 1)			,			dtype=tf.intaa   ) * 2
						__SCREAMING_SNAKE_CASE						   =				tf.concat([ids_tensor((4, 6)			,			self.vocab_size - 3   ) + 3, eos_column_vector]			,			axis=1   )
						__SCREAMING_SNAKE_CASE						   =				input_ids.shape[0]
						__SCREAMING_SNAKE_CASE						   =				OPTConfig(
						    vocab_size=self.vocab_size			,			hidden_size=2_4			,			num_hidden_layers=2			,			num_attention_heads=2			,			ffn_dim=3_2			,			max_position_embeddings=4_8			,			eos_token_id=2			,			pad_token_id=1			,			bos_token_id=0			,			)
						return config, input_ids, batch_size




@require_sentencepiece
@require_tf
class  UpperCamelCase_	( unittest.TestCase):

	"""simple docstring"""





	@slow
	def   UpperCAmelCase_      ( self			:				List[Any]   )       ->	List[Any]:
						__SCREAMING_SNAKE_CASE						   =				TFOPTModel.from_pretrained("facebook/opt-350m"   )
						__SCREAMING_SNAKE_CASE						   =				_long_tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]]   )
						__SCREAMING_SNAKE_CASE						   =				tf.not_equal(UpperCAmelCase__			,			model.config.pad_token_id   )
						with tf.GradientTape():
											__SCREAMING_SNAKE_CASE						   =				model(input_ids=UpperCAmelCase__			,			attention_mask=UpperCAmelCase__   ).last_hidden_state
						__SCREAMING_SNAKE_CASE						   =				(1, 1_1, 5_1_2)
						self.assertEqual(output.shape			,			UpperCAmelCase__   )
						__SCREAMING_SNAKE_CASE						   =				tf.constant(
						    [[-0.2_873, -1.9_218, -0.3_033], [-1.2_710, -0.1_338, -0.1_902], [0.4_095, 0.1_214, -1.3_121]]   )
						self.assertTrue(np.allclose(output[:, :3, :3]			,			UpperCAmelCase__			,			atol=4E-3   )   )

						__SCREAMING_SNAKE_CASE						   =				tf.function(UpperCAmelCase__			,			jit_compile=UpperCAmelCase__   )
						__SCREAMING_SNAKE_CASE						   =				xla_generate(UpperCAmelCase__			,			UpperCAmelCase__   )[0]
						self.assertTrue(np.allclose(output[:, :3, :3]			,			UpperCAmelCase__			,			atol=4E-2   )   )




@require_tf
@slow
class  UpperCamelCase_	( unittest.TestCase):

	"""simple docstring"""





	def   UpperCAmelCase_      ( self			:				Optional[Any]   )       ->	Optional[Any]:
						super().setUp()
						__SCREAMING_SNAKE_CASE						   =				"facebook/opt-350m"




	def   UpperCAmelCase_      ( self			:				Tuple   )       ->	Union[str, Any]:
						__SCREAMING_SNAKE_CASE						   =				TFOPTForCausalLM.from_pretrained(self.path_model   )
						__SCREAMING_SNAKE_CASE						   =				GPTaTokenizer.from_pretrained(self.path_model   )

						__SCREAMING_SNAKE_CASE						   =				[
						    "Today is a beautiful day and I want to",
						    "In the city of",
						    "Paris is the capital of France and",
						    "Computers and mobile phones have taken",
						]
						# verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False
						__SCREAMING_SNAKE_CASE						   =				tokenizer(UpperCAmelCase__			,			return_tensors="tf"			,			padding=UpperCAmelCase__			,			add_special_tokens=UpperCAmelCase__   )
						__SCREAMING_SNAKE_CASE						   =				tf.math.reduce_mean(model(inputs.input_ids			,			attention_mask=inputs.attention_mask   )[0]			,			axis=-1   )
						__SCREAMING_SNAKE_CASE						   =				tf.constant(
						    [
						        [1.3_851, -13.8_923, -10.5_229, -10.7_533, -0.2_309, -10.2_384, -0.5_365, -9.0_947, -5.1_670],
						        [-4.7_073, -10.6_276, -3.9_415, -21.5_242, -0.2_822, -0.2_822, -0.2_822, -0.2_822, -0.2_822],
						        [0.6_247, -3.4_229, -8.9_179, -1.4_297, -14.1_650, 1.4_146, -9.0_218, -0.2_703, -0.2_703],
						        [6.4_783, -1.9_913, -10.7_926, -2.3_336, 1.5_092, -0.9_974, -6.8_213, 1.3_477, 1.3_477],
						    ]   )
						self.assertTrue(np.allclose(UpperCAmelCase__			,			UpperCAmelCase__			,			atol=1E-4   )   )

						__SCREAMING_SNAKE_CASE						   =				tf.function(UpperCAmelCase__			,			jit_compile=UpperCAmelCase__   )
						__SCREAMING_SNAKE_CASE						   =				tf.math.reduce_mean(xla_generate(inputs.input_ids			,			attention_mask=inputs.attention_mask   )[0]			,			axis=-1   )
						self.assertTrue(np.allclose(UpperCAmelCase__			,			UpperCAmelCase__			,			atol=1E-4   )   )




@require_tf
@slow
class  UpperCamelCase_	( unittest.TestCase):

	"""simple docstring"""





	@property
	def   UpperCAmelCase_      ( self			:				Dict   )       ->	str:
						return [
						    "Today is a beautiful day and I want",
						    "In the city of",
						    "Paris is the capital of France and",
						    "Computers and mobile phones have taken",
						]




	def   UpperCAmelCase_      ( self			:				Union[str, Any]   )       ->	Any:
						__SCREAMING_SNAKE_CASE						   =				"facebook/opt-125m"

						__SCREAMING_SNAKE_CASE						   =				[
						    "Today is a beautiful day and I want to",
						    "In the city of New York, the city",
						    "Paris is the capital of France and the capital",
						    "Computers and mobile phones have taken over the",
						]

						__SCREAMING_SNAKE_CASE						   =				[]
						__SCREAMING_SNAKE_CASE						   =				GPTaTokenizer.from_pretrained(UpperCAmelCase__   )
						__SCREAMING_SNAKE_CASE						   =				TFOPTForCausalLM.from_pretrained(UpperCAmelCase__   )

						for prompt in self.prompts:
											__SCREAMING_SNAKE_CASE						   =				tokenizer(UpperCAmelCase__			,			return_tensors="tf"   ).input_ids

											__SCREAMING_SNAKE_CASE						   =				model.generate(UpperCAmelCase__			,			max_length=1_0   )

											__SCREAMING_SNAKE_CASE						   =				tokenizer.batch_decode(UpperCAmelCase__			,			skip_special_tokens=UpperCAmelCase__   )
											predicted_outputs += generated_string

						self.assertListEqual(UpperCAmelCase__			,			UpperCAmelCase__   )




	def   UpperCAmelCase_      ( self			:				int   )       ->	int:
						__SCREAMING_SNAKE_CASE						   =				"facebook/opt-350m"

						__SCREAMING_SNAKE_CASE						   =				GPTaTokenizer.from_pretrained(UpperCAmelCase__   )
						__SCREAMING_SNAKE_CASE						   =				TFOPTForCausalLM.from_pretrained(UpperCAmelCase__   )

						__SCREAMING_SNAKE_CASE						   =				"left"

						# use different length sentences to test batching
						__SCREAMING_SNAKE_CASE						   =				[
						    "Hello, my dog is a little",
						    "Today, I",
						]

						__SCREAMING_SNAKE_CASE						   =				tokenizer(UpperCAmelCase__			,			return_tensors="tf"			,			padding=UpperCAmelCase__   )
						__SCREAMING_SNAKE_CASE						   =				inputs["input_ids"]

						__SCREAMING_SNAKE_CASE						   =				model.generate(input_ids=UpperCAmelCase__			,			attention_mask=inputs["attention_mask"]   )

						__SCREAMING_SNAKE_CASE						   =				tokenizer(sentences[0]			,			return_tensors="tf"   ).input_ids
						__SCREAMING_SNAKE_CASE						   =				model.generate(input_ids=UpperCAmelCase__   )

						__SCREAMING_SNAKE_CASE						   =				inputs_non_padded.shape[-1] - tf.math.reduce_sum(
						    tf.cast(inputs["attention_mask"][-1]			,			tf.intaa   )   )
						__SCREAMING_SNAKE_CASE						   =				tokenizer(sentences[1]			,			return_tensors="tf"   ).input_ids
						__SCREAMING_SNAKE_CASE						   =				model.generate(input_ids=UpperCAmelCase__			,			max_length=model.config.max_length - num_paddings   )

						__SCREAMING_SNAKE_CASE						   =				tokenizer.batch_decode(UpperCAmelCase__			,			skip_special_tokens=UpperCAmelCase__   )
						__SCREAMING_SNAKE_CASE						   =				tokenizer.decode(output_non_padded[0]			,			skip_special_tokens=UpperCAmelCase__   )
						__SCREAMING_SNAKE_CASE						   =				tokenizer.decode(output_padded[0]			,			skip_special_tokens=UpperCAmelCase__   )

						__SCREAMING_SNAKE_CASE						   =				[
						    "Hello, my dog is a little bit of a dork.\nI'm a little bit",
						    "Today, I was in the middle of a conversation with a friend about the",
						]
						self.assertListEqual(UpperCAmelCase__			,			UpperCAmelCase__   )
						self.assertListEqual(UpperCAmelCase__			,			[non_padded_sentence, padded_sentence]   )




	def   UpperCAmelCase_      ( self			:				Any   )       ->	Any:
						__SCREAMING_SNAKE_CASE						   =				"facebook/opt-350m"

						__SCREAMING_SNAKE_CASE						   =				[
						    "Today is a beautiful day and I want to",
						    "In the city of San Francisco, the city",
						    "Paris is the capital of France and the capital",
						    "Computers and mobile phones have taken over the",
						]

						__SCREAMING_SNAKE_CASE						   =				[]
						__SCREAMING_SNAKE_CASE						   =				GPTaTokenizer.from_pretrained(UpperCAmelCase__   )
						__SCREAMING_SNAKE_CASE						   =				TFOPTForCausalLM.from_pretrained(UpperCAmelCase__   )

						for prompt in self.prompts:
											__SCREAMING_SNAKE_CASE						   =				tokenizer(UpperCAmelCase__			,			return_tensors="tf"   ).input_ids

											__SCREAMING_SNAKE_CASE						   =				model.generate(UpperCAmelCase__			,			max_length=1_0   )

											__SCREAMING_SNAKE_CASE						   =				tokenizer.batch_decode(UpperCAmelCase__			,			skip_special_tokens=UpperCAmelCase__   )
											predicted_outputs += generated_string

						self.assertListEqual(UpperCAmelCase__			,			UpperCAmelCase__   )







import itertools
import os
import random
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers import is_speech_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
	from transformers import WhisperFeatureExtractor

if is_torch_available():
	import torch

lowerCAmelCase_    =				random.Random()






def      lowerCamelCase_						(				_UpperCamelCase ,				_UpperCamelCase=1.0 ,				_UpperCamelCase=None ,				_UpperCamelCase=None )		->						List[Any]:






				"""simple docstring"""


				if rng is None:
								snake_case_						:    str				=  global_rng

				snake_case_						:    Any				=  []
				for batch_idx in range(shape[0] ):
								values.append([] )
								for _ in range(shape[1] ):
												values[-1].append(rng.random() * scale )

				return values



@require_torch
@require_torchaudio
class 					__lowerCAmelCase       (			unittest.TestCase     ):






			def __init__(self					,							__magic_name__					,							__magic_name__=7					,							__magic_name__=400					,							__magic_name__=2000					,							__magic_name__=10					,							__magic_name__=160					,							__magic_name__=8					,							__magic_name__=0.0					,							__magic_name__=4000					,							__magic_name__=False					,							__magic_name__=True					,							)     ->   List[str]:


							'''simple docstring'''



							snake_case_						:    Tuple				=  parent
							snake_case_						:    str				=  batch_size
							snake_case_						:    Union[str, Any]				=  min_seq_length
							snake_case_						:    Tuple				=  max_seq_length
							snake_case_						:    Optional[Any]				=  (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
							snake_case_						:    Optional[int]				=  padding_value
							snake_case_						:    Union[str, Any]				=  sampling_rate
							snake_case_						:    Optional[int]				=  return_attention_mask
							snake_case_						:    str				=  do_normalize
							snake_case_						:    str				=  feature_size
							snake_case_						:    Optional[Any]				=  chunk_length
							snake_case_						:    Union[str, Any]				=  hop_length






			def 			lowerCamelCase  (self    )     ->   Optional[int]:


							'''simple docstring'''



							return {
							    "feature_size": self.feature_size,
							    "hop_length": self.hop_length,
							    "chunk_length": self.chunk_length,
							    "padding_value": self.padding_value,
							    "sampling_rate": self.sampling_rate,
							    "return_attention_mask": self.return_attention_mask,
							    "do_normalize": self.do_normalize,
							}






			def 			lowerCamelCase  (self					,							__magic_name__=False					,							__magic_name__=False    )     ->   Optional[Any]:


							'''simple docstring'''



							def _flatten(__magic_name__    ):
											return list(itertools.chain(*__magic_name__    )    )

							if equal_length:
											snake_case_						:    int				=  [floats_list((self.max_seq_length, self.feature_size)    ) for _ in range(self.batch_size    )]
							else:
											# make sure that inputs increase in size
											snake_case_						:    int				=  [
											    floats_list((x, self.feature_size)    )
											    for x in range(self.min_seq_length					,							self.max_seq_length					,							self.seq_length_diff    )
											]
							if numpify:
											snake_case_						:    str				=  [np.asarray(__magic_name__    ) for x in speech_inputs]
							return speech_inputs




@require_torch
@require_torchaudio
class 					__lowerCAmelCase       (			_a,     unittest.TestCase     ):
			lowerCamelCase_     :     Optional[Any]       			=      WhisperFeatureExtractor if is_speech_available() else None






			def 			lowerCamelCase  (self    )     ->   Optional[int]:


							'''simple docstring'''



							snake_case_						:    List[str]				=  WhisperFeatureExtractionTester(self    )






			def 			lowerCamelCase  (self    )     ->   List[str]:


							'''simple docstring'''



							snake_case_						:    str				=  self.feature_extraction_class(**self.feat_extract_dict    )

							with tempfile.TemporaryDirectory() as tmpdirname:
											snake_case_						:    Union[str, Any]				=  feat_extract_first.save_pretrained(__magic_name__    )[0]
											check_json_file_has_correct_format(__magic_name__    )
											snake_case_						:    List[Any]				=  self.feature_extraction_class.from_pretrained(__magic_name__    )

							snake_case_						:    Optional[int]				=  feat_extract_first.to_dict()
							snake_case_						:    Dict				=  feat_extract_second.to_dict()
							snake_case_						:    List[str]				=  feat_extract_first.mel_filters
							snake_case_						:    Union[str, Any]				=  feat_extract_second.mel_filters
							self.assertTrue(np.allclose(__magic_name__					,							__magic_name__    )    )
							self.assertEqual(__magic_name__					,							__magic_name__    )






			def 			lowerCamelCase  (self    )     ->   Optional[Any]:


							'''simple docstring'''



							snake_case_						:    Optional[int]				=  self.feature_extraction_class(**self.feat_extract_dict    )

							with tempfile.TemporaryDirectory() as tmpdirname:
											snake_case_						:    List[Any]				=  os.path.join(__magic_name__					,							'''feat_extract.json'''    )
											feat_extract_first.to_json_file(__magic_name__    )
											snake_case_						:    Optional[int]				=  self.feature_extraction_class.from_json_file(__magic_name__    )

							snake_case_						:    int				=  feat_extract_first.to_dict()
							snake_case_						:    Optional[int]				=  feat_extract_second.to_dict()
							snake_case_						:    Union[str, Any]				=  feat_extract_first.mel_filters
							snake_case_						:    str				=  feat_extract_second.mel_filters
							self.assertTrue(np.allclose(__magic_name__					,							__magic_name__    )    )
							self.assertEqual(__magic_name__					,							__magic_name__    )






			def 			lowerCamelCase  (self    )     ->   int:


							'''simple docstring'''



							snake_case_						:    Optional[Any]				=  self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
							# create three inputs of length 800, 1000, and 1200
							snake_case_						:    Any				=  [floats_list((1, x)    )[0] for x in range(800					,							1400					,							200    )]
							snake_case_						:    str				=  [np.asarray(__magic_name__    ) for speech_input in speech_inputs]

							# Test feature size
							snake_case_						:    str				=  feature_extractor(__magic_name__					,							padding='''max_length'''					,							return_tensors='''np'''    ).input_features
							self.assertTrue(input_features.ndim == 3    )
							self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames    )
							self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size    )

							# Test not batched input
							snake_case_						:    Dict				=  feature_extractor(speech_inputs[0]					,							return_tensors='''np'''    ).input_features
							snake_case_						:    Optional[int]				=  feature_extractor(np_speech_inputs[0]					,							return_tensors='''np'''    ).input_features
							self.assertTrue(np.allclose(__magic_name__					,							__magic_name__					,							atol=1e-3    )    )

							# Test batched
							snake_case_						:    int				=  feature_extractor(__magic_name__					,							return_tensors='''np'''    ).input_features
							snake_case_						:    Union[str, Any]				=  feature_extractor(__magic_name__					,							return_tensors='''np'''    ).input_features
							for enc_seq_a, enc_seq_a in zip(__magic_name__					,							__magic_name__    ):
											self.assertTrue(np.allclose(__magic_name__					,							__magic_name__					,							atol=1e-3    )    )

							# Test 2-D numpy arrays are batched.
							snake_case_						:    Union[str, Any]				=  [floats_list((1, x)    )[0] for x in (800, 800, 800)]
							snake_case_						:    List[str]				=  np.asarray(__magic_name__    )
							snake_case_						:    List[Any]				=  feature_extractor(__magic_name__					,							return_tensors='''np'''    ).input_features
							snake_case_						:    Dict				=  feature_extractor(__magic_name__					,							return_tensors='''np'''    ).input_features
							for enc_seq_a, enc_seq_a in zip(__magic_name__					,							__magic_name__    ):
											self.assertTrue(np.allclose(__magic_name__					,							__magic_name__					,							atol=1e-3    )    )

							# Test truncation required
							snake_case_						:    Any				=  [floats_list((1, x)    )[0] for x in range(200					,							(feature_extractor.n_samples + 500)					,							200    )]
							snake_case_						:    Union[str, Any]				=  [np.asarray(__magic_name__    ) for speech_input in speech_inputs]

							snake_case_						:    Tuple				=  [x[: feature_extractor.n_samples] for x in speech_inputs]
							snake_case_						:    Optional[Any]				=  [np.asarray(__magic_name__    ) for speech_input in speech_inputs_truncated]

							snake_case_						:    Any				=  feature_extractor(__magic_name__					,							return_tensors='''np'''    ).input_features
							snake_case_						:    List[Any]				=  feature_extractor(__magic_name__					,							return_tensors='''np'''    ).input_features
							for enc_seq_a, enc_seq_a in zip(__magic_name__					,							__magic_name__    ):
											self.assertTrue(np.allclose(__magic_name__					,							__magic_name__					,							atol=1e-3    )    )






			def 			lowerCamelCase  (self    )     ->   int:


							'''simple docstring'''



							import torch

							snake_case_						:    str				=  self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
							snake_case_						:    Union[str, Any]				=  np.random.rand(100					,							32    ).astype(np.floataa    )
							snake_case_						:    Dict				=  np_speech_inputs.tolist()

							for inputs in [py_speech_inputs, np_speech_inputs]:
											snake_case_						:    Optional[Any]				=  feature_extractor.pad([{'''input_features''': inputs}]					,							return_tensors='''np'''    )
											self.assertTrue(np_processed.input_features.dtype == np.floataa    )
											snake_case_						:    Optional[Any]				=  feature_extractor.pad([{'''input_features''': inputs}]					,							return_tensors='''pt'''    )
											self.assertTrue(pt_processed.input_features.dtype == torch.floataa    )






			def 			lowerCamelCase  (self					,							__magic_name__    )     ->   Dict:


							'''simple docstring'''



							snake_case_						:    Optional[Any]				=  load_dataset('''hf-internal-testing/librispeech_asr_dummy'''					,							'''clean'''					,							split='''validation'''    )
							# automatic decoding with librispeech
							snake_case_						:    Optional[Any]				=  ds.sort('''id'''    ).select(range(__magic_name__    )    )[:num_samples]['''audio''']

							return [x["array"] for x in speech_samples]






			def 			lowerCamelCase  (self    )     ->   str:


							'''simple docstring'''



							snake_case_						:    str				=  torch.tensor(
							    [
							        0.1_193, -0.0_946, -0.1_098, -0.0_196, 0.0_225, -0.0_690, -0.1_736, 0.0_951,
							        0.0_971, -0.0_817, -0.0_702, 0.0_162, 0.0_260, 0.0_017, -0.0_192, -0.1_678,
							        0.0_709, -0.1_867, -0.0_655, -0.0_274, -0.0_234, -0.1_884, -0.0_516, -0.0_554,
							        -0.0_274, -0.1_425, -0.1_423, 0.0_837, 0.0_377, -0.0_854
							    ]    )
							# fmt: on

							snake_case_						:    List[Any]				=  self._load_datasamples(1    )
							snake_case_						:    Union[str, Any]				=  WhisperFeatureExtractor()
							snake_case_						:    Union[str, Any]				=  feature_extractor(__magic_name__					,							return_tensors='''pt'''    ).input_features
							self.assertEqual(input_features.shape					,							(1, 80, 3000)    )
							self.assertTrue(torch.allclose(input_features[0, 0, :30]					,							__magic_name__					,							atol=1e-4    )    )






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


							'''simple docstring'''



							snake_case_						:    Tuple				=  self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
							snake_case_						:    Optional[int]				=  self._load_datasamples(1    )[0]
							snake_case_						:    List[str]				=  ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535  # Rescale to [0, 65535] to show issue
							snake_case_						:    Optional[Any]				=  feat_extract.zero_mean_unit_var_norm([audio]					,							attention_mask=__magic_name__    )[0]

							self.assertTrue(np.all(np.mean(__magic_name__    ) < 1e-3    )    )
							self.assertTrue(np.all(np.abs(np.var(__magic_name__    ) - 1    ) < 1e-3    )    )
