


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

		"""simple docstring"""

		def __init__(		self    ,   UpperCamelCase_    ,   UpperCamelCase_=13    ,   UpperCamelCase_=7    ,   UpperCamelCase_=True    ,   UpperCamelCase_=True    ,   UpperCamelCase_=False    ,   UpperCamelCase_=True    ,   UpperCamelCase_=99    ,   UpperCamelCase_=32    ,   UpperCamelCase_=5    ,   UpperCamelCase_=4    ,   UpperCamelCase_=37    ,   UpperCamelCase_="gelu"    ,   UpperCamelCase_=0.1    ,   UpperCamelCase_=0.1    ,   UpperCamelCase_=512    ,   UpperCamelCase_=16    ,   UpperCamelCase_=2    ,   UpperCamelCase_=0.02    ,   UpperCamelCase_=3    ,   UpperCamelCase_=4    ,   UpperCamelCase_=None    ,   ):

							'''simple docstring'''


							UpperCamelCase__   :List[str]												= parent
							UpperCamelCase__   :List[str]												= batch_size
							UpperCamelCase__   :Dict												= seq_length
							UpperCamelCase__   :Dict												= is_training
							UpperCamelCase__   :Tuple												= use_input_mask
							UpperCamelCase__   :str												= use_token_type_ids
							UpperCamelCase__   :str												= use_labels
							UpperCamelCase__   :Optional[Any]												= vocab_size
							UpperCamelCase__   :Dict												= hidden_size
							UpperCamelCase__   :str												= num_hidden_layers
							UpperCamelCase__   :Optional[int]												= num_attention_heads
							UpperCamelCase__   :Optional[int]												= intermediate_size
							UpperCamelCase__   :List[Any]												= hidden_act
							UpperCamelCase__   :str												= hidden_dropout_prob
							UpperCamelCase__   :int												= attention_probs_dropout_prob
							UpperCamelCase__   :int												= max_position_embeddings
							UpperCamelCase__   :Dict												= type_vocab_size
							UpperCamelCase__   :Optional[Any]												= type_sequence_label_size
							UpperCamelCase__   :str												= initializer_range
							UpperCamelCase__   :List[str]												= num_labels
							UpperCamelCase__   :int												= num_choices
							UpperCamelCase__   :List[Any]												= scope




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :Dict												= ids_tensor([self.batch_size, self.seq_length]    ,   self.vocab_size							)

							UpperCamelCase__   :Union[str, Any]												= None
							if self.use_input_mask:
												UpperCamelCase__   :Dict												= random_attention_mask([self.batch_size, self.seq_length]							)

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

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

							UpperCamelCase__   :Tuple												= self.get_config()

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




		def     lowerCAmelCase__				(		self							):

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




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__   :Tuple												= LlamaModel(config=UpperCAmelCase__							)
							model.to(UpperCAmelCase__							)
							model.eval()
							UpperCamelCase__   :str												= model(UpperCAmelCase__    ,   attention_mask=UpperCAmelCase__							)
							UpperCamelCase__   :str												= model(UpperCAmelCase__							)
							self.parent.assertEqual(result.last_hidden_state.shape    ,   (self.batch_size, self.seq_length, self.hidden_size)							)




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   ):

							'''simple docstring'''


							UpperCamelCase__   :Union[str, Any]												= True
							UpperCamelCase__   :int												= LlamaModel(UpperCAmelCase__							)
							model.to(UpperCAmelCase__							)
							model.eval()
							UpperCamelCase__   :str												= model(
							    UpperCAmelCase__    ,   attention_mask=UpperCAmelCase__    ,   encoder_hidden_states=UpperCAmelCase__    ,   encoder_attention_mask=UpperCAmelCase__    ,   )
							UpperCamelCase__   :Any												= model(
							    UpperCAmelCase__    ,   attention_mask=UpperCAmelCase__    ,   encoder_hidden_states=UpperCAmelCase__    ,   )
							UpperCamelCase__   :Dict												= model(UpperCAmelCase__    ,   attention_mask=UpperCAmelCase__							)
							self.parent.assertEqual(result.last_hidden_state.shape    ,   (self.batch_size, self.seq_length, self.hidden_size)							)




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   ):

							'''simple docstring'''


							UpperCamelCase__   :Any												= LlamaForCausalLM(config=UpperCAmelCase__							)
							model.to(UpperCAmelCase__							)
							model.eval()
							UpperCamelCase__   :int												= model(UpperCAmelCase__    ,   attention_mask=UpperCAmelCase__    ,   labels=UpperCAmelCase__							)
							self.parent.assertEqual(result.logits.shape    ,   (self.batch_size, self.seq_length, self.vocab_size)							)




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   ):

							'''simple docstring'''


							UpperCamelCase__   :str												= True
							UpperCamelCase__   :List[str]												= True
							UpperCamelCase__   :Tuple												= LlamaForCausalLM(config=UpperCAmelCase__							)
							model.to(UpperCAmelCase__							)
							model.eval()

							# first forward pass
							UpperCamelCase__   :int												= model(
							    UpperCAmelCase__    ,   attention_mask=UpperCAmelCase__    ,   encoder_hidden_states=UpperCAmelCase__    ,   encoder_attention_mask=UpperCAmelCase__    ,   use_cache=UpperCAmelCase__    ,   )
							UpperCamelCase__   :List[Any]												= outputs.past_key_values

							# create hypothetical multiple next token and extent to next_input_ids
							UpperCamelCase__   :Union[str, Any]												= ids_tensor((self.batch_size, 3)    ,   config.vocab_size							)
							UpperCamelCase__   :Optional[int]												= ids_tensor((self.batch_size, 3)    ,   vocab_size=2							)

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

							UpperCamelCase__   :List[str]												= model(
							    UpperCAmelCase__    ,   attention_mask=UpperCAmelCase__    ,   encoder_hidden_states=UpperCAmelCase__    ,   encoder_attention_mask=UpperCAmelCase__    ,   output_hidden_states=UpperCAmelCase__    ,   )['''hidden_states'''][0]
							UpperCamelCase__   :List[Any]												= model(
							    UpperCAmelCase__    ,   attention_mask=UpperCAmelCase__    ,   encoder_hidden_states=UpperCAmelCase__    ,   encoder_attention_mask=UpperCAmelCase__    ,   past_key_values=UpperCAmelCase__    ,   output_hidden_states=UpperCAmelCase__    ,   )['''hidden_states'''][0]

							# select random slice
							UpperCamelCase__   :int												= ids_tensor((1,)    ,   output_from_past.shape[-1]							).item()
							UpperCamelCase__   :List[str]												= output_from_no_past[:, -3:, random_slice_idx].detach()
							UpperCamelCase__   :int												= 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(UpperCAmelCase__    ,   UpperCAmelCase__    ,   atol=1e-3							)							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :Optional[int]												= self.prepare_config_and_inputs()
							(
							    (
							    UpperCamelCase__  
							)					,				(
							    UpperCamelCase__  
							)					,				(
							    UpperCamelCase__  
							)					,				(
							    UpperCamelCase__  
							)					,				(
							    UpperCamelCase__  
							)					,				(
							    UpperCamelCase__  
							)					,				(
							    UpperCamelCase__  
							)					,				  
							)   :List[Any]												= config_and_inputs
							UpperCamelCase__   :Optional[Any]												= {'''input_ids''': input_ids, '''attention_mask''': input_mask}
							return config, inputs_dict



