






import collections
import inspect
import unittest

from transformers import NatConfig
from transformers.testing_utils import require_natten, require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch
				from torch import nn

				from transformers import NatBackbone, NatForImageClassification, NatModel
				from transformers.models.nat.modeling_nat import NAT_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
				from PIL import Image

				from transformers import AutoImageProcessor





class   SCREAMING_SNAKE_CASE :





							"""simple docstring"""

							def __init__(     self:      Tuple						,   __A:      Dict						,   __A:      Optional[Any]=13						,   __A:      Optional[Any]=64						,   __A:      int=4						,   __A:      Union[str, Any]=3						,   __A:      int=16						,   __A:      Union[str, Any]=[1, 2, 1]						,   __A:      Union[str, Any]=[2, 4, 8]						,   __A:      str=3						,   __A:      List[Any]=2.0						,   __A:      Any=True						,   __A:      List[str]=0.0						,   __A:      Optional[int]=0.0						,   __A:      Dict=0.1						,   __A:      Any="gelu"						,   __A:      int=True						,   __A:      Union[str, Any]=0.02						,   __A:      List[Any]=1e-5						,   __A:      str=True						,   __A:      Optional[int]=None						,   __A:      List[str]=True						,   __A:      Any=10						,   __A:      Any=["stage1", "stage2"]						,   __A:      List[str]=[1, 2]						,   )			-> Optional[Any]:
												_A									=       parent
												_A									=       batch_size
												_A									=       image_size
												_A									=       patch_size
												_A									=       num_channels
												_A									=       embed_dim
												_A									=       depths
												_A									=       num_heads
												_A									=       kernel_size
												_A									=       mlp_ratio
												_A									=       qkv_bias
												_A									=       hidden_dropout_prob
												_A									=       attention_probs_dropout_prob
												_A									=       drop_path_rate
												_A									=       hidden_act
												_A									=       patch_norm
												_A									=       layer_norm_eps
												_A									=       initializer_range
												_A									=       is_training
												_A									=       scope
												_A									=       use_labels
												_A									=       num_labels
												_A									=       out_features
												_A									=       out_indices

							def 					__A       (     self:      Optional[Any]      )			-> Any:
												_A									=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

												_A									=       None
												if self.use_labels:
																	_A									=       ids_tensor([self.batch_size]						,   self.num_labels      )

												_A									=       self.get_config()

												return config, pixel_values, labels

							def 					__A       (     self:      int      )			-> Any:
												return NatConfig(
												    num_labels=self.num_labels						,   image_size=self.image_size						,   patch_size=self.patch_size						,   num_channels=self.num_channels						,   embed_dim=self.embed_dim						,   depths=self.depths						,   num_heads=self.num_heads						,   kernel_size=self.kernel_size						,   mlp_ratio=self.mlp_ratio						,   qkv_bias=self.qkv_bias						,   hidden_dropout_prob=self.hidden_dropout_prob						,   attention_probs_dropout_prob=self.attention_probs_dropout_prob						,   drop_path_rate=self.drop_path_rate						,   hidden_act=self.hidden_act						,   patch_norm=self.patch_norm						,   layer_norm_eps=self.layer_norm_eps						,   initializer_range=self.initializer_range						,   out_features=self.out_features						,   out_indices=self.out_indices						,   )

							def 					__A       (     self:      str						,   __A:      Tuple						,   __A:      Tuple						,   __A:      int      )			-> int:
												_A									=       NatModel(config=__A      )
												model.to(__A      )
												model.eval()
												_A									=       model(__A      )

												_A									=       _A									=       (config.image_size // config.patch_size) // (2 ** (len(config.depths      ) - 1))
												_A									=       int(config.embed_dim * 2 ** (len(config.depths      ) - 1)      )

												self.parent.assertEqual(
												    result.last_hidden_state.shape						,   (self.batch_size, expected_height, expected_width, expected_dim)      )

							def 					__A       (     self:      str						,   __A:      Tuple						,   __A:      Optional[int]						,   __A:      List[Any]      )			-> str:
												_A									=       NatForImageClassification(__A      )
												model.to(__A      )
												model.eval()
												_A									=       model(__A						,   labels=__A      )
												self.parent.assertEqual(result.logits.shape						,   (self.batch_size, self.num_labels)      )

												# test greyscale images
												_A									=       1
												_A									=       NatForImageClassification(__A      )
												model.to(__A      )
												model.eval()

												_A									=       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]      )
												_A									=       model(__A      )
												self.parent.assertEqual(result.logits.shape						,   (self.batch_size, self.num_labels)      )

							def 					__A       (     self:      List[str]						,   __A:      str						,   __A:      Any						,   __A:      str      )			-> int:
												_A									=       NatBackbone(config=__A      )
												model.to(__A      )
												model.eval()
												_A									=       model(__A      )

												# verify hidden states
												self.parent.assertEqual(len(result.feature_maps      )						,   len(config.out_features      )      )
												self.parent.assertListEqual(list(result.feature_maps[0].shape      )						,   [self.batch_size, model.channels[0], 16, 16]      )

												# verify channels
												self.parent.assertEqual(len(model.channels      )						,   len(config.out_features      )      )

												# verify backbone works with out_features=None
												_A									=       None
												_A									=       NatBackbone(config=__A      )
												model.to(__A      )
												model.eval()
												_A									=       model(__A      )

												# verify feature maps
												self.parent.assertEqual(len(result.feature_maps      )						,   1      )
												self.parent.assertListEqual(list(result.feature_maps[0].shape      )						,   [self.batch_size, model.channels[-1], 4, 4]      )

												# verify channels
												self.parent.assertEqual(len(model.channels      )						,   1      )



							def 					__A       (     self:      Optional[Any]      )			-> int:
												_A									=       self.prepare_config_and_inputs()
												_A							,_A							,_A									=       config_and_inputs
												_A									=       {'''pixel_values''': pixel_values}
												return config, inputs_dict





