
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			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_=13			,     SCREAMING_SNAKE_CASE_=7			,     SCREAMING_SNAKE_CASE_=True			,     SCREAMING_SNAKE_CASE_=True			,     SCREAMING_SNAKE_CASE_=False			,     SCREAMING_SNAKE_CASE_=True			,     SCREAMING_SNAKE_CASE_=99			,     SCREAMING_SNAKE_CASE_=32			,     SCREAMING_SNAKE_CASE_=5			,     SCREAMING_SNAKE_CASE_=4			,     SCREAMING_SNAKE_CASE_=37			,     SCREAMING_SNAKE_CASE_="gelu"			,     SCREAMING_SNAKE_CASE_=0.1			,     SCREAMING_SNAKE_CASE_=0.1			,     SCREAMING_SNAKE_CASE_=5_12			,     SCREAMING_SNAKE_CASE_=16			,     SCREAMING_SNAKE_CASE_=2			,     SCREAMING_SNAKE_CASE_=0.02			,     SCREAMING_SNAKE_CASE_=3			,     SCREAMING_SNAKE_CASE_=4			,     SCREAMING_SNAKE_CASE_=None			,     ):
       UpperCamelCase__												=							parent
       UpperCamelCase__												=							batch_size
       UpperCamelCase__												=							seq_length
       UpperCamelCase__												=							is_training
       UpperCamelCase__												=							use_input_mask
       UpperCamelCase__												=							use_token_type_ids
       UpperCamelCase__												=							use_labels
       UpperCamelCase__												=							vocab_size
       UpperCamelCase__												=							hidden_size
       UpperCamelCase__												=							num_hidden_layers
       UpperCamelCase__												=							num_attention_heads
       UpperCamelCase__												=							intermediate_size
       UpperCamelCase__												=							hidden_act
       UpperCamelCase__												=							hidden_dropout_prob
       UpperCamelCase__												=							attention_probs_dropout_prob
       UpperCamelCase__												=							max_position_embeddings
       UpperCamelCase__												=							type_vocab_size
       UpperCamelCase__												=							type_sequence_label_size
       UpperCamelCase__												=							initializer_range
       UpperCamelCase__												=							num_labels
       UpperCamelCase__												=							num_choices
       UpperCamelCase__												=							scope







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

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

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

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

       UpperCamelCase__												=							self.get_config()

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







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







  def 			UpperCAmelCase_   (self			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_		):
       UpperCamelCase__												=							LlamaModel(config=__UpperCamelCase		)
       model.to(__UpperCamelCase		)
       model.eval()
       UpperCamelCase__												=							model(__UpperCamelCase			,     attention_mask=__UpperCamelCase		)
       UpperCamelCase__												=							model(__UpperCamelCase		)
       self.parent.assertEqual(result.last_hidden_state.shape			,     (self.batch_size, self.seq_length, self.hidden_size)		)







  def 			UpperCAmelCase_   (self			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     ):
       UpperCamelCase__												=							True
       UpperCamelCase__												=							LlamaModel(__UpperCamelCase		)
       model.to(__UpperCamelCase		)
       model.eval()
       UpperCamelCase__												=							model(
           __UpperCamelCase			,     attention_mask=__UpperCamelCase			,     encoder_hidden_states=__UpperCamelCase			,     encoder_attention_mask=__UpperCamelCase			,     )
       UpperCamelCase__												=							model(
           __UpperCamelCase			,     attention_mask=__UpperCamelCase			,     encoder_hidden_states=__UpperCamelCase			,     )
       UpperCamelCase__												=							model(__UpperCamelCase			,     attention_mask=__UpperCamelCase		)
       self.parent.assertEqual(result.last_hidden_state.shape			,     (self.batch_size, self.seq_length, self.hidden_size)		)







  def 			UpperCAmelCase_   (self			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     ):
       UpperCamelCase__												=							LlamaForCausalLM(config=__UpperCamelCase		)
       model.to(__UpperCamelCase		)
       model.eval()
       UpperCamelCase__												=							model(__UpperCamelCase			,     attention_mask=__UpperCamelCase			,     labels=__UpperCamelCase		)
       self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.seq_length, self.vocab_size)		)







  def 			UpperCAmelCase_   (self			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     SCREAMING_SNAKE_CASE_			,     ):
       UpperCamelCase__												=							True
       UpperCamelCase__												=							True
       UpperCamelCase__												=							LlamaForCausalLM(config=__UpperCamelCase		)
       model.to(__UpperCamelCase		)
       model.eval()

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

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

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

       UpperCamelCase__												=							model(
           __UpperCamelCase			,     attention_mask=__UpperCamelCase			,     encoder_hidden_states=__UpperCamelCase			,     encoder_attention_mask=__UpperCamelCase			,     output_hidden_states=__UpperCamelCase			,     )["""hidden_states"""][0]
       UpperCamelCase__												=							model(
           __UpperCamelCase			,     attention_mask=__UpperCamelCase			,     encoder_hidden_states=__UpperCamelCase			,     encoder_attention_mask=__UpperCamelCase			,     past_key_values=__UpperCamelCase			,     output_hidden_states=__UpperCamelCase			,     )["""hidden_states"""][0]

       # select random slice
       UpperCamelCase__												=							ids_tensor((1,)			,     output_from_past.shape[-1]		).item()
       UpperCamelCase__												=							output_from_no_past[:, -3:, random_slice_idx].detach()
       UpperCamelCase__												=							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 			UpperCAmelCase_   (self		):
       UpperCamelCase__												=							self.prepare_config_and_inputs()
       (
           (
           UpperCamelCase__
       )						,			(
           UpperCamelCase__
       )						,			(
           UpperCamelCase__
       )						,			(
           UpperCamelCase__
       )						,			(
           UpperCamelCase__
       )						,			(
           UpperCamelCase__
       )						,			(
           UpperCamelCase__
       )						,			
       )												=							config_and_inputs
       UpperCamelCase__												=							{"""input_ids""": input_ids, """attention_mask""": input_mask}
       return config, inputs_dict






