





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

  """simple docstring"""


  def __init__(							self					:						Any   ,    lowerCAmelCase_					:						Optional[int]   ,    lowerCAmelCase_					:						Any=1_3   ,    lowerCAmelCase_					:						List[Any]=7   ,    lowerCAmelCase_					:						List[str]=True   ,    lowerCAmelCase_					:						Union[str, Any]=True   ,    lowerCAmelCase_					:						List[Any]=False   ,    lowerCAmelCase_					:						List[Any]=True   ,    lowerCAmelCase_					:						Any=9_9   ,    lowerCAmelCase_					:						List[str]=3_2   ,    lowerCAmelCase_					:						List[Any]=5   ,    lowerCAmelCase_					:						List[Any]=4   ,    lowerCAmelCase_					:						List[Any]=3_7   ,    lowerCAmelCase_					:						Tuple="gelu"   ,    lowerCAmelCase_					:						Dict=0.1   ,    lowerCAmelCase_					:						List[Any]=0.1   ,    lowerCAmelCase_					:						Any=5_1_2   ,    lowerCAmelCase_					:						List[Any]=1_6   ,    lowerCAmelCase_					:						Tuple=2   ,    lowerCAmelCase_					:						int=0.02   ,    lowerCAmelCase_					:						List[str]=3   ,    lowerCAmelCase_					:						List[Any]=4   ,    lowerCAmelCase_					:						Dict=None   ,    )				->		List[Any]:
     __lowerCAmelCase				      =      parent
     __lowerCAmelCase				      =      batch_size
     __lowerCAmelCase				      =      seq_length
     __lowerCAmelCase				      =      is_training
     __lowerCAmelCase				      =      use_input_mask
     __lowerCAmelCase				      =      use_token_type_ids
     __lowerCAmelCase				      =      use_labels
     __lowerCAmelCase				      =      vocab_size
     __lowerCAmelCase				      =      hidden_size
     __lowerCAmelCase				      =      num_hidden_layers
     __lowerCAmelCase				      =      num_attention_heads
     __lowerCAmelCase				      =      intermediate_size
     __lowerCAmelCase				      =      hidden_act
     __lowerCAmelCase				      =      hidden_dropout_prob
     __lowerCAmelCase				      =      attention_probs_dropout_prob
     __lowerCAmelCase				      =      max_position_embeddings
     __lowerCAmelCase				      =      type_vocab_size
     __lowerCAmelCase				      =      type_sequence_label_size
     __lowerCAmelCase				      =      initializer_range
     __lowerCAmelCase				      =      num_labels
     __lowerCAmelCase				      =      num_choices
     __lowerCAmelCase				      =      scope






  def 							lowercase						(							self					:						List[Any]	)				->		Dict:
     __lowerCAmelCase				      =      ids_tensor([self.batch_size, self.seq_length]   ,    self.vocab_size	)

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

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

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

     __lowerCAmelCase				      =      self.get_config()

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






  def 							lowercase						(							self					:						Union[str, Any]	)				->		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=lowerCAmelCase_   ,    initializer_range=self.initializer_range   ,    )






  def 							lowercase						(							self					:						List[Any]   ,    lowerCAmelCase_					:						Optional[int]   ,    lowerCAmelCase_					:						List[Any]   ,    lowerCAmelCase_					:						Optional[Any]   ,    lowerCAmelCase_					:						List[str]   ,    lowerCAmelCase_					:						Dict   ,    lowerCAmelCase_					:						Any   ,    lowerCAmelCase_					:						Union[str, Any]	)				->		Dict:
     __lowerCAmelCase				      =      LlamaModel(config=lowerCAmelCase_	)
     model.to(lowerCAmelCase_	)
     model.eval()
     __lowerCAmelCase				      =      model(lowerCAmelCase_   ,    attention_mask=lowerCAmelCase_	)
     __lowerCAmelCase				      =      model(lowerCAmelCase_	)
     self.parent.assertEqual(result.last_hidden_state.shape   ,    (self.batch_size, self.seq_length, self.hidden_size)	)






  def 							lowercase						(							self					:						Union[str, Any]   ,    lowerCAmelCase_					:						Union[str, Any]   ,    lowerCAmelCase_					:						Dict   ,    lowerCAmelCase_					:						List[str]   ,    lowerCAmelCase_					:						Optional[int]   ,    lowerCAmelCase_					:						Optional[int]   ,    lowerCAmelCase_					:						Tuple   ,    lowerCAmelCase_					:						List[str]   ,    lowerCAmelCase_					:						Union[str, Any]   ,    lowerCAmelCase_					:						Union[str, Any]   ,    )				->		int:
     __lowerCAmelCase				      =      True
     __lowerCAmelCase				      =      LlamaModel(lowerCAmelCase_	)
     model.to(lowerCAmelCase_	)
     model.eval()
     __lowerCAmelCase				      =      model(
         lowerCAmelCase_   ,    attention_mask=lowerCAmelCase_   ,    encoder_hidden_states=lowerCAmelCase_   ,    encoder_attention_mask=lowerCAmelCase_   ,    )
     __lowerCAmelCase				      =      model(
         lowerCAmelCase_   ,    attention_mask=lowerCAmelCase_   ,    encoder_hidden_states=lowerCAmelCase_   ,    )
     __lowerCAmelCase				      =      model(lowerCAmelCase_   ,    attention_mask=lowerCAmelCase_	)
     self.parent.assertEqual(result.last_hidden_state.shape   ,    (self.batch_size, self.seq_length, self.hidden_size)	)






  def 							lowercase						(							self					:						int   ,    lowerCAmelCase_					:						List[str]   ,    lowerCAmelCase_					:						Optional[int]   ,    lowerCAmelCase_					:						Optional[Any]   ,    lowerCAmelCase_					:						Any   ,    lowerCAmelCase_					:						Union[str, Any]   ,    lowerCAmelCase_					:						List[Any]   ,    lowerCAmelCase_					:						Union[str, Any]   ,    lowerCAmelCase_					:						List[Any]   ,    lowerCAmelCase_					:						Optional[int]   ,    )				->		Optional[Any]:
     __lowerCAmelCase				      =      LlamaForCausalLM(config=lowerCAmelCase_	)
     model.to(lowerCAmelCase_	)
     model.eval()
     __lowerCAmelCase				      =      model(lowerCAmelCase_   ,    attention_mask=lowerCAmelCase_   ,    labels=lowerCAmelCase_	)
     self.parent.assertEqual(result.logits.shape   ,    (self.batch_size, self.seq_length, self.vocab_size)	)






  def 							lowercase						(							self					:						Tuple   ,    lowerCAmelCase_					:						Union[str, Any]   ,    lowerCAmelCase_					:						List[Any]   ,    lowerCAmelCase_					:						List[str]   ,    lowerCAmelCase_					:						Any   ,    lowerCAmelCase_					:						Optional[Any]   ,    lowerCAmelCase_					:						Any   ,    lowerCAmelCase_					:						Any   ,    lowerCAmelCase_					:						Optional[Any]   ,    lowerCAmelCase_					:						List[str]   ,    )				->		Optional[int]:
     __lowerCAmelCase				      =      True
     __lowerCAmelCase				      =      True
     __lowerCAmelCase				      =      LlamaForCausalLM(config=lowerCAmelCase_	)
     model.to(lowerCAmelCase_	)
     model.eval()

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

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

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

     __lowerCAmelCase				      =      model(
         lowerCAmelCase_   ,    attention_mask=lowerCAmelCase_   ,    encoder_hidden_states=lowerCAmelCase_   ,    encoder_attention_mask=lowerCAmelCase_   ,    output_hidden_states=lowerCAmelCase_   ,    )['hidden_states'][0]
     __lowerCAmelCase				      =      model(
         lowerCAmelCase_   ,    attention_mask=lowerCAmelCase_   ,    encoder_hidden_states=lowerCAmelCase_   ,    encoder_attention_mask=lowerCAmelCase_   ,    past_key_values=lowerCAmelCase_   ,    output_hidden_states=lowerCAmelCase_   ,    )['hidden_states'][0]

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






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





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

  """simple docstring"""


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






  def 							lowercase						(							self					:						Union[str, Any]	)				->		Optional[int]:
     __lowerCAmelCase				      =      LlamaModelTester(self	)
     __lowerCAmelCase				      =      ConfigTester(self   ,    config_class=lowerCAmelCase_   ,    hidden_size=3_7	)






  def 							lowercase						(							self					:						Any	)				->		Optional[Any]:
     self.config_tester.run_common_tests()






  def 							lowercase						(							self					:						Any	)				->		List[Any]:
     __lowerCAmelCase				      =      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowerCAmelCase_	)






  def 							lowercase						(							self					:						int	)				->		Dict:
     __lowerCAmelCase				      =      self.model_tester.prepare_config_and_inputs()
     for type in ["absolute", "relative_key", "relative_key_query"]:
        __lowerCAmelCase				      =      type
        self.model_tester.create_and_check_model(*lowerCAmelCase_	)






  def 							lowercase						(							self					:						Optional[Any]	)				->		Any:
     __lowerCAmelCase      ,      __lowerCAmelCase				      =      self.model_tester.prepare_config_and_inputs_for_common()
     __lowerCAmelCase				      =      3
     __lowerCAmelCase				      =      input_dict['input_ids']
     __lowerCAmelCase				      =      input_ids.ne(1	).to(lowerCAmelCase_	)
     __lowerCAmelCase				      =      ids_tensor([self.model_tester.batch_size]   ,    self.model_tester.type_sequence_label_size	)
     __lowerCAmelCase				      =      LlamaForSequenceClassification(lowerCAmelCase_	)
     model.to(lowerCAmelCase_	)
     model.eval()
     __lowerCAmelCase				      =      model(lowerCAmelCase_   ,    attention_mask=lowerCAmelCase_   ,    labels=lowerCAmelCase_	)
     self.assertEqual(result.logits.shape   ,    (self.model_tester.batch_size, self.model_tester.num_labels)	)






  def 							lowercase						(							self					:						Optional[Any]	)				->		Optional[Any]:
     __lowerCAmelCase      ,      __lowerCAmelCase				      =      self.model_tester.prepare_config_and_inputs_for_common()
     __lowerCAmelCase				      =      3
     __lowerCAmelCase				      =      'single_label_classification'
     __lowerCAmelCase				      =      input_dict['input_ids']
     __lowerCAmelCase				      =      input_ids.ne(1	).to(lowerCAmelCase_	)
     __lowerCAmelCase				      =      ids_tensor([self.model_tester.batch_size]   ,    self.model_tester.type_sequence_label_size	)
     __lowerCAmelCase				      =      LlamaForSequenceClassification(lowerCAmelCase_	)
     model.to(lowerCAmelCase_	)
     model.eval()
     __lowerCAmelCase				      =      model(lowerCAmelCase_   ,    attention_mask=lowerCAmelCase_   ,    labels=lowerCAmelCase_	)
     self.assertEqual(result.logits.shape   ,    (self.model_tester.batch_size, self.model_tester.num_labels)	)






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






  @parameterized.expand([('linear',), ('dynamic',)]	)
  def 							lowercase						(							self					:						Optional[int]   ,    lowerCAmelCase_					:						List[str]	)				->		Union[str, Any]:
     __lowerCAmelCase      ,      __lowerCAmelCase				      =      self.model_tester.prepare_config_and_inputs_for_common()
     __lowerCAmelCase				      =      ids_tensor([1, 1_0]   ,    config.vocab_size	)
     __lowerCAmelCase				      =      ids_tensor([1, int(config.max_position_embeddings * 1.5	)]   ,    config.vocab_size	)

     set_seed(4_2	)  # Fixed seed at init time so the two models get the same random weights
     __lowerCAmelCase				      =      LlamaModel(lowerCAmelCase_	)
     original_model.to(lowerCAmelCase_	)
     original_model.eval()
     __lowerCAmelCase				      =      original_model(lowerCAmelCase_	).last_hidden_state
     __lowerCAmelCase				      =      original_model(lowerCAmelCase_	).last_hidden_state

     set_seed(4_2	)  # Fixed seed at init time so the two models get the same random weights
     __lowerCAmelCase				      =      {'type': scaling_type, 'factor': 10.0}
     __lowerCAmelCase				      =      LlamaModel(lowerCAmelCase_	)
     scaled_model.to(lowerCAmelCase_	)
     scaled_model.eval()
     __lowerCAmelCase				      =      scaled_model(lowerCAmelCase_	).last_hidden_state
     __lowerCAmelCase				      =      scaled_model(lowerCAmelCase_	).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(lowerCAmelCase_   ,    lowerCAmelCase_   ,    atol=1e-5	)	)
     else:
        self.assertFalse(torch.allclose(lowerCAmelCase_   ,    lowerCAmelCase_   ,    atol=1e-5	)	)

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