@require_natten
@require_torch
class   SCREAMING_SNAKE_CASE (       snake_case     ,		snake_case     ,		unittest.TestCase    ):





							"""simple docstring"""

							A_       =    (
							    (
							        NatModel,
							        NatForImageClassification,
							        NatBackbone,
							    )
							    if is_torch_available()
							    else ()
							)
							A_       =    (
							    {"feature-extraction": NatModel, "image-classification": NatForImageClassification}
							    if is_torch_available()
							    else {}
							)
							A_       =    False

							A_       =    False
							A_       =    False
							A_       =    False
							A_       =    False

							def 					__A       (     self:      Union[str, Any]      )			-> Any:
												_A									=       NatModelTester(self      )
												_A									=       ConfigTester(self						,   config_class=__A						,   embed_dim=37      )

							def 					__A       (     self:      Optional[int]      )			-> Optional[Any]:
												self.create_and_test_config_common_properties()
												self.config_tester.create_and_test_config_to_json_string()
												self.config_tester.create_and_test_config_to_json_file()
												self.config_tester.create_and_test_config_from_and_save_pretrained()
												self.config_tester.create_and_test_config_with_num_labels()
												self.config_tester.check_config_can_be_init_without_params()
												self.config_tester.check_config_arguments_init()

							def 					__A       (     self:      List[Any]      )			-> List[Any]:
												return

							def 					__A       (     self:      str      )			-> Union[str, Any]:
												_A									=       self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*__A      )

							def 					__A       (     self:      List[str]      )			-> Tuple:
												_A									=       self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*__A      )

							def 					__A       (     self:      Tuple      )			-> Dict:
												_A									=       self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_backbone(*__A      )

							@unittest.skip(reason='''Nat does not use inputs_embeds'''      )
							def 					__A       (     self:      Optional[int]      )			-> Dict:
												pass

							@unittest.skip(reason='''Nat does not use feedforward chunking'''      )
							def 					__A       (     self:      Optional[Any]      )			-> Union[str, Any]:
												pass

							def 					__A       (     self:      Dict      )			-> Union[str, Any]:
												_A							,_A									=       self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																	_A									=       model_class(__A      )
																	self.assertIsInstance(model.get_input_embeddings()						,   (nn.Module)      )
																	_A									=       model.get_output_embeddings()
																	self.assertTrue(x is None or isinstance(__A						,   nn.Linear      )      )

							def 					__A       (     self:      Dict      )			-> int:
												_A							,_A									=       self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																	_A									=       model_class(__A      )
																	_A									=       inspect.signature(model.forward      )
																	# signature.parameters is an OrderedDict => so arg_names order is deterministic
																	_A									=       [*signature.parameters.keys()]

																	_A									=       ['''pixel_values''']
																	self.assertListEqual(arg_names[:1]						,   __A      )

							def 					__A       (     self:      Union[str, Any]      )			-> int:
												self.skipTest('''Nat\'s attention operation is handled entirely by NATTEN.'''      )

							def 					__A       (     self:      int						,   __A:      Union[str, Any]						,   __A:      Optional[int]						,   __A:      Tuple						,   __A:      Any      )			-> Any:
												_A									=       model_class(__A      )
												model.to(__A      )
												model.eval()

												with torch.no_grad():
																	_A									=       model(**self._prepare_for_class(__A						,   __A      )      )

												_A									=       outputs.hidden_states

												_A									=       getattr(
												    self.model_tester						,   '''expected_num_hidden_layers'''						,   len(self.model_tester.depths      ) + 1      )
												self.assertEqual(len(__A      )						,   __A      )

												# Nat has a different seq_length
												_A									=       (
												    config.patch_size
												    if isinstance(config.patch_size						,   collections.abc.Iterable      )
												    else (config.patch_size, config.patch_size)
												)

												_A									=       image_size[0] // patch_size[0]
												_A									=       image_size[1] // patch_size[1]

												self.assertListEqual(
												    list(hidden_states[0].shape[-3:]      )						,   [height, width, self.model_tester.embed_dim]						,   )

												if model_class.__name__ != "NatBackbone":
																	_A									=       outputs.reshaped_hidden_states
																	self.assertEqual(len(__A      )						,   __A      )

																	_A							,_A							,_A							,_A									=       reshaped_hidden_states[0].shape
																	_A									=       (
																	    reshaped_hidden_states[0].view(__A						,   __A						,   __A						,   __A      ).permute(0						,   2						,   3						,   1      )
																	)
																	self.assertListEqual(
																	    list(reshaped_hidden_states.shape[-3:]      )						,   [height, width, self.model_tester.embed_dim]						,   )

							def 					__A       (     self:      Union[str, Any]      )			-> Optional[int]:
												_A							,_A									=       self.model_tester.prepare_config_and_inputs_for_common()

												_A									=       (
												    self.model_tester.image_size
												    if isinstance(self.model_tester.image_size						,   collections.abc.Iterable      )
												    else (self.model_tester.image_size, self.model_tester.image_size)
												)

												for model_class in self.all_model_classes:
																	_A									=       True
																	self.check_hidden_states_output(__A						,   __A						,   __A						,   __A      )

																	# check that output_hidden_states also work using config
																	del inputs_dict["output_hidden_states"]
																	_A									=       True

																	self.check_hidden_states_output(__A						,   __A						,   __A						,   __A      )

							@slow
							def 					__A       (     self:      Union[str, Any]      )			-> List[str]:
												for model_name in NAT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	_A									=       NatModel.from_pretrained(__A      )
																	self.assertIsNotNone(__A      )



							def 					__A       (     self:      List[str]      )			-> List[str]:
												_A							,_A									=       self.model_tester.prepare_config_and_inputs_for_common()

												_A									=       _config_zero_init(__A      )
												for model_class in self.all_model_classes:
																	_A									=       model_class(config=__A      )
																	for name, param in model.named_parameters():
																						if "embeddings" not in name and param.requires_grad:
																											self.assertIn(
																											    ((param.data.mean() * 1e9).round() / 1e9).item()						,   [0.0, 1.0]						,   msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""						,   )





