



'''simple docstring'''




import argparse
import gc
import json
import os
import shutil
import warnings

import torch

from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer


try:
       from transformers import LlamaTokenizerFast
except ImportError as e:
       warnings.warn(e)
       warnings.warn(
           """The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion"""
       )
       a     :    Dict      						=					None
a     :    str      						=					{
    """7B""": 1_1_0_0_8,
    """13B""": 1_3_8_2_4,
    """30B""": 1_7_9_2_0,
    """65B""": 2_2_0_1_6,
    """70B""": 2_8_6_7_2,
}
a     :    Tuple      						=					{
    """7B""": 1,
    """7Bf""": 1,
    """13B""": 2,
    """13Bf""": 2,
    """30B""": 4,
    """65B""": 8,
    """70B""": 8,
    """70Bf""": 8,
}



def    __lowerCamelCase						(      _lowercase			,       _lowercase=1			,       _lowercase=2_5_6	)   ->    int:
       return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3	)	) + multiple_of - 1) // multiple_of)



def    __lowerCamelCase						(      _lowercase	)   ->    List[Any]:
       with open(_lowercase			,       """r"""	) as f:
              return json.load(_lowercase	)



def    __lowerCamelCase						(      _lowercase			,       _lowercase	)   ->    Dict:
       with open(_lowercase			,       """w"""	) as f:
              json.dump(_lowercase			,       _lowercase	)