@require_torch
class 							_UpperCAmelCase       (       unittest.TestCase       ):

  """simple docstring"""


  @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!'	)
  @slow
  def 							lowercase						(							self					:						Any	)				->		Optional[int]:
     __lowerCAmelCase				      =      [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8]
     __lowerCAmelCase				      =      LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf'   ,    device_map='auto'	)
     __lowerCAmelCase				      =      model(torch.tensor([input_ids]	)	)
     # Expected mean on dim = -1
     __lowerCAmelCase				      =      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	)   ,    lowerCAmelCase_   ,    atol=1e-2   ,    rtol=1e-2	)
     # slicing logits[0, 0, 0:30]
     # fmt: off
     __lowerCAmelCase				      =      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, :3_0]   ,    lowerCAmelCase_   ,    atol=1e-5   ,    rtol=1e-5	)






  @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!'	)
  @slow
  def 							lowercase						(							self					:						List[str]	)				->		List[str]:
     __lowerCAmelCase				      =      [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8]
     __lowerCAmelCase				      =      LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf'   ,    device_map='auto'	)
     __lowerCAmelCase				      =      model(torch.tensor(lowerCAmelCase_	)	)
     # Expected mean on dim = -1
     __lowerCAmelCase				      =      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	)   ,    lowerCAmelCase_   ,    atol=1e-2   ,    rtol=1e-2	)
     # slicing logits[0, 0, 0:30]
     # fmt: off
     __lowerCAmelCase				      =      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, :3_0]   ,    lowerCAmelCase_   ,    atol=1e-5   ,    rtol=1e-5	)






  @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!'	)
  @slow
  def 							lowercase						(							self					:						int	)				->		Tuple:
     __lowerCAmelCase				      =      [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8]
     __lowerCAmelCase				      =      LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf'   ,    device_map='auto'	)
     __lowerCAmelCase				      =      model(torch.tensor(lowerCAmelCase_	)	)
     # Expected mean on dim = -1
     __lowerCAmelCase				      =      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	)   ,    lowerCAmelCase_   ,    atol=1e-2   ,    rtol=1e-2	)
     # slicing logits[0, 0, 0:30]
     # fmt: off
     __lowerCAmelCase				      =      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	)   ,    lowerCAmelCase_   ,    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 							lowercase						(							self					:						Optional[Any]	)				->		Any:
     __lowerCAmelCase				      =      [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8]
     __lowerCAmelCase				      =      LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf'   ,    device_map='auto'	)
     __lowerCAmelCase				      =      model(torch.tensor(lowerCAmelCase_	)	)

     __lowerCAmelCase				      =      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	)   ,    lowerCAmelCase_   ,    atol=1e-2   ,    rtol=1e-2	)
     # fmt: off
     __lowerCAmelCase				      =      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, :3_0]   ,    lowerCAmelCase_   ,    atol=1e-5   ,    rtol=1e-5	)






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

     # greedy generation outputs
     __lowerCAmelCase				      =      model.generate(lowerCAmelCase_   ,    max_new_tokens=6_4   ,    top_p=lowerCAmelCase_   ,    temperature=1   ,    do_sample=lowerCAmelCase_	)
     __lowerCAmelCase				      =      tokenizer.decode(generated_ids[0]   ,    skip_special_tokens=lowerCAmelCase_	)
     self.assertEqual(lowerCAmelCase_   ,    lowerCAmelCase_	)




