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  SCREAMING_SNAKE_CASE_ :
  '''simple docstring'''


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







  def 		SCREAMING_SNAKE_CASE_		(				self    :					List[Any]     )    ->				int:
         A						:     Union[str, Any]         =ids_tensor([self.batch_size, self.seq_length]      ,	self.vocab_size     )

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

         A						:     List[Any]         =None
         if self.use_token_type_ids:
                A						:     int         =ids_tensor([self.batch_size, self.seq_length]      ,	self.type_vocab_size     )

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

         A						:     str         =self.get_config()

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







  def 		SCREAMING_SNAKE_CASE_		(				self    :					Union[str, Any]     )    ->				Union[str, Any]:
         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 		SCREAMING_SNAKE_CASE_		(				self    :					Optional[Any]      ,	SCREAMING_SNAKE_CASE__    :					Optional[Any]      ,	SCREAMING_SNAKE_CASE__    :					Dict      ,	SCREAMING_SNAKE_CASE__    :					List[Any]      ,	SCREAMING_SNAKE_CASE__    :					Union[str, Any]      ,	SCREAMING_SNAKE_CASE__    :					List[str]      ,	SCREAMING_SNAKE_CASE__    :					Optional[int]      ,	SCREAMING_SNAKE_CASE__    :					Optional[Any]     )    ->				Optional[Any]:
         A						:     int         =LlamaModel(config=UpperCAmelCase__     )
         model.to(UpperCAmelCase__     )
         model.eval()
         A						:     int         =model(UpperCAmelCase__      ,	attention_mask=UpperCAmelCase__     )
         A						:     Optional[int]         =model(UpperCAmelCase__     )
         self.parent.assertEqual(result.last_hidden_state.shape      ,	(self.batch_size, self.seq_length, self.hidden_size)     )







  def 		SCREAMING_SNAKE_CASE_		(				self    :					str      ,	SCREAMING_SNAKE_CASE__    :					Any      ,	SCREAMING_SNAKE_CASE__    :					Union[str, Any]      ,	SCREAMING_SNAKE_CASE__    :					Union[str, Any]      ,	SCREAMING_SNAKE_CASE__    :					int      ,	SCREAMING_SNAKE_CASE__    :					List[Any]      ,	SCREAMING_SNAKE_CASE__    :					str      ,	SCREAMING_SNAKE_CASE__    :					Dict      ,	SCREAMING_SNAKE_CASE__    :					int      ,	SCREAMING_SNAKE_CASE__    :					List[Any]      ,	)    ->				List[Any]:
         A						:     Dict         =True
         A						:     Dict         =LlamaModel(UpperCAmelCase__     )
         model.to(UpperCAmelCase__     )
         model.eval()
         A						:     List[Any]         =model(
             UpperCAmelCase__      ,	attention_mask=UpperCAmelCase__      ,	encoder_hidden_states=UpperCAmelCase__      ,	encoder_attention_mask=UpperCAmelCase__      ,	)
         A						:     Any         =model(
             UpperCAmelCase__      ,	attention_mask=UpperCAmelCase__      ,	encoder_hidden_states=UpperCAmelCase__      ,	)
         A						:     Any         =model(UpperCAmelCase__      ,	attention_mask=UpperCAmelCase__     )
         self.parent.assertEqual(result.last_hidden_state.shape      ,	(self.batch_size, self.seq_length, self.hidden_size)     )







  def 		SCREAMING_SNAKE_CASE_		(				self    :					str      ,	SCREAMING_SNAKE_CASE__    :					Optional[Any]      ,	SCREAMING_SNAKE_CASE__    :					Dict      ,	SCREAMING_SNAKE_CASE__    :					Optional[Any]      ,	SCREAMING_SNAKE_CASE__    :					str      ,	SCREAMING_SNAKE_CASE__    :					List[Any]      ,	SCREAMING_SNAKE_CASE__    :					Tuple      ,	SCREAMING_SNAKE_CASE__    :					Optional[Any]      ,	SCREAMING_SNAKE_CASE__    :					List[str]      ,	SCREAMING_SNAKE_CASE__    :					str      ,	)    ->				Optional[int]:
         A						:     List[str]         =LlamaForCausalLM(config=UpperCAmelCase__     )
         model.to(UpperCAmelCase__     )
         model.eval()
         A						:     Tuple         =model(UpperCAmelCase__      ,	attention_mask=UpperCAmelCase__      ,	labels=UpperCAmelCase__     )
         self.parent.assertEqual(result.logits.shape      ,	(self.batch_size, self.seq_length, self.vocab_size)     )







  def 		SCREAMING_SNAKE_CASE_		(				self    :					str      ,	SCREAMING_SNAKE_CASE__    :					Optional[int]      ,	SCREAMING_SNAKE_CASE__    :					Tuple      ,	SCREAMING_SNAKE_CASE__    :					Any      ,	SCREAMING_SNAKE_CASE__    :					Tuple      ,	SCREAMING_SNAKE_CASE__    :					int      ,	SCREAMING_SNAKE_CASE__    :					Union[str, Any]      ,	SCREAMING_SNAKE_CASE__    :					Dict      ,	SCREAMING_SNAKE_CASE__    :					Optional[int]      ,	SCREAMING_SNAKE_CASE__    :					Dict      ,	)    ->				Tuple:
         A						:     Any         =True
         A						:     str         =True
         A						:     str         =LlamaForCausalLM(config=UpperCAmelCase__     )
         model.to(UpperCAmelCase__     )
         model.eval()

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

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

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

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

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

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







  def 		SCREAMING_SNAKE_CASE_		(				self    :					List[Any]     )    ->				int:
         A						:     Optional[Any]         =self.prepare_config_and_inputs()
         (
             (
             A		
         )  ,  (
             A		
         )  ,  (
             A		
         )  ,  (
             A		
         )  ,  (
             A		
         )  ,  (
             A		
         )  ,  (
             A		
         )  ,  		
         )						:     List[str]         =config_and_inputs
         A						:     Optional[int]         ={'input_ids': input_ids, 'attention_mask': input_mask}
         return config, inputs_dict







