




"""simple docstring"""





import unittest

from parameterized import parameterized

from transformers import LlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer



class   a__					:


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


						"""simple docstring"""




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


			def    a_  (   self   :     Tuple):


						"""simple docstring"""




						__UpperCAmelCase						:			List[str]												=       ids_tensor([self.batch_size, self.seq_length]   ,	self.vocab_size)

						__UpperCAmelCase						:			Union[str, Any]												=       None
						if self.use_input_mask:
									__UpperCAmelCase						:			Tuple												=       random_attention_mask([self.batch_size, self.seq_length])

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

						__UpperCAmelCase						:			Optional[int]												=       None
						__UpperCAmelCase						:			Any												=       None
						__UpperCAmelCase						:			Any												=       None
						if self.use_labels:
									__UpperCAmelCase						:			List[Any]												=       ids_tensor([self.batch_size]   ,	self.type_sequence_label_size)
									__UpperCAmelCase						:			Tuple												=       ids_tensor([self.batch_size, self.seq_length]   ,	self.num_labels)
									__UpperCAmelCase						:			Optional[Any]												=       ids_tensor([self.batch_size]   ,	self.num_choices)

						__UpperCAmelCase						:			Optional[Any]												=       self.get_config()

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


			def    a_  (   self   :     str):


						"""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=UpperCamelCase_   ,	initializer_range=self.initializer_range   ,	)


			def    a_  (   self   :     Any   ,	UpperCamelCase_   :     str   ,	UpperCamelCase_   :     Any   ,	UpperCamelCase_   :     Optional[int]   ,	UpperCamelCase_   :     List[Any]   ,	UpperCamelCase_   :     Dict   ,	UpperCamelCase_   :     Any   ,	UpperCamelCase_   :     Dict):


						"""simple docstring"""




						__UpperCAmelCase						:			Optional[Any]												=       LlamaModel(config=UpperCamelCase_)
						model.to(UpperCamelCase_)
						model.eval()
						__UpperCAmelCase						:			List[Any]												=       model(UpperCamelCase_   ,	attention_mask=UpperCamelCase_)
						__UpperCAmelCase						:			Dict												=       model(UpperCamelCase_)
						self.parent.assertEqual(result.last_hidden_state.shape   ,	(self.batch_size, self.seq_length, self.hidden_size))


			def    a_  (   self   :     Union[str, Any]   ,	UpperCamelCase_   :     str   ,	UpperCamelCase_   :     Optional[Any]   ,	UpperCamelCase_   :     Dict   ,	UpperCamelCase_   :     str   ,	UpperCamelCase_   :     Optional[Any]   ,	UpperCamelCase_   :     Tuple   ,	UpperCamelCase_   :     Dict   ,	UpperCamelCase_   :     Optional[Any]   ,	UpperCamelCase_   :     str   ,	):


						"""simple docstring"""




						__UpperCAmelCase						:			Dict												=       True
						__UpperCAmelCase						:			List[str]												=       LlamaModel(UpperCamelCase_)
						model.to(UpperCamelCase_)
						model.eval()
						__UpperCAmelCase						:			Any												=       model(
						    UpperCamelCase_   ,	attention_mask=UpperCamelCase_   ,	encoder_hidden_states=UpperCamelCase_   ,	encoder_attention_mask=UpperCamelCase_   ,	)
						__UpperCAmelCase						:			List[Any]												=       model(
						    UpperCamelCase_   ,	attention_mask=UpperCamelCase_   ,	encoder_hidden_states=UpperCamelCase_   ,	)
						__UpperCAmelCase						:			Union[str, Any]												=       model(UpperCamelCase_   ,	attention_mask=UpperCamelCase_)
						self.parent.assertEqual(result.last_hidden_state.shape   ,	(self.batch_size, self.seq_length, self.hidden_size))


			def    a_  (   self   :     str   ,	UpperCamelCase_   :     List[str]   ,	UpperCamelCase_   :     List[Any]   ,	UpperCamelCase_   :     List[Any]   ,	UpperCamelCase_   :     str   ,	UpperCamelCase_   :     Optional[int]   ,	UpperCamelCase_   :     Tuple   ,	UpperCamelCase_   :     int   ,	UpperCamelCase_   :     List[Any]   ,	UpperCamelCase_   :     int   ,	):


						"""simple docstring"""




						__UpperCAmelCase						:			List[Any]												=       LlamaForCausalLM(config=UpperCamelCase_)
						model.to(UpperCamelCase_)
						model.eval()
						__UpperCAmelCase						:			str												=       model(UpperCamelCase_   ,	attention_mask=UpperCamelCase_   ,	labels=UpperCamelCase_)
						self.parent.assertEqual(result.logits.shape   ,	(self.batch_size, self.seq_length, self.vocab_size))


			def    a_  (   self   :     List[str]   ,	UpperCamelCase_   :     Dict   ,	UpperCamelCase_   :     Optional[int]   ,	UpperCamelCase_   :     Any   ,	UpperCamelCase_   :     Optional[Any]   ,	UpperCamelCase_   :     Any   ,	UpperCamelCase_   :     Tuple   ,	UpperCamelCase_   :     Any   ,	UpperCamelCase_   :     Optional[int]   ,	UpperCamelCase_   :     int   ,	):


						"""simple docstring"""




						__UpperCAmelCase						:			Dict												=       True
						__UpperCAmelCase						:			List[str]												=       True
						__UpperCAmelCase						:			List[str]												=       LlamaForCausalLM(config=UpperCamelCase_)
						model.to(UpperCamelCase_)
						model.eval()

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

						# create hypothetical multiple next token and extent to next_input_ids
						__UpperCAmelCase						:			List[str]												=       ids_tensor((self.batch_size, 3)   ,	config.vocab_size)
						__UpperCAmelCase						:			Dict												=       ids_tensor((self.batch_size, 3)   ,	vocab_size=2)

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

						__UpperCAmelCase						:			Tuple												=       model(
						    UpperCamelCase_   ,	attention_mask=UpperCamelCase_   ,	encoder_hidden_states=UpperCamelCase_   ,	encoder_attention_mask=UpperCamelCase_   ,	output_hidden_states=UpperCamelCase_   ,	)["hidden_states"][0]
						__UpperCAmelCase						:			int												=       model(
						    UpperCamelCase_   ,	attention_mask=UpperCamelCase_   ,	encoder_hidden_states=UpperCamelCase_   ,	encoder_attention_mask=UpperCamelCase_   ,	past_key_values=UpperCamelCase_   ,	output_hidden_states=UpperCamelCase_   ,	)["hidden_states"][0]

						# select random slice
						__UpperCAmelCase						:			List[str]												=       ids_tensor((1,)   ,	output_from_past.shape[-1]).item()
						__UpperCAmelCase						:			Tuple												=       output_from_no_past[:, -3:, random_slice_idx].detach()
						__UpperCAmelCase						:			Tuple												=       output_from_past[:, :, random_slice_idx].detach()

						self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])

						# test that outputs are equal for slice
						self.parent.assertTrue(torch.allclose(UpperCamelCase_   ,	UpperCamelCase_   ,	atol=1e-3))


			def    a_  (   self   :     List[str]):


						"""simple docstring"""




						__UpperCAmelCase						:			List[Any]												=       self.prepare_config_and_inputs()
						(
						    (
						    __UpperCAmelCase
						)						,  (
						    __UpperCAmelCase
						)						,  (
						    __UpperCAmelCase
						)						,  (
						    __UpperCAmelCase
						)						,  (
						    __UpperCAmelCase
						)						,  (
						    __UpperCAmelCase
						)						,  (
						    __UpperCAmelCase
						)						,  
						)						:			Any												=       config_and_inputs
						__UpperCAmelCase						:			List[Any]												=       {"input_ids": input_ids, "attention_mask": input_mask}
						return config, inputs_dict






@require_torch
class   a__					(						__magic_name__				,     __magic_name__				,     __magic_name__				,     unittest.TestCase ):
			lowercase_		=						(LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else ()
			lowercase_		=						(LlamaForCausalLM,) if is_torch_available() else ()
			lowercase_		=						(
			    {
			        "feature-extraction": LlamaModel,
			        "text-classification": LlamaForSequenceClassification,
			        "text-generation": LlamaForCausalLM,
			        "zero-shot": LlamaForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)
			lowercase_		=						False
			lowercase_		=						False


			def    a_  (   self   :     Tuple):


						"""simple docstring"""




						__UpperCAmelCase						:			Optional[int]												=       LlamaModelTester(self)
						__UpperCAmelCase						:			str												=       ConfigTester(self   ,	config_class=UpperCamelCase_   ,	hidden_size=37)


			def    a_  (   self   :     Union[str, Any]):


						"""simple docstring"""




						self.config_tester.run_common_tests()


			def    a_  (   self   :     Tuple):


						"""simple docstring"""




						__UpperCAmelCase						:			Optional[int]												=       self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*UpperCamelCase_)


			def    a_  (   self   :     Any):


						"""simple docstring"""




						__UpperCAmelCase						:			Optional[Any]												=       self.model_tester.prepare_config_and_inputs()
						for type in ["absolute", "relative_key", "relative_key_query"]:
									__UpperCAmelCase						:			Optional[Any]												=       type
									self.model_tester.create_and_check_model(*UpperCamelCase_)


			def    a_  (   self   :     Dict):


						"""simple docstring"""




						__UpperCAmelCase						,  __UpperCAmelCase						:			Optional[Any]												=       self.model_tester.prepare_config_and_inputs_for_common()
						__UpperCAmelCase						:			Optional[int]												=       3
						__UpperCAmelCase						:			List[Any]												=       input_dict["input_ids"]
						__UpperCAmelCase						:			Tuple												=       input_ids.ne(1).to(UpperCamelCase_)
						__UpperCAmelCase						:			List[str]												=       ids_tensor([self.model_tester.batch_size]   ,	self.model_tester.type_sequence_label_size)
						__UpperCAmelCase						:			Optional[Any]												=       LlamaForSequenceClassification(UpperCamelCase_)
						model.to(UpperCamelCase_)
						model.eval()
						__UpperCAmelCase						:			Dict												=       model(UpperCamelCase_   ,	attention_mask=UpperCamelCase_   ,	labels=UpperCamelCase_)
						self.assertEqual(result.logits.shape   ,	(self.model_tester.batch_size, self.model_tester.num_labels))


			def    a_  (   self   :     Optional[Any]):


						"""simple docstring"""




						__UpperCAmelCase						,  __UpperCAmelCase						:			Union[str, Any]												=       self.model_tester.prepare_config_and_inputs_for_common()
						__UpperCAmelCase						:			Union[str, Any]												=       3
						__UpperCAmelCase						:			Optional[Any]												=       "single_label_classification"
						__UpperCAmelCase						:			str												=       input_dict["input_ids"]
						__UpperCAmelCase						:			List[str]												=       input_ids.ne(1).to(UpperCamelCase_)
						__UpperCAmelCase						:			List[Any]												=       ids_tensor([self.model_tester.batch_size]   ,	self.model_tester.type_sequence_label_size)
						__UpperCAmelCase						:			str												=       LlamaForSequenceClassification(UpperCamelCase_)
						model.to(UpperCamelCase_)
						model.eval()
						__UpperCAmelCase						:			Any												=       model(UpperCamelCase_   ,	attention_mask=UpperCamelCase_   ,	labels=UpperCamelCase_)
						self.assertEqual(result.logits.shape   ,	(self.model_tester.batch_size, self.model_tester.num_labels))


			def    a_  (   self   :     Union[str, Any]):


						"""simple docstring"""




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


			@unittest.skip("LLaMA buffers include complex numbers, which breaks this test")
			def    a_  (   self   :     Dict):


						"""simple docstring"""




						pass


			@parameterized.expand([("linear",), ("dynamic",)])
			def    a_  (   self   :     int   ,	UpperCamelCase_   :     Any):


						"""simple docstring"""




						__UpperCAmelCase						,  __UpperCAmelCase						:			Tuple												=       self.model_tester.prepare_config_and_inputs_for_common()
						__UpperCAmelCase						:			str												=       ids_tensor([1, 10]   ,	config.vocab_size)
						__UpperCAmelCase						:			int												=       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												=       LlamaModel(UpperCamelCase_)
						original_model.to(UpperCamelCase_)
						original_model.eval()
						__UpperCAmelCase						:			Any												=       original_model(UpperCamelCase_).last_hidden_state
						__UpperCAmelCase						:			Tuple												=       original_model(UpperCamelCase_).last_hidden_state

						set_seed(42)  # Fixed seed at init time so the two models get the same random weights
						__UpperCAmelCase						:			str												=       {"type": scaling_type, "factor": 10.0}
						__UpperCAmelCase						:			Union[str, Any]												=       LlamaModel(UpperCamelCase_)
						scaled_model.to(UpperCamelCase_)
						scaled_model.eval()
						__UpperCAmelCase						:			Optional[Any]												=       scaled_model(UpperCamelCase_).last_hidden_state
						__UpperCAmelCase						:			Tuple												=       scaled_model(UpperCamelCase_).last_hidden_state

						# Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
						# maximum sequence length, so the outputs for the short input should match.
						if scaling_type == "dynamic":
									self.assertTrue(torch.allclose(UpperCamelCase_   ,	UpperCamelCase_   ,	atol=1e-5))
						else:
									self.assertFalse(torch.allclose(UpperCamelCase_   ,	UpperCamelCase_   ,	atol=1e-5))

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






@require_torch
class   a__					(						unittest.TestCase ):


			@unittest.skip("Logits are not exactly the same, once we fix the instabalities somehow, will update!")
			@slow
			def    a_  (   self   :     Optional[int]):


						"""simple docstring"""




						__UpperCAmelCase						:			Optional[int]												=       [1, 306, 4658, 278, 6593, 310, 2834, 338]
						__UpperCAmelCase						:			List[str]												=       LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf"   ,	device_map="auto")
						__UpperCAmelCase						:			Optional[Any]												=       model(torch.tensor([input_ids]))
						# Expected mean on dim = -1
						__UpperCAmelCase						:			Union[str, Any]												=       torch.tensor([[-6.6550, -4.1227, -4.9859, -3.2406, 0.8262, -3.0033, 1.2964, -3.3699]])
						torch.testing.assert_close(out.mean(-1)   ,	UpperCamelCase_   ,	atol=1e-2   ,	rtol=1e-2)
						# slicing logits[0, 0, 0:30]
						# fmt: off
						__UpperCAmelCase						:			Dict												=       torch.tensor([-12.8281, -7.4453, -0.4639, -8.0625, -7.2500, -8.0000, -6.4883, -7.7695, -7.8438, -7.0312, -6.2188, -7.1328, -1.8496, 1.9961, -8.6250, -6.7227, -12.8281, -6.9492, -7.0742, -7.7852, -7.5820, -7.9062, -6.9375, -7.9805, -8.3438, -8.1562, -8.0469, -7.6250, -7.7422, -7.3398,])
						# fmt: on
						torch.testing.assert_close(out[0, 0, :30]   ,	UpperCamelCase_   ,	atol=1e-5   ,	rtol=1e-5)


			@unittest.skip("Logits are not exactly the same, once we fix the instabalities somehow, will update!")
			@slow
			def    a_  (   self   :     Union[str, Any]):


						"""simple docstring"""




						__UpperCAmelCase						:			List[Any]												=       [1, 306, 4658, 278, 6593, 310, 2834, 338]
						__UpperCAmelCase						:			List[Any]												=       LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-13b-hf"   ,	device_map="auto")
						__UpperCAmelCase						:			Any												=       model(torch.tensor(UpperCamelCase_))
						# Expected mean on dim = -1
						__UpperCAmelCase						:			int												=       torch.tensor([[-2.0622, -1.2794, -1.1638, -0.9788, -1.4603, -1.0238, -1.7893, -1.4411]])
						torch.testing.assert_close(out.mean(-1)   ,	UpperCamelCase_   ,	atol=1e-2   ,	rtol=1e-2)
						# slicing logits[0, 0, 0:30]
						# fmt: off
						__UpperCAmelCase						:			str												=       torch.tensor([-8.1406, -8.0547, 2.7461, -1.2344, -0.1448, -1.8262, -1.0020, -1.8154, -1.6895, -1.8516, -2.3574, -0.9277, 3.7598, 6.5742, -1.2998, -0.1177, -8.1406, -2.9688, -2.9199, -3.1699, -3.5254, -2.3555, -2.7988, -3.4141, -2.8262, -4.5195, -3.3379, -3.3164, -2.7832, -3.0273])
						# fmt: on
						torch.testing.assert_close(out[0, 0, :30]   ,	UpperCamelCase_   ,	atol=1e-5   ,	rtol=1e-5)


			@unittest.skip("Logits are not exactly the same, once we fix the instabalities somehow, will update!")
			@slow
			def    a_  (   self   :     Tuple):


						"""simple docstring"""




						__UpperCAmelCase						:			str												=       [1, 306, 4658, 278, 6593, 310, 2834, 338]
						__UpperCAmelCase						:			Any												=       LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-13b-chat-hf"   ,	device_map="auto")
						__UpperCAmelCase						:			Optional[Any]												=       model(torch.tensor(UpperCamelCase_))
						# Expected mean on dim = -1
						__UpperCAmelCase						:			int												=       torch.tensor([[-0.8562, -1.8520, -0.7551, -0.4162, -1.5161, -1.2038, -2.4823, -2.3254]])
						torch.testing.assert_close(out.mean(-1)   ,	UpperCamelCase_   ,	atol=1e-2   ,	rtol=1e-2)
						# slicing logits[0, 0, 0:30]
						# fmt: off
						__UpperCAmelCase						:			Optional[Any]												=       torch.tensor([-2.2227, 4.8828, 0.9023, -0.4578, -0.7871, -0.1033, -0.6221, -0.5786, -0.7803, -1.0674, -1.2920, -0.1570, 0.8008, 2.0723, -0.9497, 0.2771, -2.2227, -0.7612, -1.4346, -1.2061, -1.6426, -0.3000, -0.7139, -1.1934, -1.8691, -1.6973, -1.5947, -1.2705, -0.3523, -0.5513])
						# fmt: on
						torch.testing.assert_close(out.mean(-1)   ,	UpperCamelCase_   ,	atol=1e-2   ,	rtol=1e-2)


			@unittest.skip(
			    "Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test")
			@slow
			def    a_  (   self   :     Tuple):


						"""simple docstring"""




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

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


			@unittest.skip("Model is curently gated")
			@slow
			def    a_  (   self   :     List[Any]):


						"""simple docstring"""




						__UpperCAmelCase						:			Dict												=       "Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the \"princi"
						__UpperCAmelCase						:			int												=       "Simply put, the theory of relativity states that "
						__UpperCAmelCase						:			Union[str, Any]												=       LlamaTokenizer.from_pretrained("meta-llama/Llama-2-13b-chat-hf")
						__UpperCAmelCase						:			str												=       tokenizer.encode(UpperCamelCase_   ,	return_tensors="pt")
						__UpperCAmelCase						:			int												=       LlamaForCausalLM.from_pretrained(
						    "meta-llama/Llama-2-13b-chat-hf"   ,	device_map="sequential"   ,	use_safetensors=UpperCamelCase_)

						# greedy generation outputs
						__UpperCAmelCase						:			int												=       model.generate(UpperCamelCase_   ,	max_new_tokens=64   ,	top_p=UpperCamelCase_   ,	temperature=1   ,	do_sample=UpperCamelCase_)
						__UpperCAmelCase						:			List[Any]												=       tokenizer.decode(generated_ids[0]   ,	skip_special_tokens=UpperCamelCase_)
						self.assertEqual(UpperCamelCase_   ,	UpperCamelCase_)



'''simple docstring'''

import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()


class 					_lowercase						(   lowerCAmelCase		,unittest.TestCase ):
      '''simple docstring'''


      UpperCAmelCase_   :   Any   				= KandinskyInpaintPipeline
      UpperCAmelCase_   :   str   				= ['''prompt''', '''image_embeds''', '''negative_image_embeds''', '''image''', '''mask_image''']
      UpperCAmelCase_   :   Union[str, Any]   				= [
          '''prompt''',
          '''negative_prompt''',
          '''image_embeds''',
          '''negative_image_embeds''',
          '''image''',
          '''mask_image''',
      ]
      UpperCAmelCase_   :   Union[str, Any]   				= [
          '''generator''',
          '''height''',
          '''width''',
          '''latents''',
          '''guidance_scale''',
          '''negative_prompt''',
          '''num_inference_steps''',
          '''return_dict''',
          '''guidance_scale''',
          '''num_images_per_prompt''',
          '''output_type''',
          '''return_dict''',
      ]
      UpperCAmelCase_   :   Optional[int]   				= False




      @property
      def 		lowerCAmelCase__       (					self				)      ->      Dict:



         '''simple docstring'''



         return 32




      @property
      def 		lowerCAmelCase__       (					self				)      ->      Optional[Any]:



         '''simple docstring'''



         return 32




      @property
      def 		lowerCAmelCase__       (					self				)      ->      Dict:



         '''simple docstring'''



         return self.time_input_dim




      @property
      def 		lowerCAmelCase__       (					self				)      ->      Optional[int]:



         '''simple docstring'''



         return self.time_input_dim * 4




      @property
      def 		lowerCAmelCase__       (					self				)      ->      Dict:



         '''simple docstring'''



         return 100




      @property
      def 		lowerCAmelCase__       (					self				)      ->      int:



         '''simple docstring'''



         UpperCAmelCase__				:					Optional[Any] 					=	XLMRobertaTokenizerFast.from_pretrained('''YiYiXu/tiny-random-mclip-base'''				)
         return tokenizer




      @property
      def 		lowerCAmelCase__       (					self				)      ->      int:



         '''simple docstring'''



         torch.manual_seed(0				)
         UpperCAmelCase__				:					Any 					=	MCLIPConfig(
             numDims=self.cross_attention_dim       ,transformerDimensions=self.text_embedder_hidden_size       ,hidden_size=self.text_embedder_hidden_size       ,intermediate_size=37       ,num_attention_heads=4       ,num_hidden_layers=5       ,vocab_size=1005       ,)

         UpperCAmelCase__				:					Any 					=	MultilingualCLIP(lowerCamelCase_				)
         UpperCAmelCase__				:					Optional[Any] 					=	text_encoder.eval()

         return text_encoder




      @property
      def 		lowerCAmelCase__       (					self				)      ->      Union[str, Any]:



         '''simple docstring'''



         torch.manual_seed(0				)

         UpperCAmelCase__				:					Tuple 					=	{
             '''in_channels''': 9,
             # Out channels is double in channels because predicts mean and variance
             '''out_channels''': 8,
             '''addition_embed_type''': '''text_image''',
             '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''),
             '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''),
             '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''',
             '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2),
             '''layers_per_block''': 1,
             '''encoder_hid_dim''': self.text_embedder_hidden_size,
             '''encoder_hid_dim_type''': '''text_image_proj''',
             '''cross_attention_dim''': self.cross_attention_dim,
             '''attention_head_dim''': 4,
             '''resnet_time_scale_shift''': '''scale_shift''',
             '''class_embed_type''': None,
         }

         UpperCAmelCase__				:					List[str] 					=	UNetaDConditionModel(**lowerCamelCase_				)
         return model




      @property
      def 		lowerCAmelCase__       (					self				)      ->      List[str]:



         '''simple docstring'''



         return {
             "block_out_channels": [32, 64],
             "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
             "in_channels": 3,
             "latent_channels": 4,
             "layers_per_block": 1,
             "norm_num_groups": 8,
             "norm_type": "spatial",
             "num_vq_embeddings": 12,
             "out_channels": 3,
             "up_block_types": [
                 "AttnUpDecoderBlock2D",
                 "UpDecoderBlock2D",
             ],
             "vq_embed_dim": 4,
         }




      @property
      def 		lowerCAmelCase__       (					self				)      ->      Tuple:



         '''simple docstring'''



         torch.manual_seed(0				)
         UpperCAmelCase__				:					Union[str, Any] 					=	VQModel(**self.dummy_movq_kwargs				)
         return model




      def 		lowerCAmelCase__       (					self				)      ->      Any:



         '''simple docstring'''



         UpperCAmelCase__				:					List[Any] 					=	self.dummy_text_encoder
         UpperCAmelCase__				:					Optional[int] 					=	self.dummy_tokenizer
         UpperCAmelCase__				:					Optional[Any] 					=	self.dummy_unet
         UpperCAmelCase__				:					Any 					=	self.dummy_movq

         UpperCAmelCase__				:					Tuple 					=	DDIMScheduler(
             num_train_timesteps=1000       ,beta_schedule='''linear'''       ,beta_start=0.0_0085       ,beta_end=0.012       ,clip_sample=lowerCamelCase_       ,set_alpha_to_one=lowerCamelCase_       ,steps_offset=1       ,prediction_type='''epsilon'''       ,thresholding=lowerCamelCase_       ,)

         UpperCAmelCase__				:					Dict 					=	{
             '''text_encoder''': text_encoder,
             '''tokenizer''': tokenizer,
             '''unet''': unet,
             '''scheduler''': scheduler,
             '''movq''': movq,
         }

         return components




      def 		lowerCAmelCase__       (					self       ,lowerCamelCase_       ,lowerCamelCase_=0				)      ->      Tuple:



         '''simple docstring'''



         UpperCAmelCase__				:					Dict 					=	floats_tensor((1, self.cross_attention_dim)       ,rng=random.Random(lowerCamelCase_				)				).to(lowerCamelCase_				)
         UpperCAmelCase__				:					str 					=	floats_tensor((1, self.cross_attention_dim)       ,rng=random.Random(seed + 1				)				).to(lowerCamelCase_				)
         # create init_image
         UpperCAmelCase__				:					str 					=	floats_tensor((1, 3, 64, 64)       ,rng=random.Random(lowerCamelCase_				)				).to(lowerCamelCase_				)
         UpperCAmelCase__				:					Optional[Any] 					=	image.cpu().permute(0       ,2       ,3       ,1				)[0]
         UpperCAmelCase__				:					Union[str, Any] 					=	Image.fromarray(np.uinta(lowerCamelCase_				)				).convert('''RGB'''				).resize((256, 256)				)
         # create mask
         UpperCAmelCase__				:					List[str] 					=	np.ones((64, 64)       ,dtype=np.floataa				)
         UpperCAmelCase__				:					Optional[Any] 					=	0

         if str(lowerCamelCase_				).startswith('''mps'''				):
            UpperCAmelCase__				:					Any 					=	torch.manual_seed(lowerCamelCase_				)
         else:
            UpperCAmelCase__				:					Dict 					=	torch.Generator(device=lowerCamelCase_				).manual_seed(lowerCamelCase_				)
         UpperCAmelCase__				:					Optional[Any] 					=	{
             '''prompt''': '''horse''',
             '''image''': init_image,
             '''mask_image''': mask,
             '''image_embeds''': image_embeds,
             '''negative_image_embeds''': negative_image_embeds,
             '''generator''': generator,
             '''height''': 64,
             '''width''': 64,
             '''num_inference_steps''': 2,
             '''guidance_scale''': 4.0,
             '''output_type''': '''np''',
         }
         return inputs




      def 		lowerCAmelCase__       (					self				)      ->      Dict:



         '''simple docstring'''



         UpperCAmelCase__				:					Tuple 					=	'''cpu'''

         UpperCAmelCase__				:					List[str] 					=	self.get_dummy_components()

         UpperCAmelCase__				:					Tuple 					=	self.pipeline_class(**lowerCamelCase_				)
         UpperCAmelCase__				:					int 					=	pipe.to(lowerCamelCase_				)

         pipe.set_progress_bar_config(disable=lowerCamelCase_				)

         UpperCAmelCase__				:					Tuple 					=	pipe(**self.get_dummy_inputs(lowerCamelCase_				)				)
         UpperCAmelCase__				:					List[Any] 					=	output.images

         UpperCAmelCase__				:					Union[str, Any] 					=	pipe(
             **self.get_dummy_inputs(lowerCamelCase_				)       ,return_dict=lowerCamelCase_       ,)[0]

         UpperCAmelCase__				:					Tuple 					=	image[0, -3:, -3:, -1]
         UpperCAmelCase__				:					int 					=	image_from_tuple[0, -3:, -3:, -1]

         print(f'''image.shape {image.shape}'''				)

         assert image.shape == (1, 64, 64, 3)

         UpperCAmelCase__				:					List[Any] 					=	np.array(
             [0.832_6919, 0.7379_0467, 0.2091_8581, 0.930_9612, 0.551_1791, 0.4371_3328, 0.551_3321, 0.4992_2934, 0.5949_7786]				)

         assert (
             np.abs(image_slice.flatten() - expected_slice				).max() < 1e-2
         ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}'''
         assert (
             np.abs(image_from_tuple_slice.flatten() - expected_slice				).max() < 1e-2
         ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}'''




      def 		lowerCAmelCase__       (					self				)      ->      Dict:



         '''simple docstring'''



         super().test_inference_batch_single_identical(expected_max_diff=3e-3				)




@slow
@require_torch_gpu
class 					_lowercase						(   unittest.TestCase ):
      '''simple docstring'''


      def 		lowerCAmelCase__       (					self				)      ->      List[str]:



         '''simple docstring'''



         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()




      def 		lowerCAmelCase__       (					self				)      ->      str:



         '''simple docstring'''



         UpperCAmelCase__				:					Dict 					=	load_numpy(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
             '''/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy'''				)

         UpperCAmelCase__				:					str 					=	load_image(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png'''				)
         UpperCAmelCase__				:					Union[str, Any] 					=	np.ones((768, 768)       ,dtype=np.floataa				)
         UpperCAmelCase__				:					int 					=	0

         UpperCAmelCase__				:					List[Any] 					=	'''a hat'''

         UpperCAmelCase__				:					str 					=	KandinskyPriorPipeline.from_pretrained(
             '''kandinsky-community/kandinsky-2-1-prior'''       ,torch_dtype=torch.floataa				)
         pipe_prior.to(lowerCamelCase_				)

         UpperCAmelCase__				:					List[str] 					=	KandinskyInpaintPipeline.from_pretrained(
             '''kandinsky-community/kandinsky-2-1-inpaint'''       ,torch_dtype=torch.floataa				)
         UpperCAmelCase__				:					Tuple 					=	pipeline.to(lowerCamelCase_				)
         pipeline.set_progress_bar_config(disable=lowerCamelCase_				)

         UpperCAmelCase__				:					List[Any] 					=	torch.Generator(device='''cpu'''				).manual_seed(0				)
         UpperCAmelCase__					,   UpperCAmelCase__				:					int 					=	pipe_prior(
             lowerCamelCase_       ,generator=lowerCamelCase_       ,num_inference_steps=5       ,negative_prompt=''''''       ,).to_tuple()

         UpperCAmelCase__				:					Optional[Any] 					=	pipeline(
             lowerCamelCase_       ,image=lowerCamelCase_       ,mask_image=lowerCamelCase_       ,image_embeds=lowerCamelCase_       ,negative_image_embeds=lowerCamelCase_       ,generator=lowerCamelCase_       ,num_inference_steps=100       ,height=768       ,width=768       ,output_type='''np'''       ,)

         UpperCAmelCase__				:					str 					=	output.images[0]

         assert image.shape == (768, 768, 3)

         assert_mean_pixel_difference(lowerCamelCase_       ,lowerCamelCase_				)