@require_torch
class       __A(							_UpperCAmelCase							, _UpperCAmelCase							, _UpperCAmelCase							, unittest.TestCase					):

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







  def 			UpperCAmelCase_   (self		):
       UpperCamelCase__												=							LlamaModelTester(self		)
       UpperCamelCase__												=							ConfigTester(self			,     config_class=__UpperCamelCase			,     hidden_size=37		)







  def 			UpperCAmelCase_   (self		):
       self.config_tester.run_common_tests()







  def 			UpperCAmelCase_   (self		):
       UpperCamelCase__												=							self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__UpperCamelCase		)







  def 			UpperCAmelCase_   (self		):
       UpperCamelCase__												=							self.model_tester.prepare_config_and_inputs()
       for type in ["absolute", "relative_key", "relative_key_query"]:
            UpperCamelCase__												=							type
            self.model_tester.create_and_check_model(*__UpperCamelCase		)







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







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







  def 			UpperCAmelCase_   (self		):
       UpperCamelCase__						,			UpperCamelCase__												=							self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase__												=							3
       UpperCamelCase__												=							"""multi_label_classification"""
       UpperCamelCase__												=							input_dict["""input_ids"""]
       UpperCamelCase__												=							input_ids.ne(1		).to(__UpperCamelCase		)
       UpperCamelCase__												=							ids_tensor(
           [self.model_tester.batch_size, config.num_labels]			,     self.model_tester.type_sequence_label_size		).to(torch.float		)
       UpperCamelCase__												=							LlamaForSequenceClassification(__UpperCamelCase		)
       model.to(__UpperCamelCase		)
       model.eval()
       UpperCamelCase__												=							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 			UpperCAmelCase_   (self		):
       pass







  @parameterized.expand([("""linear""",), ("""dynamic""",)]		)
  def 			UpperCAmelCase_   (self			,     SCREAMING_SNAKE_CASE_		):
       UpperCamelCase__						,			UpperCamelCase__												=							self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase__												=							ids_tensor([1, 10]			,     config.vocab_size		)
       UpperCamelCase__												=							ids_tensor([1, int(config.max_position_embeddings * 1.5		)]			,     config.vocab_size		)

       set_seed(42		)  # Fixed seed at init time so the two models get the same random weights
       UpperCamelCase__												=							LlamaModel(__UpperCamelCase		)
       original_model.to(__UpperCamelCase		)
       original_model.eval()
       UpperCamelCase__												=							original_model(__UpperCamelCase		).last_hidden_state
       UpperCamelCase__												=							original_model(__UpperCamelCase		).last_hidden_state

       set_seed(42		)  # Fixed seed at init time so the two models get the same random weights
       UpperCamelCase__												=							{"""type""": scaling_type, """factor""": 10.0}
       UpperCamelCase__												=							LlamaModel(__UpperCamelCase		)
       scaled_model.to(__UpperCamelCase		)
       scaled_model.eval()
       UpperCamelCase__												=							scaled_model(__UpperCamelCase		).last_hidden_state
       UpperCamelCase__												=							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       __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		):
       UpperCamelCase__												=							[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38]
       UpperCamelCase__												=							LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-7b-hf"""			,     device_map="""auto"""		)
       UpperCamelCase__												=							model(torch.tensor([input_ids]		)		)
       # Expected mean on dim = -1
       UpperCamelCase__												=							torch.tensor([[-6.6550, -4.1227, -4.9859, -3.2406, 0.8262, -3.0033, 1.2964, -3.3699]]		)
       torch.testing.assert_close(out.mean(-1		)			,     __UpperCamelCase			,     atol=1E-2			,     rtol=1E-2		)
       # slicing logits[0, 0, 0:30]
       # fmt: off
       UpperCamelCase__												=							torch.tensor([-12.82_81, -7.4453, -0.4639, -8.0625, -7.2500, -8.0000, -6.4883, -7.7695, -7.8438, -7.0312, -6.2188, -7.1328, -1.8496, 1.9961, -8.6250, -6.7227, -12.82_81, -6.9492, -7.0742, -7.7852, -7.5820, -7.9062, -6.9375, -7.9805, -8.3438, -8.1562, -8.0469, -7.6250, -7.7422, -7.3398,]		)
       # fmt: on
       torch.testing.assert_close(out[0, 0, :30]			,     __UpperCamelCase			,     atol=1E-5			,     rtol=1E-5		)







  @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!"""		)
  @slow
  def 			UpperCAmelCase_   (self		):
       UpperCamelCase__												=							[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38]
       UpperCamelCase__												=							LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-hf"""			,     device_map="""auto"""		)
       UpperCamelCase__												=							model(torch.tensor(__UpperCamelCase		)		)
       # Expected mean on dim = -1
       UpperCamelCase__												=							torch.tensor([[-2.0622, -1.2794, -1.1638, -0.9788, -1.4603, -1.0238, -1.7893, -1.4411]]		)
       torch.testing.assert_close(out.mean(-1		)			,     __UpperCamelCase			,     atol=1E-2			,     rtol=1E-2		)
       # slicing logits[0, 0, 0:30]
       # fmt: off
       UpperCamelCase__												=							torch.tensor([-8.1406, -8.0547, 2.7461, -1.2344, -0.1448, -1.8262, -1.0020, -1.8154, -1.6895, -1.8516, -2.3574, -0.9277, 3.7598, 6.5742, -1.2998, -0.1177, -8.1406, -2.9688, -2.9199, -3.1699, -3.5254, -2.3555, -2.7988, -3.4141, -2.8262, -4.5195, -3.3379, -3.3164, -2.7832, -3.0273]		)
       # fmt: on
       torch.testing.assert_close(out[0, 0, :30]			,     __UpperCamelCase			,     atol=1E-5			,     rtol=1E-5		)







  @unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!"""		)
  @slow
  def 			UpperCAmelCase_   (self		):
       UpperCamelCase__												=							[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38]
       UpperCamelCase__												=							LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-chat-hf"""			,     device_map="""auto"""		)
       UpperCamelCase__												=							model(torch.tensor(__UpperCamelCase		)		)
       # Expected mean on dim = -1
       UpperCamelCase__												=							torch.tensor([[-0.8562, -1.8520, -0.7551, -0.4162, -1.5161, -1.2038, -2.4823, -2.3254]]		)
       torch.testing.assert_close(out.mean(-1		)			,     __UpperCamelCase			,     atol=1E-2			,     rtol=1E-2		)
       # slicing logits[0, 0, 0:30]
       # fmt: off
       UpperCamelCase__												=							torch.tensor([-2.2227, 4.8828, 0.9023, -0.4578, -0.7871, -0.1033, -0.6221, -0.5786, -0.7803, -1.0674, -1.2920, -0.1570, 0.8008, 2.0723, -0.9497, 0.2771, -2.2227, -0.7612, -1.4346, -1.2061, -1.6426, -0.3000, -0.7139, -1.1934, -1.8691, -1.6973, -1.5947, -1.2705, -0.3523, -0.5513]		)
       # fmt: on
       torch.testing.assert_close(out.mean(-1		)			,     __UpperCamelCase			,     atol=1E-2			,     rtol=1E-2		)







  @unittest.skip(
      """Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test"""		)
  @slow
  def 			UpperCAmelCase_   (self		):
       UpperCamelCase__												=							[1, 3_06, 46_58, 2_78, 65_93, 3_10, 28_34, 3_38]
       UpperCamelCase__												=							LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-70b-hf"""			,     device_map="""auto"""		)
       UpperCamelCase__												=							model(torch.tensor(__UpperCamelCase		)		)

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







  @unittest.skip("""Model is curently gated"""		)
  @slow
  def 			UpperCAmelCase_   (self		):
       UpperCamelCase__												=							"""Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the \"princi"""
       UpperCamelCase__												=							"""Simply put, the theory of relativity states that """
       UpperCamelCase__												=							LlamaTokenizer.from_pretrained("""meta-llama/Llama-2-13b-chat-hf"""		)
       UpperCamelCase__												=							tokenizer.encode(__UpperCamelCase			,     return_tensors="""pt"""		)
       UpperCamelCase__												=							LlamaForCausalLM.from_pretrained(
           """meta-llama/Llama-2-13b-chat-hf"""			,     device_map="""sequential"""			,     use_safetensors=__UpperCamelCase		)

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