@require_natten
@require_vision
@require_torch
class   SCREAMING_SNAKE_CASE (       unittest.TestCase    ):





							"""simple docstring"""

							@cached_property
							def 					__A       (     self:      int      )			-> str:
												return AutoImageProcessor.from_pretrained('''shi-labs/nat-mini-in1k-224'''      ) if is_vision_available() else None



							@slow
							def 					__A       (     self:      str      )			-> str:
												_A									=       NatForImageClassification.from_pretrained('''shi-labs/nat-mini-in1k-224'''      ).to(__A      )
												_A									=       self.default_image_processor

												_A									=       Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
												_A									=       image_processor(images=__A						,   return_tensors='''pt'''      ).to(__A      )

												# forward pass
												with torch.no_grad():
																	_A									=       model(**__A      )

												# verify the logits
												_A									=       torch.Size((1, 10_00)      )
												self.assertEqual(outputs.logits.shape						,   __A      )
												_A									=       torch.tensor([0.3_805, -0.8_676, -0.3_912]      ).to(__A      )
												self.assertTrue(torch.allclose(outputs.logits[0, :3]						,   __A						,   atol=1e-4      )      )





@require_torch
@require_natten
class   SCREAMING_SNAKE_CASE (       unittest.TestCase     ,		snake_case    ):





							"""simple docstring"""

							A_       =    (NatBackbone,) if is_torch_available() else ()
							A_       =    NatConfig

							def 					__A       (     self:      Dict      )			-> str:
												_A									=       NatModelTester(self      )