def    __lowerCamelCase						(      _lowercase			,       _lowercase			,       _lowercase			,       _lowercase=True	)   ->    Dict:
       os.makedirs(_lowercase			,       exist_ok=_lowercase	)
       UpperCAmelCase  :	int							  =	os.path.join(_lowercase			,       """tmp"""	)
       os.makedirs(_lowercase			,       exist_ok=_lowercase	)

       UpperCAmelCase  :	Optional[int]							  =	read_json(os.path.join(_lowercase			,       """params.json"""	)	)
       UpperCAmelCase  :	Dict							  =	NUM_SHARDS[model_size]
       UpperCAmelCase  :	int							  =	params["""n_layers"""]
       UpperCAmelCase  :	str							  =	params["""n_heads"""]
       UpperCAmelCase  :	Optional[Any]							  =	n_heads // num_shards
       UpperCAmelCase  :	List[str]							  =	params["""dim"""]
       UpperCAmelCase  :	str							  =	dim // n_heads
       UpperCAmelCase  :	Optional[int]							  =	1_0_0_0_0.0
       UpperCAmelCase  :	str							  =	1.0 / (base ** (torch.arange(0			,       _lowercase			,       2	).float() / dims_per_head))

       if "n_kv_heads" in params:
              UpperCAmelCase  :	List[Any]							  =	params["""n_kv_heads"""]  # for GQA / MQA
              UpperCAmelCase  :	str							  =	n_heads_per_shard // num_key_value_heads
              UpperCAmelCase  :	int							  =	dim // num_key_value_heads
       else:  # compatibility with other checkpoints
              UpperCAmelCase  :	Optional[int]							  =	n_heads
              UpperCAmelCase  :	Dict							  =	n_heads_per_shard
              UpperCAmelCase  :	Union[str, Any]							  =	dim

       # permute for sliced rotary
       def permute(_lowercase			,       _lowercase=n_heads			,       _lowercase=dim			,       _lowercase=dim	):
              return w.view(_lowercase			,       dima // n_heads // 2			,       2			,       _lowercase	).transpose(1			,       2	).reshape(_lowercase			,       _lowercase	)

       print(F'''Fetching all parameters from the checkpoint at {input_base_path}.'''	)
       # Load weights
       if model_size == "7B":
              # Not sharded
              # (The sharded implementation would also work, but this is simpler.)
              UpperCAmelCase  :	Tuple							  =	torch.load(os.path.join(_lowercase			,       """consolidated.00.pth"""	)			,       map_location="""cpu"""	)
       else:
              # Sharded
              UpperCAmelCase  :	Optional[Any]							  =	[
                  torch.load(os.path.join(_lowercase			,       F'''consolidated.{i:02d}.pth'''	)			,       map_location="""cpu"""	)
                  for i in range(_lowercase	)
              ]
       UpperCAmelCase  :	Optional[int]							  =	0
       UpperCAmelCase  :	Any							  =	{"""weight_map""": {}}
       for layer_i in range(_lowercase	):
              UpperCAmelCase  :	Dict							  =	F'''pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin'''
              if model_size == "7B":
                     # Unsharded
                     UpperCAmelCase  :	List[Any]							  =	{
                         F'''model.layers.{layer_i}.self_attn.q_proj.weight''': permute(
                             loaded[F'''layers.{layer_i}.attention.wq.weight''']	),
                         F'''model.layers.{layer_i}.self_attn.k_proj.weight''': permute(
                             loaded[F'''layers.{layer_i}.attention.wk.weight''']	),
                         F'''model.layers.{layer_i}.self_attn.v_proj.weight''': loaded[F'''layers.{layer_i}.attention.wv.weight'''],
                         F'''model.layers.{layer_i}.self_attn.o_proj.weight''': loaded[F'''layers.{layer_i}.attention.wo.weight'''],
                         F'''model.layers.{layer_i}.mlp.gate_proj.weight''': loaded[F'''layers.{layer_i}.feed_forward.w1.weight'''],
                         F'''model.layers.{layer_i}.mlp.down_proj.weight''': loaded[F'''layers.{layer_i}.feed_forward.w2.weight'''],
                         F'''model.layers.{layer_i}.mlp.up_proj.weight''': loaded[F'''layers.{layer_i}.feed_forward.w3.weight'''],
                         F'''model.layers.{layer_i}.input_layernorm.weight''': loaded[F'''layers.{layer_i}.attention_norm.weight'''],
                         F'''model.layers.{layer_i}.post_attention_layernorm.weight''': loaded[F'''layers.{layer_i}.ffn_norm.weight'''],
                     }
              else:
                     # Sharded
                     # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share
                     # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is
                     # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned.

                     UpperCAmelCase  :	List[str]							  =	{
                         F'''model.layers.{layer_i}.input_layernorm.weight''': loaded[0][
                             F'''layers.{layer_i}.attention_norm.weight'''
                         ].clone(),
                         F'''model.layers.{layer_i}.post_attention_layernorm.weight''': loaded[0][
                             F'''layers.{layer_i}.ffn_norm.weight'''
                         ].clone(),
                     }
                     UpperCAmelCase  :	int							  =	permute(
                         torch.cat(
                             [
                                 loaded[i][F'''layers.{layer_i}.attention.wq.weight'''].view(_lowercase			,       _lowercase			,       _lowercase	)
                                 for i in range(_lowercase	)
                             ]			,       dim=0			,       ).reshape(_lowercase			,       _lowercase	)	)
                     UpperCAmelCase  :	Optional[Any]							  =	permute(
                         torch.cat(
                             [
                                 loaded[i][F'''layers.{layer_i}.attention.wk.weight'''].view(
                                     _lowercase			,       _lowercase			,       _lowercase	)
                                 for i in range(_lowercase	)
                             ]			,       dim=0			,       ).reshape(_lowercase			,       _lowercase	)			,       _lowercase			,       _lowercase			,       _lowercase			,       )
                     UpperCAmelCase  :	List[str]							  =	torch.cat(
                         [
                             loaded[i][F'''layers.{layer_i}.attention.wv.weight'''].view(
                                 _lowercase			,       _lowercase			,       _lowercase	)
                             for i in range(_lowercase	)
                         ]			,       dim=0			,       ).reshape(_lowercase			,       _lowercase	)

                     UpperCAmelCase  :	Tuple							  =	torch.cat(
                         [loaded[i][F'''layers.{layer_i}.attention.wo.weight'''] for i in range(_lowercase	)]			,       dim=1	)
                     UpperCAmelCase  :	Optional[int]							  =	torch.cat(
                         [loaded[i][F'''layers.{layer_i}.feed_forward.w1.weight'''] for i in range(_lowercase	)]			,       dim=0	)
                     UpperCAmelCase  :	Dict							  =	torch.cat(
                         [loaded[i][F'''layers.{layer_i}.feed_forward.w2.weight'''] for i in range(_lowercase	)]			,       dim=1	)
                     UpperCAmelCase  :	Optional[int]							  =	torch.cat(
                         [loaded[i][F'''layers.{layer_i}.feed_forward.w3.weight'''] for i in range(_lowercase	)]			,       dim=0	)

              UpperCAmelCase  :	Optional[int]							  =	inv_freq
              for k, v in state_dict.items():
                     UpperCAmelCase  :	List[str]							  =	filename
                     param_count += v.numel()
              torch.save(_lowercase			,       os.path.join(_lowercase			,       _lowercase	)	)

       UpperCAmelCase  :	Any							  =	F'''pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin'''
       if model_size == "7B":
              # Unsharded
              UpperCAmelCase  :	Any							  =	{
                  """model.embed_tokens.weight""": loaded["""tok_embeddings.weight"""],
                  """model.norm.weight""": loaded["""norm.weight"""],
                  """lm_head.weight""": loaded["""output.weight"""],
              }
       else:
              UpperCAmelCase  :	Any							  =	{
                  """model.norm.weight""": loaded[0]["""norm.weight"""],
                  """model.embed_tokens.weight""": torch.cat(
                      [loaded[i]["""tok_embeddings.weight"""] for i in range(_lowercase	)]			,       dim=1	),
                  """lm_head.weight""": torch.cat([loaded[i]["""output.weight"""] for i in range(_lowercase	)]			,       dim=0	),
              }

       for k, v in state_dict.items():
              UpperCAmelCase  :	Any							  =	filename
              param_count += v.numel()
       torch.save(_lowercase			,       os.path.join(_lowercase			,       _lowercase	)	)

       # Write configs
       UpperCAmelCase  :	str							  =	{"""total_size""": param_count * 2}
       write_json(_lowercase			,       os.path.join(_lowercase			,       """pytorch_model.bin.index.json"""	)	)
       UpperCAmelCase  :	List[str]							  =	params["""ffn_dim_multiplier"""] if """ffn_dim_multiplier""" in params else 1
       UpperCAmelCase  :	Optional[int]							  =	params["""multiple_of"""] if """multiple_of""" in params else 2_5_6
       UpperCAmelCase  :	Any							  =	LlamaConfig(
           hidden_size=_lowercase			,       intermediate_size=compute_intermediate_size(_lowercase			,       _lowercase			,       _lowercase	)			,       num_attention_heads=params["""n_heads"""]			,       num_hidden_layers=params["""n_layers"""]			,       rms_norm_eps=params["""norm_eps"""]			,       num_key_value_heads=_lowercase			,       )
       config.save_pretrained(_lowercase	)

       # Make space so we can load the model properly now.
       del state_dict
       del loaded
       gc.collect()

       print("""Loading the checkpoint in a Llama model."""	)
       UpperCAmelCase  :	Tuple							  =	LlamaForCausalLM.from_pretrained(_lowercase			,       torch_dtype=torch.floataa			,       low_cpu_mem_usage=_lowercase	)
       # Avoid saving this as part of the config.
       del model.config._name_or_path

       print("""Saving in the Transformers format."""	)
       model.save_pretrained(_lowercase			,       safe_serialization=_lowercase	)
       shutil.rmtree(_lowercase	)



def    __lowerCamelCase						(      _lowercase			,       _lowercase	)   ->    Optional[Any]:
       # Initialize the tokenizer based on the `spm` model
       UpperCAmelCase  :	Union[str, Any]							  =	LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast
       print(F'''Saving a {tokenizer_class.__name__} to {tokenizer_path}.'''	)
       UpperCAmelCase  :	List[str]							  =	tokenizer_class(_lowercase	)
       tokenizer.save_pretrained(_lowercase	)



def    __lowerCamelCase						(      )   ->    Optional[int]:
       UpperCAmelCase  :	Optional[Any]							  =	argparse.ArgumentParser()
       parser.add_argument(
           """--input_dir"""			,       help="""Location of LLaMA weights, which contains tokenizer.model and model folders"""			,       )
       parser.add_argument(
           """--model_size"""			,       choices=["""7B""", """7Bf""", """13B""", """13Bf""", """30B""", """65B""", """70B""", """70Bf""", """tokenizer_only"""]			,       )
       parser.add_argument(
           """--output_dir"""			,       help="""Location to write HF model and tokenizer"""			,       )
       parser.add_argument("""--safe_serialization"""			,       type=_lowercase			,       help="""Whether or not to save using `safetensors`."""	)
       UpperCAmelCase  :	Tuple							  =	parser.parse_args()
       if args.model_size != "tokenizer_only":
              write_model(
                  model_path=args.output_dir			,       input_base_path=os.path.join(args.input_dir			,       args.model_size	)			,       model_size=args.model_size			,       safe_serialization=args.safe_serialization			,       )
       UpperCAmelCase  :	Optional[int]							  =	os.path.join(args.input_dir			,       """tokenizer.model"""	)
       write_tokenizer(args.output_dir			,       _lowercase	)


if __name__ == "__main__":
       main()






'''simple docstring'''




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





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





	def 				_lowercase(						self					)    ->    Dict:
								UpperCAmelCase  :	Dict							  =	ids_tensor([self.batch_size, self.seq_length]	,	self.vocab_size					)

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

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

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

								UpperCAmelCase  :	int							  =	self.get_config()

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





	def 				_lowercase(						self					)    ->    Dict:
								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=A	,	initializer_range=self.initializer_range	,	use_stable_embedding=A	,	)





	def 				_lowercase(						self	,	A	,	A	,	A	,	A	,	A	,	A	,	A					)    ->    str:
								UpperCAmelCase  :	Union[str, Any]							  =	OpenLlamaModel(config=A					)
								model.to(A					)
								model.eval()
								UpperCAmelCase  :	Dict							  =	model(A	,	attention_mask=A					)
								UpperCAmelCase  :	Optional[int]							  =	model(A					)
								self.parent.assertEqual(result.last_hidden_state.shape	,	(self.batch_size, self.seq_length, self.hidden_size)					)





	def 				_lowercase(						self	,	A	,	A	,	A	,	A	,	A	,	A	,	A	,	A	,	A	,	)    ->    List[Any]:
								UpperCAmelCase  :	Optional[int]							  =	True
								UpperCAmelCase  :	Union[str, Any]							  =	OpenLlamaModel(A					)
								model.to(A					)
								model.eval()
								UpperCAmelCase  :	List[Any]							  =	model(
								    A	,	attention_mask=A	,	encoder_hidden_states=A	,	encoder_attention_mask=A	,	)
								UpperCAmelCase  :	str							  =	model(
								    A	,	attention_mask=A	,	encoder_hidden_states=A	,	)
								UpperCAmelCase  :	List[Any]							  =	model(A	,	attention_mask=A					)
								self.parent.assertEqual(result.last_hidden_state.shape	,	(self.batch_size, self.seq_length, self.hidden_size)					)





	def 				_lowercase(						self	,	A	,	A	,	A	,	A	,	A	,	A	,	A	,	A	,	A	,	)    ->    int:
								UpperCAmelCase  :	Optional[int]							  =	OpenLlamaForCausalLM(config=A					)
								model.to(A					)
								model.eval()
								UpperCAmelCase  :	Tuple							  =	model(A	,	attention_mask=A	,	labels=A					)
								self.parent.assertEqual(result.logits.shape	,	(self.batch_size, self.seq_length, self.vocab_size)					)





	def 				_lowercase(						self	,	A	,	A	,	A	,	A	,	A	,	A	,	A	,	A	,	A	,	)    ->    int:
								UpperCAmelCase  :	Dict							  =	True
								UpperCAmelCase  :	Tuple							  =	True
								UpperCAmelCase  :	str							  =	OpenLlamaForCausalLM(config=A					)
								model.to(A					)
								model.eval()

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

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

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

								UpperCAmelCase  :	List[Any]							  =	model(
								    A	,	attention_mask=A	,	encoder_hidden_states=A	,	encoder_attention_mask=A	,	output_hidden_states=A	,	)["""hidden_states"""][0]
								UpperCAmelCase  :	Optional[Any]							  =	model(
								    A	,	attention_mask=A	,	encoder_hidden_states=A	,	encoder_attention_mask=A	,	past_key_values=A	,	output_hidden_states=A	,	)["""hidden_states"""][0]

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






	def 				_lowercase(						self					)    ->    Union[str, Any]:
								UpperCAmelCase  :	Union[str, Any]							  =	self.prepare_config_and_inputs()
								(
								    (
								    UpperCAmelCase
								)  ,  (
								    UpperCAmelCase
								)  ,  (
								    UpperCAmelCase
								)  ,  (
								    UpperCAmelCase
								)  ,  (
								    UpperCAmelCase
								)  ,  (
								    UpperCAmelCase
								)  ,  (
								    UpperCAmelCase
								)  ,  
								)  :	Tuple							  =	config_and_inputs
								UpperCAmelCase  :	str							  =	{"""input_ids""": input_ids, """attention_mask""": input_mask}
								return config, inputs_dict




