'''simple docstring'''




import unittest

from parameterized import parameterized

from transformers import LlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer


class       UpperCAmelCase__  :






   """simple docstring"""
   def __init__(self       ,				_a       ,				_a=13       ,				_a=7       ,				_a=True       ,				_a=True       ,				_a=False       ,				_a=True       ,				_a=99       ,				_a=32       ,				_a=5       ,				_a=4       ,				_a=37       ,				_a="gelu"       ,				_a=0.1       ,				_a=0.1       ,				_a=512       ,				_a=16       ,				_a=2       ,				_a=0.02       ,				_a=3       ,				_a=4       ,				_a=None       ,				)    ->     str:
        lowercase_					:       List[str]     				=					parent
        lowercase_					:       int     				=					batch_size
        lowercase_					:       Any     				=					seq_length
        lowercase_					:       Tuple     				=					is_training
        lowercase_					:       Tuple     				=					use_input_mask
        lowercase_					:       str     				=					use_token_type_ids
        lowercase_					:       List[Any]     				=					use_labels
        lowercase_					:       int     				=					vocab_size
        lowercase_					:       Dict     				=					hidden_size
        lowercase_					:       int     				=					num_hidden_layers
        lowercase_					:       Tuple     				=					num_attention_heads
        lowercase_					:       Optional[Any]     				=					intermediate_size
        lowercase_					:       Dict     				=					hidden_act
        lowercase_					:       Optional[Any]     				=					hidden_dropout_prob
        lowercase_					:       Union[str, Any]     				=					attention_probs_dropout_prob
        lowercase_					:       Dict     				=					max_position_embeddings
        lowercase_					:       Tuple     				=					type_vocab_size
        lowercase_					:       int     				=					type_sequence_label_size
        lowercase_					:       Dict     				=					initializer_range
        lowercase_					:       Tuple     				=					num_labels
        lowercase_					:       Optional[int]     				=					num_choices
        lowercase_					:       List[str]     				=					scope
   def 		_lowerCamelCase (self				)    ->     str:
        lowercase_					:       Dict     				=					ids_tensor([self.batch_size, self.seq_length]       ,				self.vocab_size				)

        lowercase_					:       Any     				=					None
        if self.use_input_mask:
             lowercase_					:       int     				=					random_attention_mask([self.batch_size, self.seq_length]				)

        lowercase_					:       Tuple     				=					None
        if self.use_token_type_ids:
             lowercase_					:       str     				=					ids_tensor([self.batch_size, self.seq_length]       ,				self.type_vocab_size				)

        lowercase_					:       int     				=					None
        lowercase_					:       Optional[int]     				=					None
        lowercase_					:       Dict     				=					None
        if self.use_labels:
             lowercase_					:       Any     				=					ids_tensor([self.batch_size]       ,				self.type_sequence_label_size				)
             lowercase_					:       List[str]     				=					ids_tensor([self.batch_size, self.seq_length]       ,				self.num_labels				)
             lowercase_					:       int     				=					ids_tensor([self.batch_size]       ,				self.num_choices				)

        lowercase_					:       str     				=					self.get_config()

        return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
   def 		_lowerCamelCase (self				)    ->     List[str]:
        return LlamaConfig(
            vocab_size=self.vocab_size       ,				hidden_size=self.hidden_size       ,				num_hidden_layers=self.num_hidden_layers       ,				num_attention_heads=self.num_attention_heads       ,				intermediate_size=self.intermediate_size       ,				hidden_act=self.hidden_act       ,				hidden_dropout_prob=self.hidden_dropout_prob       ,				attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,				max_position_embeddings=self.max_position_embeddings       ,				type_vocab_size=self.type_vocab_size       ,				is_decoder=_a       ,				initializer_range=self.initializer_range       ,				)
   def 		_lowerCamelCase (self       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a				)    ->     Tuple:
        lowercase_					:       Any     				=					LlamaModel(config=_a				)
        model.to(_a				)
        model.eval()
        lowercase_					:       Any     				=					model(_a       ,				attention_mask=_a				)
        lowercase_					:       Optional[Any]     				=					model(_a				)
        self.parent.assertEqual(result.last_hidden_state.shape       ,				(self.batch_size, self.seq_length, self.hidden_size)				)
   def 		_lowerCamelCase (self       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				)    ->     str:
        lowercase_					:       Dict     				=					True
        lowercase_					:       Any     				=					LlamaModel(_a				)
        model.to(_a				)
        model.eval()
        lowercase_					:       List[Any]     				=					model(
            _a       ,				attention_mask=_a       ,				encoder_hidden_states=_a       ,				encoder_attention_mask=_a       ,				)
        lowercase_					:       List[str]     				=					model(
            _a       ,				attention_mask=_a       ,				encoder_hidden_states=_a       ,				)
        lowercase_					:       Tuple     				=					model(_a       ,				attention_mask=_a				)
        self.parent.assertEqual(result.last_hidden_state.shape       ,				(self.batch_size, self.seq_length, self.hidden_size)				)
   def 		_lowerCamelCase (self       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				)    ->     int:
        lowercase_					:       Any     				=					LlamaForCausalLM(config=_a				)
        model.to(_a				)
        model.eval()
        lowercase_					:       Any     				=					model(_a       ,				attention_mask=_a       ,				labels=_a				)
        self.parent.assertEqual(result.logits.shape       ,				(self.batch_size, self.seq_length, self.vocab_size)				)
   def 		_lowerCamelCase (self       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				)    ->     List[Any]:
        lowercase_					:       int     				=					True
        lowercase_					:       Dict     				=					True
        lowercase_					:       Optional[int]     				=					LlamaForCausalLM(config=_a				)
        model.to(_a				)
        model.eval()

        # first forward pass
        lowercase_					:       Union[str, Any]     				=					model(
            _a       ,				attention_mask=_a       ,				encoder_hidden_states=_a       ,				encoder_attention_mask=_a       ,				use_cache=_a       ,				)
        lowercase_					:       List[Any]     				=					outputs.past_key_values

        # create hypothetical multiple next token and extent to next_input_ids
        lowercase_					:       int     				=					ids_tensor((self.batch_size, 3)       ,				config.vocab_size				)
        lowercase_					:       Tuple     				=					ids_tensor((self.batch_size, 3)       ,				vocab_size=2				)

        # append to next input_ids and
        lowercase_					:       int     				=					torch.cat([input_ids, next_tokens]       ,				dim=-1				)
        lowercase_					:       Dict     				=					torch.cat([input_mask, next_mask]       ,				dim=-1				)

        lowercase_					:       int     				=					model(
            _a       ,				attention_mask=_a       ,				encoder_hidden_states=_a       ,				encoder_attention_mask=_a       ,				output_hidden_states=_a       ,				)['hidden_states'][0]
        lowercase_					:       Optional[int]     				=					model(
            _a       ,				attention_mask=_a       ,				encoder_hidden_states=_a       ,				encoder_attention_mask=_a       ,				past_key_values=_a       ,				output_hidden_states=_a       ,				)['hidden_states'][0]

        # select random slice
        lowercase_					:       Optional[int]     				=					ids_tensor((1,)       ,				output_from_past.shape[-1]				).item()
        lowercase_					:       str     				=					output_from_no_past[:, -3:, random_slice_idx].detach()
        lowercase_					:       Dict     				=					output_from_past[:, :, random_slice_idx].detach()

        self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]				)

        # test that outputs are equal for slice
        self.parent.assertTrue(torch.allclose(_a       ,				_a       ,				atol=1e-3				)				)





   def 		_lowerCamelCase (self				)    ->     Dict:
        lowercase_					:       Union[str, Any]     				=					self.prepare_config_and_inputs()
        (
            (
            lowercase_
        )				,(
            lowercase_
        )				,(
            lowercase_
        )				,(
            lowercase_
        )				,(
            lowercase_
        )				,(
            lowercase_
        )				,(
            lowercase_
        )				,
        )					:       Dict     				=					config_and_inputs
        lowercase_					:       Optional[Any]     				=					{'input_ids': input_ids, 'attention_mask': input_mask}
        return config, inputs_dict



