






'''simple docstring'''







from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging


UpperCamelCase     :   Optional[Any]	      =		logging.get_logger(__name__)

UpperCamelCase     :   List[str]	      =		{
    'Helsinki-NLP/opus-mt-en-de': 'https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/config.json',
    # See all Marian models at https://huggingface.co/models?filter=marian
}




class 		UpperCamelCase__     (a      ):




		'''simple docstring'''





		_UpperCamelCase						=       'marian'
		_UpperCamelCase						=       ['past_key_values']
		_UpperCamelCase						=       {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}






		def __init__(   self ,_lowerCAmelCase=5_81_01 ,_lowerCAmelCase=None ,_lowerCAmelCase=10_24 ,_lowerCAmelCase=12 ,_lowerCAmelCase=40_96 ,_lowerCAmelCase=16 ,_lowerCAmelCase=12 ,_lowerCAmelCase=40_96 ,_lowerCAmelCase=16 ,_lowerCAmelCase=0.0 ,_lowerCAmelCase=0.0 ,_lowerCAmelCase=True ,_lowerCAmelCase=True ,_lowerCAmelCase="gelu" ,_lowerCAmelCase=10_24 ,_lowerCAmelCase=0.1 ,_lowerCAmelCase=0.0 ,_lowerCAmelCase=0.0 ,_lowerCAmelCase=0.02 ,_lowerCAmelCase=5_81_00 ,_lowerCAmelCase=False ,_lowerCAmelCase=5_81_00 ,_lowerCAmelCase=0 ,_lowerCAmelCase=0 ,_lowerCAmelCase=True ,**_lowerCAmelCase ,):
								lowerCamelCase__								=	vocab_size
								lowerCamelCase__								=	decoder_vocab_size or vocab_size
								lowerCamelCase__								=	max_position_embeddings
								lowerCamelCase__								=	d_model
								lowerCamelCase__								=	encoder_ffn_dim
								lowerCamelCase__								=	encoder_layers
								lowerCamelCase__								=	encoder_attention_heads
								lowerCamelCase__								=	decoder_ffn_dim
								lowerCamelCase__								=	decoder_layers
								lowerCamelCase__								=	decoder_attention_heads
								lowerCamelCase__								=	dropout
								lowerCamelCase__								=	attention_dropout
								lowerCamelCase__								=	activation_dropout
								lowerCamelCase__								=	activation_function
								lowerCamelCase__								=	init_std
								lowerCamelCase__								=	encoder_layerdrop
								lowerCamelCase__								=	decoder_layerdrop
								lowerCamelCase__								=	use_cache
								lowerCamelCase__								=	encoder_layers
								lowerCamelCase__								=	scale_embedding  # scale factor will be sqrt(d_model) if True
								lowerCamelCase__								=	share_encoder_decoder_embeddings
								super().__init__(
								    pad_token_id=_lowerCAmelCase ,eos_token_id=_lowerCAmelCase ,is_encoder_decoder=_lowerCAmelCase ,decoder_start_token_id=_lowerCAmelCase ,forced_eos_token_id=_lowerCAmelCase ,**_lowerCAmelCase ,)