import inspect
from typing import List, Optional, Union

import torch
from torch import nn
from torch.nn import functional as F
from torchvision import transforms
from transformers import CLIPImageProcessor, CLIPModel, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    DPMSolverMultistepScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput




class 							a_ (						nn.Module		):


							'''simple docstring'''






							def __init__(		self			,			lowercase_			,			lowercase_=1.0   )					->					Any:
														'''simple docstring'''

														super().__init__()

														lowerCAmelCase_										=     cut_size
														lowerCAmelCase_										=     cut_power






							def      _lowercase       (		self			,			lowercase_			,			lowercase_   )					->					int:
														'''simple docstring'''

														lowerCAmelCase_						,   lowerCAmelCase_										=     pixel_values.shape[2:4]
														lowerCAmelCase_										=     min(lowercase_			,			lowercase_   )
														lowerCAmelCase_										=     min(lowercase_			,			lowercase_			,			self.cut_size   )
														lowerCAmelCase_										=     []
														for _ in range(lowercase_   ):
																					lowerCAmelCase_										=     int(torch.rand([]   ) ** self.cut_power * (max_size - min_size) + min_size   )
																					lowerCAmelCase_										=     torch.randint(0			,			sideX - size + 1			,			()   )
																					lowerCAmelCase_										=     torch.randint(0			,			sideY - size + 1			,			()   )
																					lowerCAmelCase_										=     pixel_values[:, :, offsety : offsety + size, offsetx : offsetx + size]
																					cutouts.append(F.adaptive_avg_poolad(lowercase_			,			self.cut_size   )   )
														return torch.cat(lowercase_   )


def      lowerCamelCase					(						a_ ,						a_	)	->			Optional[int]:
							lowerCAmelCase_										=     F.normalize(a_ ,						dim=-1	)
							lowerCAmelCase_										=     F.normalize(a_ ,						dim=-1	)
							return (x - y).norm(dim=-1	).div(2	).arcsin().pow(2	).mul(2	)
def      lowerCamelCase					(						a_ ,						a_	)	->			int:
							for param in model.parameters():
														lowerCAmelCase_										=     value