@require_torch
class  SCREAMING_SNAKE_CASE_ (					lowerCAmelCase_   ,						lowerCAmelCase_   ,						lowerCAmelCase_   ,						unittest.TestCase			):
  '''simple docstring'''


  lowercase		:     Dict            =				(LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else ()
  lowercase		:     str            =				(LlamaForCausalLM,) if is_torch_available() else ()
  lowercase		:     Optional[Any]            =				(
      {
          "feature-extraction": LlamaModel,
          "text-classification": LlamaForSequenceClassification,
          "text-generation": LlamaForCausalLM,
          "zero-shot": LlamaForSequenceClassification,
      }
      if is_torch_available()
      else {}
  )
  lowercase		:     str            =				False
  lowercase		:     str            =				False







  def 		SCREAMING_SNAKE_CASE_		(				self    :					int     )    ->				Optional[int]:
         A						:     Any         =LlamaModelTester(self     )
         A						:     Tuple         =ConfigTester(self      ,	config_class=UpperCAmelCase__      ,	hidden_size=37     )







  def 		SCREAMING_SNAKE_CASE_		(				self    :					Any     )    ->				Tuple:
         self.config_tester.run_common_tests()







  def 		SCREAMING_SNAKE_CASE_		(				self    :					str     )    ->				Optional[int]:
         A						:     Union[str, Any]         =self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*UpperCAmelCase__     )







  def 		SCREAMING_SNAKE_CASE_		(				self    :					Union[str, Any]     )    ->				str:
         A						:     List[Any]         =self.model_tester.prepare_config_and_inputs()
         for type in ["absolute", "relative_key", "relative_key_query"]:
                A						:     int         =type
                self.model_tester.create_and_check_model(*UpperCAmelCase__     )







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







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







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

         set_seed(42     )  # Fixed seed at init time so the two models get the same random weights
         A						:     Dict         =LlamaModel(UpperCAmelCase__     )
         original_model.to(UpperCAmelCase__     )
         original_model.eval()
         A						:     List[str]         =original_model(UpperCAmelCase__     ).last_hidden_state
         A						:     Optional[Any]         =original_model(UpperCAmelCase__     ).last_hidden_state

         set_seed(42     )  # Fixed seed at init time so the two models get the same random weights
         A						:     Optional[int]         ={'type': scaling_type, 'factor': 1_0.0}
         A						:     int         =LlamaModel(UpperCAmelCase__     )
         scaled_model.to(UpperCAmelCase__     )
         scaled_model.eval()
         A						:     str         =scaled_model(UpperCAmelCase__     ).last_hidden_state
         A						:     List[Any]         =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  SCREAMING_SNAKE_CASE_ (					unittest.TestCase			):
  '''simple docstring'''


  @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!'     )
  @slow
  def 		SCREAMING_SNAKE_CASE_		(				self    :					Any     )    ->				Optional[int]:
         A						:     Optional[int]         =[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38]
         A						:     List[Any]         =LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf'      ,	device_map='auto'     )
         A						:     Any         =model(torch.tensor([input_ids]     )     )
         # Expected mean on dim = -1
         A						:     Tuple         =torch.tensor([[-6.6_5_5_0, -4.1_2_2_7, -4.9_8_5_9, -3.2_4_0_6, 0.8_2_6_2, -3.0_0_3_3, 1.2_9_6_4, -3.3_6_9_9]]     )
         torch.testing.assert_close(out.mean(-1     )      ,	UpperCAmelCase__      ,	atol=1e-2      ,	rtol=1e-2     )
         # slicing logits[0, 0, 0:30]
         # fmt: off
         A						:     Optional[Any]         =torch.tensor([-1_2.8_2_8_1, -7.4_4_5_3, -0.4_6_3_9, -8.0_6_2_5, -7.2_5_0_0, -8.0_0_0_0, -6.4_8_8_3, -7.7_6_9_5, -7.8_4_3_8, -7.0_3_1_2, -6.2_1_8_8, -7.1_3_2_8, -1.8_4_9_6, 1.9_9_6_1, -8.6_2_5_0, -6.7_2_2_7, -1_2.8_2_8_1, -6.9_4_9_2, -7.0_7_4_2, -7.7_8_5_2, -7.5_8_2_0, -7.9_0_6_2, -6.9_3_7_5, -7.9_8_0_5, -8.3_4_3_8, -8.1_5_6_2, -8.0_4_6_9, -7.6_2_5_0, -7.7_4_2_2, -7.3_3_9_8,]     )
         # 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 		SCREAMING_SNAKE_CASE_		(				self    :					int     )    ->				List[str]:
         A						:     Any         =[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38]
         A						:     List[Any]         =LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf'      ,	device_map='auto'     )
         A						:     List[str]         =model(torch.tensor(UpperCAmelCase__     )     )
         # Expected mean on dim = -1
         A						:     Union[str, Any]         =torch.tensor([[-2.0_6_2_2, -1.2_7_9_4, -1.1_6_3_8, -0.9_7_8_8, -1.4_6_0_3, -1.0_2_3_8, -1.7_8_9_3, -1.4_4_1_1]]     )
         torch.testing.assert_close(out.mean(-1     )      ,	UpperCAmelCase__      ,	atol=1e-2      ,	rtol=1e-2     )
         # slicing logits[0, 0, 0:30]
         # fmt: off
         A						:     Dict         =torch.tensor([-8.1_4_0_6, -8.0_5_4_7, 2.7_4_6_1, -1.2_3_4_4, -0.1_4_4_8, -1.8_2_6_2, -1.0_0_2_0, -1.8_1_5_4, -1.6_8_9_5, -1.8_5_1_6, -2.3_5_7_4, -0.9_2_7_7, 3.7_5_9_8, 6.5_7_4_2, -1.2_9_9_8, -0.1_1_7_7, -8.1_4_0_6, -2.9_6_8_8, -2.9_1_9_9, -3.1_6_9_9, -3.5_2_5_4, -2.3_5_5_5, -2.7_9_8_8, -3.4_1_4_1, -2.8_2_6_2, -4.5_1_9_5, -3.3_3_7_9, -3.3_1_6_4, -2.7_8_3_2, -3.0_2_7_3]     )
         # 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 		SCREAMING_SNAKE_CASE_		(				self    :					int     )    ->				int:
         A						:     Optional[Any]         =[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38]
         A						:     Dict         =LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf'      ,	device_map='auto'     )
         A						:     str         =model(torch.tensor(UpperCAmelCase__     )     )
         # Expected mean on dim = -1
         A						:     Union[str, Any]         =torch.tensor([[-0.8_5_6_2, -1.8_5_2_0, -0.7_5_5_1, -0.4_1_6_2, -1.5_1_6_1, -1.2_0_3_8, -2.4_8_2_3, -2.3_2_5_4]]     )
         torch.testing.assert_close(out.mean(-1     )      ,	UpperCAmelCase__      ,	atol=1e-2      ,	rtol=1e-2     )
         # slicing logits[0, 0, 0:30]
         # fmt: off
         A						:     Tuple         =torch.tensor([-2.2_2_2_7, 4.8_8_2_8, 0.9_0_2_3, -0.4_5_7_8, -0.7_8_7_1, -0.1_0_3_3, -0.6_2_2_1, -0.5_7_8_6, -0.7_8_0_3, -1.0_6_7_4, -1.2_9_2_0, -0.1_5_7_0, 0.8_0_0_8, 2.0_7_2_3, -0.9_4_9_7, 0.2_7_7_1, -2.2_2_2_7, -0.7_6_1_2, -1.4_3_4_6, -1.2_0_6_1, -1.6_4_2_6, -0.3_0_0_0, -0.7_1_3_9, -1.1_9_3_4, -1.8_6_9_1, -1.6_9_7_3, -1.5_9_4_7, -1.2_7_0_5, -0.3_5_2_3, -0.5_5_1_3]     )
         # 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 		SCREAMING_SNAKE_CASE_		(				self    :					Tuple     )    ->				Dict:
         A						:     str         =[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38]
         A						:     Tuple         =LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf'      ,	device_map='auto'     )
         A						:     List[Any]         =model(torch.tensor(UpperCAmelCase__     )     )

         A						:     Dict         =torch.tensor(
             [[-4.2_3_2_7, -3.3_3_6_0, -4.6_6_6_5, -4.7_6_3_1, -1.8_1_8_0, -3.4_1_7_0, -1.4_2_1_1, -3.1_8_1_0]]      ,	dtype=torch.floataa     )
         torch.testing.assert_close(out.mean(-1     )      ,	UpperCAmelCase__      ,	atol=1e-2      ,	rtol=1e-2     )
         # fmt: off
         A						:     Tuple         =torch.tensor([-9.4_9_2_2, -3.9_5_5_1, 1.7_9_9_8, -5.6_7_5_8, -5.1_0_5_5, -5.8_9_8_4, -4.8_3_2_0, -6.8_0_8_6, -6.5_3_9_1, -5.6_1_7_2, -5.5_8_2_0, -5.5_3_5_2, 1.7_8_8_1, 3.6_2_8_9, -6.5_1_1_7, -3.4_7_8_5, -9.5_0_0_0, -6.0_3_5_2, -6.8_1_2_5, -6.0_1_9_5, -6.6_8_3_6, -5.4_7_2_7, -6.2_8_1_2, -6.0_3_9_1, -7.3_3_9_8, -7.4_2_9_7, -7.4_8_4_4, -6.5_8_2_0, -5.8_7_8_9, -5.5_3_1_2]     )
         # 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 		SCREAMING_SNAKE_CASE_		(				self    :					Union[str, Any]     )    ->				Any:
         A						:     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'
         A						:     Any         ='Simply put, the theory of relativity states that '
         A						:     Dict         =LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf'     )
         A						:     Dict         =tokenizer.encode(UpperCAmelCase__      ,	return_tensors='pt'     )
         A						:     Dict         =LlamaForCausalLM.from_pretrained(
             'meta-llama/Llama-2-13b-chat-hf'      ,	device_map='sequential'      ,	use_safetensors=UpperCAmelCase__     )

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







