



"""simple docstring"""







import unittest

from transformers import AutoTokenizer, FalconConfig, is_torch_available
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 (
							    FalconForCausalLM,
							    FalconForQuestionAnswering,
							    FalconForSequenceClassification,
							    FalconForTokenClassification,
							    FalconModel,
							)
class        __A       :







		'''simple docstring'''





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






				"""simple docstring"""



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







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






				"""simple docstring"""



				lowercase__   :    Optional[Any]				=			ids_tensor([self.batch_size, self.seq_length]			,self.vocab_size						)

				lowercase__   :    int				=			None
				if self.use_input_mask:
						lowercase__   :    str				=			random_attention_mask([self.batch_size, self.seq_length]						)

				lowercase__   :    Dict				=			None

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

				lowercase__   :    Optional[int]				=			self.get_config()

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







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






				"""simple docstring"""



				return FalconConfig(
				    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=_snake_case			,initializer_range=self.initializer_range			,pad_token_id=1			,new_decoder_architecture=_snake_case			,)







		def 					UpperCAmelCase    (	self						:  Dict			,_snake_case						:  Dict			,_snake_case						:  List[str]			,_snake_case						:  Optional[Any]			,_snake_case						:  List[str]			,_snake_case						:  Any			,_snake_case						:  str			,_snake_case						:  Optional[Any]						)					->		Union[str, Any]:






				"""simple docstring"""



				lowercase__   :    Union[str, Any]				=			FalconModel(config=_snake_case						)
				model.to(_snake_case						)
				model.eval()
				lowercase__   :    str				=			model(_snake_case			,attention_mask=_snake_case						)
				lowercase__   :    Union[str, Any]				=			model(_snake_case						)
				self.parent.assertEqual(result.last_hidden_state.shape			,(self.batch_size, self.seq_length, self.hidden_size)						)







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






				"""simple docstring"""



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







		def 					UpperCAmelCase    (	self						:  Dict			,_snake_case						:  Tuple			,_snake_case						:  str			,_snake_case						:  List[Any]			,_snake_case						:  Optional[Any]			,_snake_case						:  Union[str, Any]			,_snake_case						:  str			,_snake_case						:  Tuple			,_snake_case						:  Union[str, Any]			,_snake_case						:  str			,)					->		List[str]:






				"""simple docstring"""



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







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






				"""simple docstring"""



				lowercase__   :    Optional[Any]				=			True
				lowercase__   :    str				=			True
				lowercase__   :    str				=			FalconForCausalLM(config=_snake_case						)
				model.to(_snake_case						)
				model.eval()

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

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

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

				lowercase__   :    List[str]				=			model(
				    _snake_case			,attention_mask=_snake_case			,encoder_hidden_states=_snake_case			,encoder_attention_mask=_snake_case			,output_hidden_states=_snake_case			,)['''hidden_states'''][0]
				lowercase__   :    List[str]				=			model(
				    _snake_case			,attention_mask=_snake_case			,encoder_hidden_states=_snake_case			,encoder_attention_mask=_snake_case			,past_key_values=_snake_case			,output_hidden_states=_snake_case			,)['''hidden_states'''][0]

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







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






				"""simple docstring"""



				lowercase__   :    str				=			self.prepare_config_and_inputs()
				(
				    (
				    lowercase__
				)		,			(
				    lowercase__
				)		,			(
				    lowercase__
				)		,			(
				    lowercase__
				)		,			(
				    lowercase__
				)		,			(
				    lowercase__
				)		,			(
				    lowercase__
				)		,			
				)   :    Optional[Any]				=			config_and_inputs
				lowercase__   :    Union[str, Any]				=			{'''input_ids''': input_ids, '''attention_mask''': input_mask}
				return config, inputs_dict





