





'''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 __a			:





   def __init__(       self					:      Dict					,lowerCamelCase					:      str					,lowerCamelCase					:      Dict=13					,lowerCamelCase					:      Dict=7					,lowerCamelCase					:      int=True					,lowerCamelCase					:      Tuple=True					,lowerCamelCase					:      List[Any]=False					,lowerCamelCase					:      List[str]=True					,lowerCamelCase					:      List[str]=99					,lowerCamelCase					:      Optional[int]=32					,lowerCamelCase					:      Any=5					,lowerCamelCase					:      Any=4					,lowerCamelCase					:      Union[str, Any]=37					,lowerCamelCase					:      Optional[int]="gelu"					,lowerCamelCase					:      Tuple=0.1					,lowerCamelCase					:      Union[str, Any]=0.1					,lowerCamelCase					:      Optional[int]=512					,lowerCamelCase					:      Dict=16					,lowerCamelCase					:      Dict=2					,lowerCamelCase					:      str=0.02					,lowerCamelCase					:      Optional[int]=3					,lowerCamelCase					:      str=4					,lowerCamelCase					:      Tuple=None					,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							parent
      __SCREAMING_SNAKE_CASE   				=							batch_size
      __SCREAMING_SNAKE_CASE   				=							seq_length
      __SCREAMING_SNAKE_CASE   				=							is_training
      __SCREAMING_SNAKE_CASE   				=							use_input_mask
      __SCREAMING_SNAKE_CASE   				=							use_token_type_ids
      __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   				=							type_vocab_size
      __SCREAMING_SNAKE_CASE   				=							type_sequence_label_size
      __SCREAMING_SNAKE_CASE   				=							initializer_range
      __SCREAMING_SNAKE_CASE   				=							num_labels
      __SCREAMING_SNAKE_CASE   				=							num_choices
      __SCREAMING_SNAKE_CASE   				=							scope





   def   UpperCAmelCase__  (       self					:      str     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							ids_tensor([self.batch_size, self.seq_length]					,self.vocab_size     )

      __SCREAMING_SNAKE_CASE   				=							None
      if self.use_input_mask:
         __SCREAMING_SNAKE_CASE   				=							random_attention_mask([self.batch_size, self.seq_length]     )

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

      __SCREAMING_SNAKE_CASE   				=							None
      __SCREAMING_SNAKE_CASE   				=							None
      __SCREAMING_SNAKE_CASE   				=							None
      if self.use_labels:
         __SCREAMING_SNAKE_CASE   				=							ids_tensor([self.batch_size]					,self.type_sequence_label_size     )
         __SCREAMING_SNAKE_CASE   				=							ids_tensor([self.batch_size, self.seq_length]					,self.num_labels     )
         __SCREAMING_SNAKE_CASE   				=							ids_tensor([self.batch_size]					,self.num_choices     )

      __SCREAMING_SNAKE_CASE   				=							self.get_config()

      return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels





   def   UpperCAmelCase__  (       self					:      Optional[Any]     ):

      '''simple docstring'''

      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=lowerCamelCase					,initializer_range=self.initializer_range					,)





   def   UpperCAmelCase__  (       self					:      Optional[Any]					,lowerCamelCase					:      List[Any]					,lowerCamelCase					:      Dict					,lowerCamelCase					:      str					,lowerCamelCase					:      List[Any]					,lowerCamelCase					:      Dict					,lowerCamelCase					:      Union[str, Any]					,lowerCamelCase					:      str     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							LlamaModel(config=lowerCamelCase     )
      model.to(lowerCamelCase     )
      model.eval()
      __SCREAMING_SNAKE_CASE   				=							model(lowerCamelCase					,attention_mask=lowerCamelCase     )
      __SCREAMING_SNAKE_CASE   				=							model(lowerCamelCase     )
      self.parent.assertEqual(result.last_hidden_state.shape					,(self.batch_size, self.seq_length, self.hidden_size)     )





   def   UpperCAmelCase__  (       self					:      List[str]					,lowerCamelCase					:      List[str]					,lowerCamelCase					:      Any					,lowerCamelCase					:      List[Any]					,lowerCamelCase					:      Optional[Any]					,lowerCamelCase					:      Tuple					,lowerCamelCase					:      Tuple					,lowerCamelCase					:      Union[str, Any]					,lowerCamelCase					:      List[Any]					,lowerCamelCase					:      List[str]					,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							True
      __SCREAMING_SNAKE_CASE   				=							LlamaModel(lowerCamelCase     )
      model.to(lowerCamelCase     )
      model.eval()
      __SCREAMING_SNAKE_CASE   				=							model(
          lowerCamelCase					,attention_mask=lowerCamelCase					,encoder_hidden_states=lowerCamelCase					,encoder_attention_mask=lowerCamelCase					,)
      __SCREAMING_SNAKE_CASE   				=							model(
          lowerCamelCase					,attention_mask=lowerCamelCase					,encoder_hidden_states=lowerCamelCase					,)
      __SCREAMING_SNAKE_CASE   				=							model(lowerCamelCase					,attention_mask=lowerCamelCase     )
      self.parent.assertEqual(result.last_hidden_state.shape					,(self.batch_size, self.seq_length, self.hidden_size)     )





   def   UpperCAmelCase__  (       self					:      Tuple					,lowerCamelCase					:      Dict					,lowerCamelCase					:      Any					,lowerCamelCase					:      Tuple					,lowerCamelCase					:      Any					,lowerCamelCase					:      Tuple					,lowerCamelCase					:      Union[str, Any]					,lowerCamelCase					:      Dict					,lowerCamelCase					:      Optional[Any]					,lowerCamelCase					:      List[str]					,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							LlamaForCausalLM(config=lowerCamelCase     )
      model.to(lowerCamelCase     )
      model.eval()
      __SCREAMING_SNAKE_CASE   				=							model(lowerCamelCase					,attention_mask=lowerCamelCase					,labels=lowerCamelCase     )
      self.parent.assertEqual(result.logits.shape					,(self.batch_size, self.seq_length, self.vocab_size)     )





   def   UpperCAmelCase__  (       self					:      Union[str, Any]					,lowerCamelCase					:      Dict					,lowerCamelCase					:      Optional[Any]					,lowerCamelCase					:      Tuple					,lowerCamelCase					:      Any					,lowerCamelCase					:      List[Any]					,lowerCamelCase					:      Dict					,lowerCamelCase					:      str					,lowerCamelCase					:      Optional[Any]					,lowerCamelCase					:      List[Any]					,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							True
      __SCREAMING_SNAKE_CASE   				=							True
      __SCREAMING_SNAKE_CASE   				=							LlamaForCausalLM(config=lowerCamelCase     )
      model.to(lowerCamelCase     )
      model.eval()

      # first forward pass
      __SCREAMING_SNAKE_CASE   				=							model(
          lowerCamelCase					,attention_mask=lowerCamelCase					,encoder_hidden_states=lowerCamelCase					,encoder_attention_mask=lowerCamelCase					,use_cache=lowerCamelCase					,)
      __SCREAMING_SNAKE_CASE   				=							outputs.past_key_values

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

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

      __SCREAMING_SNAKE_CASE   				=							model(
          lowerCamelCase					,attention_mask=lowerCamelCase					,encoder_hidden_states=lowerCamelCase					,encoder_attention_mask=lowerCamelCase					,output_hidden_states=lowerCamelCase					,)["""hidden_states"""][0]
      __SCREAMING_SNAKE_CASE   				=							model(
          lowerCamelCase					,attention_mask=lowerCamelCase					,encoder_hidden_states=lowerCamelCase					,encoder_attention_mask=lowerCamelCase					,past_key_values=lowerCamelCase					,output_hidden_states=lowerCamelCase					,)["""hidden_states"""][0]

      # select random slice
      __SCREAMING_SNAKE_CASE   				=							ids_tensor((1,)					,output_from_past.shape[-1]     ).item()
      __SCREAMING_SNAKE_CASE   				=							output_from_no_past[:, -3:, random_slice_idx].detach()
      __SCREAMING_SNAKE_CASE   				=							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(lowerCamelCase					,lowerCamelCase					,atol=1E-3     )     )





   def   UpperCAmelCase__  (       self					:      str     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							self.prepare_config_and_inputs()
      (
          (
          __SCREAMING_SNAKE_CASE
      )				,  (
          __SCREAMING_SNAKE_CASE
      )				,  (
          __SCREAMING_SNAKE_CASE
      )				,  (
          __SCREAMING_SNAKE_CASE
      )				,  (
          __SCREAMING_SNAKE_CASE
      )				,  (
          __SCREAMING_SNAKE_CASE
      )				,  (
          __SCREAMING_SNAKE_CASE
      )				,  
      )   				=							config_and_inputs
      __SCREAMING_SNAKE_CASE   				=							{"""input_ids""": input_ids, """attention_mask""": input_mask}
      return config, inputs_dict







@require_torch
class __a			( _snake_case, _snake_case, _snake_case, unittest.TestCase      ):
   __UpperCamelCase :			Optional[Any]						   =						(LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else ()
   __UpperCamelCase :			int						   =						(LlamaForCausalLM,) if is_torch_available() else ()
   __UpperCamelCase :			Union[str, Any]						   =						(
       {
           'feature-extraction': LlamaModel,
           'text-classification': LlamaForSequenceClassification,
           'text-generation': LlamaForCausalLM,
           'zero-shot': LlamaForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   __UpperCamelCase :			List[str]						   =						False
   __UpperCamelCase :			Tuple						   =						False





   def   UpperCAmelCase__  (       self					:      Optional[Any]     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							LlamaModelTester(self     )
      __SCREAMING_SNAKE_CASE   				=							ConfigTester(self					,config_class=lowerCamelCase					,hidden_size=37     )





   def   UpperCAmelCase__  (       self					:      List[Any]     ):

      '''simple docstring'''

      self.config_tester.run_common_tests()





   def   UpperCAmelCase__  (       self					:      List[Any]     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowerCamelCase     )





   def   UpperCAmelCase__  (       self					:      Optional[Any]     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							self.model_tester.prepare_config_and_inputs()
      for type in ["absolute", "relative_key", "relative_key_query"]:
         __SCREAMING_SNAKE_CASE   				=							type
         self.model_tester.create_and_check_model(*lowerCamelCase     )





   def   UpperCAmelCase__  (       self					:      Optional[int]     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE   				=							self.model_tester.prepare_config_and_inputs_for_common()
      __SCREAMING_SNAKE_CASE   				=							3
      __SCREAMING_SNAKE_CASE   				=							input_dict["""input_ids"""]
      __SCREAMING_SNAKE_CASE   				=							input_ids.ne(1     ).to(lowerCamelCase     )
      __SCREAMING_SNAKE_CASE   				=							ids_tensor([self.model_tester.batch_size]					,self.model_tester.type_sequence_label_size     )
      __SCREAMING_SNAKE_CASE   				=							LlamaForSequenceClassification(lowerCamelCase     )
      model.to(lowerCamelCase     )
      model.eval()
      __SCREAMING_SNAKE_CASE   				=							model(lowerCamelCase					,attention_mask=lowerCamelCase					,labels=lowerCamelCase     )
      self.assertEqual(result.logits.shape					,(self.model_tester.batch_size, self.model_tester.num_labels)     )





   def   UpperCAmelCase__  (       self					:      Any     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE   				=							self.model_tester.prepare_config_and_inputs_for_common()
      __SCREAMING_SNAKE_CASE   				=							3
      __SCREAMING_SNAKE_CASE   				=							"""single_label_classification"""
      __SCREAMING_SNAKE_CASE   				=							input_dict["""input_ids"""]
      __SCREAMING_SNAKE_CASE   				=							input_ids.ne(1     ).to(lowerCamelCase     )
      __SCREAMING_SNAKE_CASE   				=							ids_tensor([self.model_tester.batch_size]					,self.model_tester.type_sequence_label_size     )
      __SCREAMING_SNAKE_CASE   				=							LlamaForSequenceClassification(lowerCamelCase     )
      model.to(lowerCamelCase     )
      model.eval()
      __SCREAMING_SNAKE_CASE   				=							model(lowerCamelCase					,attention_mask=lowerCamelCase					,labels=lowerCamelCase     )
      self.assertEqual(result.logits.shape					,(self.model_tester.batch_size, self.model_tester.num_labels)     )





   def   UpperCAmelCase__  (       self					:      Union[str, Any]     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE   				=							self.model_tester.prepare_config_and_inputs_for_common()
      __SCREAMING_SNAKE_CASE   				=							3
      __SCREAMING_SNAKE_CASE   				=							"""multi_label_classification"""
      __SCREAMING_SNAKE_CASE   				=							input_dict["""input_ids"""]
      __SCREAMING_SNAKE_CASE   				=							input_ids.ne(1     ).to(lowerCamelCase     )
      __SCREAMING_SNAKE_CASE   				=							ids_tensor(
          [self.model_tester.batch_size, config.num_labels]					,self.model_tester.type_sequence_label_size     ).to(torch.float     )
      __SCREAMING_SNAKE_CASE   				=							LlamaForSequenceClassification(lowerCamelCase     )
      model.to(lowerCamelCase     )
      model.eval()
      __SCREAMING_SNAKE_CASE   				=							model(lowerCamelCase					,attention_mask=lowerCamelCase					,labels=lowerCamelCase     )
      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   UpperCAmelCase__  (       self					:      List[str]     ):

      '''simple docstring'''

      pass





   @parameterized.expand([("""linear""",), ("""dynamic""",)]     )
   def   UpperCAmelCase__  (       self					:      List[Any]					,lowerCamelCase					:      Optional[Any]     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE   				=							self.model_tester.prepare_config_and_inputs_for_common()
      __SCREAMING_SNAKE_CASE   				=							ids_tensor([1, 10]					,config.vocab_size     )
      __SCREAMING_SNAKE_CASE   				=							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
      __SCREAMING_SNAKE_CASE   				=							LlamaModel(lowerCamelCase     )
      original_model.to(lowerCamelCase     )
      original_model.eval()
      __SCREAMING_SNAKE_CASE   				=							original_model(lowerCamelCase     ).last_hidden_state
      __SCREAMING_SNAKE_CASE   				=							original_model(lowerCamelCase     ).last_hidden_state

      set_seed(42     )  # Fixed seed at init time so the two models get the same random weights
      __SCREAMING_SNAKE_CASE   				=							{"""type""": scaling_type, """factor""": 10.0}
      __SCREAMING_SNAKE_CASE   				=							LlamaModel(lowerCamelCase     )
      scaled_model.to(lowerCamelCase     )
      scaled_model.eval()
      __SCREAMING_SNAKE_CASE   				=							scaled_model(lowerCamelCase     ).last_hidden_state
      __SCREAMING_SNAKE_CASE   				=							scaled_model(lowerCamelCase     ).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(lowerCamelCase					,lowerCamelCase					,atol=1E-5     )     )
      else:
         self.assertFalse(torch.allclose(lowerCamelCase					,lowerCamelCase					,atol=1E-5     )     )

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







@require_torch
class __a			( unittest.TestCase      ):





   @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!"""     )
   @slow
   def   UpperCAmelCase__  (       self					:      Optional[int]     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							[1, 306, 4658, 278, 6593, 310, 2834, 338]
      __SCREAMING_SNAKE_CASE   				=							LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-7b-hf"""					,device_map="""auto"""     )
      __SCREAMING_SNAKE_CASE   				=							model(torch.tensor([input_ids]     )     )
      # Expected mean on dim = -1
      __SCREAMING_SNAKE_CASE   				=							torch.tensor([[-6.6_550, -4.1_227, -4.9_859, -3.2_406, 0.8_262, -3.0_033, 1.2_964, -3.3_699]]     )
      torch.testing.assert_close(out.mean(-1     )					,lowerCamelCase					,atol=1E-2					,rtol=1E-2     )
      # slicing logits[0, 0, 0:30]
      # fmt: off
      __SCREAMING_SNAKE_CASE   				=							torch.tensor([-12.8_281, -7.4_453, -0.4_639, -8.0_625, -7.2_500, -8.0_000, -6.4_883, -7.7_695, -7.8_438, -7.0_312, -6.2_188, -7.1_328, -1.8_496, 1.9_961, -8.6_250, -6.7_227, -12.8_281, -6.9_492, -7.0_742, -7.7_852, -7.5_820, -7.9_062, -6.9_375, -7.9_805, -8.3_438, -8.1_562, -8.0_469, -7.6_250, -7.7_422, -7.3_398,]     )
      # fmt: on
      torch.testing.assert_close(out[0, 0, :30]					,lowerCamelCase					,atol=1E-5					,rtol=1E-5     )





   @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!"""     )
   @slow
   def   UpperCAmelCase__  (       self					:      Dict     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							[1, 306, 4658, 278, 6593, 310, 2834, 338]
      __SCREAMING_SNAKE_CASE   				=							LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-hf"""					,device_map="""auto"""     )
      __SCREAMING_SNAKE_CASE   				=							model(torch.tensor(lowerCamelCase     )     )
      # Expected mean on dim = -1
      __SCREAMING_SNAKE_CASE   				=							torch.tensor([[-2.0_622, -1.2_794, -1.1_638, -0.9_788, -1.4_603, -1.0_238, -1.7_893, -1.4_411]]     )
      torch.testing.assert_close(out.mean(-1     )					,lowerCamelCase					,atol=1E-2					,rtol=1E-2     )
      # slicing logits[0, 0, 0:30]
      # fmt: off
      __SCREAMING_SNAKE_CASE   				=							torch.tensor([-8.1_406, -8.0_547, 2.7_461, -1.2_344, -0.1_448, -1.8_262, -1.0_020, -1.8_154, -1.6_895, -1.8_516, -2.3_574, -0.9_277, 3.7_598, 6.5_742, -1.2_998, -0.1_177, -8.1_406, -2.9_688, -2.9_199, -3.1_699, -3.5_254, -2.3_555, -2.7_988, -3.4_141, -2.8_262, -4.5_195, -3.3_379, -3.3_164, -2.7_832, -3.0_273]     )
      # fmt: on
      torch.testing.assert_close(out[0, 0, :30]					,lowerCamelCase					,atol=1E-5					,rtol=1E-5     )





   @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!"""     )
   @slow
   def   UpperCAmelCase__  (       self					:      Dict     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							[1, 306, 4658, 278, 6593, 310, 2834, 338]
      __SCREAMING_SNAKE_CASE   				=							LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-chat-hf"""					,device_map="""auto"""     )
      __SCREAMING_SNAKE_CASE   				=							model(torch.tensor(lowerCamelCase     )     )
      # Expected mean on dim = -1
      __SCREAMING_SNAKE_CASE   				=							torch.tensor([[-0.8_562, -1.8_520, -0.7_551, -0.4_162, -1.5_161, -1.2_038, -2.4_823, -2.3_254]]     )
      torch.testing.assert_close(out.mean(-1     )					,lowerCamelCase					,atol=1E-2					,rtol=1E-2     )
      # slicing logits[0, 0, 0:30]
      # fmt: off
      __SCREAMING_SNAKE_CASE   				=							torch.tensor([-2.2_227, 4.8_828, 0.9_023, -0.4_578, -0.7_871, -0.1_033, -0.6_221, -0.5_786, -0.7_803, -1.0_674, -1.2_920, -0.1_570, 0.8_008, 2.0_723, -0.9_497, 0.2_771, -2.2_227, -0.7_612, -1.4_346, -1.2_061, -1.6_426, -0.3_000, -0.7_139, -1.1_934, -1.8_691, -1.6_973, -1.5_947, -1.2_705, -0.3_523, -0.5_513]     )
      # fmt: on
      torch.testing.assert_close(out.mean(-1     )					,lowerCamelCase					,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   UpperCAmelCase__  (       self					:      Union[str, Any]     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							[1, 306, 4658, 278, 6593, 310, 2834, 338]
      __SCREAMING_SNAKE_CASE   				=							LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-70b-hf"""					,device_map="""auto"""     )
      __SCREAMING_SNAKE_CASE   				=							model(torch.tensor(lowerCamelCase     )     )

      __SCREAMING_SNAKE_CASE   				=							torch.tensor(
          [[-4.2_327, -3.3_360, -4.6_665, -4.7_631, -1.8_180, -3.4_170, -1.4_211, -3.1_810]]					,dtype=torch.floataa     )
      torch.testing.assert_close(out.mean(-1     )					,lowerCamelCase					,atol=1E-2					,rtol=1E-2     )
      # fmt: off
      __SCREAMING_SNAKE_CASE   				=							torch.tensor([-9.4_922, -3.9_551, 1.7_998, -5.6_758, -5.1_055, -5.8_984, -4.8_320, -6.8_086, -6.5_391, -5.6_172, -5.5_820, -5.5_352, 1.7_881, 3.6_289, -6.5_117, -3.4_785, -9.5_000, -6.0_352, -6.8_125, -6.0_195, -6.6_836, -5.4_727, -6.2_812, -6.0_391, -7.3_398, -7.4_297, -7.4_844, -6.5_820, -5.8_789, -5.5_312]     )
      # fmt: on
      torch.testing.assert_close(out[0, 0, :30]					,lowerCamelCase					,atol=1E-5					,rtol=1E-5     )





   @unittest.skip("""Model is curently gated"""     )
   @slow
   def   UpperCAmelCase__  (       self					:      List[str]     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							"""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"""
      __SCREAMING_SNAKE_CASE   				=							"""Simply put, the theory of relativity states that """
      __SCREAMING_SNAKE_CASE   				=							LlamaTokenizer.from_pretrained("""meta-llama/Llama-2-13b-chat-hf"""     )
      __SCREAMING_SNAKE_CASE   				=							tokenizer.encode(lowerCamelCase					,return_tensors="""pt"""     )
      __SCREAMING_SNAKE_CASE   				=							LlamaForCausalLM.from_pretrained(
          """meta-llama/Llama-2-13b-chat-hf"""					,device_map="""sequential"""					,use_safetensors=lowerCamelCase     )

      # greedy generation outputs
      __SCREAMING_SNAKE_CASE   				=							model.generate(lowerCamelCase					,max_new_tokens=64					,top_p=lowerCamelCase					,temperature=1					,do_sample=lowerCamelCase     )
      __SCREAMING_SNAKE_CASE   				=							tokenizer.decode(generated_ids[0]					,skip_special_tokens=lowerCamelCase     )
      self.assertEqual(lowerCamelCase					,lowerCamelCase     )












'''simple docstring'''

import copy
from typing import Any, Dict, List, Optional, Union

import numpy as np
import torch

from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging


a   	=    logging.get_logger(__name__)







class __a			( _snake_case      ):
   __UpperCamelCase :			List[str]						   =						['input_features', 'is_longer']





   def __init__(       self					:      Union[str, Any]					,lowerCamelCase					:      Union[str, Any]=64					,lowerCamelCase					:      Any=4_8000					,lowerCamelCase					:      int=480					,lowerCamelCase					:      Any=10					,lowerCamelCase					:      Dict=1024					,lowerCamelCase					:      Union[str, Any]=0.0					,lowerCamelCase					:      int=False					,lowerCamelCase					:      float = 0					,lowerCamelCase					:      float = 1_4000					,lowerCamelCase					:      int = None					,lowerCamelCase					:      str = "fusion"					,lowerCamelCase					:      str = "repeatpad"					,**lowerCamelCase					:      Dict					,):

      '''simple docstring'''

      super().__init__(
          feature_size=lowerCamelCase					,sampling_rate=lowerCamelCase					,padding_value=lowerCamelCase					,return_attention_mask=lowerCamelCase					,**lowerCamelCase					,)
      __SCREAMING_SNAKE_CASE   				=							top_db
      __SCREAMING_SNAKE_CASE   				=							truncation
      __SCREAMING_SNAKE_CASE   				=							padding
      __SCREAMING_SNAKE_CASE   				=							fft_window_size
      __SCREAMING_SNAKE_CASE   				=							(fft_window_size >> 1) + 1
      __SCREAMING_SNAKE_CASE   				=							hop_length
      __SCREAMING_SNAKE_CASE   				=							max_length_s
      __SCREAMING_SNAKE_CASE   				=							max_length_s * sampling_rate
      __SCREAMING_SNAKE_CASE   				=							sampling_rate
      __SCREAMING_SNAKE_CASE   				=							frequency_min
      __SCREAMING_SNAKE_CASE   				=							frequency_max
      __SCREAMING_SNAKE_CASE   				=							mel_filter_bank(
          num_frequency_bins=self.nb_frequency_bins					,num_mel_filters=lowerCamelCase					,min_frequency=lowerCamelCase					,max_frequency=lowerCamelCase					,sampling_rate=lowerCamelCase					,norm=lowerCamelCase					,mel_scale="""htk"""					,)
      __SCREAMING_SNAKE_CASE   				=							mel_filter_bank(
          num_frequency_bins=self.nb_frequency_bins					,num_mel_filters=lowerCamelCase					,min_frequency=lowerCamelCase					,max_frequency=lowerCamelCase					,sampling_rate=lowerCamelCase					,norm="""slaney"""					,mel_scale="""slaney"""					,)





   def   UpperCAmelCase__  (       self					:      int     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							copy.deepcopy(self.__dict__     )
      __SCREAMING_SNAKE_CASE   				=							self.__class__.__name__
      if "mel_filters" in output:
         del output["mel_filters"]
      if "mel_filters_slaney" in output:
         del output["mel_filters_slaney"]
      return output





   def   UpperCAmelCase__  (       self					:      str					,lowerCamelCase					:      np.array					,lowerCamelCase					:      Optional[np.array] = None     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							spectrogram(
          lowerCamelCase					,window_function(self.fft_window_size					,"""hann"""     )					,frame_length=self.fft_window_size					,hop_length=self.hop_length					,power=2.0					,mel_filters=lowerCamelCase					,log_mel="""dB"""					,)
      return log_mel_spectrogram.T





   def   UpperCAmelCase__  (       self					:      int					,lowerCamelCase					:      int					,lowerCamelCase					:      Union[str, Any]					,lowerCamelCase					:      int     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							np.array_split(list(range(0					,total_frames - chunk_frames + 1     )     )					,3     )
      if len(ranges[1]     ) == 0:
         # if the audio is too short, we just use the first chunk
         __SCREAMING_SNAKE_CASE   				=							[0]
      if len(ranges[2]     ) == 0:
         # if the audio is too short, we just use the first chunk
         __SCREAMING_SNAKE_CASE   				=							[0]
      # randomly choose index for each part
      __SCREAMING_SNAKE_CASE   				=							np.random.choice(ranges[0]     )
      __SCREAMING_SNAKE_CASE   				=							np.random.choice(ranges[1]     )
      __SCREAMING_SNAKE_CASE   				=							np.random.choice(ranges[2]     )

      __SCREAMING_SNAKE_CASE   				=							mel[idx_front : idx_front + chunk_frames, :]
      __SCREAMING_SNAKE_CASE   				=							mel[idx_middle : idx_middle + chunk_frames, :]
      __SCREAMING_SNAKE_CASE   				=							mel[idx_back : idx_back + chunk_frames, :]

      __SCREAMING_SNAKE_CASE   				=							torch.tensor(mel[None, None, :]     )
      __SCREAMING_SNAKE_CASE   				=							torch.nn.functional.interpolate(
          lowerCamelCase					,size=[chunk_frames, 64]					,mode="""bilinear"""					,align_corners=lowerCamelCase     )
      __SCREAMING_SNAKE_CASE   				=							mel_shrink[0][0].numpy()
      __SCREAMING_SNAKE_CASE   				=							np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back]					,axis=0     )
      return mel_fusion





   def   UpperCAmelCase__  (       self					:      Optional[Any]					,lowerCamelCase					:      np.array					,lowerCamelCase					:      str					,lowerCamelCase					:      Tuple					,lowerCamelCase					:      Optional[Any]     ):

      '''simple docstring'''

      if waveform.shape[0] > max_length:
         if truncation == "rand_trunc":
            __SCREAMING_SNAKE_CASE   				=							True
            # random crop to max_length (for compatibility) -> this should be handled by self.pad
            __SCREAMING_SNAKE_CASE   				=							len(lowerCamelCase     ) - max_length
            __SCREAMING_SNAKE_CASE   				=							np.random.randint(0					,overflow + 1     )
            __SCREAMING_SNAKE_CASE   				=							waveform[idx : idx + max_length]
            __SCREAMING_SNAKE_CASE   				=							self._np_extract_fbank_features(lowerCamelCase					,self.mel_filters_slaney     )[None, :]
         elif truncation == "fusion":
            __SCREAMING_SNAKE_CASE   				=							self._np_extract_fbank_features(lowerCamelCase					,self.mel_filters     )
            __SCREAMING_SNAKE_CASE   				=							max_length // self.hop_length + 1  # the +1 related to how the spectrogram is computed
            __SCREAMING_SNAKE_CASE   				=							mel.shape[0]
            if chunk_frames == total_frames:
               # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length.
               # In this case, we just use the whole audio.
               __SCREAMING_SNAKE_CASE   				=							np.stack([mel, mel, mel, mel]					,axis=0     )
               __SCREAMING_SNAKE_CASE   				=							False
            else:
               __SCREAMING_SNAKE_CASE   				=							self._random_mel_fusion(lowerCamelCase					,lowerCamelCase					,lowerCamelCase     )
               __SCREAMING_SNAKE_CASE   				=							True
         else:
            raise NotImplementedError(f"""data_truncating {truncation} not implemented"""     )

      else:
         __SCREAMING_SNAKE_CASE   				=							False
         # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding
         if waveform.shape[0] < max_length:
            if padding == "repeat":
               __SCREAMING_SNAKE_CASE   				=							int(max_length / len(lowerCamelCase     )     )
               __SCREAMING_SNAKE_CASE   				=							np.stack(np.tile(lowerCamelCase					,n_repeat + 1     )     )[:max_length]
            if padding == "repeatpad":
               __SCREAMING_SNAKE_CASE   				=							int(max_length / len(lowerCamelCase     )     )
               __SCREAMING_SNAKE_CASE   				=							np.stack(np.tile(lowerCamelCase					,lowerCamelCase     )     )
            __SCREAMING_SNAKE_CASE   				=							np.pad(lowerCamelCase					,(0, max_length - waveform.shape[0])					,mode="""constant"""					,constant_values=0     )

         if truncation == "fusion":
            __SCREAMING_SNAKE_CASE   				=							self._np_extract_fbank_features(lowerCamelCase					,self.mel_filters     )
            __SCREAMING_SNAKE_CASE   				=							np.stack([input_mel, input_mel, input_mel, input_mel]					,axis=0     )
         else:
            __SCREAMING_SNAKE_CASE   				=							self._np_extract_fbank_features(lowerCamelCase					,self.mel_filters_slaney     )[None, :]

      return input_mel, longer





   def __call__(       self					:      Optional[Any]					,lowerCamelCase					:      Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]					,lowerCamelCase					:      str = None					,lowerCamelCase					:      Optional[str] = None					,lowerCamelCase					:      Optional[int] = None					,lowerCamelCase					:      Optional[int] = None					,lowerCamelCase					:      Optional[Union[str, TensorType]] = None					,**lowerCamelCase					:      str					,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							truncation if truncation is not None else self.truncation
      __SCREAMING_SNAKE_CASE   				=							padding if padding else self.padding

      if sampling_rate is not None:
         if sampling_rate != self.sampling_rate:
            raise ValueError(
                f"""The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"""
                f""" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"""
                f""" was sampled with {self.sampling_rate} and not {sampling_rate}."""     )
      else:
         logger.warning(
             """It is strongly recommended to pass the `sampling_rate` argument to this function. """
             """Failing to do so can result in silent errors that might be hard to debug."""     )

      __SCREAMING_SNAKE_CASE   				=							isinstance(lowerCamelCase					,np.ndarray     ) and len(raw_speech.shape     ) > 1
      if is_batched_numpy and len(raw_speech.shape     ) > 2:
         raise ValueError(f"""Only mono-channel audio is supported for input to {self}"""     )
      __SCREAMING_SNAKE_CASE   				=							is_batched_numpy or (
          isinstance(lowerCamelCase					,(list, tuple)     ) and (isinstance(raw_speech[0]					,(np.ndarray, tuple, list)     ))
      )

      if is_batched:
         __SCREAMING_SNAKE_CASE   				=							[np.asarray(lowerCamelCase					,dtype=np.floataa     ) for speech in raw_speech]
      elif not is_batched and not isinstance(lowerCamelCase					,np.ndarray     ):
         __SCREAMING_SNAKE_CASE   				=							np.asarray(lowerCamelCase					,dtype=np.floataa     )
      elif isinstance(lowerCamelCase					,np.ndarray     ) and raw_speech.dtype is np.dtype(np.floataa     ):
         __SCREAMING_SNAKE_CASE   				=							raw_speech.astype(np.floataa     )

      # always return batch
      if not is_batched:
         __SCREAMING_SNAKE_CASE   				=							[np.asarray(lowerCamelCase     )]

      # convert to mel spectrogram, truncate and pad if needed.
      __SCREAMING_SNAKE_CASE   				=							[
          self._get_input_mel(lowerCamelCase					,max_length if max_length else self.nb_max_samples					,lowerCamelCase					,lowerCamelCase     )
          for waveform in raw_speech
      ]

      __SCREAMING_SNAKE_CASE   				=							[]
      __SCREAMING_SNAKE_CASE   				=							[]
      for mel, longer in padded_inputs:
         input_mel.append(lowerCamelCase     )
         is_longer.append(lowerCamelCase     )

      if truncation == "fusion" and sum(lowerCamelCase     ) == 0:
         # if no audio is longer than 10s, then randomly select one audio to be longer
         __SCREAMING_SNAKE_CASE   				=							np.random.randint(0					,len(lowerCamelCase     )     )
         __SCREAMING_SNAKE_CASE   				=							True

      if isinstance(input_mel[0]					,lowerCamelCase     ):
         __SCREAMING_SNAKE_CASE   				=							[np.asarray(lowerCamelCase					,dtype=np.floataa     ) for feature in input_mel]

      # is_longer is a list of bool
      __SCREAMING_SNAKE_CASE   				=							[[longer] for longer in is_longer]

      __SCREAMING_SNAKE_CASE   				=							{"""input_features""": input_mel, """is_longer""": is_longer}
      __SCREAMING_SNAKE_CASE   				=							BatchFeature(lowerCamelCase     )

      if return_tensors is not None:
         __SCREAMING_SNAKE_CASE   				=							input_features.convert_to_tensors(lowerCamelCase     )

      return input_features