"""simple docstring"""



import copy
import os
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import pytest

from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence
from datasets.features import ArrayaD, ClassLabel, Features, Image, Value
from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects
from datasets.keyhash import DuplicatedKeysError, InvalidKeyError

from .utils import require_pil




class 		a_    (			_UpperCAmelCase						):







    def   _snake_case       (      self      :							int  )		->Union[str, Any]:






        '''simple docstring'''






        _UpperCAmelCase        = pa.array(TypedSequence([1, 2, 3]  )  )
        self.assertEqual(arr.type  ,       pa.intaa()  )







    def   _snake_case       (      self      :							List[Any]  )		->Any:






        '''simple docstring'''






        with self.assertRaises(__UpperCamelCase  ):
            _UpperCAmelCase        = pa.array(TypedSequence([1, 2, 3]  )  ,       type=pa.intaa()  )







    def   _snake_case       (      self      :							Tuple  )		->int:






        '''simple docstring'''






        with self.assertRaises(__UpperCamelCase  ):
            _UpperCAmelCase        = pa.array(TypedSequence([1, 2, 3]  ,       try_type=Value("""bool"""  )  ,       type=Value("""int64"""  )  )  )







    def   _snake_case       (      self      :							Optional[Any]  )		->Tuple:






        '''simple docstring'''






        _UpperCAmelCase        = pa.array(TypedSequence([1, 2, 3]  ,       type=Value("""int32"""  )  )  )
        self.assertEqual(arr.type  ,       pa.intaa()  )







    def   _snake_case       (      self      :							List[Any]  )		->int:






        '''simple docstring'''






        with self.assertRaises((TypeError, pa.lib.ArrowInvalid)  ):
            _UpperCAmelCase        = pa.array(TypedSequence(["""foo""", """bar"""]  ,       type=Value("""int64"""  )  )  )







    def   _snake_case       (      self      :							int  )		->Tuple:






        '''simple docstring'''






        _UpperCAmelCase        = pa.array(TypedSequence([1, 2, 3]  ,       try_type=Value("""int32"""  )  )  )
        self.assertEqual(arr.type  ,       pa.intaa()  )







    def   _snake_case       (      self      :							Dict  )		->str:






        '''simple docstring'''






        _UpperCAmelCase        = pa.array(TypedSequence(["""foo""", """bar"""]  ,       try_type=Value("""int64"""  )  )  )
        self.assertEqual(arr.type  ,       pa.string()  )







    def   _snake_case       (      self      :							Union[str, Any]  )		->Optional[int]:






        '''simple docstring'''






        _UpperCAmelCase        = pa.array(TypedSequence([[[1, 2, 3]]]  ,       type=ArrayaD((1, 3)  ,       """int64"""  )  )  )
        self.assertEqual(arr.type  ,       ArrayaDExtensionType((1, 3)  ,       """int64"""  )  )







    def   _snake_case       (      self      :							Tuple  )		->Any:






        '''simple docstring'''






        with self.assertRaises((TypeError, pa.lib.ArrowInvalid)  ):
            _UpperCAmelCase        = pa.array(TypedSequence(["""foo""", """bar"""]  ,       type=ArrayaD((1, 3)  ,       """int64"""  )  )  )







    def   _snake_case       (      self      :							List[Any]  )		->List[Any]:






        '''simple docstring'''






        _UpperCAmelCase        = pa.array(TypedSequence([[[1, 2, 3]]]  ,       try_type=ArrayaD((1, 3)  ,       """int64"""  )  )  )
        self.assertEqual(arr.type  ,       ArrayaDExtensionType((1, 3)  ,       """int64"""  )  )







    def   _snake_case       (      self      :							Any  )		->Dict:






        '''simple docstring'''






        _UpperCAmelCase        = pa.array(TypedSequence(["""foo""", """bar"""]  ,       try_type=ArrayaD((1, 3)  ,       """int64"""  )  )  )
        self.assertEqual(arr.type  ,       pa.string()  )







    @require_pil
    def   _snake_case       (      self      :							Optional[Any]  )		->Tuple:






        '''simple docstring'''






        import PIL.Image

        _UpperCAmelCase        = PIL.Image.fromarray(np.arange(10  ,       dtype=np.uinta  ).reshape(2  ,       5  )  )
        with patch(
            """datasets.arrow_writer.cast_to_python_objects"""  ,       side_effect=__UpperCamelCase  ) as mock_cast_to_python_objects:
            _UpperCAmelCase        = pa.array(TypedSequence([{"""path""": None, """bytes""": b"""image_bytes"""}, pil_image]  ,       type=Image()  )  )
            _UpperCAmelCase     ,_UpperCAmelCase        = mock_cast_to_python_objects.call_args_list[-1]
            self.assertIn("""optimize_list_casting"""  ,       __UpperCamelCase  )
            self.assertFalse(kwargs["""optimize_list_casting"""]  )