'''simple docstring'''







from __future__ import annotations

import math
import random
from typing import Any


class        A__   :



    def __init__(       self							)    ->   None:





           '''simple docstring'''
           A_						       =   []
           A_						       =   0
           A_						       =   0



    def        snake_case_      (       self							)    ->   bool:





           '''simple docstring'''
           return self.head == self.tail



    def        snake_case_      (       self		,					UpperCamelCase__							)    ->   None:





           '''simple docstring'''
           self.data.append(UpperCamelCase__							)
           A_						       =   self.tail + 1



    def        snake_case_      (       self							)    ->   Any:





           '''simple docstring'''
           A_						       =   self.data[self.head]
           A_						       =   self.head + 1
           return ret



    def        snake_case_      (       self							)    ->   int:





           '''simple docstring'''
           return self.tail - self.head







    def        snake_case_      (       self							)    ->   None:





           '''simple docstring'''
           print(self.data							)
           print("""**************"""							)
           print(self.data[self.head : self.tail]							)


class        A__   :



    def __init__(       self		,					UpperCamelCase__							)    ->   None:





           '''simple docstring'''
           A_						       =   data
           A_						       =   None
           A_						       =   None
           A_						       =   1



    def        snake_case_      (       self							)    ->   Any:





           '''simple docstring'''
           return self.data



    def        snake_case_      (       self							)    ->   MyNode | None:





           '''simple docstring'''
           return self.left



    def        snake_case_      (       self							)    ->   MyNode | None:





           '''simple docstring'''
           return self.right



    def        snake_case_      (       self							)    ->   int:





           '''simple docstring'''
           return self.height



    def        snake_case_      (       self		,					UpperCamelCase__							)    ->   None:





           '''simple docstring'''
           A_						       =   data



    def        snake_case_      (       self		,					UpperCamelCase__							)    ->   None:





           '''simple docstring'''
           A_						       =   node



    def        snake_case_      (       self		,					UpperCamelCase__							)    ->   None:





           '''simple docstring'''
           A_						       =   node







    def        snake_case_      (       self		,					UpperCamelCase__							)    ->   None:





           '''simple docstring'''
           A_						       =   height