@require_torch
class        __A       (	A_     ,A_     ,A_     ,unittest.TestCase    ):







		'''simple docstring'''





		lowerCAmelCase			:					Optional[int]   	=				(
		    (
		        FalconModel,
		        FalconForCausalLM,
		        FalconForSequenceClassification,
		        FalconForTokenClassification,
		        FalconForQuestionAnswering,
		    )
		    if is_torch_available()
		    else ()
		)
		lowerCAmelCase			:					List[Any]   	=				(FalconForCausalLM,) if is_torch_available() else ()
		lowerCAmelCase			:					int   	=				(
		    {
		        "feature-extraction": FalconModel,
		        "text-classification": FalconForSequenceClassification,
		        "text-generation": FalconForCausalLM,
		        "question-answering": FalconForQuestionAnswering,
		        "token-classification": FalconForTokenClassification,
		        "zero-shot": FalconForSequenceClassification,
		    }
		    if is_torch_available()
		    else {}
		)
		lowerCAmelCase			:					Dict   	=				False
		lowerCAmelCase			:					List[str]   	=				False







		def 					UpperCAmelCase    (	self						:  Optional[Any]						)					->		Dict:






				"""simple docstring"""



				lowercase__   :    Tuple				=			FalconModelTester(self						)
				lowercase__   :    Any				=			ConfigTester(self			,config_class=_snake_case			,hidden_size=37						)







		def 					UpperCAmelCase    (	self						:  List[str]						)					->		Dict:






				"""simple docstring"""



				self.config_tester.run_common_tests()







		def 					UpperCAmelCase    (	self						:  Any						)					->		int:






				"""simple docstring"""



				lowercase__   :    int				=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*_snake_case						)







		def 					UpperCAmelCase    (	self						:  Optional[int]						)					->		int:






				"""simple docstring"""



				lowercase__		,			*lowercase__   :    Dict				=			self.model_tester.prepare_config_and_inputs()
				for alibi in [True, False]:
						lowercase__   :    Dict				=			alibi
						self.model_tester.create_and_check_model(_snake_case			,*_snake_case						)







		def 					UpperCAmelCase    (	self						:  Optional[Any]						)					->		Dict:






				"""simple docstring"""



				lowercase__		,			lowercase__   :    Union[str, Any]				=			self.model_tester.prepare_config_and_inputs_for_common()
				lowercase__   :    str				=			3
				lowercase__   :    Optional[int]				=			input_dict['''input_ids''']
				lowercase__   :    Optional[Any]				=			input_ids.ne(1						).to(_snake_case						)
				lowercase__   :    List[str]				=			ids_tensor([self.model_tester.batch_size]			,self.model_tester.type_sequence_label_size						)
				lowercase__   :    int				=			FalconForSequenceClassification(_snake_case						)
				model.to(_snake_case						)
				model.eval()
				lowercase__   :    List[Any]				=			model(_snake_case			,attention_mask=_snake_case			,labels=_snake_case						)
				self.assertEqual(result.logits.shape			,(self.model_tester.batch_size, self.model_tester.num_labels)						)







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






				"""simple docstring"""



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







		def 					UpperCAmelCase    (	self						:  str						)					->		str:






				"""simple docstring"""



				lowercase__		,			lowercase__   :    Tuple				=			self.model_tester.prepare_config_and_inputs_for_common()
				lowercase__   :    Union[str, Any]				=			input_dict['''input_ids''']
				lowercase__   :    Union[str, Any]				=			FalconForCausalLM(_snake_case						)
				model.to(_snake_case						)
				model.eval()
				lowercase__   :    Optional[Any]				=			model(_snake_case			,use_cache=_snake_case						)
				lowercase__   :    int				=			input_ids.shape[0]
				lowercase__   :    List[str]				=			model._convert_to_rw_cache(result.past_key_values						)
				lowercase__   :    List[str]				=			model._convert_cache_to_standard_format(_snake_case			,_snake_case						)
				for layer in range(len(_snake_case						)						):
						for tensor_idx in range(2						):
								self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3						)
								self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4						)
								self.assertTrue(
								    torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx]						)						)







		def 					UpperCAmelCase    (	self						:  List[str]						)					->		Dict:






				"""simple docstring"""



				lowercase__		,			lowercase__   :    Optional[Any]				=			self.model_tester.prepare_config_and_inputs_for_common()
				lowercase__   :    Optional[int]				=			3
				lowercase__   :    Dict				=			'''multi_label_classification'''
				lowercase__   :    Optional[int]				=			input_dict['''input_ids''']
				lowercase__   :    Dict				=			input_ids.ne(1						).to(_snake_case						)
				lowercase__   :    Any				=			ids_tensor(
				    [self.model_tester.batch_size, config.num_labels]			,self.model_tester.type_sequence_label_size						).to(torch.float						)
				lowercase__   :    Tuple				=			FalconForSequenceClassification(_snake_case						)
				model.to(_snake_case						)
				model.eval()
				lowercase__   :    Tuple				=			model(_snake_case			,attention_mask=_snake_case			,labels=_snake_case						)
				self.assertEqual(result.logits.shape			,(self.model_tester.batch_size, self.model_tester.num_labels)						)







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






				"""simple docstring"""



				for model_class in self.all_generative_model_classes:
						lowercase__		,			lowercase__   :    List[str]				=			self.model_tester.prepare_config_and_inputs_for_common()

						# If it doesn't support cache, pass the test
						if not hasattr(_snake_case			,'''use_cache'''						):
								return

						lowercase__   :    Optional[Any]				=			model_class(_snake_case						).to(_snake_case						)
						if "use_cache" not in inputs:
								lowercase__   :    Optional[int]				=			True
						lowercase__   :    List[str]				=			model(**_snake_case						)

						# If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format)
						if "past_key_values" not in outputs:
								return

						lowercase__   :    Tuple				=			(
						    getattr(_snake_case			,'''decoder_layers'''			,_snake_case						)
						    or getattr(_snake_case			,'''num_decoder_layers'''			,_snake_case						)
						    or config.num_hidden_layers
						)
						lowercase__   :    Optional[int]				=			getattr(_snake_case			,'''num_kv_heads'''			,config.num_attention_heads						)
						lowercase__   :    Optional[int]				=			getattr(_snake_case			,'''d_model'''			,config.hidden_size						)
						lowercase__   :    Union[str, Any]				=			embed_dim // num_attention_heads

						lowercase__   :    Union[str, Any]				=			outputs['''past_key_values''']
						self.assertEqual(len(_snake_case						)			,_snake_case						)

						lowercase__		,			lowercase__   :    Union[str, Any]				=			inputs['''input_ids'''].shape
						for i in range(_snake_case						):
								if config.new_decoder_architecture:
										lowercase__   :    Union[str, Any]				=			config.num_attention_heads
								elif config.multi_query:
										lowercase__   :    Union[str, Any]				=			1
								self.assertEqual(len(past_kv[0]						)			,2						)  # K V for the decoder = 2
								self.assertEqual(
								    past_kv[i][0].shape			,(batch_size, num_attention_heads, seq_length, per_head_embed_dim)						)
								self.assertEqual(
								    past_kv[i][1].shape			,(batch_size, num_attention_heads, seq_length, per_head_embed_dim)						)





