




import unittest

from parameterized import parameterized

from transformers import OpenLlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, 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 OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel
class 						_A :






  def __init__(  self		:     List[Any]				,						_A		:     int				,						_A		:     Optional[int]=13				,						_A		:     Dict=7				,						_A		:     List[str]=True				,						_A		:     Optional[Any]=True				,						_A		:     Union[str, Any]=False				,						_A		:     Any=True				,						_A		:     Optional[Any]=99				,						_A		:     Tuple=32				,						_A		:     Union[str, Any]=5				,						_A		:     Dict=4				,						_A		:     Optional[int]=37				,						_A		:     Any="gelu"				,						_A		:     List[str]=0.1				,						_A		:     Union[str, Any]=0.1				,						_A		:     int=512				,						_A		:     Any=16				,						_A		:     List[Any]=2				,						_A		:     str=0.02				,						_A		:     Dict=3				,						_A		:     Dict=4				,						_A		:     int=None				,						)		->   Tuple:






       """simple docstring"""







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






  def  __a      (  self		:     List[str]				)		->   Union[str, Any]:






       """simple docstring"""







       lowercase :       Tuple       =			ids_tensor([self.batch_size, self.seq_length]				,						self.vocab_size				)

       lowercase :       Any       =			None
       if self.use_input_mask:
            lowercase :       Optional[int]       =			random_attention_mask([self.batch_size, self.seq_length]				)

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

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

       lowercase :       Any       =			self.get_config()

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






  def  __a      (  self		:     Optional[int]				)		->   Tuple:






       """simple docstring"""







       return OpenLlamaConfig(
           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				,						use_stable_embedding=lowerCamelCase__				,						)






  def  __a      (  self		:     Optional[int]				,						_A		:     Optional[Any]				,						_A		:     List[Any]				,						_A		:     Dict				,						_A		:     List[Any]				,						_A		:     int				,						_A		:     Union[str, Any]				,						_A		:     List[Any]				)		->   Union[str, Any]:






       """simple docstring"""







       lowercase :       Tuple       =			OpenLlamaModel(config=lowerCamelCase__				)
       model.to(lowerCamelCase__				)
       model.eval()
       lowercase :       int       =			model(lowerCamelCase__				,						attention_mask=lowerCamelCase__				)
       lowercase :       int       =			model(lowerCamelCase__				)
       self.parent.assertEqual(result.last_hidden_state.shape				,						(self.batch_size, self.seq_length, self.hidden_size)				)






  def  __a      (  self		:     Optional[int]				,						_A		:     Dict				,						_A		:     Optional[int]				,						_A		:     str				,						_A		:     Optional[int]				,						_A		:     Union[str, Any]				,						_A		:     Dict				,						_A		:     Dict				,						_A		:     Tuple				,						_A		:     Optional[int]				,						)		->   List[Any]:






       """simple docstring"""







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






  def  __a      (  self		:     List[str]				,						_A		:     Tuple				,						_A		:     Optional[int]				,						_A		:     Any				,						_A		:     Dict				,						_A		:     Optional[Any]				,						_A		:     Tuple				,						_A		:     Dict				,						_A		:     Any				,						_A		:     Tuple				,						)		->   Tuple:






       """simple docstring"""







       lowercase :       Tuple       =			OpenLlamaForCausalLM(config=lowerCamelCase__				)
       model.to(lowerCamelCase__				)
       model.eval()
       lowercase :       Optional[Any]       =			model(lowerCamelCase__				,						attention_mask=lowerCamelCase__				,						labels=lowerCamelCase__				)
       self.parent.assertEqual(result.logits.shape				,						(self.batch_size, self.seq_length, self.vocab_size)				)






  def  __a      (  self		:     List[Any]				,						_A		:     List[Any]				,						_A		:     Union[str, Any]				,						_A		:     str				,						_A		:     Optional[int]				,						_A		:     List[Any]				,						_A		:     Optional[Any]				,						_A		:     int				,						_A		:     Optional[int]				,						_A		:     List[Any]				,						)		->   List[str]:






       """simple docstring"""







       lowercase :       List[str]       =			True
       lowercase :       List[Any]       =			True
       lowercase :       List[str]       =			OpenLlamaForCausalLM(config=lowerCamelCase__				)
       model.to(lowerCamelCase__				)
       model.eval()

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

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

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

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






  def  __a      (  self		:     Dict				)		->   Any:






       """simple docstring"""







       lowercase :       Optional[Any]       =			self.prepare_config_and_inputs()
       (
           lowercase			
       ) :       Dict       =			config_and_inputs
       lowercase :       int       =			{'''input_ids''': input_ids, '''attention_mask''': input_mask}
       return config, inputs_dict


