






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    :







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







		__lowercase             =  parent
		__lowercase             =  batch_size
		__lowercase             =  seq_length
		__lowercase             =  is_training
		__lowercase             =  use_input_mask
		__lowercase             =  use_token_type_ids
		__lowercase             =  use_labels
		__lowercase             =  vocab_size
		__lowercase             =  hidden_size
		__lowercase             =  num_hidden_layers
		__lowercase             =  num_attention_heads
		__lowercase             =  intermediate_size
		__lowercase             =  hidden_act
		__lowercase             =  hidden_dropout_prob
		__lowercase             =  attention_probs_dropout_prob
		__lowercase             =  max_position_embeddings
		__lowercase             =  type_vocab_size
		__lowercase             =  type_sequence_label_size
		__lowercase             =  initializer_range
		__lowercase             =  num_labels
		__lowercase             =  num_choices
		__lowercase             =  scope







	def  _a   (  self      :							Dict			)		-> Any:
		"""simple docstring"""







		__lowercase             =  ids_tensor([self.batch_size, self.seq_length]       ,				self.vocab_size			)

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

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

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

		__lowercase             =  self.get_config()

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







	def  _a   (  self      :							List[Any]			)		-> Tuple:
		"""simple docstring"""







		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  _a   (  self      :							Dict       ,				_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							Union[str, Any]       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							Dict       ,				_lowerCAmelCase      :							Optional[int]       ,				_lowerCAmelCase      :							Tuple			)		-> List[str]:
		"""simple docstring"""







		__lowercase             =  LlamaModel(config=_lowerCAmelCase			)
		model.to(_lowerCAmelCase			)
		model.eval()
		__lowercase             =  model(_lowerCAmelCase       ,				attention_mask=_lowerCAmelCase			)
		__lowercase             =  model(_lowerCAmelCase			)
		self.parent.assertEqual(result.last_hidden_state.shape       ,				(self.batch_size, self.seq_length, self.hidden_size)			)







	def  _a   (  self      :							Any       ,				_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							List[str]       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							Optional[int]       ,				_lowerCAmelCase      :							int       ,				)		-> Optional[Any]:
		"""simple docstring"""







		__lowercase             =  True
		__lowercase             =  LlamaModel(_lowerCAmelCase			)
		model.to(_lowerCAmelCase			)
		model.eval()
		__lowercase             =  model(
		    _lowerCAmelCase       ,				attention_mask=_lowerCAmelCase       ,				encoder_hidden_states=_lowerCAmelCase       ,				encoder_attention_mask=_lowerCAmelCase       ,				)
		__lowercase             =  model(
		    _lowerCAmelCase       ,				attention_mask=_lowerCAmelCase       ,				encoder_hidden_states=_lowerCAmelCase       ,				)
		__lowercase             =  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      :							Optional[int]       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							List[str]       ,				_lowerCAmelCase      :							Dict       ,				_lowerCAmelCase      :							Dict       ,				_lowerCAmelCase      :							Dict       ,				_lowerCAmelCase      :							Any       ,				)		-> Optional[int]:
		"""simple docstring"""







		__lowercase             =  LlamaForCausalLM(config=_lowerCAmelCase			)
		model.to(_lowerCAmelCase			)
		model.eval()
		__lowercase             =  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      :							Dict       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							Union[str, Any]       ,				_lowerCAmelCase      :							Optional[int]       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							str       ,				)		-> List[str]:
		"""simple docstring"""







		__lowercase             =  True
		__lowercase             =  True
		__lowercase             =  LlamaForCausalLM(config=_lowerCAmelCase			)
		model.to(_lowerCAmelCase			)
		model.eval()

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

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

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

		__lowercase             =  model(
		    _lowerCAmelCase       ,				attention_mask=_lowerCAmelCase       ,				encoder_hidden_states=_lowerCAmelCase       ,				encoder_attention_mask=_lowerCAmelCase       ,				output_hidden_states=_lowerCAmelCase       ,				)["""hidden_states"""][0]
		__lowercase             =  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             =  ids_tensor((1,)       ,				output_from_past.shape[-1]			).item()
		__lowercase             =  output_from_no_past[:, -3:, random_slice_idx].detach()
		__lowercase             =  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      :							Optional[Any]			)		-> List[str]:
		"""simple docstring"""







		__lowercase             =  self.prepare_config_and_inputs()
		(
		    (
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						
		)             =  config_and_inputs
		__lowercase             =  {"""input_ids""": input_ids, """attention_mask""": input_mask}
		return config, inputs_dict


@require_torch
class        __UpperCamelCase    (     _lowerCAmelCase   ,			_lowerCAmelCase   ,			_lowerCAmelCase   ,			unittest.TestCase   ):
	__snake_case	:int   =       (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else ()
	__snake_case	:List[Any]   =       (LlamaForCausalLM,) if is_torch_available() else ()
	__snake_case	:Tuple   =       (
	    {
	        'feature-extraction': LlamaModel,
	        'text-classification': LlamaForSequenceClassification,
	        'text-generation': LlamaForCausalLM,
	        'zero-shot': LlamaForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	__snake_case	:Union[str, Any]   =       False
	__snake_case	:int   =       False







	def  _a   (  self      :							Optional[Any]			)		-> Union[str, Any]:
		"""simple docstring"""







		__lowercase             =  LlamaModelTester(self			)
		__lowercase             =  ConfigTester(self       ,				config_class=_lowerCAmelCase       ,				hidden_size=37			)







	def  _a   (  self      :							Dict			)		-> str:
		"""simple docstring"""







		self.config_tester.run_common_tests()







	def  _a   (  self      :							Tuple			)		-> int:
		"""simple docstring"""







		__lowercase             =  self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_model(*_lowerCAmelCase			)







	def  _a   (  self      :							int			)		-> Dict:
		"""simple docstring"""







		__lowercase             =  self.model_tester.prepare_config_and_inputs()
		for type in ["absolute", "relative_key", "relative_key_query"]:
			__lowercase             =  type
			self.model_tester.create_and_check_model(*_lowerCAmelCase			)







	def  _a   (  self      :							Optional[Any]			)		-> List[str]:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs_for_common()
		__lowercase             =  3
		__lowercase             =  input_dict["""input_ids"""]
		__lowercase             =  input_ids.ne(1			).to(_lowerCAmelCase			)
		__lowercase             =  ids_tensor([self.model_tester.batch_size]       ,				self.model_tester.type_sequence_label_size			)
		__lowercase             =  LlamaForSequenceClassification(_lowerCAmelCase			)
		model.to(_lowerCAmelCase			)
		model.eval()
		__lowercase             =  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      :							int			)		-> Any:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs_for_common()
		__lowercase             =  3
		__lowercase             =  """single_label_classification"""
		__lowercase             =  input_dict["""input_ids"""]
		__lowercase             =  input_ids.ne(1			).to(_lowerCAmelCase			)
		__lowercase             =  ids_tensor([self.model_tester.batch_size]       ,				self.model_tester.type_sequence_label_size			)
		__lowercase             =  LlamaForSequenceClassification(_lowerCAmelCase			)
		model.to(_lowerCAmelCase			)
		model.eval()
		__lowercase             =  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      :							Union[str, Any]			)		-> str:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs_for_common()
		__lowercase             =  3
		__lowercase             =  """multi_label_classification"""
		__lowercase             =  input_dict["""input_ids"""]
		__lowercase             =  input_ids.ne(1			).to(_lowerCAmelCase			)
		__lowercase             =  ids_tensor(
		    [self.model_tester.batch_size, config.num_labels]       ,				self.model_tester.type_sequence_label_size			).to(torch.float			)
		__lowercase             =  LlamaForSequenceClassification(_lowerCAmelCase			)
		model.to(_lowerCAmelCase			)
		model.eval()
		__lowercase             =  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  _a   (  self      :							Union[str, Any]			)		-> Tuple:
		"""simple docstring"""







		pass







	@parameterized.expand([("""linear""",), ("""dynamic""",)]			)
	def  _a   (  self      :							Union[str, Any]       ,				_lowerCAmelCase      :							Tuple			)		-> str:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs_for_common()
		__lowercase             =  ids_tensor([1, 10]       ,				config.vocab_size			)
		__lowercase             =  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             =  LlamaModel(_lowerCAmelCase			)
		original_model.to(_lowerCAmelCase			)
		original_model.eval()
		__lowercase             =  original_model(_lowerCAmelCase			).last_hidden_state
		__lowercase             =  original_model(_lowerCAmelCase			).last_hidden_state

		set_seed(42			)  # Fixed seed at init time so the two models get the same random weights
		__lowercase             =  {"""type""": scaling_type, """factor""": 10.0}
		__lowercase             =  LlamaModel(_lowerCAmelCase			)
		scaled_model.to(_lowerCAmelCase			)
		scaled_model.eval()
		__lowercase             =  scaled_model(_lowerCAmelCase			).last_hidden_state
		__lowercase             =  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   ):







	@unittest.skip("""Logits are not exactly the same, once we fix the instabalities somehow, will update!"""			)
	@slow
	def  _a   (  self      :							Any			)		-> List[Any]:
		"""simple docstring"""







		__lowercase             =  [1, 306, 4658, 278, 6593, 310, 2834, 338]
		__lowercase             =  LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-7b-hf"""       ,				device_map="""auto"""			)
		__lowercase             =  model(torch.tensor([input_ids]			)			)
		# Expected mean on dim = -1
		__lowercase             =  torch.tensor([[-6.6_550, -4.1_227, -4.9_859, -3.2_406, 0.8_262, -3.0_033, 1.2_964, -3.3_699]]			)
		torch.testing.assert_close(out.mean(-1			)       ,				_lowerCAmelCase       ,				atol=1e-2       ,				rtol=1e-2			)
		# slicing logits[0, 0, 0:30]
		# fmt: off
		__lowercase             =  torch.tensor([-12.8_281, -7.4_453, -0.4_639, -8.0_625, -7.2_500, -8.0_000, -6.4_883, -7.7_695, -7.8_438, -7.0_312, -6.2_188, -7.1_328, -1.8_496, 1.9_961, -8.6_250, -6.7_227, -12.8_281, -6.9_492, -7.0_742, -7.7_852, -7.5_820, -7.9_062, -6.9_375, -7.9_805, -8.3_438, -8.1_562, -8.0_469, -7.6_250, -7.7_422, -7.3_398,]			)
		# fmt: on
		torch.testing.assert_close(out[0, 0, :30]       ,				_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  _a   (  self      :							Union[str, Any]			)		-> Tuple:
		"""simple docstring"""







		__lowercase             =  [1, 306, 4658, 278, 6593, 310, 2834, 338]
		__lowercase             =  LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-hf"""       ,				device_map="""auto"""			)
		__lowercase             =  model(torch.tensor(_lowerCAmelCase			)			)
		# Expected mean on dim = -1
		__lowercase             =  torch.tensor([[-2.0_622, -1.2_794, -1.1_638, -0.9_788, -1.4_603, -1.0_238, -1.7_893, -1.4_411]]			)
		torch.testing.assert_close(out.mean(-1			)       ,				_lowerCAmelCase       ,				atol=1e-2       ,				rtol=1e-2			)
		# slicing logits[0, 0, 0:30]
		# fmt: off
		__lowercase             =  torch.tensor([-8.1_406, -8.0_547, 2.7_461, -1.2_344, -0.1_448, -1.8_262, -1.0_020, -1.8_154, -1.6_895, -1.8_516, -2.3_574, -0.9_277, 3.7_598, 6.5_742, -1.2_998, -0.1_177, -8.1_406, -2.9_688, -2.9_199, -3.1_699, -3.5_254, -2.3_555, -2.7_988, -3.4_141, -2.8_262, -4.5_195, -3.3_379, -3.3_164, -2.7_832, -3.0_273]			)
		# fmt: on
		torch.testing.assert_close(out[0, 0, :30]       ,				_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  _a   (  self      :							int			)		-> Any:
		"""simple docstring"""







		__lowercase             =  [1, 306, 4658, 278, 6593, 310, 2834, 338]
		__lowercase             =  LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-chat-hf"""       ,				device_map="""auto"""			)
		__lowercase             =  model(torch.tensor(_lowerCAmelCase			)			)
		# Expected mean on dim = -1
		__lowercase             =  torch.tensor([[-0.8_562, -1.8_520, -0.7_551, -0.4_162, -1.5_161, -1.2_038, -2.4_823, -2.3_254]]			)
		torch.testing.assert_close(out.mean(-1			)       ,				_lowerCAmelCase       ,				atol=1e-2       ,				rtol=1e-2			)
		# slicing logits[0, 0, 0:30]
		# fmt: off
		__lowercase             =  torch.tensor([-2.2_227, 4.8_828, 0.9_023, -0.4_578, -0.7_871, -0.1_033, -0.6_221, -0.5_786, -0.7_803, -1.0_674, -1.2_920, -0.1_570, 0.8_008, 2.0_723, -0.9_497, 0.2_771, -2.2_227, -0.7_612, -1.4_346, -1.2_061, -1.6_426, -0.3_000, -0.7_139, -1.1_934, -1.8_691, -1.6_973, -1.5_947, -1.2_705, -0.3_523, -0.5_513]			)
		# 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  _a   (  self      :							Union[str, Any]			)		-> Tuple:
		"""simple docstring"""







		__lowercase             =  [1, 306, 4658, 278, 6593, 310, 2834, 338]
		__lowercase             =  LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-70b-hf"""       ,				device_map="""auto"""			)
		__lowercase             =  model(torch.tensor(_lowerCAmelCase			)			)

		__lowercase             =  torch.tensor(
		    [[-4.2_327, -3.3_360, -4.6_665, -4.7_631, -1.8_180, -3.4_170, -1.4_211, -3.1_810]]       ,				dtype=torch.floataa			)
		torch.testing.assert_close(out.mean(-1			)       ,				_lowerCAmelCase       ,				atol=1e-2       ,				rtol=1e-2			)
		# fmt: off
		__lowercase             =  torch.tensor([-9.4_922, -3.9_551, 1.7_998, -5.6_758, -5.1_055, -5.8_984, -4.8_320, -6.8_086, -6.5_391, -5.6_172, -5.5_820, -5.5_352, 1.7_881, 3.6_289, -6.5_117, -3.4_785, -9.5_000, -6.0_352, -6.8_125, -6.0_195, -6.6_836, -5.4_727, -6.2_812, -6.0_391, -7.3_398, -7.4_297, -7.4_844, -6.5_820, -5.8_789, -5.5_312]			)
		# fmt: on
		torch.testing.assert_close(out[0, 0, :30]       ,				_lowerCAmelCase       ,				atol=1e-5       ,				rtol=1e-5			)







	@unittest.skip("""Model is curently gated"""			)
	@slow
	def  _a   (  self      :							List[str]			)		-> int:
		"""simple docstring"""







		__lowercase             =  """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"""
		__lowercase             =  """Simply put, the theory of relativity states that """
		__lowercase             =  LlamaTokenizer.from_pretrained("""meta-llama/Llama-2-13b-chat-hf"""			)
		__lowercase             =  tokenizer.encode(_lowerCAmelCase       ,				return_tensors="""pt"""			)
		__lowercase             =  LlamaForCausalLM.from_pretrained(
		    """meta-llama/Llama-2-13b-chat-hf"""       ,				device_map="""sequential"""       ,				use_safetensors=_lowerCAmelCase			)

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