@require_torch
class        __A       (	unittest.TestCase    ):







		'''simple docstring'''





		@slow
		def 					UpperCAmelCase    (	self						:  Any						)					->		Any:






				"""simple docstring"""



				lowercase__   :    Dict				=			AutoTokenizer.from_pretrained('''Rocketknight1/falcon-rw-1b'''						)
				lowercase__   :    int				=			FalconForCausalLM.from_pretrained('''Rocketknight1/falcon-rw-1b'''						)
				model.eval()
				model.to(_snake_case						)
				lowercase__   :    int				=			tokenizer('''My favorite food is'''			,return_tensors='''pt'''						).to(_snake_case						)

				lowercase__   :    List[Any]				=			(
				    '''My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday.'''
				)

				lowercase__   :    Dict				=			model.generate(**_snake_case			,do_sample=_snake_case			,max_new_tokens=19						)
				lowercase__   :    Optional[int]				=			tokenizer.batch_decode(_snake_case						)[0]

				self.assertEqual(_snake_case			,_snake_case						)







		@slow
		def 					UpperCAmelCase    (	self						:  Union[str, Any]						)					->		Optional[Any]:






				"""simple docstring"""



				for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
						lowercase__   :    List[Any]				=			AutoTokenizer.from_pretrained(_snake_case						)
						lowercase__   :    List[Any]				=			FalconForCausalLM.from_pretrained(_snake_case						)
						model.eval()
						model.to(_snake_case						)
						lowercase__   :    Optional[int]				=			tokenizer('''My favorite food is'''			,return_tensors='''pt'''						).to(_snake_case						)

						# We just test that these run without errors - the models are randomly initialized
						# and so the actual text outputs will be garbage
						model.generate(**_snake_case			,do_sample=_snake_case			,max_new_tokens=4						)
						model.generate(**_snake_case			,do_sample=_snake_case			,max_new_tokens=4						)
						model.generate(**_snake_case			,num_beams=2			,max_new_tokens=4						)







		@slow
		def 					UpperCAmelCase    (	self						:  int						)					->		Any:






				"""simple docstring"""



				with torch.no_grad():
						for repo in [
						    "Rocketknight1/falcon-rw-1b",
						    "Rocketknight1/tiny-random-falcon-7b",
						    "Rocketknight1/tiny-random-falcon-40b",
						]:
								lowercase__   :    Any				=			AutoTokenizer.from_pretrained(_snake_case						)
								lowercase__   :    Optional[Any]				=			FalconForCausalLM.from_pretrained(_snake_case						)
								model.eval()
								model.to(device=_snake_case						)
								lowercase__   :    Any				=			tokenizer('''My favorite food is'''			,return_tensors='''pt'''						).to(_snake_case						)

								# Test results are the same with and without cache
								lowercase__   :    Dict				=			model.generate(**_snake_case			,do_sample=_snake_case			,max_new_tokens=20			,use_cache=_snake_case						)
								lowercase__   :    Tuple				=			model.generate(**_snake_case			,do_sample=_snake_case			,max_new_tokens=20			,use_cache=_snake_case						)
								self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0						)