@require_torch
class       UpperCAmelCase__  (       _snake_case					,     _snake_case					,     _snake_case					,     unittest.TestCase			):






   """simple docstring"""
   A							:       Union[str, Any]     =    (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else ()
   A							:       int     =    (LlamaForCausalLM,) if is_torch_available() else ()
   A							:       List[str]     =    (
       {
           '''feature-extraction''': LlamaModel,
           '''text-classification''': LlamaForSequenceClassification,
           '''text-generation''': LlamaForCausalLM,
           '''zero-shot''': LlamaForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   A							:       Tuple     =    False
   A							:       Dict     =    False
   def 		_lowerCamelCase (self				)    ->     Optional[int]:
        lowercase_					:       Optional[Any]     				=					LlamaModelTester(self				)
        lowercase_					:       str     				=					ConfigTester(self       ,				config_class=_a       ,				hidden_size=37				)
   def 		_lowerCamelCase (self				)    ->     Union[str, Any]:
        self.config_tester.run_common_tests()
   def 		_lowerCamelCase (self				)    ->     List[str]:
        lowercase_					:       Union[str, Any]     				=					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*_a				)
   def 		_lowerCamelCase (self				)    ->     Tuple:
        lowercase_					:       Optional[Any]     				=					self.model_tester.prepare_config_and_inputs()
        for type in ["absolute", "relative_key", "relative_key_query"]:
             lowercase_					:       Dict     				=					type
             self.model_tester.create_and_check_model(*_a				)
   def 		_lowerCamelCase (self				)    ->     Union[str, Any]:
        lowercase_				,lowercase_					:       Union[str, Any]     				=					self.model_tester.prepare_config_and_inputs_for_common()
        lowercase_					:       Dict     				=					3
        lowercase_					:       Optional[int]     				=					input_dict['input_ids']
        lowercase_					:       Tuple     				=					input_ids.ne(1				).to(_a				)
        lowercase_					:       int     				=					ids_tensor([self.model_tester.batch_size]       ,				self.model_tester.type_sequence_label_size				)
        lowercase_					:       Optional[int]     				=					LlamaForSequenceClassification(_a				)
        model.to(_a				)
        model.eval()
        lowercase_					:       Dict     				=					model(_a       ,				attention_mask=_a       ,				labels=_a				)
        self.assertEqual(result.logits.shape       ,				(self.model_tester.batch_size, self.model_tester.num_labels)				)
   def 		_lowerCamelCase (self				)    ->     Any:
        lowercase_				,lowercase_					:       Tuple     				=					self.model_tester.prepare_config_and_inputs_for_common()
        lowercase_					:       Optional[int]     				=					3
        lowercase_					:       Optional[int]     				=					'single_label_classification'
        lowercase_					:       Union[str, Any]     				=					input_dict['input_ids']
        lowercase_					:       Optional[int]     				=					input_ids.ne(1				).to(_a				)
        lowercase_					:       str     				=					ids_tensor([self.model_tester.batch_size]       ,				self.model_tester.type_sequence_label_size				)
        lowercase_					:       List[str]     				=					LlamaForSequenceClassification(_a				)
        model.to(_a				)
        model.eval()
        lowercase_					:       Optional[int]     				=					model(_a       ,				attention_mask=_a       ,				labels=_a				)
        self.assertEqual(result.logits.shape       ,				(self.model_tester.batch_size, self.model_tester.num_labels)				)
   def 		_lowerCamelCase (self				)    ->     int:
        lowercase_				,lowercase_					:       Optional[Any]     				=					self.model_tester.prepare_config_and_inputs_for_common()
        lowercase_					:       Dict     				=					3
        lowercase_					:       Dict     				=					'multi_label_classification'
        lowercase_					:       List[Any]     				=					input_dict['input_ids']
        lowercase_					:       Any     				=					input_ids.ne(1				).to(_a				)
        lowercase_					:       Optional[int]     				=					ids_tensor(
            [self.model_tester.batch_size, config.num_labels]       ,				self.model_tester.type_sequence_label_size				).to(torch.float				)
        lowercase_					:       Union[str, Any]     				=					LlamaForSequenceClassification(_a				)
        model.to(_a				)
        model.eval()
        lowercase_					:       List[Any]     				=					model(_a       ,				attention_mask=_a       ,				labels=_a				)
        self.assertEqual(result.logits.shape       ,				(self.model_tester.batch_size, self.model_tester.num_labels)				)
   @unittest.skip('LLaMA buffers include complex numbers, which breaks this test'				)
   def 		_lowerCamelCase (self				)    ->     Union[str, Any]:
        pass





   @parameterized.expand([('linear',), ('dynamic',)]				)
   def 		_lowerCamelCase (self       ,				_a				)    ->     Tuple:
        lowercase_				,lowercase_					:       List[str]     				=					self.model_tester.prepare_config_and_inputs_for_common()
        lowercase_					:       Union[str, Any]     				=					ids_tensor([1, 10]       ,				config.vocab_size				)
        lowercase_					:       Optional[int]     				=					ids_tensor([1, int(config.max_position_embeddings * 1.5				)]       ,				config.vocab_size				)

        set_seed(42				)  # Fixed seed at init time so the two models get the same random weights
        lowercase_					:       Tuple     				=					LlamaModel(_a				)
        original_model.to(_a				)
        original_model.eval()
        lowercase_					:       Optional[Any]     				=					original_model(_a				).last_hidden_state
        lowercase_					:       int     				=					original_model(_a				).last_hidden_state

        set_seed(42				)  # Fixed seed at init time so the two models get the same random weights
        lowercase_					:       List[Any]     				=					{'type': scaling_type, 'factor': 10.0}
        lowercase_					:       List[Any]     				=					LlamaModel(_a				)
        scaled_model.to(_a				)
        scaled_model.eval()
        lowercase_					:       Dict     				=					scaled_model(_a				).last_hidden_state
        lowercase_					:       Any     				=					scaled_model(_a				).last_hidden_state

        # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
        # maximum sequence length, so the outputs for the short input should match.
        if scaling_type == "dynamic":
             self.assertTrue(torch.allclose(_a       ,				_a       ,				atol=1e-5				)				)
        else:
             self.assertFalse(torch.allclose(_a       ,				_a       ,				atol=1e-5				)				)

        # The output should be different for long inputs
        self.assertFalse(torch.allclose(_a       ,				_a       ,				atol=1e-5				)				)



@require_torch
class       UpperCAmelCase__  (       unittest.TestCase			):






   """simple docstring"""
   @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!'				)
   @slow
   def 		_lowerCamelCase (self				)    ->     List[str]:
        lowercase_					:       int     				=					[1, 306, 4_658, 278, 6_593, 310, 2_834, 338]
        lowercase_					:       List[str]     				=					LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf'       ,				device_map='auto'				)
        lowercase_					:       int     				=					model(torch.tensor([input_ids]				)				)
        # Expected mean on dim = -1
        lowercase_					:       List[str]     				=					torch.tensor([[-6.65_50, -4.12_27, -4.98_59, -3.24_06, 0.82_62, -3.00_33, 1.29_64, -3.36_99]]				)
        torch.testing.assert_close(out.mean(-1				)       ,				_a       ,				atol=1e-2       ,				rtol=1e-2				)
        # slicing logits[0, 0, 0:30]
        # fmt: off
        lowercase_					:       Union[str, Any]     				=					torch.tensor([-12.82_81, -7.44_53, -0.46_39, -8.06_25, -7.25_00, -8.00_00, -6.48_83, -7.76_95, -7.84_38, -7.03_12, -6.21_88, -7.13_28, -1.84_96, 1.99_61, -8.62_50, -6.72_27, -12.82_81, -6.94_92, -7.07_42, -7.78_52, -7.58_20, -7.90_62, -6.93_75, -7.98_05, -8.34_38, -8.15_62, -8.04_69, -7.62_50, -7.74_22, -7.33_98,]				)
        # fmt: on
        torch.testing.assert_close(out[0, 0, :30]       ,				_a       ,				atol=1e-5       ,				rtol=1e-5				)
   @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!'				)
   @slow
   def 		_lowerCamelCase (self				)    ->     Dict:
        lowercase_					:       Tuple     				=					[1, 306, 4_658, 278, 6_593, 310, 2_834, 338]
        lowercase_					:       List[Any]     				=					LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf'       ,				device_map='auto'				)
        lowercase_					:       Tuple     				=					model(torch.tensor(_a				)				)
        # Expected mean on dim = -1
        lowercase_					:       Optional[Any]     				=					torch.tensor([[-2.06_22, -1.27_94, -1.16_38, -0.97_88, -1.46_03, -1.02_38, -1.78_93, -1.44_11]]				)
        torch.testing.assert_close(out.mean(-1				)       ,				_a       ,				atol=1e-2       ,				rtol=1e-2				)
        # slicing logits[0, 0, 0:30]
        # fmt: off
        lowercase_					:       Any     				=					torch.tensor([-8.14_06, -8.05_47, 2.74_61, -1.23_44, -0.14_48, -1.82_62, -1.00_20, -1.81_54, -1.68_95, -1.85_16, -2.35_74, -0.92_77, 3.75_98, 6.57_42, -1.29_98, -0.11_77, -8.14_06, -2.96_88, -2.91_99, -3.16_99, -3.52_54, -2.35_55, -2.79_88, -3.41_41, -2.82_62, -4.51_95, -3.33_79, -3.31_64, -2.78_32, -3.02_73]				)
        # fmt: on
        torch.testing.assert_close(out[0, 0, :30]       ,				_a       ,				atol=1e-5       ,				rtol=1e-5				)
   @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!'				)
   @slow
   def 		_lowerCamelCase (self				)    ->     Optional[Any]:
        lowercase_					:       Optional[int]     				=					[1, 306, 4_658, 278, 6_593, 310, 2_834, 338]
        lowercase_					:       Union[str, Any]     				=					LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf'       ,				device_map='auto'				)
        lowercase_					:       Optional[Any]     				=					model(torch.tensor(_a				)				)
        # Expected mean on dim = -1
        lowercase_					:       str     				=					torch.tensor([[-0.85_62, -1.85_20, -0.75_51, -0.41_62, -1.51_61, -1.20_38, -2.48_23, -2.32_54]]				)
        torch.testing.assert_close(out.mean(-1				)       ,				_a       ,				atol=1e-2       ,				rtol=1e-2				)
        # slicing logits[0, 0, 0:30]
        # fmt: off
        lowercase_					:       Dict     				=					torch.tensor([-2.22_27, 4.88_28, 0.90_23, -0.45_78, -0.78_71, -0.10_33, -0.62_21, -0.57_86, -0.78_03, -1.06_74, -1.29_20, -0.15_70, 0.80_08, 2.07_23, -0.94_97, 0.27_71, -2.22_27, -0.76_12, -1.43_46, -1.20_61, -1.64_26, -0.30_00, -0.71_39, -1.19_34, -1.86_91, -1.69_73, -1.59_47, -1.27_05, -0.35_23, -0.55_13]				)
        # fmt: on
        torch.testing.assert_close(out.mean(-1				)       ,				_a       ,				atol=1e-2       ,				rtol=1e-2				)
   @unittest.skip(
       'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test'				)
   @slow
   def 		_lowerCamelCase (self				)    ->     Optional[Any]:
        lowercase_					:       Union[str, Any]     				=					[1, 306, 4_658, 278, 6_593, 310, 2_834, 338]
        lowercase_					:       Any     				=					LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf'       ,				device_map='auto'				)
        lowercase_					:       Any     				=					model(torch.tensor(_a				)				)

        lowercase_					:       Union[str, Any]     				=					torch.tensor(
            [[-4.23_27, -3.33_60, -4.66_65, -4.76_31, -1.81_80, -3.41_70, -1.42_11, -3.18_10]]       ,				dtype=torch.floataa				)
        torch.testing.assert_close(out.mean(-1				)       ,				_a       ,				atol=1e-2       ,				rtol=1e-2				)
        # fmt: off
        lowercase_					:       Tuple     				=					torch.tensor([-9.49_22, -3.95_51, 1.79_98, -5.67_58, -5.10_55, -5.89_84, -4.83_20, -6.80_86, -6.53_91, -5.61_72, -5.58_20, -5.53_52, 1.78_81, 3.62_89, -6.51_17, -3.47_85, -9.50_00, -6.03_52, -6.81_25, -6.01_95, -6.68_36, -5.47_27, -6.28_12, -6.03_91, -7.33_98, -7.42_97, -7.48_44, -6.58_20, -5.87_89, -5.53_12]				)
        # fmt: on
        torch.testing.assert_close(out[0, 0, :30]       ,				_a       ,				atol=1e-5       ,				rtol=1e-5				)





   @unittest.skip('Model is curently gated'				)
   @slow
   def 		_lowerCamelCase (self				)    ->     List[str]:
        lowercase_					:       Optional[Any]     				=					'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi'
        lowercase_					:       List[Any]     				=					'Simply put, the theory of relativity states that '
        lowercase_					:       str     				=					LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf'				)
        lowercase_					:       str     				=					tokenizer.encode(_a       ,				return_tensors='pt'				)
        lowercase_					:       List[str]     				=					LlamaForCausalLM.from_pretrained(
            'meta-llama/Llama-2-13b-chat-hf'       ,				device_map='sequential'       ,				use_safetensors=_a				)

        # greedy generation outputs
        lowercase_					:       Optional[Any]     				=					model.generate(_a       ,				max_new_tokens=64       ,				top_p=_a       ,				temperature=1       ,				do_sample=_a				)
        lowercase_					:       Optional[int]     				=					tokenizer.decode(generated_ids[0]       ,				skip_special_tokens=_a				)
        self.assertEqual(_a       ,				_a				)





'''simple docstring'''




import numpy as np

from transformers import BatchFeature
from transformers.testing_utils import require_tf, require_torch

from .test_feature_extraction_common import FeatureExtractionSavingTestMixin


class       UpperCAmelCase__  (       _snake_case			):






   """simple docstring"""
   # to overwrite at feature extractactor specific tests
   A							:       List[str]     =    None
   A							:       Tuple     =    None
   @property
   def 		_lowerCamelCase (self				)    ->     Any:
        return self.feat_extract_tester.prepare_feat_extract_dict()
   def 		_lowerCamelCase (self				)    ->     str:
        lowercase_					:       Dict     				=					self.feature_extraction_class(**self.feat_extract_dict				)
        self.assertTrue(hasattr(_a       ,				'feature_size'				)				)
        self.assertTrue(hasattr(_a       ,				'sampling_rate'				)				)
        self.assertTrue(hasattr(_a       ,				'padding_value'				)				)
   def 		_lowerCamelCase (self				)    ->     Dict:
        lowercase_					:       List[str]     				=					self.feat_extract_tester.prepare_inputs_for_common()
        lowercase_					:       Union[str, Any]     				=					self.feature_extraction_class(**self.feat_extract_dict				)
        lowercase_					:       Union[str, Any]     				=					feat_extract.model_input_names[0]

        lowercase_					:       Union[str, Any]     				=					BatchFeature({input_name: speech_inputs}				)

        self.assertTrue(all(len(_a				) == len(_a				) for x, y in zip(_a       ,				processed_features[input_name]				)				)				)

        lowercase_					:       Optional[int]     				=					self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a				)
        lowercase_					:       Tuple     				=					BatchFeature({input_name: speech_inputs}       ,				tensor_type='np'				)

        lowercase_					:       Dict     				=					processed_features[input_name]

        if len(batch_features_input.shape				) < 3:
             lowercase_					:       Optional[Any]     				=					batch_features_input[:, :, None]

        self.assertTrue(
            batch_features_input.shape
            == (self.feat_extract_tester.batch_size, len(speech_inputs[0]				), self.feat_extract_tester.feature_size)				)
   @require_torch
   def 		_lowerCamelCase (self				)    ->     Tuple:
        lowercase_					:       List[Any]     				=					self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a				)
        lowercase_					:       Any     				=					self.feature_extraction_class(**self.feat_extract_dict				)
        lowercase_					:       int     				=					feat_extract.model_input_names[0]

        lowercase_					:       Union[str, Any]     				=					BatchFeature({input_name: speech_inputs}       ,				tensor_type='pt'				)

        lowercase_					:       Tuple     				=					processed_features[input_name]

        if len(batch_features_input.shape				) < 3:
             lowercase_					:       List[str]     				=					batch_features_input[:, :, None]

        self.assertTrue(
            batch_features_input.shape
            == (self.feat_extract_tester.batch_size, len(speech_inputs[0]				), self.feat_extract_tester.feature_size)				)
   @require_tf
   def 		_lowerCamelCase (self				)    ->     Union[str, Any]:
        lowercase_					:       List[Any]     				=					self.feat_extract_tester.prepare_inputs_for_common(equal_length=_a				)
        lowercase_					:       int     				=					self.feature_extraction_class(**self.feat_extract_dict				)
        lowercase_					:       Dict     				=					feat_extract.model_input_names[0]

        lowercase_					:       List[Any]     				=					BatchFeature({input_name: speech_inputs}       ,				tensor_type='tf'				)

        lowercase_					:       int     				=					processed_features[input_name]

        if len(batch_features_input.shape				) < 3:
             lowercase_					:       Union[str, Any]     				=					batch_features_input[:, :, None]

        self.assertTrue(
            batch_features_input.shape
            == (self.feat_extract_tester.batch_size, len(speech_inputs[0]				), self.feat_extract_tester.feature_size)				)
   def 		_lowerCamelCase (self       ,				_a=False				)    ->     Union[str, Any]:
        def _inputs_have_equal_length(_a				):
             lowercase_					:       Optional[Any]     				=					len(input[0]				)
             for input_slice in input[1:]:
                  if len(_a				) != length:
                       return False
             return True

        def _inputs_are_equal(_a       ,				_a				):
             if len(_a				) != len(_a				):
                  return False

             for input_slice_a, input_slice_a in zip(_a       ,				_a				):
                  if not np.allclose(np.asarray(_a				)       ,				np.asarray(_a				)       ,				atol=1e-3				):
                       return False
             return True

        lowercase_					:       int     				=					self.feature_extraction_class(**self.feat_extract_dict				)
        lowercase_					:       str     				=					self.feat_extract_tester.prepare_inputs_for_common(numpify=_a				)
        lowercase_					:       Union[str, Any]     				=					feat_extract.model_input_names[0]

        lowercase_					:       Union[str, Any]     				=					BatchFeature({input_name: speech_inputs}				)

        lowercase_					:       Optional[Any]     				=					self.feat_extract_tester.seq_length_diff
        lowercase_					:       Union[str, Any]     				=					self.feat_extract_tester.max_seq_length + pad_diff
        lowercase_					:       str     				=					self.feat_extract_tester.min_seq_length
        lowercase_					:       Optional[Any]     				=					self.feat_extract_tester.batch_size
        lowercase_					:       Any     				=					self.feat_extract_tester.feature_size

        # test padding for List[int] + numpy
        lowercase_					:       List[str]     				=					feat_extract.pad(_a       ,				padding=_a				)
        lowercase_					:       Any     				=					input_a[input_name]

        lowercase_					:       str     				=					feat_extract.pad(_a       ,				padding='longest'				)
        lowercase_					:       List[str]     				=					input_a[input_name]

        lowercase_					:       Dict     				=					feat_extract.pad(_a       ,				padding='max_length'       ,				max_length=len(speech_inputs[-1]				)				)
        lowercase_					:       Any     				=					input_a[input_name]

        lowercase_					:       Any     				=					feat_extract.pad(_a       ,				padding='longest'       ,				return_tensors='np'				)
        lowercase_					:       str     				=					input_a[input_name]

        # max_length parameter has to be provided when setting `padding="max_length"`
        with self.assertRaises(_a				):
             feat_extract.pad(_a       ,				padding='max_length'				)[input_name]

        lowercase_					:       Union[str, Any]     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=_a       ,				return_tensors='np'				)
        lowercase_					:       Any     				=					input_a[input_name]

        self.assertFalse(_inputs_have_equal_length(_a				)				)
        self.assertTrue(_inputs_have_equal_length(_a				)				)
        self.assertTrue(_inputs_have_equal_length(_a				)				)
        self.assertTrue(_inputs_are_equal(_a       ,				_a				)				)
        self.assertTrue(len(input_a[0]				) == pad_min_length				)
        self.assertTrue(len(input_a[1]				) == pad_min_length + pad_diff				)
        self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0]				))				)
        self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length)				)

        if feature_size > 1:
             self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size				)

        # test padding for `pad_to_multiple_of` for List[int] + numpy
        lowercase_					:       Tuple     				=					feat_extract.pad(_a       ,				pad_to_multiple_of=10				)
        lowercase_					:       Dict     				=					input_a[input_name]

        lowercase_					:       int     				=					feat_extract.pad(_a       ,				padding='longest'       ,				pad_to_multiple_of=10				)
        lowercase_					:       Union[str, Any]     				=					input_a[input_name]

        lowercase_					:       Optional[int]     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				pad_to_multiple_of=10       ,				max_length=_a				)
        lowercase_					:       Tuple     				=					input_a[input_name]

        lowercase_					:       Optional[int]     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				pad_to_multiple_of=10       ,				max_length=_a       ,				return_tensors='np'       ,				)
        lowercase_					:       Union[str, Any]     				=					input_a[input_name]

        self.assertTrue(all(len(_a				) % 10 == 0 for x in input_a				)				)
        self.assertTrue(_inputs_are_equal(_a       ,				_a				)				)

        lowercase_					:       str     				=					pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10
        self.assertTrue(all(len(_a				) == expected_mult_pad_length for x in input_a				)				)
        self.assertEqual(input_a.shape[:2]       ,				(batch_size, expected_mult_pad_length)				)

        if feature_size > 1:
             self.assertTrue(input_a.shape[2] == feature_size				)

        # Check padding value is correct
        lowercase_					:       Optional[int]     				=					(np.ones(self.feat_extract_tester.feature_size				) * feat_extract.padding_value).sum()
        self.assertTrue(
            abs(np.asarray(input_a[0]				)[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length)				)
            < 1e-3				)
        self.assertTrue(
            abs(
                np.asarray(input_a[1]				)[pad_min_length + pad_diff :].sum()
                - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff)				)
            < 1e-3				)
        self.assertTrue(
            abs(
                np.asarray(input_a[2]				)[pad_min_length + 2 * pad_diff :].sum()
                - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff)				)
            < 1e-3				)
        self.assertTrue(
            abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length)				) < 1e-3				)
        self.assertTrue(
            abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length)				)
            < 1e-3				)
   def 		_lowerCamelCase (self       ,				_a=False				)    ->     Union[str, Any]:
        def _inputs_have_equal_length(_a				):
             lowercase_					:       str     				=					len(input[0]				)
             for input_slice in input[1:]:
                  if len(_a				) != length:
                       return False
             return True

        def _inputs_are_equal(_a       ,				_a				):
             if len(_a				) != len(_a				):
                  return False

             for input_slice_a, input_slice_a in zip(_a       ,				_a				):
                  if not np.allclose(np.asarray(_a				)       ,				np.asarray(_a				)       ,				atol=1e-3				):
                       return False
             return True

        lowercase_					:       Any     				=					self.feature_extraction_class(**self.feat_extract_dict				)
        lowercase_					:       List[Any]     				=					self.feat_extract_tester.prepare_inputs_for_common(numpify=_a				)
        lowercase_					:       List[str]     				=					feat_extract.model_input_names[0]

        lowercase_					:       str     				=					BatchFeature({input_name: speech_inputs}				)

        # truncate to smallest
        lowercase_					:       Union[str, Any]     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=len(speech_inputs[0]				)       ,				truncation=_a				)
        lowercase_					:       List[str]     				=					input_a[input_name]

        lowercase_					:       Optional[int]     				=					feat_extract.pad(_a       ,				padding='max_length'       ,				max_length=len(speech_inputs[0]				)				)
        lowercase_					:       Union[str, Any]     				=					input_a[input_name]

        self.assertTrue(_inputs_have_equal_length(_a				)				)
        self.assertFalse(_inputs_have_equal_length(_a				)				)

        # truncate to smallest with np
        lowercase_					:       List[str]     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=len(speech_inputs[0]				)       ,				return_tensors='np'       ,				truncation=_a       ,				)
        lowercase_					:       List[str]     				=					input_a[input_name]

        lowercase_					:       List[Any]     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=len(speech_inputs[0]				)       ,				return_tensors='np'				)
        lowercase_					:       List[Any]     				=					input_a[input_name]

        self.assertTrue(_inputs_have_equal_length(_a				)				)
        self.assertTrue(input_a.shape[1] == len(speech_inputs[0]				)				)

        # since truncation forces padding to be smaller than longest input
        # function can't return `np.ndarray`, but has to return list
        self.assertFalse(_inputs_have_equal_length(_a				)				)

        # truncate to middle
        lowercase_					:       int     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=len(speech_inputs[1]				)       ,				truncation=_a       ,				return_tensors='np'       ,				)
        lowercase_					:       Union[str, Any]     				=					input_a[input_name]

        lowercase_					:       str     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=len(speech_inputs[1]				)       ,				truncation=_a				)
        lowercase_					:       int     				=					input_a[input_name]

        lowercase_					:       Dict     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=len(speech_inputs[1]				)       ,				return_tensors='np'				)
        lowercase_					:       Optional[int]     				=					input_a[input_name]

        self.assertTrue(input_a.shape[1] == len(speech_inputs[1]				)				)
        self.assertTrue(_inputs_have_equal_length(_a				)				)
        self.assertTrue(_inputs_have_equal_length(_a				)				)
        self.assertTrue(_inputs_are_equal(_a       ,				_a				)				)

        # since truncation forces padding to be smaller than longest input
        # function can't return `np.ndarray`, but has to return list
        self.assertFalse(_inputs_have_equal_length(_a				)				)
        self.assertTrue(len(input_a[-1]				) == len(speech_inputs[-1]				)				)

        # padding has to be max_length when setting `truncation=True`
        with self.assertRaises(_a				):
             feat_extract.pad(_a       ,				truncation=_a				)[input_name]

        # padding has to be max_length when setting `truncation=True`
        with self.assertRaises(_a				):
             feat_extract.pad(_a       ,				padding='longest'       ,				truncation=_a				)[input_name]

        # padding has to be max_length when setting `truncation=True`
        with self.assertRaises(_a				):
             feat_extract.pad(_a       ,				padding='longest'       ,				truncation=_a				)[input_name]

        # max_length parameter has to be provided when setting `truncation=True` and padding="max_length"
        with self.assertRaises(_a				):
             feat_extract.pad(_a       ,				padding='max_length'       ,				truncation=_a				)[input_name]

        # test truncation for `pad_to_multiple_of` for List[int] + numpy
        lowercase_					:       str     				=					12
        lowercase_					:       List[Any]     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=len(speech_inputs[0]				)       ,				pad_to_multiple_of=_a       ,				truncation=_a       ,				)
        lowercase_					:       Any     				=					input_a[input_name]

        lowercase_					:       List[Any]     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=len(speech_inputs[0]				)       ,				pad_to_multiple_of=_a       ,				)
        lowercase_					:       str     				=					input_a[input_name]

        # retrieve expected_length as multiple of pad_to_multiple_of
        lowercase_					:       Dict     				=					len(speech_inputs[0]				)
        if expected_length % pad_to_multiple_of != 0:
             lowercase_					:       List[Any]     				=					((len(speech_inputs[0]				) // pad_to_multiple_of) + 1) * pad_to_multiple_of

        self.assertTrue(len(input_a[0]				) == expected_length				)
        self.assertTrue(_inputs_have_equal_length(_a				)				)
        self.assertFalse(_inputs_have_equal_length(_a				)				)
   def 		_lowerCamelCase (self				)    ->     str:
        self._check_padding(numpify=_a				)
   def 		_lowerCamelCase (self				)    ->     Optional[int]:
        self._check_padding(numpify=_a				)
   def 		_lowerCamelCase (self				)    ->     Any:
        self._check_truncation(numpify=_a				)
   def 		_lowerCamelCase (self				)    ->     Any:
        self._check_truncation(numpify=_a				)
   @require_torch
   def 		_lowerCamelCase (self				)    ->     int:
        lowercase_					:       Tuple     				=					self.feature_extraction_class(**self.feat_extract_dict				)
        lowercase_					:       List[Any]     				=					self.feat_extract_tester.prepare_inputs_for_common()
        lowercase_					:       Optional[Any]     				=					feat_extract.model_input_names[0]

        lowercase_					:       Dict     				=					BatchFeature({input_name: speech_inputs}				)

        lowercase_					:       Tuple     				=					feat_extract.pad(_a       ,				padding='longest'       ,				return_tensors='np'				)[input_name]
        lowercase_					:       List[Any]     				=					feat_extract.pad(_a       ,				padding='longest'       ,				return_tensors='pt'				)[input_name]

        self.assertTrue(abs(input_np.astype(np.floataa				).sum() - input_pt.numpy().astype(np.floataa				).sum()				) < 1e-2				)
   @require_tf
   def 		_lowerCamelCase (self				)    ->     List[Any]:
        lowercase_					:       Any     				=					self.feature_extraction_class(**self.feat_extract_dict				)
        lowercase_					:       Optional[int]     				=					self.feat_extract_tester.prepare_inputs_for_common()
        lowercase_					:       List[Any]     				=					feat_extract.model_input_names[0]

        lowercase_					:       Tuple     				=					BatchFeature({input_name: speech_inputs}				)

        lowercase_					:       List[Any]     				=					feat_extract.pad(_a       ,				padding='longest'       ,				return_tensors='np'				)[input_name]
        lowercase_					:       Optional[int]     				=					feat_extract.pad(_a       ,				padding='longest'       ,				return_tensors='tf'				)[input_name]

        self.assertTrue(abs(input_np.astype(np.floataa				).sum() - input_tf.numpy().astype(np.floataa				).sum()				) < 1e-2				)
   def 		_lowerCamelCase (self				)    ->     List[str]:
        lowercase_					:       Any     				=					self.feat_extract_dict
        lowercase_					:       List[Any]     				=					True
        lowercase_					:       Tuple     				=					self.feature_extraction_class(**_a				)
        lowercase_					:       Optional[Any]     				=					self.feat_extract_tester.prepare_inputs_for_common()
        lowercase_					:       str     				=					[len(_a				) for x in speech_inputs]
        lowercase_					:       Union[str, Any]     				=					feat_extract.model_input_names[0]

        lowercase_					:       List[Any]     				=					BatchFeature({input_name: speech_inputs}				)

        lowercase_					:       str     				=					feat_extract.pad(_a       ,				padding='longest'       ,				return_tensors='np'				)
        self.assertIn('attention_mask'       ,				_a				)
        self.assertListEqual(list(processed.attention_mask.shape				)       ,				list(processed[input_name].shape[:2]				)				)
        self.assertListEqual(processed.attention_mask.sum(-1				).tolist()       ,				_a				)





   def 		_lowerCamelCase (self				)    ->     List[Any]:
        lowercase_					:       Union[str, Any]     				=					self.feat_extract_dict
        lowercase_					:       List[Any]     				=					True
        lowercase_					:       List[Any]     				=					self.feature_extraction_class(**_a				)
        lowercase_					:       List[Any]     				=					self.feat_extract_tester.prepare_inputs_for_common()
        lowercase_					:       Optional[int]     				=					[len(_a				) for x in speech_inputs]
        lowercase_					:       int     				=					feat_extract.model_input_names[0]

        lowercase_					:       Tuple     				=					BatchFeature({input_name: speech_inputs}				)
        lowercase_					:       Optional[Any]     				=					min(_a				)

        lowercase_					:       int     				=					feat_extract.pad(
            _a       ,				padding='max_length'       ,				max_length=_a       ,				truncation=_a       ,				return_tensors='np'				)
        self.assertIn('attention_mask'       ,				_a				)
        self.assertListEqual(
            list(processed_pad.attention_mask.shape				)       ,				[processed_pad[input_name].shape[0], max_length]				)
        self.assertListEqual(
            processed_pad.attention_mask[:, :max_length].sum(-1				).tolist()       ,				[max_length for x in speech_inputs]				)




