




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





       '''simple docstring'''






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







             '''simple docstring'''







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







       def     UpperCamelCase_				(	self   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	List[str]   =		ids_tensor([self.batch_size, self.seq_length],				self.vocab_size   )

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

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

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

             SCREAMING_SNAKE_CASE					:	int   =		self.get_config()

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







       def     UpperCamelCase_				(	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=__lowercase,				initializer_range=self.initializer_range,				)







       def     UpperCamelCase_				(	self,				A,				A,				A,				A,				A,				A,				A   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	str   =		LlamaModel(config=__lowercase   )
             model.to(__lowercase   )
             model.eval()
             SCREAMING_SNAKE_CASE					:	str   =		model(__lowercase,				attention_mask=__lowercase   )
             SCREAMING_SNAKE_CASE					:	Any   =		model(__lowercase   )
             self.parent.assertEqual(result.last_hidden_state.shape,				(self.batch_size, self.seq_length, self.hidden_size)   )







       def     UpperCamelCase_				(	self,				A,				A,				A,				A,				A,				A,				A,				A,				A,				):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	Optional[Any]   =		True
             SCREAMING_SNAKE_CASE					:	Dict   =		LlamaModel(__lowercase   )
             model.to(__lowercase   )
             model.eval()
             SCREAMING_SNAKE_CASE					:	int   =		model(
                 __lowercase,				attention_mask=__lowercase,				encoder_hidden_states=__lowercase,				encoder_attention_mask=__lowercase,				)
             SCREAMING_SNAKE_CASE					:	Any   =		model(
                 __lowercase,				attention_mask=__lowercase,				encoder_hidden_states=__lowercase,				)
             SCREAMING_SNAKE_CASE					:	Tuple   =		model(__lowercase,				attention_mask=__lowercase   )
             self.parent.assertEqual(result.last_hidden_state.shape,				(self.batch_size, self.seq_length, self.hidden_size)   )







       def     UpperCamelCase_				(	self,				A,				A,				A,				A,				A,				A,				A,				A,				A,				):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	Optional[int]   =		LlamaForCausalLM(config=__lowercase   )
             model.to(__lowercase   )
             model.eval()
             SCREAMING_SNAKE_CASE					:	Any   =		model(__lowercase,				attention_mask=__lowercase,				labels=__lowercase   )
             self.parent.assertEqual(result.logits.shape,				(self.batch_size, self.seq_length, self.vocab_size)   )







       def     UpperCamelCase_				(	self,				A,				A,				A,				A,				A,				A,				A,				A,				A,				):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	str   =		True
             SCREAMING_SNAKE_CASE					:	Tuple   =		True
             SCREAMING_SNAKE_CASE					:	List[Any]   =		LlamaForCausalLM(config=__lowercase   )
             model.to(__lowercase   )
             model.eval()

             # first forward pass
             SCREAMING_SNAKE_CASE					:	Union[str, Any]   =		model(
                 __lowercase,				attention_mask=__lowercase,				encoder_hidden_states=__lowercase,				encoder_attention_mask=__lowercase,				use_cache=__lowercase,				)
             SCREAMING_SNAKE_CASE					:	Optional[Any]   =		outputs.past_key_values

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

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

             SCREAMING_SNAKE_CASE					:	Union[str, Any]   =		model(
                 __lowercase,				attention_mask=__lowercase,				encoder_hidden_states=__lowercase,				encoder_attention_mask=__lowercase,				output_hidden_states=__lowercase,				)['''hidden_states'''][0]
             SCREAMING_SNAKE_CASE					:	Tuple   =		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
             SCREAMING_SNAKE_CASE					:	Any   =		ids_tensor((1,),				output_from_past.shape[-1]   ).item()
             SCREAMING_SNAKE_CASE					:	Optional[Any]   =		output_from_no_past[:, -3:, random_slice_idx].detach()
             SCREAMING_SNAKE_CASE					:	Union[str, 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     UpperCamelCase_				(	self   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	Union[str, Any]   =		self.prepare_config_and_inputs()
             (
                 SCREAMING_SNAKE_CASE       
             )					:	List[Any]   =		config_and_inputs
             SCREAMING_SNAKE_CASE					:	Any   =		{'''input_ids''': input_ids, '''attention_mask''': input_mask}
             return config, inputs_dict






@require_torch
class 				_a							(       UpperCAmelCase_      ,	UpperCAmelCase_      ,	UpperCAmelCase_      ,	unittest.TestCase      ):





       '''simple docstring'''






       A		:							Union[str, Any]								=		(LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else ()
       A		:							Union[str, Any]								=		(LlamaForCausalLM,) if is_torch_available() else ()
       A		:							List[Any]								=		(
           {
               """feature-extraction""": LlamaModel,
               """text-classification""": LlamaForSequenceClassification,
               """text-generation""": LlamaForCausalLM,
               """zero-shot""": LlamaForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )
       A		:							Tuple								=		False
       A		:							Any								=		False







       def     UpperCamelCase_				(	self   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	Dict   =		LlamaModelTester(self   )
             SCREAMING_SNAKE_CASE					:	Union[str, Any]   =		ConfigTester(self,				config_class=__lowercase,				hidden_size=37   )







       def     UpperCamelCase_				(	self   ):







             '''simple docstring'''







             self.config_tester.run_common_tests()







       def     UpperCamelCase_				(	self   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	int   =		self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*__lowercase   )







       def     UpperCamelCase_				(	self   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	List[str]   =		self.model_tester.prepare_config_and_inputs()
             for type in ["absolute", "relative_key", "relative_key_query"]:
                   SCREAMING_SNAKE_CASE					:	Any   =		type
                   self.model_tester.create_and_check_model(*__lowercase   )







       def     UpperCamelCase_				(	self   ):







             '''simple docstring'''







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







       def     UpperCamelCase_				(	self   ):







             '''simple docstring'''







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







       def     UpperCamelCase_				(	self   ):







             '''simple docstring'''







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







             '''simple docstring'''







             pass







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







             '''simple docstring'''







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

             set_seed(42   )  # Fixed seed at init time so the two models get the same random weights
             SCREAMING_SNAKE_CASE					:	List[str]   =		{'''type''': scaling_type, '''factor''': 10.0}
             SCREAMING_SNAKE_CASE					:	int   =		LlamaModel(__lowercase   )
             scaled_model.to(__lowercase   )
             scaled_model.eval()
             SCREAMING_SNAKE_CASE					:	List[str]   =		scaled_model(__lowercase   ).last_hidden_state
             SCREAMING_SNAKE_CASE					:	List[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 				_a							(       unittest.TestCase      ):





       '''simple docstring'''






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







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	Dict   =		[1, 306, 4_658, 278, 6_593, 310, 2_834, 338]
             SCREAMING_SNAKE_CASE					:	Optional[Any]   =		LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf',				device_map='auto'   )
             SCREAMING_SNAKE_CASE					:	Tuple   =		model(torch.tensor([input_ids]   )   )
             # Expected mean on dim = -1
             SCREAMING_SNAKE_CASE					:	Any   =		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
             SCREAMING_SNAKE_CASE					:	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     UpperCamelCase_				(	self   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	str   =		[1, 306, 4_658, 278, 6_593, 310, 2_834, 338]
             SCREAMING_SNAKE_CASE					:	Any   =		LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf',				device_map='auto'   )
             SCREAMING_SNAKE_CASE					:	Optional[int]   =		model(torch.tensor(__lowercase   )   )
             # Expected mean on dim = -1
             SCREAMING_SNAKE_CASE					:	Any   =		torch.tensor([[-2.06_22, -1.27_94, -1.16_38, -0.97_88, -1.46_03, -1.02_38, -1.78_93, -1.44_11]]   )
             torch.testing.assert_close(out.mean(-1   ),				__lowercase,				atol=1E-2,				rtol=1E-2   )
             # slicing logits[0, 0, 0:30]
             # fmt: off
             SCREAMING_SNAKE_CASE					:	Union[str, Any]   =		torch.tensor([-8.14_06, -8.05_47, 2.74_61, -1.23_44, -0.14_48, -1.82_62, -1.00_20, -1.81_54, -1.68_95, -1.85_16, -2.35_74, -0.92_77, 3.75_98, 6.57_42, -1.29_98, -0.11_77, -8.14_06, -2.96_88, -2.91_99, -3.16_99, -3.52_54, -2.35_55, -2.79_88, -3.41_41, -2.82_62, -4.51_95, -3.33_79, -3.31_64, -2.78_32, -3.02_73]   )
             # fmt: on
             torch.testing.assert_close(out[0, 0, :30],				__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     UpperCamelCase_				(	self   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	Any   =		[1, 306, 4_658, 278, 6_593, 310, 2_834, 338]
             SCREAMING_SNAKE_CASE					:	Optional[int]   =		LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf',				device_map='auto'   )
             SCREAMING_SNAKE_CASE					:	str   =		model(torch.tensor(__lowercase   )   )
             # Expected mean on dim = -1
             SCREAMING_SNAKE_CASE					:	List[Any]   =		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
             SCREAMING_SNAKE_CASE					:	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     UpperCamelCase_				(	self   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	Any   =		[1, 306, 4_658, 278, 6_593, 310, 2_834, 338]
             SCREAMING_SNAKE_CASE					:	List[Any]   =		LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf',				device_map='auto'   )
             SCREAMING_SNAKE_CASE					:	List[str]   =		model(torch.tensor(__lowercase   )   )

             SCREAMING_SNAKE_CASE					:	Dict   =		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
             SCREAMING_SNAKE_CASE					:	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     UpperCamelCase_				(	self   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	List[Any]   =		'''Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi'''
             SCREAMING_SNAKE_CASE					:	Optional[int]   =		'''Simply put, the theory of relativity states that '''
             SCREAMING_SNAKE_CASE					:	Tuple   =		LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf'   )
             SCREAMING_SNAKE_CASE					:	Dict   =		tokenizer.encode(__lowercase,				return_tensors='pt'   )
             SCREAMING_SNAKE_CASE					:	Tuple   =		LlamaForCausalLM.from_pretrained(
                 'meta-llama/Llama-2-13b-chat-hf',				device_map='sequential',				use_safetensors=__lowercase   )

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



import re

import jax.numpy as jnp
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.random import PRNGKey

from ..utils import logging


__lowercase							 =					logging.get_logger(__name__)



def lowerCamelCase  (   SCREAMING_SNAKE_CASE	):
    '''simple docstring'''







    __UpperCamelCase     :Tuple			  =		R'''\w+[.]\d+'''
    __UpperCamelCase     :List[str]			  =		re.findall(SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE	)
    for pat in pats:
        __UpperCamelCase     :int			  =		key.replace(SCREAMING_SNAKE_CASE  ,			'''_'''.join(pat.split('''.'''	)	)	)
    return key



def lowerCamelCase  (   SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE	):
    '''simple docstring'''







    __UpperCamelCase     :Tuple			  =		pt_tuple_key[:-1] + ('''scale''',)
    if (
        any('''norm''' in str_ for str_ in pt_tuple_key	)
        and (pt_tuple_key[-1] == "bias")
        and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict)
        and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict)
    ):
        __UpperCamelCase     :str			  =		pt_tuple_key[:-1] + ('''scale''',)
        return renamed_pt_tuple_key, pt_tensor
    elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict:
        __UpperCamelCase     :Any			  =		pt_tuple_key[:-1] + ('''scale''',)
        return renamed_pt_tuple_key, pt_tensor

    # embedding
    if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict:
        __UpperCamelCase     :str			  =		pt_tuple_key[:-1] + ('''embedding''',)
        return renamed_pt_tuple_key, pt_tensor

    # conv layer
    __UpperCamelCase     :List[str]			  =		pt_tuple_key[:-1] + ('''kernel''',)
    if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4:
        __UpperCamelCase     :List[Any]			  =		pt_tensor.transpose(2  ,			3  ,			1  ,			0	)
        return renamed_pt_tuple_key, pt_tensor

    # linear layer
    __UpperCamelCase     :List[str]			  =		pt_tuple_key[:-1] + ('''kernel''',)
    if pt_tuple_key[-1] == "weight":
        __UpperCamelCase     :Any			  =		pt_tensor.T
        return renamed_pt_tuple_key, pt_tensor

    # old PyTorch layer norm weight
    __UpperCamelCase     :int			  =		pt_tuple_key[:-1] + ('''weight''',)
    if pt_tuple_key[-1] == "gamma":
        return renamed_pt_tuple_key, pt_tensor

    # old PyTorch layer norm bias
    __UpperCamelCase     :int			  =		pt_tuple_key[:-1] + ('''bias''',)
    if pt_tuple_key[-1] == "beta":
        return renamed_pt_tuple_key, pt_tensor

    return pt_tuple_key, pt_tensor



def lowerCamelCase  (   SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE=42	):
    '''simple docstring'''







    __UpperCamelCase     :Union[str, Any]			  =		{k: v.numpy() for k, v in pt_state_dict.items()}

    # Step 2: Since the model is stateless, get random Flax params
    __UpperCamelCase     :str			  =		flax_model.init_weights(PRNGKey(SCREAMING_SNAKE_CASE	)	)

    __UpperCamelCase     :int			  =		flatten_dict(SCREAMING_SNAKE_CASE	)
    __UpperCamelCase     :List[Any]			  =		{}

    # Need to change some parameters name to match Flax names
    for pt_key, pt_tensor in pt_state_dict.items():
        __UpperCamelCase     :List[Any]			  =		rename_key(SCREAMING_SNAKE_CASE	)
        __UpperCamelCase     :List[Any]			  =		tuple(renamed_pt_key.split('''.'''	)	)

        # Correctly rename weight parameters
        __UpperCamelCase  ,       __UpperCamelCase     :Any			  =		rename_key_and_reshape_tensor(SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE	)

        if flax_key in random_flax_state_dict:
            if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
                raise ValueError(
                    f"""PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape """
                    f"""{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}."""	)

        # also add unexpected weight so that warning is thrown
        __UpperCamelCase     :str			  =		jnp.asarray(SCREAMING_SNAKE_CASE	)

    return unflatten_dict(SCREAMING_SNAKE_CASE	)