class 		UpperCamelCase__     (a      ):




		'''simple docstring'''





		@property
		# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.inputs
		def       UpperCamelCase_       (   self							):
								if self.task in ["default", "seq2seq-lm"]:
														lowerCamelCase__								=	OrderedDict(
														    [
														        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
														        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
														    ]							)

														if self.use_past:
																				lowerCamelCase__								=	{0: """batch"""}
																				lowerCamelCase__								=	{0: """batch""", 1: """past_decoder_sequence + sequence"""}
														else:
																				lowerCamelCase__								=	{0: """batch""", 1: """decoder_sequence"""}
																				lowerCamelCase__								=	{0: """batch""", 1: """decoder_sequence"""}

														if self.use_past:
																				self.fill_with_past_key_values_(_lowerCAmelCase ,direction="""inputs"""							)
								elif self.task == "causal-lm":
														# TODO: figure this case out.
														lowerCamelCase__								=	OrderedDict(
														    [
														        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
														        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
														    ]							)
														if self.use_past:
																				lowerCamelCase__							,      lowerCamelCase__								=	self.num_layers
																				for i in range(_lowerCAmelCase							):
																										lowerCamelCase__								=	{0: """batch""", 2: """past_sequence + sequence"""}
																										lowerCamelCase__								=	{0: """batch""", 2: """past_sequence + sequence"""}
								else:
														lowerCamelCase__								=	OrderedDict(
														    [
														        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
														        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
														        ("""decoder_input_ids""", {0: """batch""", 1: """decoder_sequence"""}),
														        ("""decoder_attention_mask""", {0: """batch""", 1: """decoder_sequence"""}),
														    ]							)

								return common_inputs






		@property
		# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
		def       UpperCamelCase_       (   self							):
								if self.task in ["default", "seq2seq-lm"]:
														lowerCamelCase__								=	super().outputs
								else:
														lowerCamelCase__								=	super(_lowerCAmelCase ,self							).outputs
														if self.use_past:
																				lowerCamelCase__							,      lowerCamelCase__								=	self.num_layers
																				for i in range(_lowerCAmelCase							):
																										lowerCamelCase__								=	{0: """batch""", 2: """past_sequence + sequence"""}
																										lowerCamelCase__								=	{0: """batch""", 2: """past_sequence + sequence"""}
								return common_outputs






		def       UpperCamelCase_       (   self ,_lowerCAmelCase ,_lowerCAmelCase = -1 ,_lowerCAmelCase = -1 ,_lowerCAmelCase = False ,_lowerCAmelCase = None ,):
								lowerCamelCase__								=	self._generate_dummy_inputs_for_encoder_and_decoder(
								    _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase							)

								# Generate decoder inputs
								lowerCamelCase__								=	seq_length if not self.use_past else 1
								lowerCamelCase__								=	self._generate_dummy_inputs_for_encoder_and_decoder(
								    _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase							)
								lowerCamelCase__								=	{F'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()}
								lowerCamelCase__								=	dict(**_lowerCAmelCase ,**_lowerCAmelCase							)

								if self.use_past:
														if not is_torch_available():
																				raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""							)
														else:
																				import torch
														lowerCamelCase__							,      lowerCamelCase__								=	common_inputs["""input_ids"""].shape
														lowerCamelCase__								=	common_inputs["""decoder_input_ids"""].shape[1]
														lowerCamelCase__							,      lowerCamelCase__								=	self.num_attention_heads
														lowerCamelCase__								=	(
														    batch,
														    num_encoder_attention_heads,
														    encoder_seq_length,
														    self._config.hidden_size // num_encoder_attention_heads,
														)
														lowerCamelCase__								=	decoder_seq_length + 3
														lowerCamelCase__								=	(
														    batch,
														    num_decoder_attention_heads,
														    decoder_past_length,
														    self._config.hidden_size // num_decoder_attention_heads,
														)

														lowerCamelCase__								=	torch.cat(
														    [common_inputs["""decoder_attention_mask"""], torch.ones(_lowerCAmelCase ,_lowerCAmelCase							)] ,dim=1							)

														lowerCamelCase__								=	[]
														# If the number of encoder and decoder layers are present in the model configuration, both are considered
														lowerCamelCase__							,      lowerCamelCase__								=	self.num_layers
														lowerCamelCase__								=	min(_lowerCAmelCase ,_lowerCAmelCase							)
														lowerCamelCase__								=	max(_lowerCAmelCase ,_lowerCAmelCase							) - min_num_layers
														lowerCamelCase__								=	"""encoder""" if num_encoder_layers > num_decoder_layers else """decoder"""

														for _ in range(_lowerCAmelCase							):
																				common_inputs["past_key_values"].append(
																				    (
																				        torch.zeros(_lowerCAmelCase							),
																				        torch.zeros(_lowerCAmelCase							),
																				        torch.zeros(_lowerCAmelCase							),
																				        torch.zeros(_lowerCAmelCase							),
																				    )							)
														# TODO: test this.
														lowerCamelCase__								=	encoder_shape if remaining_side_name == """encoder""" else decoder_shape
														for _ in range(_lowerCAmelCase ,_lowerCAmelCase							):
																				common_inputs["past_key_values"].append((torch.zeros(_lowerCAmelCase							), torch.zeros(_lowerCAmelCase							))							)
								return common_inputs






		def       UpperCamelCase_       (   self ,_lowerCAmelCase ,_lowerCAmelCase = -1 ,_lowerCAmelCase = -1 ,_lowerCAmelCase = False ,_lowerCAmelCase = None ,):
								lowerCamelCase__								=	self._generate_dummy_inputs_for_encoder_and_decoder(
								    _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase							)

								if self.use_past:
														if not is_torch_available():
																				raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""							)
														else:
																				import torch
														lowerCamelCase__							,      lowerCamelCase__								=	common_inputs["""input_ids"""].shape
														# Not using the same length for past_key_values
														lowerCamelCase__								=	seqlen + 2
														lowerCamelCase__							,      lowerCamelCase__								=	self.num_layers
														lowerCamelCase__							,      lowerCamelCase__								=	self.num_attention_heads
														lowerCamelCase__								=	(
														    batch,
														    num_encoder_attention_heads,
														    past_key_values_length,
														    self._config.hidden_size // num_encoder_attention_heads,
														)

														lowerCamelCase__								=	common_inputs["""attention_mask"""].dtype
														lowerCamelCase__								=	torch.cat(
														    [common_inputs["""attention_mask"""], torch.ones(_lowerCAmelCase ,_lowerCAmelCase ,dtype=_lowerCAmelCase							)] ,dim=1							)
														lowerCamelCase__								=	[
														    (torch.zeros(_lowerCAmelCase							), torch.zeros(_lowerCAmelCase							)) for _ in range(_lowerCAmelCase							)
														]
								return common_inputs






		def       UpperCamelCase_       (   self ,_lowerCAmelCase ,_lowerCAmelCase = -1 ,_lowerCAmelCase = -1 ,_lowerCAmelCase = False ,_lowerCAmelCase = None ,):
								# Copied from OnnxConfig.generate_dummy_inputs
								# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
								# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
								lowerCamelCase__								=	compute_effective_axis_dimension(
								    _lowerCAmelCase ,fixed_dimension=OnnxConfig.default_fixed_batch ,num_token_to_add=0							)

								# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
								lowerCamelCase__								=	tokenizer.num_special_tokens_to_add(_lowerCAmelCase							)
								lowerCamelCase__								=	compute_effective_axis_dimension(
								    _lowerCAmelCase ,fixed_dimension=OnnxConfig.default_fixed_sequence ,num_token_to_add=_lowerCAmelCase							)

								# Generate dummy inputs according to compute batch and sequence
								lowerCamelCase__								=	[""" """.join([tokenizer.unk_token]							) * seq_length] * batch_size
								lowerCamelCase__								=	dict(tokenizer(_lowerCAmelCase ,return_tensors=_lowerCAmelCase							)							)
								return common_inputs






		def       UpperCamelCase_       (   self ,_lowerCAmelCase ,_lowerCAmelCase = -1 ,_lowerCAmelCase = -1 ,_lowerCAmelCase = False ,_lowerCAmelCase = None ,):
								if self.task in ["default", "seq2seq-lm"]:
														lowerCamelCase__								=	self._generate_dummy_inputs_for_default_and_seqaseq_lm(
														    _lowerCAmelCase ,batch_size=_lowerCAmelCase ,seq_length=_lowerCAmelCase ,is_pair=_lowerCAmelCase ,framework=_lowerCAmelCase							)

								else:
														lowerCamelCase__								=	self._generate_dummy_inputs_for_causal_lm(
														    _lowerCAmelCase ,batch_size=_lowerCAmelCase ,seq_length=_lowerCAmelCase ,is_pair=_lowerCAmelCase ,framework=_lowerCAmelCase							)

								return common_inputs






		def       UpperCamelCase_       (   self ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase							):
								if self.task in ["default", "seq2seq-lm"]:
														lowerCamelCase__								=	super()._flatten_past_key_values_(_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase							)
								else:
														lowerCamelCase__								=	super(_lowerCAmelCase ,self							)._flatten_past_key_values_(
														    _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase							)






		@property
		def       UpperCamelCase_       (   self							):
								return 1E-4







