



from typing import Any, Callable, Dict, List, Optional, Union

import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker


a__    =	"""CompVis/stable-diffusion-v1-1"""
a__    =	"""CompVis/stable-diffusion-v1-2"""
a__    =	"""CompVis/stable-diffusion-v1-3"""
a__    =	"""CompVis/stable-diffusion-v1-4"""







class 		snake_case						(	SCREAMING_SNAKE_CASE_  ):



   '''simple docstring'''






   def __init__(					self							:			List[str]				,		lowerCAmelCase							:			AutoencoderKL				,		lowerCAmelCase							:			CLIPTextModel				,		lowerCAmelCase							:			CLIPTokenizer				,		lowerCAmelCase							:			UNetaDConditionModel				,		lowerCAmelCase							:			Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]				,		lowerCAmelCase							:			StableDiffusionSafetyChecker				,		lowerCAmelCase							:			CLIPImageProcessor				,		lowerCAmelCase							:			bool = True				,		)				->				int:

    """simple docstring"""







    super()._init_()

    _snake_case    :  List[Any]					=					StableDiffusionPipeline.from_pretrained(lowerCAmelCase)
    _snake_case    :  str					=					StableDiffusionPipeline.from_pretrained(lowerCAmelCase)
    _snake_case    :  Optional[Any]					=					StableDiffusionPipeline.from_pretrained(lowerCAmelCase)
    _snake_case    :  Optional[Any]					=					StableDiffusionPipeline(
        vae=lowerCAmelCase				,		text_encoder=lowerCAmelCase				,		tokenizer=lowerCAmelCase				,		unet=lowerCAmelCase				,		scheduler=lowerCAmelCase				,		safety_checker=lowerCAmelCase				,		feature_extractor=lowerCAmelCase				,		requires_safety_checker=lowerCAmelCase				,		)

    self.register_modules(pipelinea=self.pipea				,		pipelinea=self.pipea				,		pipelinea=self.pipea				,		pipelinea=self.pipea)

   @property
   def      UpperCamelCase_  (					self							:			List[str])				->				Dict[str, Any]:

    """simple docstring"""







    return {k: getattr(self				,		lowerCAmelCase) for k in self.config.keys() if not k.startswith("""_""")}

   def      UpperCamelCase_  (					self							:			List[Any]				,		lowerCAmelCase							:			Optional[Union[str, int]] = "auto")				->				List[Any]:

    """simple docstring"""







    if slice_size == "auto":
     # half the attention head size is usually a good trade-off between
     # speed and memory
     _snake_case    :  Optional[int]					=					self.unet.config.attention_head_dim // 2
    self.unet.set_attention_slice(lowerCAmelCase)

   def      UpperCamelCase_  (					self							:			Tuple)				->				List[Any]:

    """simple docstring"""







    self.enable_attention_slicing(lowerCAmelCase)

   @torch.no_grad()
   def      UpperCamelCase_  (					self							:			List[Any]				,		lowerCAmelCase							:			Union[str, List[str]]				,		lowerCAmelCase							:			int = 512				,		lowerCAmelCase							:			int = 512				,		lowerCAmelCase							:			int = 50				,		lowerCAmelCase							:			float = 7.5				,		lowerCAmelCase							:			Optional[Union[str, List[str]]] = None				,		lowerCAmelCase							:			Optional[int] = 1				,		lowerCAmelCase							:			float = 0.0				,		lowerCAmelCase							:			Optional[torch.Generator] = None				,		lowerCAmelCase							:			Optional[torch.FloatTensor] = None				,		lowerCAmelCase							:			Optional[str] = "pil"				,		lowerCAmelCase							:			bool = True				,		lowerCAmelCase							:			Optional[Callable[[int, int, torch.FloatTensor], None]] = None				,		lowerCAmelCase							:			int = 1				,		**lowerCAmelCase							:			Any				,		)				->				Optional[Any]:

    """simple docstring"""







    return self.pipea(
        prompt=lowerCAmelCase				,		height=lowerCAmelCase				,		width=lowerCAmelCase				,		num_inference_steps=lowerCAmelCase				,		guidance_scale=lowerCAmelCase				,		negative_prompt=lowerCAmelCase				,		num_images_per_prompt=lowerCAmelCase				,		eta=lowerCAmelCase				,		generator=lowerCAmelCase				,		latents=lowerCAmelCase				,		output_type=lowerCAmelCase				,		return_dict=lowerCAmelCase				,		callback=lowerCAmelCase				,		callback_steps=lowerCAmelCase				,		**lowerCAmelCase				,		)

   @torch.no_grad()
   def      UpperCamelCase_  (					self							:			List[Any]				,		lowerCAmelCase							:			Union[str, List[str]]				,		lowerCAmelCase							:			int = 512				,		lowerCAmelCase							:			int = 512				,		lowerCAmelCase							:			int = 50				,		lowerCAmelCase							:			float = 7.5				,		lowerCAmelCase							:			Optional[Union[str, List[str]]] = None				,		lowerCAmelCase							:			Optional[int] = 1				,		lowerCAmelCase							:			float = 0.0				,		lowerCAmelCase							:			Optional[torch.Generator] = None				,		lowerCAmelCase							:			Optional[torch.FloatTensor] = None				,		lowerCAmelCase							:			Optional[str] = "pil"				,		lowerCAmelCase							:			bool = True				,		lowerCAmelCase							:			Optional[Callable[[int, int, torch.FloatTensor], None]] = None				,		lowerCAmelCase							:			int = 1				,		**lowerCAmelCase							:			int				,		)				->				str:

    """simple docstring"""







    return self.pipea(
        prompt=lowerCAmelCase				,		height=lowerCAmelCase				,		width=lowerCAmelCase				,		num_inference_steps=lowerCAmelCase				,		guidance_scale=lowerCAmelCase				,		negative_prompt=lowerCAmelCase				,		num_images_per_prompt=lowerCAmelCase				,		eta=lowerCAmelCase				,		generator=lowerCAmelCase				,		latents=lowerCAmelCase				,		output_type=lowerCAmelCase				,		return_dict=lowerCAmelCase				,		callback=lowerCAmelCase				,		callback_steps=lowerCAmelCase				,		**lowerCAmelCase				,		)

   @torch.no_grad()
   def      UpperCamelCase_  (					self							:			Any				,		lowerCAmelCase							:			Union[str, List[str]]				,		lowerCAmelCase							:			int = 512				,		lowerCAmelCase							:			int = 512				,		lowerCAmelCase							:			int = 50				,		lowerCAmelCase							:			float = 7.5				,		lowerCAmelCase							:			Optional[Union[str, List[str]]] = None				,		lowerCAmelCase							:			Optional[int] = 1				,		lowerCAmelCase							:			float = 0.0				,		lowerCAmelCase							:			Optional[torch.Generator] = None				,		lowerCAmelCase							:			Optional[torch.FloatTensor] = None				,		lowerCAmelCase							:			Optional[str] = "pil"				,		lowerCAmelCase							:			bool = True				,		lowerCAmelCase							:			Optional[Callable[[int, int, torch.FloatTensor], None]] = None				,		lowerCAmelCase							:			int = 1				,		**lowerCAmelCase							:			int				,		)				->				Any:

    """simple docstring"""







    return self.pipea(
        prompt=lowerCAmelCase				,		height=lowerCAmelCase				,		width=lowerCAmelCase				,		num_inference_steps=lowerCAmelCase				,		guidance_scale=lowerCAmelCase				,		negative_prompt=lowerCAmelCase				,		num_images_per_prompt=lowerCAmelCase				,		eta=lowerCAmelCase				,		generator=lowerCAmelCase				,		latents=lowerCAmelCase				,		output_type=lowerCAmelCase				,		return_dict=lowerCAmelCase				,		callback=lowerCAmelCase				,		callback_steps=lowerCAmelCase				,		**lowerCAmelCase				,		)

   @torch.no_grad()
   def      UpperCamelCase_  (					self							:			Union[str, Any]				,		lowerCAmelCase							:			Union[str, List[str]]				,		lowerCAmelCase							:			int = 512				,		lowerCAmelCase							:			int = 512				,		lowerCAmelCase							:			int = 50				,		lowerCAmelCase							:			float = 7.5				,		lowerCAmelCase							:			Optional[Union[str, List[str]]] = None				,		lowerCAmelCase							:			Optional[int] = 1				,		lowerCAmelCase							:			float = 0.0				,		lowerCAmelCase							:			Optional[torch.Generator] = None				,		lowerCAmelCase							:			Optional[torch.FloatTensor] = None				,		lowerCAmelCase							:			Optional[str] = "pil"				,		lowerCAmelCase							:			bool = True				,		lowerCAmelCase							:			Optional[Callable[[int, int, torch.FloatTensor], None]] = None				,		lowerCAmelCase							:			int = 1				,		**lowerCAmelCase							:			Dict				,		)				->				Dict:

    """simple docstring"""







    return self.pipea(
        prompt=lowerCAmelCase				,		height=lowerCAmelCase				,		width=lowerCAmelCase				,		num_inference_steps=lowerCAmelCase				,		guidance_scale=lowerCAmelCase				,		negative_prompt=lowerCAmelCase				,		num_images_per_prompt=lowerCAmelCase				,		eta=lowerCAmelCase				,		generator=lowerCAmelCase				,		latents=lowerCAmelCase				,		output_type=lowerCAmelCase				,		return_dict=lowerCAmelCase				,		callback=lowerCAmelCase				,		callback_steps=lowerCAmelCase				,		**lowerCAmelCase				,		)


   @torch.no_grad()
   def      UpperCamelCase_  (					self							:			int				,		lowerCAmelCase							:			Union[str, List[str]]				,		lowerCAmelCase							:			int = 512				,		lowerCAmelCase							:			int = 512				,		lowerCAmelCase							:			int = 50				,		lowerCAmelCase							:			float = 7.5				,		lowerCAmelCase							:			Optional[Union[str, List[str]]] = None				,		lowerCAmelCase							:			Optional[int] = 1				,		lowerCAmelCase							:			float = 0.0				,		lowerCAmelCase							:			Optional[torch.Generator] = None				,		lowerCAmelCase							:			Optional[torch.FloatTensor] = None				,		lowerCAmelCase							:			Optional[str] = "pil"				,		lowerCAmelCase							:			bool = True				,		lowerCAmelCase							:			Optional[Callable[[int, int, torch.FloatTensor], None]] = None				,		lowerCAmelCase							:			int = 1				,		**lowerCAmelCase							:			Optional[int]				,		)				->				Any:

    """simple docstring"""







    _snake_case    :  Dict					=					"""cuda""" if torch.cuda.is_available() else """cpu"""
    self.to(lowerCAmelCase)

    # Checks if the height and width are divisible by 8 or not
    if height % 8 != 0 or width % 8 != 0:
     raise ValueError(F'''`height` and `width` must be divisible by 8 but are {height} and {width}.''')

    # Get first result from Stable Diffusion Checkpoint v1.1
    _snake_case    :  Optional[Any]					=					self.textaimg_sda_a(
        prompt=lowerCAmelCase				,		height=lowerCAmelCase				,		width=lowerCAmelCase				,		num_inference_steps=lowerCAmelCase				,		guidance_scale=lowerCAmelCase				,		negative_prompt=lowerCAmelCase				,		num_images_per_prompt=lowerCAmelCase				,		eta=lowerCAmelCase				,		generator=lowerCAmelCase				,		latents=lowerCAmelCase				,		output_type=lowerCAmelCase				,		return_dict=lowerCAmelCase				,		callback=lowerCAmelCase				,		callback_steps=lowerCAmelCase				,		**lowerCAmelCase				,		)

    # Get first result from Stable Diffusion Checkpoint v1.2
    _snake_case    :  Optional[int]					=					self.textaimg_sda_a(
        prompt=lowerCAmelCase				,		height=lowerCAmelCase				,		width=lowerCAmelCase				,		num_inference_steps=lowerCAmelCase				,		guidance_scale=lowerCAmelCase				,		negative_prompt=lowerCAmelCase				,		num_images_per_prompt=lowerCAmelCase				,		eta=lowerCAmelCase				,		generator=lowerCAmelCase				,		latents=lowerCAmelCase				,		output_type=lowerCAmelCase				,		return_dict=lowerCAmelCase				,		callback=lowerCAmelCase				,		callback_steps=lowerCAmelCase				,		**lowerCAmelCase				,		)

    # Get first result from Stable Diffusion Checkpoint v1.3
    _snake_case    :  str					=					self.textaimg_sda_a(
        prompt=lowerCAmelCase				,		height=lowerCAmelCase				,		width=lowerCAmelCase				,		num_inference_steps=lowerCAmelCase				,		guidance_scale=lowerCAmelCase				,		negative_prompt=lowerCAmelCase				,		num_images_per_prompt=lowerCAmelCase				,		eta=lowerCAmelCase				,		generator=lowerCAmelCase				,		latents=lowerCAmelCase				,		output_type=lowerCAmelCase				,		return_dict=lowerCAmelCase				,		callback=lowerCAmelCase				,		callback_steps=lowerCAmelCase				,		**lowerCAmelCase				,		)

    # Get first result from Stable Diffusion Checkpoint v1.4
    _snake_case    :  List[str]					=					self.textaimg_sda_a(
        prompt=lowerCAmelCase				,		height=lowerCAmelCase				,		width=lowerCAmelCase				,		num_inference_steps=lowerCAmelCase				,		guidance_scale=lowerCAmelCase				,		negative_prompt=lowerCAmelCase				,		num_images_per_prompt=lowerCAmelCase				,		eta=lowerCAmelCase				,		generator=lowerCAmelCase				,		latents=lowerCAmelCase				,		output_type=lowerCAmelCase				,		return_dict=lowerCAmelCase				,		callback=lowerCAmelCase				,		callback_steps=lowerCAmelCase				,		**lowerCAmelCase				,		)

    # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result
    return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]])





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



   '''simple docstring'''






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

    """simple docstring"""







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

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

    """simple docstring"""







    _snake_case    :  Union[str, Any]					=					ids_tensor([self.batch_size, self.seq_length]				,		self.vocab_size)

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

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

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

    _snake_case    :  Any					=					self.get_config()

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

   def      UpperCamelCase_  (					self							:			List[Any])				->				Any:

    """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      UpperCamelCase_  (					self							:			Tuple				,		lowerCAmelCase							:			List[Any]				,		lowerCAmelCase							:			str				,		lowerCAmelCase							:			Any				,		lowerCAmelCase							:			str				,		lowerCAmelCase							:			Tuple				,		lowerCAmelCase							:			Any				,		lowerCAmelCase							:			int)				->				Optional[int]:

    """simple docstring"""







    _snake_case    :  List[str]					=					LlamaModel(config=lowerCAmelCase)
    model.to(lowerCAmelCase)
    model.eval()
    _snake_case    :  int					=					model(lowerCAmelCase				,		attention_mask=lowerCAmelCase)
    _snake_case    :  str					=					model(lowerCAmelCase)
    self.parent.assertEqual(result.last_hidden_state.shape				,		(self.batch_size, self.seq_length, self.hidden_size))

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

    """simple docstring"""







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

   def      UpperCamelCase_  (					self							:			List[Any]				,		lowerCAmelCase							:			List[str]				,		lowerCAmelCase							:			str				,		lowerCAmelCase							:			List[Any]				,		lowerCAmelCase							:			List[str]				,		lowerCAmelCase							:			Dict				,		lowerCAmelCase							:			List[Any]				,		lowerCAmelCase							:			Any				,		lowerCAmelCase							:			Union[str, Any]				,		lowerCAmelCase							:			Union[str, Any]				,		)				->				Dict:

    """simple docstring"""







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

   def      UpperCamelCase_  (					self							:			Optional[Any]				,		lowerCAmelCase							:			Tuple				,		lowerCAmelCase							:			Optional[int]				,		lowerCAmelCase							:			Optional[int]				,		lowerCAmelCase							:			Optional[int]				,		lowerCAmelCase							:			List[Any]				,		lowerCAmelCase							:			Optional[Any]				,		lowerCAmelCase							:			str				,		lowerCAmelCase							:			Optional[Any]				,		lowerCAmelCase							:			List[str]				,		)				->				Tuple:

    """simple docstring"""







    _snake_case    :  str					=					True
    _snake_case    :  Optional[Any]					=					True
    _snake_case    :  List[Any]					=					LlamaForCausalLM(config=lowerCAmelCase)
    model.to(lowerCAmelCase)
    model.eval()

    # first forward pass
    _snake_case    :  Tuple					=					model(
        lowerCAmelCase				,		attention_mask=lowerCAmelCase				,		encoder_hidden_states=lowerCAmelCase				,		encoder_attention_mask=lowerCAmelCase				,		use_cache=lowerCAmelCase				,		)
    _snake_case    :  Tuple					=					outputs.past_key_values

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

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

    _snake_case    :  Tuple					=					model(
        lowerCAmelCase				,		attention_mask=lowerCAmelCase				,		encoder_hidden_states=lowerCAmelCase				,		encoder_attention_mask=lowerCAmelCase				,		output_hidden_states=lowerCAmelCase				,		)["""hidden_states"""][0]
    _snake_case    :  Optional[Any]					=					model(
        lowerCAmelCase				,		attention_mask=lowerCAmelCase				,		encoder_hidden_states=lowerCAmelCase				,		encoder_attention_mask=lowerCAmelCase				,		past_key_values=lowerCAmelCase				,		output_hidden_states=lowerCAmelCase				,		)["""hidden_states"""][0]

    # select random slice
    _snake_case    :  str					=					ids_tensor((1,)				,		output_from_past.shape[-1]).item()
    _snake_case    :  Union[str, Any]					=					output_from_no_past[:, -3:, random_slice_idx].detach()
    _snake_case    :  Optional[int]					=					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      UpperCamelCase_  (					self							:			Union[str, Any])				->				Optional[Any]:

    """simple docstring"""







    _snake_case    :  str					=					self.prepare_config_and_inputs()
    (
        (
        _snake_case
    )	,    (
        _snake_case
    )	,    (
        _snake_case
    )	,    (
        _snake_case
    )	,    (
        _snake_case
    )	,    (
        _snake_case
    )	,    (
        _snake_case
    )	,    
    )    :  List[str]					=					config_and_inputs
    _snake_case    :  Optional[int]					=					{"""input_ids""": input_ids, """attention_mask""": input_mask}
    return config, inputs_dict







@require_torch
class 		snake_case						(	SCREAMING_SNAKE_CASE_					,SCREAMING_SNAKE_CASE_					,SCREAMING_SNAKE_CASE_					,unittest.TestCase  ):



   '''simple docstring'''






   snake_case_					: int          =		(LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else ()
   snake_case_					: Optional[int]          =		(LlamaForCausalLM,) if is_torch_available() else ()
   snake_case_					: int          =		(
       {
           """feature-extraction""": LlamaModel,
           """text-classification""": LlamaForSequenceClassification,
           """text-generation""": LlamaForCausalLM,
           """zero-shot""": LlamaForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   snake_case_					: Dict          =		False
   snake_case_					: int          =		False

   def      UpperCamelCase_  (					self							:			Tuple)				->				int:

    """simple docstring"""







    _snake_case    :  int					=					LlamaModelTester(self)
    _snake_case    :  Union[str, Any]					=					ConfigTester(self				,		config_class=lowerCAmelCase				,		hidden_size=37)

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

    """simple docstring"""







    self.config_tester.run_common_tests()

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

    """simple docstring"""







    _snake_case    :  Dict					=					self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*lowerCAmelCase)

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

    """simple docstring"""







    _snake_case    :  Optional[int]					=					self.model_tester.prepare_config_and_inputs()
    for type in ["absolute", "relative_key", "relative_key_query"]:
     _snake_case    :  List[Any]					=					type
     self.model_tester.create_and_check_model(*lowerCAmelCase)

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

    """simple docstring"""







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

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

    """simple docstring"""







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

   def      UpperCamelCase_  (					self							:			int)				->				str:

    """simple docstring"""







    _snake_case	,    _snake_case    :  List[str]					=					self.model_tester.prepare_config_and_inputs_for_common()
    _snake_case    :  List[Any]					=					3
    _snake_case    :  Any					=					"""multi_label_classification"""
    _snake_case    :  str					=					input_dict["""input_ids"""]
    _snake_case    :  List[str]					=					input_ids.ne(1).to(lowerCAmelCase)
    _snake_case    :  List[Any]					=					ids_tensor(
        [self.model_tester.batch_size, config.num_labels]				,		self.model_tester.type_sequence_label_size).to(torch.float)
    _snake_case    :  Tuple					=					LlamaForSequenceClassification(lowerCAmelCase)
    model.to(lowerCAmelCase)
    model.eval()
    _snake_case    :  int					=					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      UpperCamelCase_  (					self							:			Any)				->				int:

    """simple docstring"""







    pass


   @parameterized.expand([("""linear""",), ("""dynamic""",)])
   def      UpperCamelCase_  (					self							:			int				,		lowerCAmelCase							:			Optional[Any])				->				List[Any]:

    """simple docstring"""







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

    set_seed(42)  # Fixed seed at init time so the two models get the same random weights
    _snake_case    :  Optional[int]					=					{"""type""": scaling_type, """factor""": 10.0}
    _snake_case    :  Dict					=					LlamaModel(lowerCAmelCase)
    scaled_model.to(lowerCAmelCase)
    scaled_model.eval()
    _snake_case    :  str					=					scaled_model(lowerCAmelCase).last_hidden_state
    _snake_case    :  List[Any]					=					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 		snake_case						(	unittest.TestCase  ):



   '''simple docstring'''






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

    """simple docstring"""







    _snake_case    :  int					=					[1, 306, 4658, 278, 6593, 310, 2834, 338]
    _snake_case    :  Any					=					LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-7b-hf"""				,		device_map="""auto""")
    _snake_case    :  Tuple					=					model(torch.tensor([input_ids]))
    # Expected mean on dim = -1
    _snake_case    :  Union[str, Any]					=					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
    _snake_case    :  Optional[Any]					=					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      UpperCamelCase_  (					self							:			List[str])				->				Dict:

    """simple docstring"""







    _snake_case    :  str					=					[1, 306, 4658, 278, 6593, 310, 2834, 338]
    _snake_case    :  int					=					LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-hf"""				,		device_map="""auto""")
    _snake_case    :  List[Any]					=					model(torch.tensor(lowerCAmelCase))
    # Expected mean on dim = -1
    _snake_case    :  Any					=					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
    _snake_case    :  List[str]					=					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      UpperCamelCase_  (					self							:			List[str])				->				List[str]:

    """simple docstring"""







    _snake_case    :  Any					=					[1, 306, 4658, 278, 6593, 310, 2834, 338]
    _snake_case    :  Union[str, Any]					=					LlamaForCausalLM.from_pretrained("""meta-llama/Llama-2-13b-chat-hf"""				,		device_map="""auto""")
    _snake_case    :  int					=					model(torch.tensor(lowerCAmelCase))
    # Expected mean on dim = -1
    _snake_case    :  List[Any]					=					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
    _snake_case    :  Any					=					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      UpperCamelCase_  (					self							:			Union[str, Any])				->				Union[str, Any]:

    """simple docstring"""







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

    _snake_case    :  Any					=					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
    _snake_case    :  Dict					=					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      UpperCamelCase_  (					self							:			Tuple)				->				Any:

    """simple docstring"""







    _snake_case    :  List[Any]					=					"""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"""
    _snake_case    :  Optional[Any]					=					"""Simply put, the theory of relativity states that """
    _snake_case    :  Union[str, Any]					=					LlamaTokenizer.from_pretrained("""meta-llama/Llama-2-13b-chat-hf""")
    _snake_case    :  Dict					=					tokenizer.encode(lowerCAmelCase				,		return_tensors="""pt""")
    _snake_case    :  Optional[Any]					=					LlamaForCausalLM.from_pretrained(
        """meta-llama/Llama-2-13b-chat-hf"""				,		device_map="""sequential"""				,		use_safetensors=lowerCAmelCase)

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