import collections
import json
import math
import os
import re
import time
from fnmatch import fnmatch
from typing import Dict

import requests
from slack_sdk import WebClient


_lowercase							:      Optional[Any]      							=WebClient(token=os.environ['''CI_SLACK_BOT_TOKEN'''])



def A__  (			lowercase:     Optional[int]					)				->		Optional[int]:
       A						:     str         =test_results.split(' '					)

       A						:     List[str]         =0
       A						:     Tuple         =0

       # When the output is short enough, the output is surrounded by = signs: "== OUTPUT =="
       # When it is too long, those signs are not present.
       A						:     List[str]         =expressions[-2] if '=' in expressions[-1] else expressions[-1]

       for i, expression in enumerate(lowercase					):
              if "failed" in expression:
                     failed += int(expressions[i - 1]					)
              if "passed" in expression:
                     success += int(expressions[i - 1]					)

       return failed, success, time_spent



def A__  (			lowercase:     List[Any]					)				->		str:
       A						:     Union[str, Any]         ={}
       A						:     Optional[Any]         =None
       A						:     Union[str, Any]         =False
       for line in failures_short_lines.split('\n'					):
              if re.search(r'_ \[doctest\]',		lowercase					):
                     A						:     List[Any]         =True
                     A						:     Any         =line.split(' '					)[2]
              elif in_error and not line.split(' '					)[0].isdigit():
                     A						:     Dict         =line
                     A						:     List[str]         =False

       return failures