def 			_UpperCamelCase						(    _A       ,   _A   )     ->	Dict:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferReader(_A   ) if isinstance(_A       ,   pa.Buffer   ) else pa.memory_map(_A   )
    _UpperCAmelCase        = pa.ipc.open_stream(_A   )
    _UpperCAmelCase        = f.read_all()
    assert len(pa_table.to_batches()   ) == expected_num_chunks
    assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}
    del pa_table


@pytest.mark.parametrize("""writer_batch_size"""       ,   [None, 1, 1_0]   )
@pytest.mark.parametrize(
    """fields"""       ,   [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}]   )
def 			_UpperCamelCase						(    _A       ,   _A   )     ->	Any:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferOutputStream()
    _UpperCAmelCase        = pa.schema(_A   ) if fields else None
    with ArrowWriter(stream=_A       ,   schema=_A       ,   writer_batch_size=_A   ) as writer:
        writer.write({"""col_1""": """foo""", """col_2""": 1}   )
        writer.write({"""col_1""": """bar""", """col_2""": 2}   )
        _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    if not fields:
        _UpperCAmelCase        = {"""col_1""": pa.string(), """col_2""": pa.intaa()}
    assert writer._schema == pa.schema(_A       ,   metadata=writer._schema.metadata   )
    _check_output(output.getvalue()       ,   expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )


