






import math
import unittest

from transformers import BioGptConfig, 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 (
	    BioGptForCausalLM,
	    BioGptForSequenceClassification,
	    BioGptForTokenClassification,
	    BioGptModel,
	    BioGptTokenizer,
	)
	from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST




class  UpperCamelCase_      :



	'''simple docstring'''




	def __init__(       self       ,			a       ,			a=13       ,			a=7       ,			a=True       ,			a=True       ,			a=False       ,			a=True       ,			a=99       ,			a=32       ,			a=5       ,			a=4       ,			a=37       ,			a="gelu"       ,			a=0.1       ,			a=0.1       ,			a=5_12       ,			a=16       ,			a=2       ,			a=0.02       ,			a=3       ,			a=4       ,			a=None       ,			)       ->    str:
								snake_case_				=							parent
								snake_case_				=							batch_size
								snake_case_				=							seq_length
								snake_case_				=							is_training
								snake_case_				=							use_input_mask
								snake_case_				=							use_token_type_ids
								snake_case_				=							use_labels
								snake_case_				=							vocab_size
								snake_case_				=							hidden_size
								snake_case_				=							num_hidden_layers
								snake_case_				=							num_attention_heads
								snake_case_				=							intermediate_size
								snake_case_				=							hidden_act
								snake_case_				=							hidden_dropout_prob
								snake_case_				=							attention_probs_dropout_prob
								snake_case_				=							max_position_embeddings
								snake_case_				=							type_vocab_size
								snake_case_				=							type_sequence_label_size
								snake_case_				=							initializer_range
								snake_case_				=							num_labels
								snake_case_				=							num_choices
								snake_case_				=							scope




	def 							_UpperCamelCase			(       self					)       ->    Optional[Any]:
								snake_case_				=							ids_tensor([self.batch_size, self.seq_length]       ,			self.vocab_size					)

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

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

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

								snake_case_				=							self.get_config()

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




	def 							_UpperCamelCase			(       self					)       ->    List[Any]:
								return BioGptConfig(
								    vocab_size=self.vocab_size       ,			hidden_size=self.hidden_size       ,			num_hidden_layers=self.num_hidden_layers       ,			num_attention_heads=self.num_attention_heads       ,			intermediate_size=self.intermediate_size       ,			hidden_act=self.hidden_act       ,			hidden_dropout_prob=self.hidden_dropout_prob       ,			attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,			max_position_embeddings=self.max_position_embeddings       ,			type_vocab_size=self.type_vocab_size       ,			is_decoder=a       ,			initializer_range=self.initializer_range       ,			)




	def 							_UpperCamelCase			(       self       ,			a       ,			a       ,			a       ,			a       ,			a       ,			a       ,			a					)       ->    Optional[Any]:
								snake_case_				=							BioGptModel(config=a					)
								model.to(a					)
								model.eval()
								snake_case_				=							model(a       ,			attention_mask=a					)
								snake_case_				=							model(a					)
								self.parent.assertEqual(result.last_hidden_state.shape       ,			(self.batch_size, self.seq_length, self.hidden_size)					)




	def 							_UpperCamelCase			(       self       ,			a       ,			a       ,			a       ,			a       ,			a       ,			a       ,			a       ,			a       ,			a       ,			)       ->    Union[str, Any]:
								snake_case_				=							BioGptForCausalLM(config=a					)
								model.to(a					)
								model.eval()
								snake_case_				=							model(a       ,			attention_mask=a       ,			token_type_ids=a       ,			labels=a					)
								self.parent.assertEqual(result.logits.shape       ,			(self.batch_size, self.seq_length, self.vocab_size)					)




	def 							_UpperCamelCase			(       self       ,			a       ,			a       ,			a       ,			a       ,			a       ,			*a					)       ->    Dict:
								snake_case_				=							BioGptModel(config=a					)
								model.to(a					)
								model.eval()

								# create attention mask
								snake_case_				=							torch.ones(input_ids.shape       ,			dtype=torch.long       ,			device=a					)
								snake_case_				=							self.seq_length // 2
								snake_case_				=							0

								# first forward pass
								snake_case_			,		snake_case_				=							model(a       ,			attention_mask=a					).to_tuple()

								# create hypothetical next token and extent to next_input_ids
								snake_case_				=							ids_tensor((self.batch_size, 1)       ,			config.vocab_size					)

								# change a random masked slice from input_ids
								snake_case_				=							ids_tensor((1,)       ,			a					).item() + 1
								snake_case_				=							ids_tensor((self.batch_size, 1)       ,			config.vocab_size					).squeeze(-1					)
								snake_case_				=							random_other_next_tokens

								# append to next input_ids and attn_mask
								snake_case_				=							torch.cat([input_ids, next_tokens]       ,			dim=-1					)
								snake_case_				=							torch.cat(
								    [attn_mask, torch.ones((attn_mask.shape[0], 1)       ,			dtype=torch.long       ,			device=a					)]       ,			dim=1       ,			)

								# get two different outputs
								snake_case_				=							model(a       ,			attention_mask=a					)['last_hidden_state']
								snake_case_				=							model(a       ,			past_key_values=a       ,			attention_mask=a					)['last_hidden_state']

								# select random slice
								snake_case_				=							ids_tensor((1,)       ,			output_from_past.shape[-1]					).item()
								snake_case_				=							output_from_no_past[:, -1, random_slice_idx].detach()
								snake_case_				=							output_from_past[:, 0, random_slice_idx].detach()

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




	def 							_UpperCamelCase			(       self       ,			a       ,			a       ,			a       ,			a       ,			a       ,			*a					)       ->    Optional[int]:
								snake_case_				=							BioGptModel(config=a					).to(a					).eval()

								snake_case_				=							torch.ones(input_ids.shape       ,			dtype=torch.long       ,			device=a					)

								# first forward pass
								snake_case_				=							model(a       ,			attention_mask=a       ,			use_cache=a					)

								snake_case_			,		snake_case_				=							outputs.to_tuple()

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

								# append to next input_ids and
								snake_case_				=							torch.cat([input_ids, next_tokens]       ,			dim=-1					)
								snake_case_				=							torch.cat([attention_mask, next_attn_mask]       ,			dim=-1					)

								snake_case_				=							model(a       ,			attention_mask=a					)['last_hidden_state']
								snake_case_				=							model(a       ,			attention_mask=a       ,			past_key_values=a					)[
								    'last_hidden_state'
								]

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

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

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




	def 							_UpperCamelCase			(       self       ,			a       ,			a       ,			a       ,			a       ,			a       ,			*a       ,			a=False					)       ->    Optional[int]:
								snake_case_				=							BioGptForCausalLM(a					)
								model.to(a					)
								if gradient_checkpointing:
															model.gradient_checkpointing_enable()

								snake_case_				=							model(a       ,			labels=a					)
								self.parent.assertEqual(result.loss.shape       ,			()					)
								self.parent.assertEqual(result.logits.shape       ,			(self.batch_size, self.seq_length, self.vocab_size)					)
								result.loss.backward()




	def 							_UpperCamelCase			(       self       ,			a       ,			*a					)       ->    str:
								snake_case_				=							BioGptModel(a					)
								snake_case_				=							model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers					)
								for key in model.state_dict().keys():
															if "c_proj" in key and "weight" in key:
																						self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key]					) - model_std					)       ,			0.001					)
																						self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key]					) - 0.0					)       ,			0.01					)




	def 							_UpperCamelCase			(       self       ,			a       ,			a       ,			a       ,			a       ,			a       ,			*a					)       ->    Any:
								snake_case_				=							self.num_labels
								snake_case_				=							BioGptForTokenClassification(a					)
								model.to(a					)
								model.eval()
								snake_case_				=							model(a       ,			attention_mask=a       ,			token_type_ids=a					)
								self.parent.assertEqual(result.logits.shape       ,			(self.batch_size, self.seq_length, self.num_labels)					)






	def 							_UpperCamelCase			(       self					)       ->    str:
								snake_case_				=							self.prepare_config_and_inputs()
								(
								    (
								    snake_case_
								)			,		(
								    snake_case_
								)			,		(
								    snake_case_
								)			,		(
								    snake_case_
								)			,		(
								    snake_case_
								)			,		(
								    snake_case_
								)			,		(
								    snake_case_
								)			,		
								)				=							config_and_inputs
								snake_case_				=							{'input_ids': input_ids, 'attention_mask': input_mask}
								return config, inputs_dict