class  SCREAMING_SNAKE_CASE_ :
  '''simple docstring'''


  def __init__(				self    :					str      ,	SCREAMING_SNAKE_CASE__    :					str      ,	SCREAMING_SNAKE_CASE__    :					Dict     )    ->				List[str]:
         A						:     Tuple         =title

         A						:     Dict         =doc_test_results['time_spent'].split(','     )[0]
         A						:     Union[str, Any]         =doc_test_results['success']
         A						:     Any         =doc_test_results['failures']
         A						:     Optional[Any]         =self.n_success + self.n_failures

         # Failures and success of the modeling tests
         A						:     Union[str, Any]         =doc_test_results







  @property
  def 		SCREAMING_SNAKE_CASE_		(				self    :					Tuple     )    ->				str:
         A						:     Any         =[self._time_spent]
         A						:     List[str]         =0

         for time in time_spent:
                A						:     List[Any]         =time.split(':'     )

                # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute.
                if len(SCREAMING_SNAKE_CASE__     ) == 1:
                       A						:     List[str]         =[0, 0, time_parts[0]]

                A  ,  A  ,  A						:     Tuple         =int(time_parts[0]     ), int(time_parts[1]     ), float(time_parts[2]     )
                total_secs += hours * 36_00 + minutes * 60 + seconds

         A  ,  A  ,  A						:     str         =total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60
         return f'{int(SCREAMING_SNAKE_CASE__     )}h{int(SCREAMING_SNAKE_CASE__     )}m{int(SCREAMING_SNAKE_CASE__     )}s'







  @property
  def 		SCREAMING_SNAKE_CASE_		(				self    :					Tuple     )    ->				Dict:
         return {"type": "header", "text": {"type": "plain_text", "text": self.title}}







  @property
  def 		SCREAMING_SNAKE_CASE_		(				self    :					List[str]     )    ->				Dict:
         return {
             "type": "section",
             "text": {
                 "type": "plain_text",
                 "text": f'🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.',
                 "emoji": True,
             },
             "accessory": {
                 "type": "button",
                 "text": {"type": "plain_text", "text": "Check Action results", "emoji": True},
                 "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}',
             },
         }







  @property
  def 		SCREAMING_SNAKE_CASE_		(				self    :					List[Any]     )    ->				Dict:
         return {
             "type": "section",
             "text": {
                 "type": "plain_text",
                 "text": (
                     f'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in'
                     f' {self.time}.'
                 ),
                 "emoji": True,
             },
             "accessory": {
                 "type": "button",
                 "text": {"type": "plain_text", "text": "Check Action results", "emoji": True},
                 "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}',
             },
         }







  @property
  def 		SCREAMING_SNAKE_CASE_		(				self    :					Optional[int]     )    ->				Dict:
         A						:     Tuple         =40
         A						:     Optional[Any]         ={k: v['failed'] for k, v in doc_test_results.items() if isinstance(SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__     )}

         A						:     Any         =''
         for category, failures in category_failures.items():
                if len(SCREAMING_SNAKE_CASE__     ) == 0:
                       continue

                if report != "":
                       report += "\n\n"

                report += f'*{category} failures*:'.ljust(line_length // 2     ).rjust(line_length // 2     ) + "\n"
                report += "`"
                report += "`\n`".join(SCREAMING_SNAKE_CASE__     )
                report += "`"

         return {
             "type": "section",
             "text": {
                 "type": "mrkdwn",
                 "text": f'The following examples had failures:\n\n\n{report}\n',
             },
         }







  @property
  def 		SCREAMING_SNAKE_CASE_		(				self    :					Optional[Any]     )    ->				str:
         A						:     Optional[int]         =[self.header]

         if self.n_failures > 0:
                blocks.append(self.failures     )

         if self.n_failures > 0:
                blocks.extend([self.category_failures]     )

         if self.n_failures == 0:
                blocks.append(self.no_failures     )

         return json.dumps(SCREAMING_SNAKE_CASE__     )







  @staticmethod
  def 		SCREAMING_SNAKE_CASE_		(				)    ->				Optional[Any]:
         A						:     Tuple         =[
             {
                 'type': 'section',
                 'text': {
                     'type': 'plain_text',
                     'text': 'There was an issue running the tests.',
                 },
                 'accessory': {
                     'type': 'button',
                     'text': {'type': 'plain_text', 'text': 'Check Action results', 'emoji': True},
                     'url': f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}',
                 },
             }
         ]

         print('Sending the following payload'     )
         print(json.dumps({'blocks': json.loads(SCREAMING_SNAKE_CASE__     )}     )     )

         client.chat_postMessage(
             channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY']      ,	text='There was an issue running the tests.'      ,	blocks=SCREAMING_SNAKE_CASE__      ,	)







  def 		SCREAMING_SNAKE_CASE_		(				self    :					Dict     )    ->				Optional[int]:
         print('Sending the following payload'     )
         print(json.dumps({'blocks': json.loads(self.payload     )}     )     )

         A						:     Any         =f'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else 'All tests passed.'

         A						:     Dict         =client.chat_postMessage(
             channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY']      ,	blocks=self.payload      ,	text=SCREAMING_SNAKE_CASE__      ,	)







  def 		SCREAMING_SNAKE_CASE_		(				self    :					Dict      ,	SCREAMING_SNAKE_CASE__    :					List[str]      ,	SCREAMING_SNAKE_CASE__    :					Optional[Any]      ,	SCREAMING_SNAKE_CASE__    :					int      ,	SCREAMING_SNAKE_CASE__    :					Optional[Any]     )    ->				Optional[int]:
         A						:     List[str]         =''
         for key, value in failures.items():
                A						:     Any         =value[:2_00] + ' [Truncated]' if len(SCREAMING_SNAKE_CASE__     ) > 2_50 else value
                failures_text += f'*{key}*\n_{value}_\n\n'

         A						:     Union[str, Any]         =job_name
         A						:     Any         ={'type': 'section', 'text': {'type': 'mrkdwn', 'text': text}}

         if job_link is not None:
                A						:     int         ={
                    'type': 'button',
                    'text': {'type': 'plain_text', 'text': 'GitHub Action job', 'emoji': True},
                    'url': job_link,
                }

         return [
             {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}},
             content,
             {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}},
         ]







  def 		SCREAMING_SNAKE_CASE_		(				self    :					Tuple     )    ->				List[Any]:
         if self.thread_ts is None:
                raise ValueError('Can only post reply if a post has been made.'     )

         A						:     Union[str, Any]         =self.doc_test_results.pop('job_link'     )
         self.doc_test_results.pop('failures'     )
         self.doc_test_results.pop('success'     )
         self.doc_test_results.pop('time_spent'     )

         A						:     Union[str, Any]         =sorted(self.doc_test_results.items()      ,	key=lambda SCREAMING_SNAKE_CASE__     : t[0]     )
         for job, job_result in sorted_dict:
                if len(job_result['failures']     ):
                       A						:     Any         =f'*Num failures* :{len(job_result["failed"]     )} \n'
                       A						:     List[Any]         =job_result['failures']
                       A						:     Any         =self.get_reply_blocks(SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__      ,	text=SCREAMING_SNAKE_CASE__     )

                       print('Sending the following reply'     )
                       print(json.dumps({'blocks': blocks}     )     )

                       client.chat_postMessage(
                           channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY']      ,	text=f'Results for {job}'      ,	blocks=SCREAMING_SNAKE_CASE__      ,	thread_ts=self.thread_ts['ts']      ,	)

                       time.sleep(1     )







def A__  (			)				->		Union[str, Any]:
       A						:     Any         =os.environ['GITHUB_RUN_ID']
       A						:     List[Any]         =F'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100'
       A						:     Union[str, Any]         =requests.get(lowercase					).json()
       A						:     List[Any]         ={}

       try:
              jobs.update({job['name']: job['html_url'] for job in result['jobs']}					)
              A						:     List[str]         =math.ceil((result['total_count'] - 100) / 100					)

              for i in range(lowercase					):
                     A						:     List[str]         =requests.get(url + F'&page={i + 2}'					).json()
                     jobs.update({job['name']: job['html_url'] for job in result['jobs']}					)

              return jobs
       except Exception as e:
              print('Unknown error, could not fetch links.',		lowercase					)

       return {}



def A__  (			lowercase:     str					)				->		Optional[Any]:
       A						:     Any         ={}

       if os.path.exists(lowercase					):
              A						:     List[Any]         =os.listdir(lowercase					)
              for file in files:
                     try:
                            with open(os.path.join(lowercase,		lowercase					),		encoding='utf-8'					) as f:
                                   A						:     Optional[int]         =f.read()
                     except UnicodeDecodeError as e:
                            raise ValueError(F'Could not open {os.path.join(lowercase,		lowercase					)}.'					) from e

       return _artifact



def A__  (			)				->		int:



       class  SCREAMING_SNAKE_CASE_ :
         '''simple docstring'''


         def __init__(				self    :					Optional[int]      ,	SCREAMING_SNAKE_CASE__    :					str     )    ->				List[str]:
                A						:     Dict         =name
                A						:     Dict         =[]







         def __str__(				self    :					Optional[Any]     )    ->				List[str]:
                return self.name







         def 		SCREAMING_SNAKE_CASE_		(				self    :					int      ,	SCREAMING_SNAKE_CASE__    :					str     )    ->				List[Any]:
                self.paths.append({'name': self.name, 'path': path}     )







       A						:     Dict[str, Artifact]         ={}

       A						:     str         =filter(os.path.isdir,		os.listdir()					)
       for directory in directories:
              A						:     Tuple         =directory
              if artifact_name not in _available_artifacts:
                     A						:     int         =Artifact(lowercase					)

                     _available_artifacts[artifact_name].add_path(lowercase					)

       return _available_artifacts


if __name__ == "__main__":
    _lowercase							:      Optional[int]      							=get_job_links()
    _lowercase							:      str      							=retrieve_available_artifacts()

    _lowercase							:      List[Any]      							=collections.OrderedDict(
        [
            ('''*.py''', '''API Examples'''),
            ('''*.md''', '''MD Examples'''),
        ]
    )

    # This dict will contain all the information relative to each doc test category:
    # - failed: list of failed tests
    # - failures: dict in the format 'test': 'error_message'
    _lowercase							:      Optional[Any]      							={
        v: {
            '''failed''': [],
            '''failures''': {},
        }
        for v in docs.values()
    }

    # Link to the GitHub Action job
    _lowercase							:      List[Any]      							=github_actions_job_links.get('''run_doctests''')

    _lowercase							:      int      							=available_artifacts['''doc_tests_gpu_test_reports'''].paths[0]
    _lowercase							:      Dict      							=retrieve_artifact(artifact_path['''name'''])
    if "stats" in artifact:
        _lowercase							,	_lowercase							,	_lowercase							:      List[Any]      							=handle_test_results(artifact['''stats'''])
        _lowercase							:      Any      							=failed
        _lowercase							:      Union[str, Any]      							=success
        _lowercase							:      str      							=time_spent[1:-1] + ''', '''

        _lowercase							:      Any      							=extract_first_line_failure(artifact['''failures_short'''])
        for line in artifact["summary_short"].split('''\n'''):
            if re.search('''FAILED''', line):
                _lowercase							:      Tuple      							=line.replace('''FAILED ''', '''''')
                _lowercase							:      int      							=line.split()[0].replace('''\n''', '''''')

                if "::" in line:
                    _lowercase							,	_lowercase							:      str      							=line.split('''::''')
                else:
                    _lowercase							,	_lowercase							:      Union[str, Any]      							=line, line

                for file_regex in docs.keys():
                    if fnmatch(file_path, file_regex):
                        _lowercase							:      Any      							=docs[file_regex]
                        doc_test_results[category]["failed"].append(test)

                        _lowercase							:      Any      							=all_failures[test] if test in all_failures else '''N/A'''
                        _lowercase							:      Tuple      							=failure
                        break

    _lowercase							:      Optional[int]      							=Message('''🤗 Results of the doc tests.''', doc_test_results)
    message.post()
    message.post_reply()