def 			_UpperCamelCase						(    )     ->	Dict:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferOutputStream()
    _UpperCAmelCase        = Features({"""labels""": ClassLabel(names=["""neg""", """pos"""]   )}   )
    with ArrowWriter(stream=_A       ,   features=_A   ) as writer:
        writer.write({"""labels""": 0}   )
        writer.write({"""labels""": 1}   )
        _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    assert writer._schema == features.arrow_schema
    assert writer._schema.metadata == features.arrow_schema.metadata
    _UpperCAmelCase        = pa.BufferReader(output.getvalue()   )
    _UpperCAmelCase        = pa.ipc.open_stream(_A   )
    _UpperCAmelCase        = f.read_all()
    _UpperCAmelCase        = pa_table.schema
    assert pa_table.num_rows == 2
    assert schema == features.arrow_schema
    assert schema.metadata == features.arrow_schema.metadata
    assert features == Features.from_arrow_schema(_A   )


@pytest.mark.parametrize("""writer_batch_size"""       ,   [None, 1, 1_0]   )
def 			_UpperCamelCase						(    _A   )     ->	int:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferOutputStream()
    with ArrowWriter(
        stream=_A       ,   writer_batch_size=_A       ,   hash_salt="""split_name"""       ,   check_duplicates=_A       ,   ) as writer:
        with pytest.raises(_A   ):
            writer.write({"""col_1""": """foo""", """col_2""": 1}       ,   key=[1, 2]   )
            _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()