def    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      int:
       if node is None:
              return 0
       return node.get_height()
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__					)      ->      int:
       if a > b:
              return a
       return b
def    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      MyNode:
       print("""left rotation node:""",							node.get_data()					)
       A_						       =   node.get_left()
       assert ret is not None
       node.set_left(ret.get_right()					)
       ret.set_right(UpperCAmelCase__					)
       A_						       =   my_max(get_height(node.get_right()					),							get_height(node.get_left()					)					) + 1
       node.set_height(UpperCAmelCase__					)
       A_						       =   my_max(get_height(ret.get_right()					),							get_height(ret.get_left()					)					) + 1
       ret.set_height(UpperCAmelCase__					)
       return ret
def    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      MyNode:
       print("""right rotation node:""",							node.get_data()					)
       A_						       =   node.get_right()
       assert ret is not None
       node.set_right(ret.get_left()					)
       ret.set_left(UpperCAmelCase__					)
       A_						       =   my_max(get_height(node.get_right()					),							get_height(node.get_left()					)					) + 1
       node.set_height(UpperCAmelCase__					)
       A_						       =   my_max(get_height(ret.get_right()					),							get_height(ret.get_left()					)					) + 1
       ret.set_height(UpperCAmelCase__					)
       return ret
def    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      MyNode:
       A_						       =   node.get_left()
       assert left_child is not None
       node.set_left(left_rotation(UpperCAmelCase__					)					)
       return right_rotation(UpperCAmelCase__					)