"""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 lowerCAmelCase__      :






			'''simple docstring'''



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

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

							_lowerCamelCase	:     Tuple       =       None
							if self.use_token_type_ids:
											_lowerCamelCase	:     Optional[int]       =       ids_tensor([self.batch_size, self.seq_length]    , self.type_vocab_size    )

							_lowerCamelCase	:     List[Any]       =       None
							_lowerCamelCase	:     Optional[Any]       =       None
							_lowerCamelCase	:     Optional[Any]       =       None
							if self.use_labels:
											_lowerCamelCase	:     Any       =       ids_tensor([self.batch_size]    , self.type_sequence_label_size    )
											_lowerCamelCase	:     Tuple       =       ids_tensor([self.batch_size, self.seq_length]    , self.num_labels    )
											_lowerCamelCase	:     Optional[Any]       =       ids_tensor([self.batch_size]    , self.num_choices    )

							_lowerCamelCase	:     List[Any]       =       self.get_config()

							return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
			def    A_       (    self    ):
							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=lowercase    , initializer_range=self.initializer_range    , )
			def    A_       (    self    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    ):
							_lowerCamelCase	:     str       =       LlamaModel(config=lowercase    )
							model.to(lowercase    )
							model.eval()
							_lowerCamelCase	:     List[Any]       =       model(lowercase    , attention_mask=lowercase    )
							_lowerCamelCase	:     Any       =       model(lowercase    )
							self.parent.assertEqual(result.last_hidden_state.shape    , (self.batch_size, self.seq_length, self.hidden_size)    )
			def    A_       (    self    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , ):
							_lowerCamelCase	:     str       =       True
							_lowerCamelCase	:     Dict       =       LlamaModel(lowercase    )
							model.to(lowercase    )
							model.eval()
							_lowerCamelCase	:     Union[str, Any]       =       model(
							    lowercase    , attention_mask=lowercase    , encoder_hidden_states=lowercase    , encoder_attention_mask=lowercase    , )
							_lowerCamelCase	:     Tuple       =       model(
							    lowercase    , attention_mask=lowercase    , encoder_hidden_states=lowercase    , )
							_lowerCamelCase	:     Union[str, Any]       =       model(lowercase    , attention_mask=lowercase    )
							self.parent.assertEqual(result.last_hidden_state.shape    , (self.batch_size, self.seq_length, self.hidden_size)    )
			def    A_       (    self    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , ):
							_lowerCamelCase	:     Optional[Any]       =       LlamaForCausalLM(config=lowercase    )
							model.to(lowercase    )
							model.eval()
							_lowerCamelCase	:     List[Any]       =       model(lowercase    , attention_mask=lowercase    , labels=lowercase    )
							self.parent.assertEqual(result.logits.shape    , (self.batch_size, self.seq_length, self.vocab_size)    )
			def    A_       (    self    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , ):
							_lowerCamelCase	:     int       =       True
							_lowerCamelCase	:     Optional[Any]       =       True
							_lowerCamelCase	:     str       =       LlamaForCausalLM(config=lowercase    )
							model.to(lowercase    )
							model.eval()

							# first forward pass
							_lowerCamelCase	:     Dict       =       model(
							    lowercase    , attention_mask=lowercase    , encoder_hidden_states=lowercase    , encoder_attention_mask=lowercase    , use_cache=lowercase    , )
							_lowerCamelCase	:     Union[str, Any]       =       outputs.past_key_values

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

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

							_lowerCamelCase	:     Any       =       model(
							    lowercase    , attention_mask=lowercase    , encoder_hidden_states=lowercase    , encoder_attention_mask=lowercase    , output_hidden_states=lowercase    , )['hidden_states'][0]
							_lowerCamelCase	:     Dict       =       model(
							    lowercase    , attention_mask=lowercase    , encoder_hidden_states=lowercase    , encoder_attention_mask=lowercase    , past_key_values=lowercase    , output_hidden_states=lowercase    , )['hidden_states'][0]

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






			def    A_       (    self    ):
							_lowerCamelCase	:     Tuple       =       self.prepare_config_and_inputs()
							(
							    (
							    _lowerCamelCase
							),					(
							    _lowerCamelCase
							),					(
							    _lowerCamelCase
							),					(
							    _lowerCamelCase
							),					(
							    _lowerCamelCase
							),					(
							    _lowerCamelCase
							),					(
							    _lowerCamelCase
							),					
							)	:     List[str]       =       config_and_inputs
							_lowerCamelCase	:     int       =       {'input_ids': input_ids, 'attention_mask': input_mask}
							return config, inputs_dict






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






			'''simple docstring'''



			lowerCamelCase__ =     (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else ()
			lowerCamelCase__ =     (LlamaForCausalLM,) if is_torch_available() else ()
			lowerCamelCase__ =     (
			    {
			        """feature-extraction""": LlamaModel,
			        """text-classification""": LlamaForSequenceClassification,
			        """text-generation""": LlamaForCausalLM,
			        """zero-shot""": LlamaForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)
			lowerCamelCase__ =     False
			lowerCamelCase__ =     False
			def    A_       (    self    ):
							_lowerCamelCase	:     Optional[Any]       =       LlamaModelTester(self    )
							_lowerCamelCase	:     List[Any]       =       ConfigTester(self    , config_class=lowercase    , hidden_size=37    )
			def    A_       (    self    ):
							self.config_tester.run_common_tests()
			def    A_       (    self    ):
							_lowerCamelCase	:     Optional[int]       =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowercase    )
			def    A_       (    self    ):
							_lowerCamelCase	:     Any       =       self.model_tester.prepare_config_and_inputs()
							for type in ["absolute", "relative_key", "relative_key_query"]:
											_lowerCamelCase	:     Any       =       type
											self.model_tester.create_and_check_model(*lowercase    )
			def    A_       (    self    ):
							_lowerCamelCase,					_lowerCamelCase	:     Tuple       =       self.model_tester.prepare_config_and_inputs_for_common()
							_lowerCamelCase	:     List[str]       =       3
							_lowerCamelCase	:     Dict       =       input_dict['input_ids']
							_lowerCamelCase	:     List[str]       =       input_ids.ne(1    ).to(lowercase    )
							_lowerCamelCase	:     Tuple       =       ids_tensor([self.model_tester.batch_size]    , self.model_tester.type_sequence_label_size    )
							_lowerCamelCase	:     Union[str, Any]       =       LlamaForSequenceClassification(lowercase    )
							model.to(lowercase    )
							model.eval()
							_lowerCamelCase	:     List[str]       =       model(lowercase    , attention_mask=lowercase    , labels=lowercase    )
							self.assertEqual(result.logits.shape    , (self.model_tester.batch_size, self.model_tester.num_labels)    )
			def    A_       (    self    ):
							_lowerCamelCase,					_lowerCamelCase	:     Optional[Any]       =       self.model_tester.prepare_config_and_inputs_for_common()
							_lowerCamelCase	:     Dict       =       3
							_lowerCamelCase	:     List[str]       =       'single_label_classification'
							_lowerCamelCase	:     Union[str, Any]       =       input_dict['input_ids']
							_lowerCamelCase	:     List[Any]       =       input_ids.ne(1    ).to(lowercase    )
							_lowerCamelCase	:     Optional[Any]       =       ids_tensor([self.model_tester.batch_size]    , self.model_tester.type_sequence_label_size    )
							_lowerCamelCase	:     List[Any]       =       LlamaForSequenceClassification(lowercase    )
							model.to(lowercase    )
							model.eval()
							_lowerCamelCase	:     int       =       model(lowercase    , attention_mask=lowercase    , labels=lowercase    )
							self.assertEqual(result.logits.shape    , (self.model_tester.batch_size, self.model_tester.num_labels)    )
			def    A_       (    self    ):
							_lowerCamelCase,					_lowerCamelCase	:     List[str]       =       self.model_tester.prepare_config_and_inputs_for_common()
							_lowerCamelCase	:     List[Any]       =       3
							_lowerCamelCase	:     Union[str, Any]       =       'multi_label_classification'
							_lowerCamelCase	:     Dict       =       input_dict['input_ids']
							_lowerCamelCase	:     Optional[Any]       =       input_ids.ne(1    ).to(lowercase    )
							_lowerCamelCase	:     List[Any]       =       ids_tensor(
							    [self.model_tester.batch_size, config.num_labels]    , self.model_tester.type_sequence_label_size    ).to(torch.float    )
							_lowerCamelCase	:     Optional[Any]       =       LlamaForSequenceClassification(lowercase    )
							model.to(lowercase    )
							model.eval()
							_lowerCamelCase	:     int       =       model(lowercase    , attention_mask=lowercase    , labels=lowercase    )
							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    A_       (    self    ):
							pass






			@parameterized.expand([('linear',), ('dynamic',)]    )
			def    A_       (    self    , lowercase    ):
							_lowerCamelCase,					_lowerCamelCase	:     Any       =       self.model_tester.prepare_config_and_inputs_for_common()
							_lowerCamelCase	:     List[Any]       =       ids_tensor([1, 10]    , config.vocab_size    )
							_lowerCamelCase	:     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
							_lowerCamelCase	:     Union[str, Any]       =       LlamaModel(lowercase    )
							original_model.to(lowercase    )
							original_model.eval()
							_lowerCamelCase	:     str       =       original_model(lowercase    ).last_hidden_state
							_lowerCamelCase	:     int       =       original_model(lowercase    ).last_hidden_state

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

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






@require_torch
class lowerCAmelCase__      (	unittest.TestCase		):






			'''simple docstring'''



			@unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!'    )
			@slow
			def    A_       (    self    ):
							_lowerCamelCase	:     Union[str, Any]       =       [1, 306, 4658, 278, 6593, 310, 2834, 338]
							_lowerCamelCase	:     Dict       =       LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf'    , device_map='auto'    )
							_lowerCamelCase	:     Union[str, Any]       =       model(torch.tensor([input_ids]    )    )
							# Expected mean on dim = -1
							_lowerCamelCase	:     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    )    , lowercase    , atol=1E-2    , rtol=1E-2    )
							# slicing logits[0, 0, 0:30]
							# fmt: off
							_lowerCamelCase	:     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]    , lowercase    , atol=1E-5    , rtol=1E-5    )
			@unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!'    )
			@slow
			def    A_       (    self    ):
							_lowerCamelCase	:     List[Any]       =       [1, 306, 4658, 278, 6593, 310, 2834, 338]
							_lowerCamelCase	:     str       =       LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf'    , device_map='auto'    )
							_lowerCamelCase	:     List[Any]       =       model(torch.tensor(lowercase    )    )
							# Expected mean on dim = -1
							_lowerCamelCase	:     Tuple       =       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    )    , lowercase    , atol=1E-2    , rtol=1E-2    )
							# slicing logits[0, 0, 0:30]
							# fmt: off
							_lowerCamelCase	:     Dict       =       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]    , lowercase    , atol=1E-5    , rtol=1E-5    )
			@unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!'    )
			@slow
			def    A_       (    self    ):
							_lowerCamelCase	:     Union[str, Any]       =       [1, 306, 4658, 278, 6593, 310, 2834, 338]
							_lowerCamelCase	:     Optional[Any]       =       LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf'    , device_map='auto'    )
							_lowerCamelCase	:     int       =       model(torch.tensor(lowercase    )    )
							# Expected mean on dim = -1
							_lowerCamelCase	:     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    )    , lowercase    , atol=1E-2    , rtol=1E-2    )
							# slicing logits[0, 0, 0:30]
							# fmt: off
							_lowerCamelCase	:     Union[str, Any]       =       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    )    , lowercase    , 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    A_       (    self    ):
							_lowerCamelCase	:     Tuple       =       [1, 306, 4658, 278, 6593, 310, 2834, 338]
							_lowerCamelCase	:     int       =       LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf'    , device_map='auto'    )
							_lowerCamelCase	:     Union[str, Any]       =       model(torch.tensor(lowercase    )    )

							_lowerCamelCase	:     Optional[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    )    , lowercase    , atol=1E-2    , rtol=1E-2    )
							# fmt: off
							_lowerCamelCase	:     List[str]       =       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]    , lowercase    , atol=1E-5    , rtol=1E-5    )






			@unittest.skip('Model is curently gated'    )
			@slow
			def    A_       (    self    ):
							_lowerCamelCase	:     List[str]       =       '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'
							_lowerCamelCase	:     str       =       'Simply put, the theory of relativity states that '
							_lowerCamelCase	:     List[Any]       =       LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf'    )
							_lowerCamelCase	:     List[str]       =       tokenizer.encode(lowercase    , return_tensors='pt'    )
							_lowerCamelCase	:     List[str]       =       LlamaForCausalLM.from_pretrained(
							    'meta-llama/Llama-2-13b-chat-hf'    , device_map='sequential'    , use_safetensors=lowercase    )

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