@require_torch
class 						_A (  __lowerCAmelCase      ,       __lowerCAmelCase      ,       __lowerCAmelCase      ,       unittest.TestCase				):
  _UpperCamelCase       :      int			=      (
      (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else ()
  )
  _UpperCamelCase       :      Dict			=      (OpenLlamaForCausalLM,) if is_torch_available() else ()
  _UpperCamelCase       :      Any			=      (
      {
          "feature-extraction": OpenLlamaModel,
          "text-classification": OpenLlamaForSequenceClassification,
          "text-generation": OpenLlamaForCausalLM,
          "zero-shot": OpenLlamaForSequenceClassification,
      }
      if is_torch_available()
      else {}
  )
  _UpperCamelCase       :      str			=      False
  _UpperCamelCase       :      Any			=      False






  def  __a      (  self		:     Tuple				)		->   Optional[int]:






       """simple docstring"""







       lowercase :       Dict       =			OpenLlamaModelTester(self				)
       lowercase :       int       =			ConfigTester(self				,						config_class=lowerCamelCase__				,						hidden_size=37				)






  def  __a      (  self		:     Tuple				)		->   Tuple:






       """simple docstring"""







       self.config_tester.run_common_tests()






  def  __a      (  self		:     Any				)		->   str:






       """simple docstring"""







       lowercase :       List[Any]       =			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*lowerCamelCase__				)






  def  __a      (  self		:     str				)		->   Optional[Any]:






       """simple docstring"""







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






  def  __a      (  self		:     Tuple				)		->   str:






       """simple docstring"""







       lowercase :       Dict       =			self.model_tester.prepare_config_and_inputs_for_common()
       lowercase :       str       =			3
       lowercase :       Optional[Any]       =			input_dict['''input_ids''']
       lowercase :       str       =			input_ids.ne(1				).to(lowerCamelCase__				)
       lowercase :       int       =			ids_tensor([self.model_tester.batch_size]				,						self.model_tester.type_sequence_label_size				)
       lowercase :       str       =			OpenLlamaForSequenceClassification(lowerCamelCase__				)
       model.to(lowerCamelCase__				)
       model.eval()
       lowercase :       Dict       =			model(lowerCamelCase__				,						attention_mask=lowerCamelCase__				,						labels=lowerCamelCase__				)
       self.assertEqual(result.logits.shape				,						(self.model_tester.batch_size, self.model_tester.num_labels)				)






  def  __a      (  self		:     Optional[int]				)		->   str:






       """simple docstring"""







       lowercase :       Dict       =			self.model_tester.prepare_config_and_inputs_for_common()
       lowercase :       str       =			3
       lowercase :       Union[str, Any]       =			'''single_label_classification'''
       lowercase :       Any       =			input_dict['''input_ids''']
       lowercase :       str       =			input_ids.ne(1				).to(lowerCamelCase__				)
       lowercase :       Dict       =			ids_tensor([self.model_tester.batch_size]				,						self.model_tester.type_sequence_label_size				)
       lowercase :       Dict       =			OpenLlamaForSequenceClassification(lowerCamelCase__				)
       model.to(lowerCamelCase__				)
       model.eval()
       lowercase :       Dict       =			model(lowerCamelCase__				,						attention_mask=lowerCamelCase__				,						labels=lowerCamelCase__				)
       self.assertEqual(result.logits.shape				,						(self.model_tester.batch_size, self.model_tester.num_labels)				)






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






       """simple docstring"""







       lowercase :       Optional[int]       =			self.model_tester.prepare_config_and_inputs_for_common()
       lowercase :       Optional[Any]       =			3
       lowercase :       Any       =			'''multi_label_classification'''
       lowercase :       Union[str, Any]       =			input_dict['''input_ids''']
       lowercase :       List[Any]       =			input_ids.ne(1				).to(lowerCamelCase__				)
       lowercase :       str       =			ids_tensor(
           [self.model_tester.batch_size, config.num_labels]				,						self.model_tester.type_sequence_label_size				).to(torch.float				)
       lowercase :       Union[str, Any]       =			OpenLlamaForSequenceClassification(lowerCamelCase__				)
       model.to(lowerCamelCase__				)
       model.eval()
       lowercase :       str       =			model(lowerCamelCase__				,						attention_mask=lowerCamelCase__				,						labels=lowerCamelCase__				)
       self.assertEqual(result.logits.shape				,						(self.model_tester.batch_size, self.model_tester.num_labels)				)






  @unittest.skip('''Open-Llama buffers include complex numbers, which breaks this test'''				)
  def  __a      (  self		:     Dict				)		->   int:






       """simple docstring"""







       pass






  @parameterized.expand([('''linear''',), ('''dynamic''',)]				)
  def  __a      (  self		:     Dict				,						_A		:     Optional[Any]				)		->   Union[str, Any]:






       """simple docstring"""







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

       set_seed(42				)  # Fixed seed at init time so the two models get the same random weights
       lowercase :       List[Any]       =			{'''type''': scaling_type, '''factor''': 10.0}
       lowercase :       List[str]       =			OpenLlamaModel(lowerCamelCase__				)
       scaled_model.to(lowerCamelCase__				)
       scaled_model.eval()
       lowercase :       Any       =			scaled_model(lowerCamelCase__				).last_hidden_state
       lowercase :       Tuple       =			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				)				)