'''simple docstring'''

from typing import List, Optional, Union

import torch

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)


lowercase_					= logging.get_logger(__name__)  # pylint: disable=invalid-name

lowercase_					= """
    Examples:
        ```py
        >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline
        >>> import torch

        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-prior\")
        >>> pipe_prior.to(\"cuda\")
        >>> prompt = \"red cat, 4k photo\"
        >>> out = pipe_prior(prompt)
        >>> image_emb = out.image_embeds
        >>> zero_image_emb = out.negative_image_embeds
        >>> pipe = KandinskyV22Pipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-decoder\")
        >>> pipe.to(\"cuda\")
        >>> image = pipe(
        ...     image_embeds=image_emb,
        ...     negative_image_embeds=zero_image_emb,
        ...     height=768,
        ...     width=768,
        ...     num_inference_steps=50,
        ... ).images
        >>> image[0].save(\"cat.png\")
        ```
"""





def lowerCamelCase						(     __lowerCamelCase :    str					,       __lowerCamelCase :    Optional[Any]					,       __lowerCamelCase :    List[Any]=8    )						->Tuple:
    _SCREAMING_SNAKE_CASE									=			height // scale_factor**2
    if height % scale_factor**2 != 0:
        new_height += 1
    _SCREAMING_SNAKE_CASE									=			width // scale_factor**2
    if width % scale_factor**2 != 0:
        new_width += 1
    return new_height * scale_factor, new_width * scale_factor