@require_torch
class  UpperCamelCase_      (			snake_case_       ,					snake_case_       ,					snake_case_       ,					unittest.TestCase				):



	'''simple docstring'''




	lowerCAmelCase													= (
	    (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification)
	    if is_torch_available()
	    else ()
	)
	lowerCAmelCase													= (BioGptForCausalLM,) if is_torch_available() else ()
	lowerCAmelCase													= (
	    {
	        '''feature-extraction''': BioGptModel,
	        '''text-classification''': BioGptForSequenceClassification,
	        '''text-generation''': BioGptForCausalLM,
	        '''token-classification''': BioGptForTokenClassification,
	        '''zero-shot''': BioGptForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	lowerCAmelCase													= False




	def 							_UpperCamelCase			(       self					)       ->    int:
								snake_case_				=							BioGptModelTester(self					)
								snake_case_				=							ConfigTester(self       ,			config_class=a       ,			hidden_size=37					)




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




	def 							_UpperCamelCase			(       self					)       ->    Optional[int]:
								snake_case_				=							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*a					)




	def 							_UpperCamelCase			(       self					)       ->    Optional[Any]:
								snake_case_				=							self.model_tester.prepare_config_and_inputs()
								for type in ["absolute", "relative_key", "relative_key_query"]:
															snake_case_				=							type
															self.model_tester.create_and_check_model(*a					)




	def 							_UpperCamelCase			(       self					)       ->    str:
								snake_case_				=							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_biogpt_model_attention_mask_past(*a					)




	def 							_UpperCamelCase			(       self					)       ->    Optional[int]:
								snake_case_				=							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_forward_and_backwards(*a       ,			gradient_checkpointing=a					)




	def 							_UpperCamelCase			(       self					)       ->    Optional[Any]:
								snake_case_				=							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_biogpt_model_past_large_inputs(*a					)




	def 							_UpperCamelCase			(       self					)       ->    int:
								snake_case_				=							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_biogpt_weight_initialization(*a					)




	def 							_UpperCamelCase			(       self					)       ->    Optional[int]:
								snake_case_				=							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_biogpt_for_token_classification(*a					)




	@slow
	def 							_UpperCamelCase			(       self					)       ->    str:
								snake_case_				=							BioGptForCausalLM.from_pretrained('microsoft/biogpt'					)
								model.to(a					)
								snake_case_				=							BioGptTokenizer.from_pretrained('microsoft/biogpt'					)

								snake_case_				=							'left'

								# Define PAD Token = EOS Token = 50256
								snake_case_				=							tokenizer.eos_token
								snake_case_				=							model.config.eos_token_id

								# use different length sentences to test batching
								snake_case_				=							[
								    'Hello, my dog is a little',
								    'Today, I',
								]

								snake_case_				=							tokenizer(a       ,			return_tensors='pt'       ,			padding=a					)
								snake_case_				=							inputs['input_ids'].to(a					)

								snake_case_				=							model.generate(
								    input_ids=a       ,			attention_mask=inputs['attention_mask'].to(a					)       ,			)

								snake_case_				=							tokenizer(sentences[0]       ,			return_tensors='pt'					).input_ids.to(a					)
								snake_case_				=							model.generate(input_ids=a					)

								snake_case_				=							inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item()
								snake_case_				=							tokenizer(sentences[1]       ,			return_tensors='pt'					).input_ids.to(a					)
								snake_case_				=							model.generate(input_ids=a       ,			max_length=model.config.max_length - num_paddings					)

								snake_case_				=							tokenizer.batch_decode(a       ,			skip_special_tokens=a					)
								snake_case_				=							tokenizer.decode(output_non_padded[0]       ,			skip_special_tokens=a					)
								snake_case_				=							tokenizer.decode(output_padded[0]       ,			skip_special_tokens=a					)

								snake_case_				=							[
								    'Hello, my dog is a little bit bigger than a little bit.',
								    'Today, I have a good idea of how to use the information',
								]
								self.assertListEqual(a       ,			a					)
								self.assertListEqual(a       ,			[non_padded_sentence, padded_sentence]					)




	@slow
	def 							_UpperCamelCase			(       self					)       ->    List[Any]:
								for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															snake_case_				=							BioGptModel.from_pretrained(a					)
															self.assertIsNotNone(a					)




	def 							_UpperCamelCase			(       self					)       ->    Dict:
								snake_case_			,		snake_case_				=							self.model_tester.prepare_config_and_inputs_for_common()
								snake_case_				=							3
								snake_case_				=							input_dict['input_ids']
								snake_case_				=							input_ids.ne(1					).to(a					)
								snake_case_				=							ids_tensor([self.model_tester.batch_size]       ,			self.model_tester.type_sequence_label_size					)
								snake_case_				=							BioGptForSequenceClassification(a					)
								model.to(a					)
								model.eval()
								snake_case_				=							model(a       ,			attention_mask=a       ,			labels=a					)
								self.assertEqual(result.logits.shape       ,			(self.model_tester.batch_size, self.model_tester.num_labels)					)






	def 							_UpperCamelCase			(       self					)       ->    List[str]:
								snake_case_			,		snake_case_				=							self.model_tester.prepare_config_and_inputs_for_common()
								snake_case_				=							3
								snake_case_				=							'multi_label_classification'
								snake_case_				=							input_dict['input_ids']
								snake_case_				=							input_ids.ne(1					).to(a					)
								snake_case_				=							ids_tensor(
								    [self.model_tester.batch_size, config.num_labels]       ,			self.model_tester.type_sequence_label_size					).to(torch.float					)
								snake_case_				=							BioGptForSequenceClassification(a					)
								model.to(a					)
								model.eval()
								snake_case_				=							model(a       ,			attention_mask=a       ,			labels=a					)
								self.assertEqual(result.logits.shape       ,			(self.model_tester.batch_size, self.model_tester.num_labels)					)






@require_torch
class  UpperCamelCase_      (			unittest.TestCase				):



	'''simple docstring'''




	@slow
	def 							_UpperCamelCase			(       self					)       ->    Tuple:
								snake_case_				=							BioGptForCausalLM.from_pretrained('microsoft/biogpt'					)
								snake_case_				=							torch.tensor([[2, 48_05, 9, 6_56, 21]]					)
								snake_case_				=							model(a					)[0]

								snake_case_				=							4_23_84

								snake_case_				=							torch.Size((1, 5, vocab_size)					)
								self.assertEqual(output.shape       ,			a					)

								snake_case_				=							torch.tensor(
								    [[[-9.5_236, -9.8_918, 10.4_557], [-11.0_469, -9.6_423, 8.1_022], [-8.8_664, -7.8_826, 5.5_325]]]					)

								self.assertTrue(torch.allclose(output[:, :3, :3]       ,			a       ,			atol=1E-4					)					)






	@slow
	def 							_UpperCamelCase			(       self					)       ->    int:
								snake_case_				=							BioGptTokenizer.from_pretrained('microsoft/biogpt'					)
								snake_case_				=							BioGptForCausalLM.from_pretrained('microsoft/biogpt'					)
								model.to(a					)

								torch.manual_seed(0					)
								snake_case_				=							tokenizer('COVID-19 is'       ,			return_tensors='pt'					).to(a					)
								snake_case_				=							model.generate(
								    **a       ,			min_length=1_00       ,			max_length=10_24       ,			num_beams=5       ,			early_stopping=a       ,			)
								snake_case_				=							tokenizer.decode(output_ids[0]       ,			skip_special_tokens=a					)

								snake_case_				=							(
								    'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the'
								    ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and'
								    ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),'
								    ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and'
								    ' more than 800,000 deaths.'
								)
								self.assertEqual(a       ,			a					)













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  							=					"\n    Examples:\n        ```py\n        >>> import torch\n        >>> import numpy as np\n\n        >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n        >>> from transformers import pipeline\n        >>> from diffusers.utils import load_image\n\n\n        >>> def make_hint(image, depth_estimator):\n        ...     image = depth_estimator(image)[\"depth\"]\n        ...     image = np.array(image)\n        ...     image = image[:, :, None]\n        ...     image = np.concatenate([image, image, image], axis=2)\n        ...     detected_map = torch.from_numpy(image).float() / 255.0\n        ...     hint = detected_map.permute(2, 0, 1)\n        ...     return hint\n\n\n        >>> depth_estimator = pipeline(\"depth-estimation\")\n\n        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n        ...     \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16\n        ... )\n        >>> pipe_prior = pipe_prior.to(\"cuda\")\n\n        >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n        ...     \"kandinsky-community/kandinsky-2-2-controlnet-depth\", torch_dtype=torch.float16\n        ... )\n        >>> pipe = pipe.to(\"cuda\")\n\n\n        >>> img = load_image(\n        ...     \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\n        ...     \"/kandinsky/cat.png\"\n        ... ).resize((768, 768))\n\n        >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to(\"cuda\")\n\n        >>> prompt = \"A robot, 4k photo\"\n        >>> negative_prior_prompt = \"lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature\"\n\n        >>> generator = torch.Generator(device=\"cuda\").manual_seed(43)\n\n        >>> image_emb, zero_image_emb = pipe_prior(\n        ...     prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n        ... ).to_tuple()\n\n        >>> images = pipe(\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=zero_image_emb,\n        ...     hint=hint,\n        ...     num_inference_steps=50,\n        ...     generator=generator,\n        ...     height=768,\n        ...     width=768,\n        ... ).images\n\n        >>> images[0].save(\"robot_cat.png\")\n        ```\n"