@pytest.mark.parametrize("""writer_batch_size"""       ,   [None, 2, 1_0]   )
def 			_UpperCamelCase						(    _A   )     ->	List[Any]:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferOutputStream()
    with ArrowWriter(
        stream=_A       ,   writer_batch_size=_A       ,   hash_salt="""split_name"""       ,   check_duplicates=_A       ,   ) as writer:
        with pytest.raises(_A   ):
            writer.write({"""col_1""": """foo""", """col_2""": 1}       ,   key=1_0   )
            writer.write({"""col_1""": """bar""", """col_2""": 2}       ,   key=1_0   )
            _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()


@pytest.mark.parametrize("""writer_batch_size"""       ,   [None, 2, 1_0]   )
def 			_UpperCamelCase						(    _A   )     ->	Dict:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferOutputStream()
    with ArrowWriter(
        stream=_A       ,   writer_batch_size=_A       ,   hash_salt="""split_name"""       ,   check_duplicates=_A       ,   ) as writer:
        writer.write({"""col_1""": """foo""", """col_2""": 1}       ,   key=1   )
        writer.write({"""col_1""": """bar""", """col_2""": 2}       ,   key=2   )
        _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    _check_output(output.getvalue()       ,   expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )


@pytest.mark.parametrize("""writer_batch_size"""       ,   [None, 1, 1_0]   )
@pytest.mark.parametrize(
    """fields"""       ,   [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}]   )
def 			_UpperCamelCase						(    _A       ,   _A   )     ->	Any:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferOutputStream()
    _UpperCAmelCase        = pa.schema(_A   ) if fields else None
    with ArrowWriter(stream=_A       ,   schema=_A       ,   writer_batch_size=_A   ) as writer:
        writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]}   )
        writer.write_batch({"""col_1""": [], """col_2""": []}   )
        _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    if not fields:
        _UpperCAmelCase        = {"""col_1""": pa.string(), """col_2""": pa.intaa()}
    assert writer._schema == pa.schema(_A       ,   metadata=writer._schema.metadata   )
    _check_output(output.getvalue()       ,   expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )


@pytest.mark.parametrize("""writer_batch_size"""       ,   [None, 1, 1_0]   )
@pytest.mark.parametrize(
    """fields"""       ,   [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}]   )