@require_torch
class     UpperCamelCase_				(							__magic_name__   ,  __magic_name__   ,  __magic_name__   ,  unittest.TestCase    ):
	lowercase    =				(
	    (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else ()
	)
	lowercase    =				(OpenLlamaForCausalLM,) if is_torch_available() else ()
	lowercase    =				(
	    {
	        'feature-extraction': OpenLlamaModel,
	        'text-classification': OpenLlamaForSequenceClassification,
	        'text-generation': OpenLlamaForCausalLM,
	        'zero-shot': OpenLlamaForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	lowercase    =				False
	lowercase    =				False





	def 				_lowercase(						self					)    ->    Tuple:
								UpperCAmelCase  :	Dict							  =	OpenLlamaModelTester(self					)
								UpperCAmelCase  :	List[str]							  =	ConfigTester(self	,	config_class=A	,	hidden_size=37					)





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





	def 				_lowercase(						self					)    ->    int:
								UpperCAmelCase  :	Tuple							  =	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*A					)





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





	def 				_lowercase(						self					)    ->    str:
								UpperCAmelCase  ,  UpperCAmelCase  :	List[str]							  =	self.model_tester.prepare_config_and_inputs_for_common()
								UpperCAmelCase  :	List[str]							  =	3
								UpperCAmelCase  :	Optional[Any]							  =	input_dict["""input_ids"""]
								UpperCAmelCase  :	str							  =	input_ids.ne(1					).to(A					)
								UpperCAmelCase  :	Tuple							  =	ids_tensor([self.model_tester.batch_size]	,	self.model_tester.type_sequence_label_size					)
								UpperCAmelCase  :	Optional[Any]							  =	OpenLlamaForSequenceClassification(A					)
								model.to(A					)
								model.eval()
								UpperCAmelCase  :	List[Any]							  =	model(A	,	attention_mask=A	,	labels=A					)
								self.assertEqual(result.logits.shape	,	(self.model_tester.batch_size, self.model_tester.num_labels)					)





	def 				_lowercase(						self					)    ->    Union[str, Any]:
								UpperCAmelCase  ,  UpperCAmelCase  :	Union[str, Any]							  =	self.model_tester.prepare_config_and_inputs_for_common()
								UpperCAmelCase  :	Dict							  =	3
								UpperCAmelCase  :	Any							  =	"""single_label_classification"""
								UpperCAmelCase  :	Dict							  =	input_dict["""input_ids"""]
								UpperCAmelCase  :	Optional[Any]							  =	input_ids.ne(1					).to(A					)
								UpperCAmelCase  :	str							  =	ids_tensor([self.model_tester.batch_size]	,	self.model_tester.type_sequence_label_size					)
								UpperCAmelCase  :	Optional[Any]							  =	OpenLlamaForSequenceClassification(A					)
								model.to(A					)
								model.eval()
								UpperCAmelCase  :	Tuple							  =	model(A	,	attention_mask=A	,	labels=A					)
								self.assertEqual(result.logits.shape	,	(self.model_tester.batch_size, self.model_tester.num_labels)					)





	def 				_lowercase(						self					)    ->    int:
								UpperCAmelCase  ,  UpperCAmelCase  :	Dict							  =	self.model_tester.prepare_config_and_inputs_for_common()
								UpperCAmelCase  :	Tuple							  =	3
								UpperCAmelCase  :	Optional[Any]							  =	"""multi_label_classification"""
								UpperCAmelCase  :	Dict							  =	input_dict["""input_ids"""]
								UpperCAmelCase  :	int							  =	input_ids.ne(1					).to(A					)
								UpperCAmelCase  :	int							  =	ids_tensor(
								    [self.model_tester.batch_size, config.num_labels]	,	self.model_tester.type_sequence_label_size					).to(torch.float					)
								UpperCAmelCase  :	Any							  =	OpenLlamaForSequenceClassification(A					)
								model.to(A					)
								model.eval()
								UpperCAmelCase  :	Dict							  =	model(A	,	attention_mask=A	,	labels=A					)
								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 				_lowercase(						self					)    ->    Dict:
								pass






	@parameterized.expand([("""linear""",), ("""dynamic""",)]					)
	def 				_lowercase(						self	,	A					)    ->    str:
								UpperCAmelCase  ,  UpperCAmelCase  :	Any							  =	self.model_tester.prepare_config_and_inputs_for_common()
								UpperCAmelCase  :	Dict							  =	ids_tensor([1, 10]	,	config.vocab_size					)
								UpperCAmelCase  :	List[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
								UpperCAmelCase  :	Any							  =	OpenLlamaModel(A					)
								original_model.to(A					)
								original_model.eval()
								UpperCAmelCase  :	List[str]							  =	original_model(A					).last_hidden_state
								UpperCAmelCase  :	List[Any]							  =	original_model(A					).last_hidden_state

								set_seed(42					)  # Fixed seed at init time so the two models get the same random weights
								UpperCAmelCase  :	Union[str, Any]							  =	{"""type""": scaling_type, """factor""": 1_0.0}
								UpperCAmelCase  :	str							  =	OpenLlamaModel(A					)
								scaled_model.to(A					)
								scaled_model.eval()
								UpperCAmelCase  :	List[str]							  =	scaled_model(A					).last_hidden_state
								UpperCAmelCase  :	Optional[int]							  =	scaled_model(A					).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(A	,	A	,	atol=1e-5					)					)
								else:
															self.assertFalse(torch.allclose(A	,	A	,	atol=1e-5					)					)

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