def 						__UpperCAmelCase			(     a_							,     a_							,     a_=8):
							snake_case_				=							height // scale_factor**2
							if height % scale_factor**2 != 0:
														new_height += 1
							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  UpperCamelCase_      (			snake_case_				):



	'''simple docstring'''




	def __init__(       self       ,			a       ,			a       ,			a       ,			)       ->    Tuple:
								super().__init__()

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




	def 							_UpperCamelCase			(       self       ,			a       ,			a       ,			a       ,			a       ,			a       ,			a					)       ->    Any:
								if latents is None:
															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}'''					)
															snake_case_				=							latents.to(a					)

								snake_case_				=							latents * scheduler.init_noise_sigma
								return latents




	def 							_UpperCamelCase			(       self       ,			a=0					)       ->    str:
								if is_accelerate_available():
															from accelerate import cpu_offload
								else:
															raise ImportError('Please install accelerate via `pip install accelerate`'					)

								snake_case_				=							torch.device(F'''cuda:{gpu_id}'''					)

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




	def 							_UpperCamelCase			(       self       ,			a=0					)       ->    List[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.'					)

								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)

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

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




	@property
	# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
	def 							_UpperCamelCase			(       self					)       ->    Any:
								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       ,			a = 5_12       ,			a = 5_12       ,			a = 1_00       ,			a = 4.0       ,			a = 1       ,			a = None       ,			a = None       ,			a = "pil"       ,			a = True       ,			)       ->    List[str]:
								snake_case_				=							self._execution_device

								snake_case_				=							guidance_scale > 1.0

								if isinstance(a       ,			a					):
															snake_case_				=							torch.cat(a       ,			dim=0					)
								if isinstance(a       ,			a					):
															snake_case_				=							torch.cat(a       ,			dim=0					)
								if isinstance(a       ,			a					):
															snake_case_				=							torch.cat(a       ,			dim=0					)

								snake_case_				=							image_embeds.shape[0] * num_images_per_prompt

								if do_classifier_free_guidance:
															snake_case_				=							image_embeds.repeat_interleave(a       ,			dim=0					)
															snake_case_				=							negative_image_embeds.repeat_interleave(a       ,			dim=0					)
															snake_case_				=							hint.repeat_interleave(a       ,			dim=0					)

								snake_case_				=							torch.cat([negative_image_embeds, image_embeds]       ,			dim=0					).to(dtype=self.unet.dtype       ,			device=a					)
								snake_case_				=							torch.cat([hint, hint]       ,			dim=0					).to(dtype=self.unet.dtype       ,			device=a					)
								self.scheduler.set_timesteps(a       ,			device=a					)
								snake_case_				=							self.scheduler.timesteps

								snake_case_				=							self.movq.config.latent_channels

								snake_case_			,		snake_case_				=							downscale_height_and_width(a       ,			a       ,			self.movq_scale_factor					)

								# create initial latent
								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
															snake_case_				=							torch.cat([latents] * 2					) if do_classifier_free_guidance else latents

															snake_case_				=							{'image_embeds': image_embeds, 'hint': hint}
															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:
																						snake_case_			,		snake_case_				=							noise_pred.split(latents.shape[1]       ,			dim=1					)
																						snake_case_			,		snake_case_				=							noise_pred.chunk(2					)
																						snake_case_			,		snake_case_				=							variance_pred.chunk(2					)
																						snake_case_				=							noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
																						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"]
															):
																						snake_case_			,		snake_case_				=							noise_pred.split(latents.shape[1]       ,			dim=1					)

															# compute the previous noisy sample x_t -> x_t-1
															snake_case_				=							self.scheduler.step(
															    a       ,			a       ,			a       ,			generator=a       ,			)[0]
								# post-processing
								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"]:
															snake_case_				=							image * 0.5 + 0.5
															snake_case_				=							image.clamp(0       ,			1					)
															snake_case_				=							image.cpu().permute(0       ,			2       ,			3       ,			1					).float().numpy()

								if output_type == "pil":
															snake_case_				=							self.numpy_to_pil(a					)

								if not return_dict:
															return (image,)

								return ImagePipelineOutput(images=a					)