def    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      MyNode:
       A_						       =   node.get_right()
       assert right_child is not None
       node.set_right(right_rotation(UpperCAmelCase__					)					)
       return left_rotation(UpperCAmelCase__					)
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__					)      ->      MyNode | None:
       if node is None:
              return MyNode(UpperCAmelCase__					)
       if data < node.get_data():
              node.set_left(insert_node(node.get_left(),							UpperCAmelCase__					)					)
              if (
                  get_height(node.get_left()					) - get_height(node.get_right()					) == 2
              ):  # an unbalance detected
                     A_						       =   node.get_left()
                     assert left_child is not None
                     if (
                         data < left_child.get_data()
                     ):  # new node is the left child of the left child
                            A_						       =   right_rotation(UpperCAmelCase__					)
                     else:
                            A_						       =   lr_rotation(UpperCAmelCase__					)
       else:
              node.set_right(insert_node(node.get_right(),							UpperCAmelCase__					)					)
              if get_height(node.get_right()					) - get_height(node.get_left()					) == 2:
                     A_						       =   node.get_right()
                     assert right_child is not None
                     if data < right_child.get_data():
                            A_						       =   rl_rotation(UpperCAmelCase__					)
                     else:
                            A_						       =   left_rotation(UpperCAmelCase__					)
       A_						       =   my_max(get_height(node.get_right()					),							get_height(node.get_left()					)					) + 1
       node.set_height(UpperCAmelCase__					)
       return node
def    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      Any:
       while True:
              A_						       =   root.get_right()
              if right_child is None:
                     break
              A_						       =   right_child
       return root.get_data()