def 			_UpperCamelCase						(    _A       ,   _A   )     ->	str:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferOutputStream()
    _UpperCAmelCase        = pa.schema(_A   ) if fields else None
    with ArrowWriter(stream=_A       ,   schema=_A       ,   writer_batch_size=_A   ) as writer:
        writer.write_table(pa.Table.from_pydict({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]}   )   )
        _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    if not fields:
        _UpperCAmelCase        = {"""col_1""": pa.string(), """col_2""": pa.intaa()}
    assert writer._schema == pa.schema(_A       ,   metadata=writer._schema.metadata   )
    _check_output(output.getvalue()       ,   expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )


@pytest.mark.parametrize("""writer_batch_size"""       ,   [None, 1, 1_0]   )
@pytest.mark.parametrize(
    """fields"""       ,   [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}]   )
def 			_UpperCamelCase						(    _A       ,   _A   )     ->	int:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferOutputStream()
    _UpperCAmelCase        = pa.schema(_A   ) if fields else None
    with ArrowWriter(stream=_A       ,   schema=_A       ,   writer_batch_size=_A   ) as writer:
        writer.write_row(pa.Table.from_pydict({"""col_1""": ["""foo"""], """col_2""": [1]}   )   )
        writer.write_row(pa.Table.from_pydict({"""col_1""": ["""bar"""], """col_2""": [2]}   )   )
        _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    if not fields:
        _UpperCAmelCase        = {"""col_1""": pa.string(), """col_2""": pa.intaa()}
    assert writer._schema == pa.schema(_A       ,   metadata=writer._schema.metadata   )
    _check_output(output.getvalue()       ,   expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )


def 			_UpperCamelCase						(    )     ->	Dict:





    """simple docstring"""

    with tempfile.TemporaryDirectory() as tmp_dir:
        _UpperCAmelCase        = {"""col_1""": pa.string(), """col_2""": pa.intaa()}
        _UpperCAmelCase        = os.path.join(_A       ,   """test.arrow"""   )
        with ArrowWriter(path=_A       ,   schema=pa.schema(_A   )   ) as writer:
            writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]}   )
            _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()
        assert num_examples == 2
        assert num_bytes > 0
        assert writer._schema == pa.schema(_A       ,   metadata=writer._schema.metadata   )
        _check_output(_A       ,   1   )


def 			_UpperCamelCase						(    _A   )     ->	Optional[int]:





    """simple docstring"""

    if pa.types.is_list(_A   ):
        return get_base_dtype(arr_type.value_type   )
    else:
        return arr_type


def 			_UpperCamelCase						(    _A       ,   _A   )     ->	str:





    """simple docstring"""

    if isinstance(lst[0]       ,   _A   ):
        change_first_primitive_element_in_list(lst[0]       ,   _A   )
    else:
        _UpperCAmelCase        = value


@pytest.mark.parametrize("""optimized_int_type, expected_dtype"""       ,   [(None, pa.intaa()), (Value("""int32"""   ), pa.intaa())]   )
@pytest.mark.parametrize("""sequence"""       ,   [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]   )
def 			_UpperCamelCase						(    _A       ,   _A       ,   _A   )     ->	Optional[int]:





    """simple docstring"""

    _UpperCAmelCase        = pa.array(TypedSequence(_A       ,   optimized_int_type=_A   )   )
    assert get_base_dtype(arr.type   ) == expected_dtype


@pytest.mark.parametrize(
    """col, expected_dtype"""       ,   [
        ("""attention_mask""", pa.inta()),
        ("""special_tokens_mask""", pa.inta()),
        ("""token_type_ids""", pa.inta()),
        ("""input_ids""", pa.intaa()),
        ("""other""", pa.intaa()),
    ]       ,   )