lowerCAmelCase_						=			range(2, 20 + 1)
lowerCAmelCase_						=			[10**k for k in range(ks[-1] + 1)]
lowerCAmelCase_						=			{}






def  snake_case(    __magic_name__			,		__magic_name__			,		__magic_name__			,		__magic_name__   )			->							Any:





     '''simple docstring'''


     lowercase :       str       =			sum(a_i[j] for j in range(__magic_name__			,		len(__magic_name__   )   )   )
     lowercase :       Any       =			sum(a_i[j] * base[j] for j in range(min(len(__magic_name__   )			,		__magic_name__   )   )   )

     lowercase      ,	lowercase :       Optional[int]       =			0, 0
     lowercase :       str       =			n - i

     lowercase :       Optional[int]       =			memo.get(__magic_name__   )

     if sub_memo is not None:
          lowercase :       List[str]       =			sub_memo.get(__magic_name__   )

          if jumps is not None and len(__magic_name__   ) > 0:
               # find and make the largest jump without going over
               lowercase :       Dict       =			-1
               for _k in range(len(__magic_name__   ) - 1			,		-1			,		-1   ):
                    if jumps[_k][2] <= k and jumps[_k][1] <= max_dn:
                         lowercase :       Any       =			_k
                         break

               if max_jump >= 0:
                    lowercase      ,	lowercase      ,	lowercase :       List[str]       =			jumps[max_jump]
                    # since the difference between jumps is cached, add c
                    lowercase :       str       =			diff + c
                    for j in range(min(__magic_name__			,		len(__magic_name__   )   )   ):
                         lowercase      ,	lowercase :       Optional[Any]       =			divmod(__magic_name__			,		10   )
                    if new_c > 0:
                         add(__magic_name__			,		__magic_name__			,		__magic_name__   )

          else:
               lowercase :       Dict       =			[]
     else:
          lowercase :       Union[str, Any]       =			{c: []}
          lowercase :       Optional[Any]       =			sub_memo

     if dn >= max_dn or c + diff >= base[k]:
          return diff, dn

     if k > ks[0]:
          while True:
               # keep doing smaller jumps
               lowercase      ,	lowercase :       str       =			next_term(__magic_name__			,		k - 1			,		i + dn			,		__magic_name__   )
               diff += _diff
               dn += terms_jumped

               if dn >= max_dn or c + diff >= base[k]:
                    break
     else:
          # would be too small a jump, just compute sequential terms instead
          lowercase      ,	lowercase :       Optional[Any]       =			compute(__magic_name__			,		__magic_name__			,		i + dn			,		__magic_name__   )
          diff += _diff
          dn += terms_jumped

     lowercase :       Optional[Any]       =			sub_memo[c]

     # keep jumps sorted by # of terms skipped
     lowercase :       List[Any]       =			0
     while j < len(__magic_name__   ):
          if jumps[j][1] > dn:
               break
          j += 1

     # cache the jump for this value digitsum(b) and c
     sub_memo[c].insert(__magic_name__			,		(diff, dn, k)   )
     return (diff, dn)