def    UpperCAmelCase__     (   UpperCAmelCase__					)      ->      Any:
       while True:
              A_						       =   root.get_left()
              if left_child is None:
                     break
              A_						       =   left_child
       return root.get_data()
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__					)      ->      MyNode | None:
       A_						       =   root.get_left()
       A_						       =   root.get_right()
       if root.get_data() == data:
              if left_child is not None and right_child is not None:
                     A_						       =   get_left_most(UpperCAmelCase__					)
                     root.set_data(UpperCAmelCase__					)
                     root.set_right(del_node(UpperCAmelCase__,							UpperCAmelCase__					)					)
              elif left_child is not None:
                     A_						       =   left_child
              elif right_child is not None:
                     A_						       =   right_child
              else:
                     return None
       elif root.get_data() > data:
              if left_child is None:
                     print("""No such data"""					)
                     return root
              else:
                     root.set_left(del_node(UpperCAmelCase__,							UpperCAmelCase__					)					)
       else:  # root.get_data() < data
              if right_child is None:
                     return root
              else:
                     root.set_right(del_node(UpperCAmelCase__,							UpperCAmelCase__					)					)

       if get_height(UpperCAmelCase__					) - get_height(UpperCAmelCase__					) == 2:
              assert right_child is not None
              if get_height(right_child.get_right()					) > get_height(right_child.get_left()					):
                     A_						       =   left_rotation(UpperCAmelCase__					)
              else:
                     A_						       =   rl_rotation(UpperCAmelCase__					)
       elif get_height(UpperCAmelCase__					) - get_height(UpperCAmelCase__					) == -2:
              assert left_child is not None
              if get_height(left_child.get_left()					) > get_height(left_child.get_right()					):
                     A_						       =   right_rotation(UpperCAmelCase__					)
              else:
                     A_						       =   lr_rotation(UpperCAmelCase__					)
       A_						       =   my_max(get_height(root.get_right()					),							get_height(root.get_left()					)					) + 1
       root.set_height(UpperCAmelCase__					)
       return root


class        A__   :



    def __init__(       self							)    ->   None:





           '''simple docstring'''
           A_						       =   None



    def        snake_case_      (       self							)    ->   int:





           '''simple docstring'''
           return get_height(self.root							)



    def        snake_case_      (       self		,					UpperCamelCase__							)    ->   None:





           '''simple docstring'''
           print("""insert:""" + str(UpperCamelCase__							)							)
           A_						       =   insert_node(self.root		,					UpperCamelCase__							)



    def        snake_case_      (       self		,					UpperCamelCase__							)    ->   None:





           '''simple docstring'''
           print("""delete:""" + str(UpperCamelCase__							)							)
           if self.root is None:
                  print("""Tree is empty!"""							)
                  return
           A_						       =   del_node(self.root		,					UpperCamelCase__							)







    def __str__(       self		,					)    ->   str:  # a level traversale, gives a more intuitive look on the tree





           '''simple docstring'''
           A_						       =   """"""
           A_						       =   MyQueue()
           q.push(self.root							)
           A_						       =   self.get_height()
           if layer == 0:
                  return output
           A_						       =   0
           while not q.is_empty():
                  A_						       =   q.pop()
                  A_						       =   """ """ * int(math.pow(2		,					layer - 1							)							)
                  output += space
                  if node is None:
                         output += "*"
                         q.push(UpperCamelCase__							)
                         q.push(UpperCamelCase__							)
                  else:
                         output += str(node.get_data()							)
                         q.push(node.get_left()							)
                         q.push(node.get_right()							)
                  output += space
                  A_						       =   cnt + 1
                  for i in range(100							):
                         if cnt == math.pow(2		,					UpperCamelCase__							) - 1:
                                A_						       =   layer - 1
                                if layer == 0:
                                       output += "\n*************************************"
                                       return output
                                output += "\n"
                                break
           output += "\n*************************************"
           return output

def    UpperCAmelCase__     (   )      ->      None:
       import doctest

       doctest.testmod()


if __name__ == "__main__":
      _test()
      __lowerCamelCase									=     AVLtree()
      __lowerCamelCase									=     list(range(10))
      random.shuffle(lst)
      for i in lst:
            t.insert(i)
            print(str(t))
      random.shuffle(lst)
      for i in lst:
            t.del_node(i)
            print(str(t))