import argparse
import json
import pickle
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, MaskFormerImageProcessor, SwinConfig
from transformers.utils import logging


logging.set_verbosity_info()
__UpperCamelCase      :      Optional[int]     						=						logging.get_logger(__name__)





def 				snake_case  (     lowerCamelCase					):




	'''simple docstring'''







	__lowercase             =  SwinConfig.from_pretrained(
	    """microsoft/swin-tiny-patch4-window7-224"""				,  out_features=["""stage1""", """stage2""", """stage3""", """stage4"""]					)
	__lowercase             =  MaskFormerConfig(backbone_config=lowerCamelCase					)

	__lowercase             =  """huggingface/label-files"""
	if "ade20k-full" in model_name:
		# this should be ok
		__lowercase             =  847
		__lowercase             =  """maskformer-ade20k-full-id2label.json"""
	elif "ade" in model_name:
		# this should be ok
		__lowercase             =  150
		__lowercase             =  """ade20k-id2label.json"""
	elif "coco-stuff" in model_name:
		# this should be ok
		__lowercase             =  171
		__lowercase             =  """maskformer-coco-stuff-id2label.json"""
	elif "coco" in model_name:
		# TODO
		__lowercase             =  133
		__lowercase             =  """coco-panoptic-id2label.json"""
	elif "cityscapes" in model_name:
		# this should be ok
		__lowercase             =  19
		__lowercase             =  """cityscapes-id2label.json"""
	elif "vistas" in model_name:
		# this should be ok
		__lowercase             =  65
		__lowercase             =  """mapillary-vistas-id2label.json"""

	__lowercase             =  json.load(open(hf_hub_download(lowerCamelCase				,  lowerCamelCase				,  repo_type="""dataset"""					)				,  """r"""					)					)
	__lowercase             =  {int(lowerCamelCase					): v for k, v in idalabel.items()}

	return config