class 					a_     (				snake_case_       ):

    '''simple docstring'''


    def __init__(		self ,		A ,		A ,		A ,		)		->   Union[str, Any]:
        super().__init__()

        self.register_modules(
            unet=A ,		scheduler=A ,		movq=A ,		)
        _SCREAMING_SNAKE_CASE									=			2 ** (len(self.movq.config.block_out_channels       ) - 1)


    def 			snake_case_(		self ,		A ,		A ,		A ,		A ,		A ,		A       )		->   Union[str, Any]:
        if latents is None:
            _SCREAMING_SNAKE_CASE									=			randn_tensor(A ,		generator=A ,		device=A ,		dtype=A       )
        else:
            if latents.shape != shape:
                raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}'       )
            _SCREAMING_SNAKE_CASE									=			latents.to(A       )

        _SCREAMING_SNAKE_CASE									=			latents * scheduler.init_noise_sigma
        return latents


    def 			snake_case_(		self ,		A=0       )		->   Dict:
        if is_accelerate_available():
            from accelerate import cpu_offload
        else:
            raise ImportError("""Please install accelerate via `pip install accelerate`"""       )

        _SCREAMING_SNAKE_CASE									=			torch.device(f'cuda:{gpu_id}'       )

        _SCREAMING_SNAKE_CASE									=			[
            self.unet,
            self.movq,
        ]
        for cpu_offloaded_model in models:
            if cpu_offloaded_model is not None:
                cpu_offload(A ,		A       )


    def 			snake_case_(		self ,		A=0       )		->   str:
        if is_accelerate_available() and is_accelerate_version(""">=""" ,		"""0.17.0.dev0"""       ):
            from accelerate import cpu_offload_with_hook
        else:
            raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher."""       )

        _SCREAMING_SNAKE_CASE									=			torch.device(f'cuda:{gpu_id}'       )

        if self.device.type != "cpu":
            self.to("""cpu""" ,		silence_dtype_warnings=A       )
            torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

        _SCREAMING_SNAKE_CASE									=			None
        for cpu_offloaded_model in [self.unet, self.movq]:
            _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			cpu_offload_with_hook(A ,		A ,		prev_module_hook=A       )

        # We'll offload the last model manually.
        _SCREAMING_SNAKE_CASE									=			hook


    @property
    # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
    def 			snake_case_(		self       )		->   Tuple:
        if not hasattr(self.unet ,		"""_hf_hook"""       ):
            return self.device
        for module in self.unet.modules():
            if (
                hasattr(A ,		"""_hf_hook"""       )
                and hasattr(module._hf_hook ,		"""execution_device"""       )
                and module._hf_hook.execution_device is not None
            ):
                return torch.device(module._hf_hook.execution_device       )
        return self.device





    @torch.no_grad()
    @replace_example_docstring(A       )
    def __call__(		self ,		A ,		A ,		A = 512 ,		A = 512 ,		A = 100 ,		A = 4.0 ,		A = 1 ,		A = None ,		A = None ,		A = "pil" ,		A = True ,		)		->   List[str]:
        _SCREAMING_SNAKE_CASE									=			self._execution_device

        _SCREAMING_SNAKE_CASE									=			guidance_scale > 1.0

        if isinstance(A ,		A       ):
            _SCREAMING_SNAKE_CASE									=			torch.cat(A ,		dim=0       )
        _SCREAMING_SNAKE_CASE									=			image_embeds.shape[0] * num_images_per_prompt
        if isinstance(A ,		A       ):
            _SCREAMING_SNAKE_CASE									=			torch.cat(A ,		dim=0       )

        if do_classifier_free_guidance:
            _SCREAMING_SNAKE_CASE									=			image_embeds.repeat_interleave(A ,		dim=0       )
            _SCREAMING_SNAKE_CASE									=			negative_image_embeds.repeat_interleave(A ,		dim=0       )

        _SCREAMING_SNAKE_CASE									=			torch.cat([negative_image_embeds, image_embeds] ,		dim=0       ).to(dtype=self.unet.dtype ,		device=A       )

        self.scheduler.set_timesteps(A ,		device=A       )
        _SCREAMING_SNAKE_CASE									=			self.scheduler.timesteps

        _SCREAMING_SNAKE_CASE									=			self.unet.config.in_channels

        _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			downscale_height_and_width(A ,		A ,		self.movq_scale_factor       )

        # create initial latent
        _SCREAMING_SNAKE_CASE									=			self.prepare_latents(
            (batch_size, num_channels_latents, height, width) ,		image_embeds.dtype ,		A ,		A ,		A ,		self.scheduler ,		)

        for i, t in enumerate(self.progress_bar(A       )       ):
            # expand the latents if we are doing classifier free guidance
            _SCREAMING_SNAKE_CASE									=			torch.cat([latents] * 2       ) if do_classifier_free_guidance else latents

            _SCREAMING_SNAKE_CASE									=			{"""image_embeds""": image_embeds}
            _SCREAMING_SNAKE_CASE									=			self.unet(
                sample=A ,		timestep=A ,		encoder_hidden_states=A ,		added_cond_kwargs=A ,		return_dict=A ,		)[0]

            if do_classifier_free_guidance:
                _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			noise_pred.split(latents.shape[1] ,		dim=1       )
                _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			noise_pred.chunk(2       )
                _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			variance_pred.chunk(2       )
                _SCREAMING_SNAKE_CASE									=			noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
                _SCREAMING_SNAKE_CASE									=			torch.cat([noise_pred, variance_pred_text] ,		dim=1       )

            if not (
                hasattr(self.scheduler.config ,		"""variance_type"""       )
                and self.scheduler.config.variance_type in ["learned", "learned_range"]
            ):
                _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			noise_pred.split(latents.shape[1] ,		dim=1       )

            # compute the previous noisy sample x_t -> x_t-1
            _SCREAMING_SNAKE_CASE									=			self.scheduler.step(
                A ,		A ,		A ,		generator=A ,		)[0]
        # post-processing
        _SCREAMING_SNAKE_CASE									=			self.movq.decode(A ,		force_not_quantize=A       )["""sample"""]

        if output_type not in ["pt", "np", "pil"]:
            raise ValueError(f'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}'       )

        if output_type in ["np", "pil"]:
            _SCREAMING_SNAKE_CASE									=			image * 0.5 + 0.5
            _SCREAMING_SNAKE_CASE									=			image.clamp(0 ,		1       )
            _SCREAMING_SNAKE_CASE									=			image.cpu().permute(0 ,		2 ,		3 ,		1       ).float().numpy()

        if output_type == "pil":
            _SCREAMING_SNAKE_CASE									=			self.numpy_to_pil(A       )

        if not return_dict:
            return (image,)

        return ImagePipelineOutput(images=A       )