class 							a_ (						a_		):


							'''simple docstring'''






							def __init__(		self			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			)					->					str:
														'''simple docstring'''

														super().__init__()
														self.register_modules(
														    vae=lowercase_			,			text_encoder=lowercase_			,			clip_model=lowercase_			,			tokenizer=lowercase_			,			unet=lowercase_			,			scheduler=lowercase_			,			feature_extractor=lowercase_			,			)

														lowerCAmelCase_										=     transforms.Normalize(mean=feature_extractor.image_mean			,			std=feature_extractor.image_std   )
														lowerCAmelCase_										=     (
														    feature_extractor.size
														    if isinstance(feature_extractor.size			,			lowercase_   )
														    else feature_extractor.size['shortest_edge']
														)
														lowerCAmelCase_										=     MakeCutouts(self.cut_out_size   )

														set_requires_grad(self.text_encoder			,			lowercase_   )
														set_requires_grad(self.clip_model			,			lowercase_   )

							def      _lowercase       (		self			,			lowercase_ = "auto"   )					->					Union[str, Any]:
														'''simple docstring'''

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

							def      _lowercase       (		self   )					->					List[Any]:
														'''simple docstring'''

														self.enable_attention_slicing(lowercase_   )

							def      _lowercase       (		self   )					->					str:
														'''simple docstring'''

														set_requires_grad(self.vae			,			lowercase_   )

							def      _lowercase       (		self   )					->					List[str]:
														'''simple docstring'''

														set_requires_grad(self.vae			,			lowercase_   )

							def      _lowercase       (		self   )					->					List[str]:
														'''simple docstring'''

														set_requires_grad(self.unet			,			lowercase_   )

							def      _lowercase       (		self   )					->					Tuple:
														'''simple docstring'''

														set_requires_grad(self.unet			,			lowercase_   )

							@torch.enable_grad()
							def      _lowercase       (		self			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_=True			,			)					->					Union[str, Any]:
														'''simple docstring'''

														lowerCAmelCase_										=     latents.detach().requires_grad_()

														lowerCAmelCase_										=     self.scheduler.scale_model_input(lowercase_			,			lowercase_   )

														# predict the noise residual
														lowerCAmelCase_										=     self.unet(lowercase_			,			lowercase_			,			encoder_hidden_states=lowercase_   ).sample

														if isinstance(self.scheduler			,			(PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler)   ):
																					lowerCAmelCase_										=     self.scheduler.alphas_cumprod[timestep]
																					lowerCAmelCase_										=     1 - alpha_prod_t
																					# compute predicted original sample from predicted noise also called
																					# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
																					lowerCAmelCase_										=     (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5

																					lowerCAmelCase_										=     torch.sqrt(lowercase_   )
																					lowerCAmelCase_										=     pred_original_sample * (fac) + latents * (1 - fac)
														elif isinstance(self.scheduler			,			lowercase_   ):
																					lowerCAmelCase_										=     self.scheduler.sigmas[index]
																					lowerCAmelCase_										=     latents - sigma * noise_pred
														else:
																					raise ValueError(f'''scheduler type {type(self.scheduler   )} not supported'''   )

														lowerCAmelCase_										=     1 / self.vae.config.scaling_factor * sample
														lowerCAmelCase_										=     self.vae.decode(lowercase_   ).sample
														lowerCAmelCase_										=     (image / 2 + 0.5).clamp(0			,			1   )

														if use_cutouts:
																					lowerCAmelCase_										=     self.make_cutouts(lowercase_			,			lowercase_   )
														else:
																					lowerCAmelCase_										=     transforms.Resize(self.cut_out_size   )(lowercase_   )
														lowerCAmelCase_										=     self.normalize(lowercase_   ).to(latents.dtype   )

														lowerCAmelCase_										=     self.clip_model.get_image_features(lowercase_   )
														lowerCAmelCase_										=     image_embeddings_clip / image_embeddings_clip.norm(p=2			,			dim=-1			,			keepdim=lowercase_   )

														if use_cutouts:
																					lowerCAmelCase_										=     spherical_dist_loss(lowercase_			,			lowercase_   )
																					lowerCAmelCase_										=     dists.view([num_cutouts, sample.shape[0], -1]   )
																					lowerCAmelCase_										=     dists.sum(2   ).mean(0   ).sum() * clip_guidance_scale
														else:
																					lowerCAmelCase_										=     spherical_dist_loss(lowercase_			,			lowercase_   ).mean() * clip_guidance_scale

														lowerCAmelCase_										=     -torch.autograd.grad(lowercase_			,			lowercase_   )[0]

														if isinstance(self.scheduler			,			lowercase_   ):
																					lowerCAmelCase_										=     latents.detach() + grads * (sigma**2)
																					lowerCAmelCase_										=     noise_pred_original
														else:
																					lowerCAmelCase_										=     noise_pred_original - torch.sqrt(lowercase_   ) * grads
														return noise_pred, latents






							@torch.no_grad()
							def __call__(		self			,			lowercase_			,			lowercase_ = 5_1_2			,			lowercase_ = 5_1_2			,			lowercase_ = 5_0			,			lowercase_ = 7.5			,			lowercase_ = 1			,			lowercase_ = 0.0			,			lowercase_ = 1_0_0			,			lowercase_ = None			,			lowercase_ = 4			,			lowercase_ = True			,			lowercase_ = None			,			lowercase_ = None			,			lowercase_ = "pil"			,			lowercase_ = True			,			)					->					str:
														'''simple docstring'''

														if isinstance(lowercase_			,			lowercase_   ):
																					lowerCAmelCase_										=     1
														elif isinstance(lowercase_			,			lowercase_   ):
																					lowerCAmelCase_										=     len(lowercase_   )
														else:
																					raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(lowercase_   )}'''   )

														if height % 8 != 0 or width % 8 != 0:
																					raise ValueError(f'''`height` and `width` have to be divisible by 8 but are {height} and {width}.'''   )

														# get prompt text embeddings
														lowerCAmelCase_										=     self.tokenizer(
														    lowercase_			,			padding='max_length'			,			max_length=self.tokenizer.model_max_length			,			truncation=lowercase_			,			return_tensors='pt'			,			)
														lowerCAmelCase_										=     self.text_encoder(text_input.input_ids.to(self.device   )   )[0]
														# duplicate text embeddings for each generation per prompt
														lowerCAmelCase_										=     text_embeddings.repeat_interleave(lowercase_			,			dim=0   )

														if clip_guidance_scale > 0:
																					if clip_prompt is not None:
																												lowerCAmelCase_										=     self.tokenizer(
																												    lowercase_			,			padding='max_length'			,			max_length=self.tokenizer.model_max_length			,			truncation=lowercase_			,			return_tensors='pt'			,			).input_ids.to(self.device   )
																					else:
																												lowerCAmelCase_										=     text_input.input_ids.to(self.device   )
																					lowerCAmelCase_										=     self.clip_model.get_text_features(lowercase_   )
																					lowerCAmelCase_										=     text_embeddings_clip / text_embeddings_clip.norm(p=2			,			dim=-1			,			keepdim=lowercase_   )
																					# duplicate text embeddings clip for each generation per prompt
																					lowerCAmelCase_										=     text_embeddings_clip.repeat_interleave(lowercase_			,			dim=0   )

														# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
														# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
														# corresponds to doing no classifier free guidance.
														lowerCAmelCase_										=     guidance_scale > 1.0
														# get unconditional embeddings for classifier free guidance
														if do_classifier_free_guidance:
																					lowerCAmelCase_										=     text_input.input_ids.shape[-1]
																					lowerCAmelCase_										=     self.tokenizer(['']			,			padding='max_length'			,			max_length=lowercase_			,			return_tensors='pt'   )
																					lowerCAmelCase_										=     self.text_encoder(uncond_input.input_ids.to(self.device   )   )[0]
																					# duplicate unconditional embeddings for each generation per prompt
																					lowerCAmelCase_										=     uncond_embeddings.repeat_interleave(lowercase_			,			dim=0   )

																					# For classifier free guidance, we need to do two forward passes.
																					# Here we concatenate the unconditional and text embeddings into a single batch
																					# to avoid doing two forward passes
																					lowerCAmelCase_										=     torch.cat([uncond_embeddings, text_embeddings]   )

														# get the initial random noise unless the user supplied it

														# Unlike in other pipelines, latents need to be generated in the target device
														# for 1-to-1 results reproducibility with the CompVis implementation.
														# However this currently doesn't work in `mps`.
														lowerCAmelCase_										=     (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
														lowerCAmelCase_										=     text_embeddings.dtype
														if latents is None:
																					if self.device.type == "mps":
																												# randn does not work reproducibly on mps
																												lowerCAmelCase_										=     torch.randn(lowercase_			,			generator=lowercase_			,			device='cpu'			,			dtype=lowercase_   ).to(
																												    self.device   )
																					else:
																												lowerCAmelCase_										=     torch.randn(lowercase_			,			generator=lowercase_			,			device=self.device			,			dtype=lowercase_   )
														else:
																					if latents.shape != latents_shape:
																												raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}'''   )
																					lowerCAmelCase_										=     latents.to(self.device   )

														# set timesteps
														lowerCAmelCase_										=     'offset' in set(inspect.signature(self.scheduler.set_timesteps   ).parameters.keys()   )
														lowerCAmelCase_										=     {}
														if accepts_offset:
																					lowerCAmelCase_										=     1

														self.scheduler.set_timesteps(lowercase_			,			**lowercase_   )

														# Some schedulers like PNDM have timesteps as arrays
														# It's more optimized to move all timesteps to correct device beforehand
														lowerCAmelCase_										=     self.scheduler.timesteps.to(self.device   )

														# scale the initial noise by the standard deviation required by the scheduler
														lowerCAmelCase_										=     latents * self.scheduler.init_noise_sigma

														# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
														# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
														# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
														# and should be between [0, 1]
														lowerCAmelCase_										=     'eta' in set(inspect.signature(self.scheduler.step   ).parameters.keys()   )
														lowerCAmelCase_										=     {}
														if accepts_eta:
																					lowerCAmelCase_										=     eta

														# check if the scheduler accepts generator
														lowerCAmelCase_										=     'generator' in set(inspect.signature(self.scheduler.step   ).parameters.keys()   )
														if accepts_generator:
																					lowerCAmelCase_										=     generator

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

																					# predict the noise residual
																					lowerCAmelCase_										=     self.unet(lowercase_			,			lowercase_			,			encoder_hidden_states=lowercase_   ).sample

																					# perform classifier free guidance
																					if do_classifier_free_guidance:
																												lowerCAmelCase_						,   lowerCAmelCase_										=     noise_pred.chunk(2   )
																												lowerCAmelCase_										=     noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

																					# perform clip guidance
																					if clip_guidance_scale > 0:
																												lowerCAmelCase_										=     (
																												    text_embeddings.chunk(2   )[1] if do_classifier_free_guidance else text_embeddings
																												)
																												lowerCAmelCase_						,   lowerCAmelCase_										=     self.cond_fn(
																												    lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			lowercase_			,			)

																					# compute the previous noisy sample x_t -> x_t-1
																					lowerCAmelCase_										=     self.scheduler.step(lowercase_			,			lowercase_			,			lowercase_			,			**lowercase_   ).prev_sample

														# scale and decode the image latents with vae
														lowerCAmelCase_										=     1 / self.vae.config.scaling_factor * latents
														lowerCAmelCase_										=     self.vae.decode(lowercase_   ).sample

														lowerCAmelCase_										=     (image / 2 + 0.5).clamp(0			,			1   )
														lowerCAmelCase_										=     image.cpu().permute(0			,			2			,			3			,			1   ).numpy()

														if output_type == "pil":
																					lowerCAmelCase_										=     self.numpy_to_pil(lowercase_   )

														if not return_dict:
																					return (image, None)

														return StableDiffusionPipelineOutput(images=lowercase_			,			nsfw_content_detected=lowercase_   )