def 				snake_case  (     lowerCamelCase					):




	'''simple docstring'''







	__lowercase             =  []
	# stem
	# fmt: off
	rename_keys.append(("""backbone.patch_embed.proj.weight""", """model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.weight""")					)
	rename_keys.append(("""backbone.patch_embed.proj.bias""", """model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.bias""")					)
	rename_keys.append(("""backbone.patch_embed.norm.weight""", """model.pixel_level_module.encoder.model.embeddings.norm.weight""")					)
	rename_keys.append(("""backbone.patch_embed.norm.bias""", """model.pixel_level_module.encoder.model.embeddings.norm.bias""")					)
	# stages
	for i in range(len(config.backbone_config.depths					)					):
		for j in range(config.backbone_config.depths[i]					):
			rename_keys.append((F'backbone.layers.{i}.blocks.{j}.norm1.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight')					)
			rename_keys.append((F'backbone.layers.{i}.blocks.{j}.norm1.bias', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias')					)
			rename_keys.append((F'backbone.layers.{i}.blocks.{j}.attn.relative_position_bias_table', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table')					)
			rename_keys.append((F'backbone.layers.{i}.blocks.{j}.attn.relative_position_index', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index')					)
			rename_keys.append((F'backbone.layers.{i}.blocks.{j}.attn.proj.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight')					)
			rename_keys.append((F'backbone.layers.{i}.blocks.{j}.attn.proj.bias', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias')					)
			rename_keys.append((F'backbone.layers.{i}.blocks.{j}.norm2.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight')					)
			rename_keys.append((F'backbone.layers.{i}.blocks.{j}.norm2.bias', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias')					)
			rename_keys.append((F'backbone.layers.{i}.blocks.{j}.mlp.fc1.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight')					)
			rename_keys.append((F'backbone.layers.{i}.blocks.{j}.mlp.fc1.bias', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias')					)
			rename_keys.append((F'backbone.layers.{i}.blocks.{j}.mlp.fc2.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.weight')					)
			rename_keys.append((F'backbone.layers.{i}.blocks.{j}.mlp.fc2.bias', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.bias')					)

		if i < 3:
			rename_keys.append((F'backbone.layers.{i}.downsample.reduction.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.reduction.weight')					)
			rename_keys.append((F'backbone.layers.{i}.downsample.norm.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.weight')					)
			rename_keys.append((F'backbone.layers.{i}.downsample.norm.bias', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.bias')					)
		rename_keys.append((F'backbone.norm{i}.weight', F'model.pixel_level_module.encoder.hidden_states_norms.{i}.weight')					)
		rename_keys.append((F'backbone.norm{i}.bias', F'model.pixel_level_module.encoder.hidden_states_norms.{i}.bias')					)

	# FPN
	rename_keys.append(("""sem_seg_head.layer_4.weight""", """model.pixel_level_module.decoder.fpn.stem.0.weight""")					)
	rename_keys.append(("""sem_seg_head.layer_4.norm.weight""", """model.pixel_level_module.decoder.fpn.stem.1.weight""")					)
	rename_keys.append(("""sem_seg_head.layer_4.norm.bias""", """model.pixel_level_module.decoder.fpn.stem.1.bias""")					)
	for source_index, target_index in zip(range(3				,  0				,  -1					)				,  range(0				,  3					)					):
		rename_keys.append((F'sem_seg_head.adapter_{source_index}.weight', F'model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.0.weight')					)
		rename_keys.append((F'sem_seg_head.adapter_{source_index}.norm.weight', F'model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.weight')					)
		rename_keys.append((F'sem_seg_head.adapter_{source_index}.norm.bias', F'model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.bias')					)
		rename_keys.append((F'sem_seg_head.layer_{source_index}.weight', F'model.pixel_level_module.decoder.fpn.layers.{target_index}.block.0.weight')					)
		rename_keys.append((F'sem_seg_head.layer_{source_index}.norm.weight', F'model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.weight')					)
		rename_keys.append((F'sem_seg_head.layer_{source_index}.norm.bias', F'model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.bias')					)
	rename_keys.append(("""sem_seg_head.mask_features.weight""", """model.pixel_level_module.decoder.mask_projection.weight""")					)
	rename_keys.append(("""sem_seg_head.mask_features.bias""", """model.pixel_level_module.decoder.mask_projection.bias""")					)

	# Transformer decoder
	for idx in range(config.decoder_config.decoder_layers					):
		# self-attention out projection
		rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.weight', F'model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.weight')					)
		rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.bias', F'model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.bias')					)
		# cross-attention out projection
		rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.weight', F'model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.weight')					)
		rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.bias', F'model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.bias')					)
		# MLP 1
		rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.weight', F'model.transformer_module.decoder.layers.{idx}.fc1.weight')					)
		rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.bias', F'model.transformer_module.decoder.layers.{idx}.fc1.bias')					)
		# MLP 2
		rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.weight', F'model.transformer_module.decoder.layers.{idx}.fc2.weight')					)
		rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.bias', F'model.transformer_module.decoder.layers.{idx}.fc2.bias')					)
		# layernorm 1 (self-attention layernorm)
		rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.weight', F'model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.weight')					)
		rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.bias', F'model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.bias')					)
		# layernorm 2 (cross-attention layernorm)
		rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.weight', F'model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.weight')					)
		rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.bias', F'model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.bias')					)
		# layernorm 3 (final layernorm)
		rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.weight', F'model.transformer_module.decoder.layers.{idx}.final_layer_norm.weight')					)
		rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.bias', F'model.transformer_module.decoder.layers.{idx}.final_layer_norm.bias')					)

	rename_keys.append(("""sem_seg_head.predictor.transformer.decoder.norm.weight""", """model.transformer_module.decoder.layernorm.weight""")					)
	rename_keys.append(("""sem_seg_head.predictor.transformer.decoder.norm.bias""", """model.transformer_module.decoder.layernorm.bias""")					)

	# heads on top
	rename_keys.append(("""sem_seg_head.predictor.query_embed.weight""", """model.transformer_module.queries_embedder.weight""")					)

	rename_keys.append(("""sem_seg_head.predictor.input_proj.weight""", """model.transformer_module.input_projection.weight""")					)
	rename_keys.append(("""sem_seg_head.predictor.input_proj.bias""", """model.transformer_module.input_projection.bias""")					)

	rename_keys.append(("""sem_seg_head.predictor.class_embed.weight""", """class_predictor.weight""")					)
	rename_keys.append(("""sem_seg_head.predictor.class_embed.bias""", """class_predictor.bias""")					)

	for i in range(3					):
		rename_keys.append((F'sem_seg_head.predictor.mask_embed.layers.{i}.weight', F'mask_embedder.{i}.0.weight')					)
		rename_keys.append((F'sem_seg_head.predictor.mask_embed.layers.{i}.bias', F'mask_embedder.{i}.0.bias')					)
	# fmt: on

	return rename_keys





def 				snake_case  (     lowerCamelCase				,  lowerCamelCase				,  lowerCamelCase					):




	'''simple docstring'''







	__lowercase             =  dct.pop(lowerCamelCase					)
	__lowercase             =  val





def 				snake_case  (     lowerCamelCase				,  lowerCamelCase					):




	'''simple docstring'''







	__lowercase             =  [int(backbone_config.embed_dim * 2**i					) for i in range(len(backbone_config.depths					)					)]
	for i in range(len(backbone_config.depths					)					):
		__lowercase             =  num_features[i]
		for j in range(backbone_config.depths[i]					):
			# fmt: off
			# read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias)
			__lowercase             =  state_dict.pop(F'backbone.layers.{i}.blocks.{j}.attn.qkv.weight'					)
			__lowercase             =  state_dict.pop(F'backbone.layers.{i}.blocks.{j}.attn.qkv.bias'					)
			# next, add query, keys and values (in that order) to the state dict
			__lowercase             =  in_proj_weight[:dim, :]
			__lowercase             =  in_proj_bias[: dim]
			__lowercase             =  in_proj_weight[
			    dim : dim * 2, :
			]
			__lowercase             =  in_proj_bias[
			    dim : dim * 2
			]
			__lowercase             =  in_proj_weight[
			    -dim :, :
			]
			__lowercase             =  in_proj_bias[-dim :]
			# fmt: on





def 				snake_case  (     lowerCamelCase				,  lowerCamelCase					):




	'''simple docstring'''







	__lowercase             =  config.decoder_config.hidden_size
	for idx in range(config.decoder_config.decoder_layers					):
		# read in weights + bias of self-attention input projection layer (in the original implementation, this is a single matrix + bias)
		__lowercase             =  state_dict.pop(F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_weight'					)
		__lowercase             =  state_dict.pop(F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_bias'					)
		# next, add query, keys and values (in that order) to the state dict
		__lowercase             =  in_proj_weight[: hidden_size, :]
		__lowercase             =  in_proj_bias[:config.hidden_size]
		__lowercase             =  in_proj_weight[hidden_size : hidden_size * 2, :]
		__lowercase             =  in_proj_bias[hidden_size : hidden_size * 2]
		__lowercase             =  in_proj_weight[-hidden_size :, :]
		__lowercase             =  in_proj_bias[-hidden_size :]
		# read in weights + bias of cross-attention input projection layer (in the original implementation, this is a single matrix + bias)
		__lowercase             =  state_dict.pop(F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_weight'					)
		__lowercase             =  state_dict.pop(F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_bias'					)
		# next, add query, keys and values (in that order) to the state dict
		__lowercase             =  in_proj_weight[: hidden_size, :]
		__lowercase             =  in_proj_bias[:config.hidden_size]
		__lowercase             =  in_proj_weight[hidden_size : hidden_size * 2, :]
		__lowercase             =  in_proj_bias[hidden_size : hidden_size * 2]
		__lowercase             =  in_proj_weight[-hidden_size :, :]
		__lowercase             =  in_proj_bias[-hidden_size :]
	# fmt: on





def 				snake_case  (     ):




	'''simple docstring'''







	__lowercase             =  """http://images.cocodataset.org/val2017/000000039769.jpg"""
	__lowercase             =  Image.open(requests.get(lowerCamelCase				,  stream=lowerCamelCase					).raw					)
	return im





@torch.no_grad()
def 				snake_case  (     lowerCamelCase				,  lowerCamelCase				,  lowerCamelCase				,  lowerCamelCase = False					):




	'''simple docstring'''







	__lowercase             =  get_maskformer_config(lowerCamelCase					)

	# load original state_dict
	with open(lowerCamelCase				,  """rb"""					) as f:
		__lowercase             =  pickle.load(lowerCamelCase					)
	__lowercase             =  data["""model"""]

	# for name, param in state_dict.items():
	#     print(name, param.shape)

	# rename keys
	__lowercase             =  create_rename_keys(lowerCamelCase					)
	for src, dest in rename_keys:
		rename_key(lowerCamelCase				,  lowerCamelCase				,  lowerCamelCase					)
	read_in_swin_q_k_v(lowerCamelCase				,  config.backbone_config					)
	read_in_decoder_q_k_v(lowerCamelCase				,  lowerCamelCase					)

	# update to torch tensors
	for key, value in state_dict.items():
		__lowercase             =  torch.from_numpy(lowerCamelCase					)

	# load 🤗 model
	__lowercase             =  MaskFormerForInstanceSegmentation(lowerCamelCase					)
	model.eval()

	for name, param in model.named_parameters():
		print(lowerCamelCase				,  param.shape					)

	__lowercase       ,						__lowercase             =  model.load_state_dict(lowerCamelCase				,  strict=lowerCamelCase					)
	assert missing_keys == [
	    "model.pixel_level_module.encoder.model.layernorm.weight",
	    "model.pixel_level_module.encoder.model.layernorm.bias",
	]
	assert len(lowerCamelCase					) == 0, F'Unexpected keys: {unexpected_keys}'

	# verify results
	__lowercase             =  prepare_img()
	if "vistas" in model_name:
		__lowercase             =  65
	elif "cityscapes" in model_name:
		__lowercase             =  65_535
	else:
		__lowercase             =  255
	__lowercase             =  True if """ade""" in model_name else False
	__lowercase             =  MaskFormerImageProcessor(ignore_index=lowerCamelCase				,  reduce_labels=lowerCamelCase					)

	__lowercase             =  image_processor(lowerCamelCase				,  return_tensors="""pt"""					)

	__lowercase             =  model(**lowerCamelCase					)

	print("""Logits:"""				,  outputs.class_queries_logits[0, :3, :3]					)

	if model_name == "maskformer-swin-tiny-ade":
		__lowercase             =  torch.tensor(
		    [[3.6353, -4.4770, -2.6065], [0.5081, -4.2394, -3.5343], [2.1909, -5.0353, -1.9323]]					)
	assert torch.allclose(outputs.class_queries_logits[0, :3, :3]				,  lowerCamelCase				,  atol=1e-4					)
	print("""Looks ok!"""					)

	if pytorch_dump_folder_path is not None:
		print(F'Saving model and image processor to {pytorch_dump_folder_path}'					)
		Path(lowerCamelCase					).mkdir(exist_ok=lowerCamelCase					)
		model.save_pretrained(lowerCamelCase					)
		image_processor.save_pretrained(lowerCamelCase					)

	if push_to_hub:
		print("""Pushing model and image processor to the hub..."""					)
		model.push_to_hub(F'nielsr/{model_name}'					)
		image_processor.push_to_hub(F'nielsr/{model_name}'					)


if __name__ == "__main__":
						__UpperCamelCase      :      Tuple     						=						argparse.ArgumentParser()
						# Required parameters
						parser.add_argument(
						    """--model_name""",
						    default="""maskformer-swin-tiny-ade""",
						    type=str,
						    help=("""Name of the MaskFormer model you'd like to convert""",),
						)
						parser.add_argument(
						    """--checkpoint_path""",
						    default="""/Users/nielsrogge/Documents/MaskFormer_checkpoints/MaskFormer-Swin-tiny-ADE20k/model.pkl""",
						    type=str,
						    help="""Path to the original state dict (.pth file).""",
						)
						parser.add_argument(
						    """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
						)
						parser.add_argument(
						    """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub."""
						)

						__UpperCamelCase      :      List[Any]     						=						parser.parse_args()
						convert_maskformer_checkpoint(
						    args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub
						)