def  snake_case(    __magic_name__			,		__magic_name__			,		__magic_name__			,		__magic_name__   )			->							Optional[int]:





     '''simple docstring'''


     if i >= n:
          return 0, i
     if k > len(__magic_name__   ):
          a_i.extend([0 for _ in range(k - len(__magic_name__   )   )]   )

     # note: a_i -> b * 10^k + c
     # ds_b -> digitsum(b)
     # ds_c -> digitsum(c)
     lowercase :       Optional[Any]       =			i
     lowercase      ,	lowercase      ,	lowercase :       List[str]       =			0, 0, 0
     for j in range(len(__magic_name__   )   ):
          if j >= k:
               ds_b += a_i[j]
          else:
               ds_c += a_i[j]

     while i < n:
          i += 1
          lowercase :       List[str]       =			ds_c + ds_b
          diff += addend
          lowercase :       Tuple       =			0
          for j in range(__magic_name__   ):
               lowercase :       int       =			a_i[j] + addend
               lowercase      ,	lowercase :       Any       =			divmod(__magic_name__			,		10   )

               ds_c += a_i[j]

          if addend > 0:
               break

     if addend > 0:
          add(__magic_name__			,		__magic_name__			,		__magic_name__   )
     return diff, i - start_i






def  snake_case(    __magic_name__			,		__magic_name__			,		__magic_name__   )			->							Tuple:





     '''simple docstring'''


     for j in range(__magic_name__			,		len(__magic_name__   )   ):
          lowercase :       Any       =			digits[j] + addend
          if s >= 10:
               lowercase      ,	lowercase :       List[str]       =			divmod(__magic_name__			,		10   )
               lowercase :       List[str]       =			addend // 10 + quotient
          else:
               lowercase :       Optional[Any]       =			s
               lowercase :       Tuple       =			addend // 10

          if addend == 0:
               break

     while addend > 0:
          lowercase      ,	lowercase :       str       =			divmod(__magic_name__			,		10   )
          digits.append(__magic_name__   )






def  snake_case(    __magic_name__ = 10**15   )			->							int:





     '''simple docstring'''


     lowercase :       List[Any]       =			[1]
     lowercase :       List[Any]       =			1
     lowercase :       str       =			0
     while True:
          lowercase      ,	lowercase :       str       =			next_term(__magic_name__			,		20			,		i + dn			,		__magic_name__   )
          dn += terms_jumped
          if dn == n - i:
               break

     lowercase :       str       =			0
     for j in range(len(__magic_name__   )   ):
          a_n += digits[j] * 10**j
     return a_n


if __name__ == "__main__":
 print(f'''{solution() = }''')