@pytest.mark.parametrize("""sequence"""       ,   [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]   )
def 			_UpperCamelCase						(    _A       ,   _A       ,   _A   )     ->	Any:





    """simple docstring"""

    _UpperCAmelCase        = pa.array(OptimizedTypedSequence(_A       ,   col=_A   )   )
    assert get_base_dtype(arr.type   ) == expected_dtype

    # not in range
    if col != "other":
        # avoids errors due to in-place modifications
        _UpperCAmelCase        = copy.deepcopy(_A   )
        _UpperCAmelCase        = np.iinfo(expected_dtype.to_pandas_dtype()   ).max + 1
        change_first_primitive_element_in_list(_A       ,   _A   )
        _UpperCAmelCase        = pa.array(OptimizedTypedSequence(_A       ,   col=_A   )   )
        assert get_base_dtype(arr.type   ) == pa.intaa()


@pytest.mark.parametrize("""raise_exception"""       ,   [False, True]   )
def 			_UpperCamelCase						(    _A       ,   _A   )     ->	Optional[Any]:





    """simple docstring"""

    _UpperCAmelCase        = str(tmp_path / """dataset-train.arrow"""   )
    try:
        with ArrowWriter(path=_A   ) as writer:
            if raise_exception:
                raise pa.lib.ArrowInvalid()
            else:
                writer.stream.close()
    except pa.lib.ArrowInvalid:
        pass
    finally:
        assert writer.stream.closed


def 			_UpperCamelCase						(    _A   )     ->	List[str]:





    """simple docstring"""

    _UpperCAmelCase        = """mock://dataset-train.arrow"""
    with ArrowWriter(path=_A       ,   storage_options=mockfs.storage_options   ) as writer:
        assert isinstance(writer._fs       ,   type(_A   )   )
        assert writer._fs.storage_options == mockfs.storage_options
        writer.write({"""col_1""": """foo""", """col_2""": 1}   )
        writer.write({"""col_1""": """bar""", """col_2""": 2}   )
        _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    assert mockfs.exists(_A   )


def 			_UpperCamelCase						(    )     ->	List[Any]:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferOutputStream()
    with ParquetWriter(stream=_A   ) as writer:
        writer.write({"""col_1""": """foo""", """col_2""": 1}   )
        writer.write({"""col_1""": """bar""", """col_2""": 2}   )
        _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    _UpperCAmelCase        = pa.BufferReader(output.getvalue()   )
    _UpperCAmelCase        = pq.read_table(_A   )
    assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}


@require_pil
@pytest.mark.parametrize("""embed_local_files"""       ,   [False, True]   )
def 			_UpperCamelCase						(    _A       ,   _A   )     ->	Union[str, Any]:





    """simple docstring"""

    import PIL.Image

    _UpperCAmelCase        = str(tmp_path / """test_image_rgb.jpg"""   )
    PIL.Image.fromarray(np.zeros((5, 5)       ,   dtype=np.uinta   )   ).save(_A       ,   format="""png"""   )
    _UpperCAmelCase        = pa.BufferOutputStream()
    with ParquetWriter(
        stream=_A       ,   features=Features({"""image""": Image()}   )       ,   embed_local_files=_A   ) as writer:
        writer.write({"""image""": image_path}   )
        writer.finalize()
    _UpperCAmelCase        = pa.BufferReader(output.getvalue()   )
    _UpperCAmelCase        = pq.read_table(_A   )
    _UpperCAmelCase        = pa_table.to_pydict()
    if embed_local_files:
        assert isinstance(out["""image"""][0]["""path"""]       ,   _A   )
        with open(_A       ,   """rb"""   ) as f:
            assert out["image"][0]["bytes"] == f.read()
    else:
        assert out["image"][0]["path"] == image_path
        assert out["image"][0]["bytes"] is None







def 			_UpperCamelCase						(    )     ->	Tuple:





    """simple docstring"""

    _UpperCAmelCase        = pa.schema([pa.field("""col_1"""       ,   pa.string()       ,   nullable=_A   )]   )
    _UpperCAmelCase        = pa.BufferOutputStream()
    with ArrowWriter(stream=_A   ) as writer:
        writer._build_writer(inferred_schema=_A   )
        assert writer._schema == pa.schema([pa.field("""col_1"""       ,   pa.string()   )]   )