@require_torch
class    lowercase	(							A__	,		A__	,		A__	,		unittest.TestCase					):

		"""simple docstring"""

		_a     =				(LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else ()
		_a     =				(LlamaForCausalLM,) if is_torch_available() else ()
		_a     =				(
		    {
		        "feature-extraction": LlamaModel,
		        "text-classification": LlamaForSequenceClassification,
		        "text-generation": LlamaForCausalLM,
		        "zero-shot": LlamaForSequenceClassification,
		    }
		    if is_torch_available()
		    else {}
		)
		_a     =				False
		_a     =				False




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :str												= LlamaModelTester(self							)
							UpperCamelCase__   :List[Any]												= ConfigTester(self    ,   config_class=UpperCAmelCase__    ,   hidden_size=37							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							self.config_tester.run_common_tests()




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :Tuple												= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*UpperCAmelCase__							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :Tuple												= self.model_tester.prepare_config_and_inputs()
							for type in ["absolute", "relative_key", "relative_key_query"]:
												UpperCamelCase__   :Optional[int]												= type
												self.model_tester.create_and_check_model(*UpperCAmelCase__							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__					,				UpperCamelCase__   :Tuple												= self.model_tester.prepare_config_and_inputs_for_common()
							UpperCamelCase__   :List[Any]												= 3
							UpperCamelCase__   :Optional[Any]												= input_dict['''input_ids''']
							UpperCamelCase__   :Union[str, Any]												= input_ids.ne(1							).to(UpperCAmelCase__							)
							UpperCamelCase__   :int												= ids_tensor([self.model_tester.batch_size]    ,   self.model_tester.type_sequence_label_size							)
							UpperCamelCase__   :Optional[Any]												= LlamaForSequenceClassification(UpperCAmelCase__							)
							model.to(UpperCAmelCase__							)
							model.eval()
							UpperCamelCase__   :List[Any]												= model(UpperCAmelCase__    ,   attention_mask=UpperCAmelCase__    ,   labels=UpperCAmelCase__							)
							self.assertEqual(result.logits.shape    ,   (self.model_tester.batch_size, self.model_tester.num_labels)							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__					,				UpperCamelCase__   :Optional[Any]												= self.model_tester.prepare_config_and_inputs_for_common()
							UpperCamelCase__   :Optional[int]												= 3
							UpperCamelCase__   :int												= '''single_label_classification'''
							UpperCamelCase__   :Union[str, Any]												= input_dict['''input_ids''']
							UpperCamelCase__   :int												= input_ids.ne(1							).to(UpperCAmelCase__							)
							UpperCamelCase__   :Any												= ids_tensor([self.model_tester.batch_size]    ,   self.model_tester.type_sequence_label_size							)
							UpperCamelCase__   :Dict												= LlamaForSequenceClassification(UpperCAmelCase__							)
							model.to(UpperCAmelCase__							)
							model.eval()
							UpperCamelCase__   :List[Any]												= model(UpperCAmelCase__    ,   attention_mask=UpperCAmelCase__    ,   labels=UpperCAmelCase__							)
							self.assertEqual(result.logits.shape    ,   (self.model_tester.batch_size, self.model_tester.num_labels)							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__					,				UpperCamelCase__   :Union[str, Any]												= self.model_tester.prepare_config_and_inputs_for_common()
							UpperCamelCase__   :Union[str, Any]												= 3
							UpperCamelCase__   :Optional[int]												= '''multi_label_classification'''
							UpperCamelCase__   :List[Any]												= input_dict['''input_ids''']
							UpperCamelCase__   :Tuple												= input_ids.ne(1							).to(UpperCAmelCase__							)
							UpperCamelCase__   :Dict												= ids_tensor(
							    [self.model_tester.batch_size, config.num_labels]    ,   self.model_tester.type_sequence_label_size							).to(torch.float							)
							UpperCamelCase__   :List[str]												= LlamaForSequenceClassification(UpperCAmelCase__							)
							model.to(UpperCAmelCase__							)
							model.eval()
							UpperCamelCase__   :Dict												= model(UpperCAmelCase__    ,   attention_mask=UpperCAmelCase__    ,   labels=UpperCAmelCase__							)
							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							):

							'''simple docstring'''


							pass




		@parameterized.expand([('''linear''',), ('''dynamic''',)]							)
		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__					,				UpperCamelCase__   :Tuple												= self.model_tester.prepare_config_and_inputs_for_common()
							UpperCamelCase__   :int												= ids_tensor([1, 10]    ,   config.vocab_size							)
							UpperCamelCase__   :List[str]												= 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
							UpperCamelCase__   :Union[str, Any]												= LlamaModel(UpperCAmelCase__							)
							original_model.to(UpperCAmelCase__							)
							original_model.eval()
							UpperCamelCase__   :Dict												= original_model(UpperCAmelCase__							).last_hidden_state
							UpperCamelCase__   :Tuple												= original_model(UpperCAmelCase__							).last_hidden_state

							set_seed(42							)  # Fixed seed at init time so the two models get the same random weights
							UpperCamelCase__   :Union[str, Any]												= {'''type''': scaling_type, '''factor''': 10.0}
							UpperCamelCase__   :Optional[int]												= LlamaModel(UpperCAmelCase__							)
							scaled_model.to(UpperCAmelCase__							)
							scaled_model.eval()
							UpperCamelCase__   :Dict												= scaled_model(UpperCAmelCase__							).last_hidden_state
							UpperCamelCase__   :List[str]												= scaled_model(UpperCAmelCase__							).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(UpperCAmelCase__    ,   UpperCAmelCase__    ,   atol=1e-5							)							)
							else:
												self.assertFalse(torch.allclose(UpperCAmelCase__    ,   UpperCAmelCase__    ,   atol=1e-5							)							)

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



@require_torch
class    lowercase	(							unittest.TestCase					):

		"""simple docstring"""

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

							'''simple docstring'''


							UpperCamelCase__   :Any												= [1, 306, 4658, 278, 6593, 310, 2834, 338]
							UpperCamelCase__   :Optional[Any]												= LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-7b-hf'''    ,   device_map='''auto'''							)
							UpperCamelCase__   :Union[str, Any]												= model(torch.tensor([input_ids]							)							)
							# Expected mean on dim = -1
							UpperCamelCase__   :List[Any]												= torch.tensor([[-6.6550, -4.1227, -4.9859, -3.2406, 0.8262, -3.0033, 1.2964, -3.3699]]							)
							torch.testing.assert_close(out.mean(-1							)    ,   UpperCAmelCase__    ,   atol=1e-2    ,   rtol=1e-2							)
							# slicing logits[0, 0, 0:30]
							# fmt: off
							UpperCamelCase__   :List[Any]												= torch.tensor([-12.8281, -7.4453, -0.4639, -8.0625, -7.2500, -8.0000, -6.4883, -7.7695, -7.8438, -7.0312, -6.2188, -7.1328, -1.8496, 1.9961, -8.6250, -6.7227, -12.8281, -6.9492, -7.0742, -7.7852, -7.5820, -7.9062, -6.9375, -7.9805, -8.3438, -8.1562, -8.0469, -7.6250, -7.7422, -7.3398,]							)
							# fmt: on
							torch.testing.assert_close(out[0, 0, :30]    ,   UpperCAmelCase__    ,   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							):

							'''simple docstring'''


							UpperCamelCase__   :str												= [1, 306, 4658, 278, 6593, 310, 2834, 338]
							UpperCamelCase__   :Any												= LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-13b-hf'''    ,   device_map='''auto'''							)
							UpperCamelCase__   :str												= model(torch.tensor(UpperCAmelCase__							)							)
							# Expected mean on dim = -1
							UpperCamelCase__   :str												= torch.tensor([[-2.0622, -1.2794, -1.1638, -0.9788, -1.4603, -1.0238, -1.7893, -1.4411]]							)
							torch.testing.assert_close(out.mean(-1							)    ,   UpperCAmelCase__    ,   atol=1e-2    ,   rtol=1e-2							)
							# slicing logits[0, 0, 0:30]
							# fmt: off
							UpperCamelCase__   :str												= torch.tensor([-8.1406, -8.0547, 2.7461, -1.2344, -0.1448, -1.8262, -1.0020, -1.8154, -1.6895, -1.8516, -2.3574, -0.9277, 3.7598, 6.5742, -1.2998, -0.1177, -8.1406, -2.9688, -2.9199, -3.1699, -3.5254, -2.3555, -2.7988, -3.4141, -2.8262, -4.5195, -3.3379, -3.3164, -2.7832, -3.0273]							)
							# fmt: on
							torch.testing.assert_close(out[0, 0, :30]    ,   UpperCAmelCase__    ,   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							):

							'''simple docstring'''


							UpperCamelCase__   :Tuple												= [1, 306, 4658, 278, 6593, 310, 2834, 338]
							UpperCamelCase__   :Dict												= LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-13b-chat-hf'''    ,   device_map='''auto'''							)
							UpperCamelCase__   :Union[str, Any]												= model(torch.tensor(UpperCAmelCase__							)							)
							# Expected mean on dim = -1
							UpperCamelCase__   :Union[str, Any]												= torch.tensor([[-0.8562, -1.8520, -0.7551, -0.4162, -1.5161, -1.2038, -2.4823, -2.3254]]							)
							torch.testing.assert_close(out.mean(-1							)    ,   UpperCAmelCase__    ,   atol=1e-2    ,   rtol=1e-2							)
							# slicing logits[0, 0, 0:30]
							# fmt: off
							UpperCamelCase__   :Any												= torch.tensor([-2.2227, 4.8828, 0.9023, -0.4578, -0.7871, -0.1033, -0.6221, -0.5786, -0.7803, -1.0674, -1.2920, -0.1570, 0.8008, 2.0723, -0.9497, 0.2771, -2.2227, -0.7612, -1.4346, -1.2061, -1.6426, -0.3000, -0.7139, -1.1934, -1.8691, -1.6973, -1.5947, -1.2705, -0.3523, -0.5513]							)
							# fmt: on
							torch.testing.assert_close(out.mean(-1							)    ,   UpperCAmelCase__    ,   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							):

							'''simple docstring'''


							UpperCamelCase__   :Any												= [1, 306, 4658, 278, 6593, 310, 2834, 338]
							UpperCamelCase__   :Optional[int]												= LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-70b-hf'''    ,   device_map='''auto'''							)
							UpperCamelCase__   :Any												= model(torch.tensor(UpperCAmelCase__							)							)

							UpperCamelCase__   :Union[str, Any]												= torch.tensor(
							    [[-4.2327, -3.3360, -4.6665, -4.7631, -1.8180, -3.4170, -1.4211, -3.1810]]    ,   dtype=torch.floataa							)
							torch.testing.assert_close(out.mean(-1							)    ,   UpperCAmelCase__    ,   atol=1e-2    ,   rtol=1e-2							)
							# fmt: off
							UpperCamelCase__   :List[Any]												= torch.tensor([-9.4922, -3.9551, 1.7998, -5.6758, -5.1055, -5.8984, -4.8320, -6.8086, -6.5391, -5.6172, -5.5820, -5.5352, 1.7881, 3.6289, -6.5117, -3.4785, -9.5000, -6.0352, -6.8125, -6.0195, -6.6836, -5.4727, -6.2812, -6.0391, -7.3398, -7.4297, -7.4844, -6.5820, -5.8789, -5.5312]							)
							# fmt: on
							torch.testing.assert_close(out[0, 0, :30]    ,   UpperCAmelCase__    ,   atol=1e-5    ,   rtol=1e-5							)




		@unittest.skip('''Model is curently gated'''							)
		@slow
		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


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

							# greedy generation outputs
							UpperCamelCase__   :Tuple												= model.generate(UpperCAmelCase__    ,   max_new_tokens=64    ,   top_p=UpperCAmelCase__    ,   temperature=1    ,   do_sample=UpperCAmelCase__							)
							UpperCamelCase__   :List[str]												= tokenizer.decode(generated_ids[0]    ,   skip_special_tokens=UpperCAmelCase__							)
							self.assertEqual(UpperCAmelCase__    ,   UpperCAmelCase__							)



"""simple docstring"""







from typing import Dict, List, Optional, Union

import numpy as np

from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin
from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy


a__				:							Union[str, Any]						=     logging.get_logger(__name__)




class  UpperCamelCase_	( UpperCamelCase):

	"""simple docstring"""





	def __init__( self			:				int			,			UpperCAmelCase__			:				int			,			UpperCAmelCase__			:				int			,			UpperCAmelCase__			:				float			,			**UpperCAmelCase__			:				List[str]   )       ->	Union[str, Any]:
						__SCREAMING_SNAKE_CASE						   =				feature_size
						__SCREAMING_SNAKE_CASE						   =				sampling_rate
						__SCREAMING_SNAKE_CASE						   =				padding_value

						__SCREAMING_SNAKE_CASE						   =				kwargs.pop("padding_side"			,			"right"   )
						__SCREAMING_SNAKE_CASE						   =				kwargs.pop("return_attention_mask"			,			UpperCAmelCase__   )

						super().__init__(**UpperCAmelCase__   )




	def   UpperCAmelCase_      ( self			:				Optional[int]			,			UpperCAmelCase__			:				Union[
	        BatchFeature,
	        List[BatchFeature],
	        Dict[str, BatchFeature],
	        Dict[str, List[BatchFeature]],
	        List[Dict[str, BatchFeature]],
	    ]			,			UpperCAmelCase__			:				Union[bool, str, PaddingStrategy] = True			,			UpperCAmelCase__			:				Optional[int] = None			,			UpperCAmelCase__			:				bool = False			,			UpperCAmelCase__			:				Optional[int] = None			,			UpperCAmelCase__			:				Optional[bool] = None			,			UpperCAmelCase__			:				Optional[Union[str, TensorType]] = None			,			)       ->	BatchFeature:
						# If we have a list of dicts, let's convert it in a dict of lists
						# We do this to allow using this method as a collate_fn function in PyTorch Dataloader
						if isinstance(UpperCAmelCase__			,			(list, tuple)   ) and isinstance(processed_features[0]			,			(dict, BatchFeature)   ):
											__SCREAMING_SNAKE_CASE						   =				{
											    key: [example[key] for example in processed_features] for key in processed_features[0].keys()
											}

						# The model's main input name, usually `input_values`, has be passed for padding
						if self.model_input_names[0] not in processed_features:
											raise ValueError(
											    "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`"
											    F""" to this method that includes {self.model_input_names[0]}, but you provided"""
											    F""" {list(processed_features.keys()   )}"""   )

						__SCREAMING_SNAKE_CASE						   =				processed_features[self.model_input_names[0]]
						__SCREAMING_SNAKE_CASE						   =				(
						    return_attention_mask if return_attention_mask is not None else self.return_attention_mask
						)

						if len(UpperCAmelCase__   ) == 0:
											if return_attention_mask:
																__SCREAMING_SNAKE_CASE						   =				[]
											return processed_features

						# If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays
						# and rebuild them afterwards if no return_tensors is specified
						# Note that we lose the specific device the tensor may be on for PyTorch

						__SCREAMING_SNAKE_CASE						   =				required_input[0]
						if isinstance(UpperCAmelCase__			,			(list, tuple)   ):
											# first_element might be an empty list/tuple in some edge cases so we grab the first non empty element.
											__SCREAMING_SNAKE_CASE						   =				0
											while len(required_input[index]   ) == 0:
																index += 1
											if index < len(UpperCAmelCase__   ):
																__SCREAMING_SNAKE_CASE						   =				required_input[index][0]

						if return_tensors is None:
											if is_tf_tensor(UpperCAmelCase__   ):
																__SCREAMING_SNAKE_CASE						   =				"tf"
											elif is_torch_tensor(UpperCAmelCase__   ):
																__SCREAMING_SNAKE_CASE						   =				"pt"
											elif isinstance(UpperCAmelCase__			,			(int, float, list, tuple, np.ndarray)   ):
																__SCREAMING_SNAKE_CASE						   =				"np"
											else:
																raise ValueError(
																    F"""type of {first_element} unknown: {type(UpperCAmelCase__   )}. """
																    "Should be one of a python, numpy, pytorch or tensorflow object."   )

						for key, value in processed_features.items():
											if isinstance(value[0]			,			(int, float)   ):
																__SCREAMING_SNAKE_CASE						   =				to_numpy(UpperCAmelCase__   )
											else:
																__SCREAMING_SNAKE_CASE						   =				[to_numpy(UpperCAmelCase__   ) for v in value]

        # Convert padding_strategy in PaddingStrategy
						__SCREAMING_SNAKE_CASE						   =				self._get_padding_strategies(padding=UpperCAmelCase__			,			max_length=UpperCAmelCase__   )

						__SCREAMING_SNAKE_CASE						   =				processed_features[self.model_input_names[0]]

						__SCREAMING_SNAKE_CASE						   =				len(UpperCAmelCase__   )
						if not all(len(UpperCAmelCase__   ) == batch_size for v in processed_features.values()   ):
											raise ValueError("Some items in the output dictionary have a different batch size than others."   )

						__SCREAMING_SNAKE_CASE						   =				[]
						for i in range(UpperCAmelCase__   ):
											__SCREAMING_SNAKE_CASE						   =				{k: v[i] for k, v in processed_features.items()}
											# truncation
											__SCREAMING_SNAKE_CASE						   =				self._truncate(
											    UpperCAmelCase__			,			max_length=UpperCAmelCase__			,			pad_to_multiple_of=UpperCAmelCase__			,			truncation=UpperCAmelCase__			,			)
											truncated_inputs.append(UpperCAmelCase__   )

						if padding_strategy == PaddingStrategy.LONGEST:
											# make sure that `max_length` cannot be longer than the longest truncated length
											__SCREAMING_SNAKE_CASE						   =				max(len(input_slice[self.model_input_names[0]]   ) for input_slice in truncated_inputs   )
											__SCREAMING_SNAKE_CASE						   =				PaddingStrategy.MAX_LENGTH

						__SCREAMING_SNAKE_CASE						   =				{}
						for i in range(UpperCAmelCase__   ):
											# padding
											__SCREAMING_SNAKE_CASE						   =				self._pad(
											    truncated_inputs[i]			,			max_length=UpperCAmelCase__			,			padding_strategy=UpperCAmelCase__			,			pad_to_multiple_of=UpperCAmelCase__			,			return_attention_mask=UpperCAmelCase__			,			)

											for key, value in outputs.items():
																if key not in batch_outputs:
																					__SCREAMING_SNAKE_CASE						   =				[]
																if value.dtype is np.dtype(np.floataa   ):
																					__SCREAMING_SNAKE_CASE						   =				value.astype(np.floataa   )
																batch_outputs[key].append(UpperCAmelCase__   )

						return BatchFeature(UpperCAmelCase__			,			tensor_type=UpperCAmelCase__   )




	def   UpperCAmelCase_      ( self			:				Optional[int]			,			UpperCAmelCase__			:				Union[Dict[str, np.ndarray], BatchFeature]			,			UpperCAmelCase__			:				Optional[int] = None			,			UpperCAmelCase__			:				PaddingStrategy = PaddingStrategy.DO_NOT_PAD			,			UpperCAmelCase__			:				Optional[int] = None			,			UpperCAmelCase__			:				Optional[bool] = None			,			)       ->	dict:
						__SCREAMING_SNAKE_CASE						   =				processed_features[self.model_input_names[0]]

						if padding_strategy == PaddingStrategy.LONGEST:
											__SCREAMING_SNAKE_CASE						   =				len(UpperCAmelCase__   )

						if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
											__SCREAMING_SNAKE_CASE						   =				((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of

						__SCREAMING_SNAKE_CASE						   =				padding_strategy != PaddingStrategy.DO_NOT_PAD and len(UpperCAmelCase__   ) < max_length

						if return_attention_mask and "attention_mask" not in processed_features:
											__SCREAMING_SNAKE_CASE						   =				np.ones(len(UpperCAmelCase__   )			,			dtype=np.intaa   )

						if needs_to_be_padded:
											__SCREAMING_SNAKE_CASE						   =				max_length - len(UpperCAmelCase__   )
											if self.padding_side == "right":
																if return_attention_mask:
																					__SCREAMING_SNAKE_CASE						   =				np.pad(
																					    processed_features["attention_mask"]			,			(0, difference)   )
																__SCREAMING_SNAKE_CASE						   =				((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference)
																__SCREAMING_SNAKE_CASE						   =				np.pad(
																    UpperCAmelCase__			,			UpperCAmelCase__			,			"constant"			,			constant_values=self.padding_value   )
											elif self.padding_side == "left":
																if return_attention_mask:
																					__SCREAMING_SNAKE_CASE						   =				np.pad(
																					    processed_features["attention_mask"]			,			(difference, 0)   )
																__SCREAMING_SNAKE_CASE						   =				((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0)
																__SCREAMING_SNAKE_CASE						   =				np.pad(
																    UpperCAmelCase__			,			UpperCAmelCase__			,			"constant"			,			constant_values=self.padding_value   )
											else:
																raise ValueError("Invalid padding strategy:" + str(self.padding_side   )   )

						return processed_features




	def   UpperCAmelCase_      ( self			:				Union[str, Any]			,			UpperCAmelCase__			:				Union[Dict[str, np.ndarray], BatchFeature]			,			UpperCAmelCase__			:				Optional[int] = None			,			UpperCAmelCase__			:				Optional[int] = None			,			UpperCAmelCase__			:				Optional[bool] = None			,			)       ->	str:
						if not truncation:
											return processed_features
						elif truncation and max_length is None:
											raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined."   )

						__SCREAMING_SNAKE_CASE						   =				processed_features[self.model_input_names[0]]

						# find `max_length` that fits `pad_to_multiple_of`
						if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
											__SCREAMING_SNAKE_CASE						   =				((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of

						__SCREAMING_SNAKE_CASE						   =				len(UpperCAmelCase__   ) > max_length

						if needs_to_be_truncated:
											__SCREAMING_SNAKE_CASE						   =				processed_features[self.model_input_names[0]][:max_length]
											if "attention_mask" in processed_features:
																__SCREAMING_SNAKE_CASE						   =				processed_features["attention_mask"][:max_length]

						return processed_features




	def   UpperCAmelCase_      ( self			:				Optional[int]			,			UpperCAmelCase__			:				Optional[Any]=False			,			UpperCAmelCase__			:				Optional[int]=None   )       ->	str:

						# Get padding strategy
						if padding is not False:
											if padding is True:
																__SCREAMING_SNAKE_CASE						   =				PaddingStrategy.LONGEST  # Default to pad to the longest sequence in the batch
											elif not isinstance(UpperCAmelCase__			,			UpperCAmelCase__   ):
																__SCREAMING_SNAKE_CASE						   =				PaddingStrategy(UpperCAmelCase__   )
											elif isinstance(UpperCAmelCase__			,			UpperCAmelCase__   ):
																__SCREAMING_SNAKE_CASE						   =				padding
						else:
											__SCREAMING_SNAKE_CASE						   =				PaddingStrategy.DO_NOT_PAD

						# Set max length if needed
						if max_length is None:
											if padding_strategy == PaddingStrategy.MAX_LENGTH:
																raise ValueError(
																    F"""When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined"""   )

        # Test if we have a padding value
						if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None):
											raise ValueError(
											    "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use"
											    " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`."   )

						return padding_strategy
