






"""simple docstring"""



from logging import getLogger
from typing import Any, Callable, List, Optional, Union

import numpy as np
import PIL
import torch

from ...schedulers import DDPMScheduler
from ..onnx_utils import ORT_TO_NP_TYPE, OnnxRuntimeModel
from ..pipeline_utils import ImagePipelineOutput
from . import StableDiffusionUpscalePipeline


__A		:	List[str]      =		getLogger(__name__)


__A		:	List[Any]      =		4
__A		:	Any      =		7

__A		:	List[str]      =		{
    '''float16''': torch.floataa,
    '''float32''': torch.floataa,
}



def 						lowercase   (    __snake_case    :			Optional[int]     ):
		if isinstance(__snake_case		, torch.Tensor     ):
				return image
		elif isinstance(__snake_case		, PIL.Image.Image     ):
				lowercase_			:			Union[str, Any]								=       [image]

		if isinstance(image[0]		, PIL.Image.Image     ):
				lowercase_	, lowercase_			:			int								=       image[0].size
				lowercase_	, lowercase_			:			Any								=       (x - x % 6_4 for x in (w, h))  # resize to integer multiple of 32

				lowercase_			:			Dict								=       [np.array(i.resize((w, h)     )     )[None, :] for i in image]
				lowercase_			:			Tuple								=       np.concatenate(__snake_case		, axis=0     )
				lowercase_			:			List[str]								=       np.array(__snake_case     ).astype(np.floataa     ) / 255.0
				lowercase_			:			Dict								=       image.transpose(0		, 3		, 1		, 2     )
				lowercase_			:			Union[str, Any]								=       2.0 * image - 1.0
				lowercase_			:			List[str]								=       torch.from_numpy(__snake_case     )
		elif isinstance(image[0]		, torch.Tensor     ):
				lowercase_			:			Any								=       torch.cat(__snake_case		, dim=0     )

		return image






class  _UpperCAmelCase	(			_A							):




					def __init__(    self					:						List[str]   ,						A					:						OnnxRuntimeModel   ,						A					:						OnnxRuntimeModel   ,						A					:						Any   ,						A					:						OnnxRuntimeModel   ,						A					:						DDPMScheduler   ,						A					:						Any   ,						A					:						int = 3_50   ,						)  ->  Optional[Any]:
							super().__init__(
							    vae=A   ,						text_encoder=A   ,						tokenizer=A   ,						unet=A   ,						low_res_scheduler=A   ,						scheduler=A   ,						safety_checker=A   ,						feature_extractor=A   ,						watermarker=A   ,						max_noise_level=A   ,						)




					def __call__(    self					:						Tuple   ,						A					:						Union[str, List[str]]   ,						A					:						Union[torch.FloatTensor, PIL.Image.Image, List[PIL.Image.Image]]   ,						A					:						int = 75   ,						A					:						float = 9.0   ,						A					:						int = 20   ,						A					:						Optional[Union[str, List[str]]] = None   ,						A					:						Optional[int] = 1   ,						A					:						float = 0.0   ,						A					:						Optional[Union[torch.Generator, List[torch.Generator]]] = None   ,						A					:						Optional[torch.FloatTensor] = None   ,						A					:						Optional[np.ndarray] = None   ,						A					:						Optional[np.ndarray] = None   ,						A					:						Optional[str] = "pil"   ,						A					:						bool = True   ,						A					:						Optional[Callable[[int, int, torch.FloatTensor], None]] = None   ,						A					:						Optional[int] = 1   ,						)  ->  str:
							self.check_inputs(A   ,						A   ,						A   ,						A       )

							# 2. Define call parameters
							if prompt is not None and isinstance(A   ,						A       ):
									lowercase_			:			List[Any]								=       1
							elif prompt is not None and isinstance(A   ,						A       ):
									lowercase_			:			Tuple								=       len(A       )
							else:
									lowercase_			:			Union[str, Any]								=       prompt_embeds.shape[0]

							lowercase_			:			Dict								=       self._execution_device
							# 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.
							lowercase_			:			Optional[int]								=       guidance_scale > 1.0

							# 3. Encode input prompt
							lowercase_			:			Tuple								=       self._encode_prompt(
							    A   ,						A   ,						A   ,						A   ,						A   ,						prompt_embeds=A   ,						negative_prompt_embeds=A   ,						)

							lowercase_			:			Any								=       ORT_TO_PT_TYPE[str(text_embeddings.dtype       )]

							# 4. Preprocess image
							lowercase_			:			Optional[int]								=       preprocess(A       )
							lowercase_			:			Optional[Any]								=       image.cpu()

							# 5. set timesteps
							self.scheduler.set_timesteps(A   ,						device=A       )
							lowercase_			:			str								=       self.scheduler.timesteps

							# 5. Add noise to image
							lowercase_			:			Any								=       torch.tensor([noise_level]   ,						dtype=torch.long   ,						device=A       )
							lowercase_			:			Tuple								=       torch.randn(image.shape   ,						generator=A   ,						device=A   ,						dtype=A       )
							lowercase_			:			Dict								=       self.low_res_scheduler.add_noise(A   ,						A   ,						A       )

							lowercase_			:			str								=       2 if do_classifier_free_guidance else 1
							lowercase_			:			str								=       np.concatenate([image] * batch_multiplier * num_images_per_prompt       )
							lowercase_			:			Dict								=       np.concatenate([noise_level] * image.shape[0]       )

							# 6. Prepare latent variables
							lowercase_	, lowercase_			:			Optional[int]								=       image.shape[2:]
							lowercase_			:			Optional[Any]								=       self.prepare_latents(
							    batch_size * num_images_per_prompt   ,						A   ,						A   ,						A   ,						A   ,						A   ,						A   ,						A   ,						)

							# 7. Check that sizes of image and latents match
							lowercase_			:			int								=       image.shape[1]
							if NUM_LATENT_CHANNELS + num_channels_image != NUM_UNET_INPUT_CHANNELS:
									raise ValueError(
									    '''Incorrect configuration settings! The config of `pipeline.unet` expects'''
									    F''' {NUM_UNET_INPUT_CHANNELS} but received `num_channels_latents`: {NUM_LATENT_CHANNELS} +'''
									    F''' `num_channels_image`: {num_channels_image} '''
									    F''' = {NUM_LATENT_CHANNELS+num_channels_image}. Please verify the config of'''
									    ''' `pipeline.unet` or your `image` input.'''       )

							# 8. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
							lowercase_			:			int								=       self.prepare_extra_step_kwargs(A   ,						A       )

							lowercase_			:			Tuple								=       next(
							    (input.type for input in self.unet.model.get_inputs() if input.name == '''timestep''')   ,						'''tensor(float)'''       )
							lowercase_			:			Any								=       ORT_TO_NP_TYPE[timestep_dtype]

							# 9. Denoising loop
							lowercase_			:			str								=       len(A       ) - num_inference_steps * self.scheduler.order
							with self.progress_bar(total=A       ) as progress_bar:
									for i, t in enumerate(A       ):
											# expand the latents if we are doing classifier free guidance
											lowercase_			:			List[str]								=       np.concatenate([latents] * 2       ) if do_classifier_free_guidance else latents

											# concat latents, mask, masked_image_latents in the channel dimension
											lowercase_			:			str								=       self.scheduler.scale_model_input(A   ,						A       )
											lowercase_			:			Union[str, Any]								=       np.concatenate([latent_model_input, image]   ,						axis=1       )

											# timestep to tensor
											lowercase_			:			Optional[int]								=       np.array([t]   ,						dtype=A       )

											# predict the noise residual
											lowercase_			:			List[str]								=       self.unet(
											    sample=A   ,						timestep=A   ,						encoder_hidden_states=A   ,						class_labels=noise_level.astype(np.intaa       )   ,						)[0]

											# perform guidance
											if do_classifier_free_guidance:
													lowercase_	, lowercase_			:			int								=       np.split(A   ,						2       )
											lowercase_			:			Any								=       noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

											# compute the previous noisy sample x_t -> x_t-1
											lowercase_			:			Dict								=       self.scheduler.step(
											    torch.from_numpy(A       )   ,						A   ,						A   ,						**A       ).prev_sample

											# call the callback, if provided
											if i == len(A       ) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
													progress_bar.update()
													if callback is not None and i % callback_steps == 0:
															callback(A   ,						A   ,						A       )

        # 10. Post-processing
							lowercase_			:			Any								=       self.decode_latents(latents.float()       )

							# 11. Convert to PIL
							if output_type == "pil":
									lowercase_			:			List[Any]								=       self.numpy_to_pil(A       )

							if not return_dict:
									return (image,)

							return ImagePipelineOutput(images=A       )




					def   A  (    self					:						Optional[Any]   ,						A					:						Union[str, Any]       )  ->  Optional[Any]:
							lowercase_			:			Union[str, Any]								=       1 / 0.08333 * latents
							lowercase_			:			Dict								=       self.vae(latent_sample=A       )[0]
							lowercase_			:			Optional[Any]								=       np.clip(image / 2 + 0.5   ,						0   ,						1       )
							lowercase_			:			List[Any]								=       image.transpose((0, 2, 3, 1)       )
							return image






					def   A  (    self					:						List[str]   ,						A					:						Union[str, List[str]]   ,						A					:						Tuple   ,						A					:						Optional[int]   ,						A					:						bool   ,						A					:						Optional[str]   ,						A					:						Optional[torch.FloatTensor] = None   ,						A					:						Optional[torch.FloatTensor] = None   ,						)  ->  Optional[Any]:
							if prompt is not None and isinstance(A   ,						A       ):
									lowercase_			:			List[Any]								=       1
							elif prompt is not None and isinstance(A   ,						A       ):
									lowercase_			:			Tuple								=       len(A       )
							else:
									lowercase_			:			Any								=       prompt_embeds.shape[0]

							if prompt_embeds is None:
									lowercase_			:			int								=       self.tokenizer(
									    A   ,						padding='''max_length'''   ,						max_length=self.tokenizer.model_max_length   ,						truncation=A   ,						return_tensors='''pt'''   ,						)
									lowercase_			:			int								=       text_inputs.input_ids
									lowercase_			:			Optional[int]								=       self.tokenizer(A   ,						padding='''longest'''   ,						return_tensors='''pt'''       ).input_ids

									if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
									    A   ,						A       ):
											lowercase_			:			int								=       self.tokenizer.batch_decode(
											    untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]       )
											logger.warning(
											    '''The following part of your input was truncated because CLIP can only handle sequences up to'''
											    F''' {self.tokenizer.model_max_length} tokens: {removed_text}'''       )

									# no positional arguments to text_encoder
									lowercase_			:			Union[str, Any]								=       self.text_encoder(
									    input_ids=text_input_ids.int().to(A       )   ,						)
									lowercase_			:			List[Any]								=       prompt_embeds[0]

							lowercase_	, lowercase_	, lowercase_			:			int								=       prompt_embeds.shape
							# duplicate text embeddings for each generation per prompt, using mps friendly method
							lowercase_			:			List[Any]								=       prompt_embeds.repeat(1   ,						A       )
							lowercase_			:			Optional[Any]								=       prompt_embeds.reshape(bs_embed * num_images_per_prompt   ,						A   ,						-1       )

							# get unconditional embeddings for classifier free guidance
							if do_classifier_free_guidance and negative_prompt_embeds is None:
									lowercase_			:			List[str]
									if negative_prompt is None:
											lowercase_			:			int								=       [''''''] * batch_size
									elif type(A       ) is not type(A       ):
											raise TypeError(
											    F'''`negative_prompt` should be the same type to `prompt`, but got {type(A       )} !='''
											    F''' {type(A       )}.'''       )
									elif isinstance(A   ,						A       ):
											lowercase_			:			Union[str, Any]								=       [negative_prompt]
									elif batch_size != len(A       ):
											raise ValueError(
											    F'''`negative_prompt`: {negative_prompt} has batch size {len(A       )}, but `prompt`:'''
											    F''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches'''
											    ''' the batch size of `prompt`.'''       )
									else:
											lowercase_			:			Any								=       negative_prompt

									lowercase_			:			Optional[int]								=       text_input_ids.shape[-1]
									lowercase_			:			int								=       self.tokenizer(
									    A   ,						padding='''max_length'''   ,						max_length=A   ,						truncation=A   ,						return_tensors='''pt'''   ,						)

									# if hasattr(uncond_input, "attention_mask"):
									#     attention_mask = uncond_input.attention_mask.to(device)
									# else:
									#     attention_mask = None

									lowercase_			:			Tuple								=       self.text_encoder(
									    input_ids=uncond_input.input_ids.int().to(A       )   ,						)
									lowercase_			:			Optional[int]								=       uncond_embeddings[0]

							if do_classifier_free_guidance:
									lowercase_			:			Dict								=       uncond_embeddings.shape[1]
									# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
									lowercase_			:			Any								=       uncond_embeddings.repeat(1   ,						A       )
									lowercase_			:			Tuple								=       uncond_embeddings.reshape(batch_size * num_images_per_prompt   ,						A   ,						-1       )

									# 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
									lowercase_			:			Optional[int]								=       np.concatenate([uncond_embeddings, prompt_embeds]       )

							return prompt_embeds











"""simple docstring"""



from typing import Callable, List, Optional, Union

import torch

from ...models import UNetaDModel
from ...schedulers import CMStochasticIterativeScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput


__A		:	Union[str, Any]      =		logging.get_logger(__name__)  # pylint: disable=invalid-name


__A		:	str      =		'''
    Examples:
        ```py
        >>> import torch

        >>> from diffusers import ConsistencyModelPipeline

        >>> device = "cuda"
        >>> # Load the cd_imagenet64_l2 checkpoint.
        >>> model_id_or_path = "openai/diffusers-cd_imagenet64_l2"
        >>> pipe = ConsistencyModelPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
        >>> pipe.to(device)

        >>> # Onestep Sampling
        >>> image = pipe(num_inference_steps=1).images[0]
        >>> image.save("cd_imagenet64_l2_onestep_sample.png")

        >>> # Onestep sampling, class-conditional image generation
        >>> # ImageNet-64 class label 145 corresponds to king penguins
        >>> image = pipe(num_inference_steps=1, class_labels=145).images[0]
        >>> image.save("cd_imagenet64_l2_onestep_sample_penguin.png")

        >>> # Multistep sampling, class-conditional image generation
        >>> # Timesteps can be explicitly specified; the particular timesteps below are from the original Github repo:
        >>> # https://github.com/openai/consistency_models/blob/main/scripts/launch.sh#L77
        >>> image = pipe(num_inference_steps=None, timesteps=[22, 0], class_labels=145).images[0]
        >>> image.save("cd_imagenet64_l2_multistep_sample_penguin.png")
        ```
'''





class  _UpperCAmelCase	(			_A							):




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

							self.register_modules(
							    unet=A   ,						scheduler=A   ,						)

							lowercase_			:			Any								=       None




					def   A  (    self					:						Tuple   ,						A					:						Union[str, Any]=0       )  ->  Optional[Any]:
							if is_accelerate_available() and is_accelerate_version('''>='''   ,						'''0.14.0'''       ):
									from accelerate import cpu_offload
							else:
									raise ImportError('''`enable_sequential_cpu_offload` requires `accelerate v0.14.0` or higher'''       )

							lowercase_			:			Any								=       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)

							for cpu_offloaded_model in [self.unet]:
									cpu_offload(A   ,						A       )

							if self.safety_checker is not None:
									cpu_offload(self.safety_checker   ,						execution_device=A   ,						offload_buffers=A       )




					def   A  (    self					:						List[Any]   ,						A					:						Optional[Any]=0       )  ->  List[Any]:
							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.'''       )

							lowercase_			:			List[str]								=       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)

							lowercase_			:			Union[str, Any]								=       None
							for cpu_offloaded_model in [self.unet]:
									lowercase_	, lowercase_			:			Optional[int]								=       cpu_offload_with_hook(A   ,						A   ,						prev_module_hook=A       )

							if self.safety_checker is not None:
									lowercase_	, lowercase_			:			Any								=       cpu_offload_with_hook(self.safety_checker   ,						A   ,						prev_module_hook=A       )

							# We'll offload the last model manually.
							lowercase_			:			str								=       hook




					@property
					# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
					def   A  (    self					:						Any       )  ->  List[str]:
							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




					def   A  (    self					:						List[str]   ,						A					:						int   ,						A					:						Union[str, Any]   ,						A					:						List[str]   ,						A					:						str   ,						A					:						int   ,						A					:						List[Any]   ,						A					:						Optional[Any]   ,						A					:						Optional[Any]=None       )  ->  Tuple:
							lowercase_			:			List[Any]								=       (batch_size, num_channels, height, width)
							if isinstance(A   ,						A       ) and len(A       ) != batch_size:
									raise ValueError(
									    F'''You have passed a list of generators of length {len(A       )}, but requested an effective batch'''
									    F''' size of {batch_size}. Make sure the batch size matches the length of the generators.'''       )

							if latents is None:
									lowercase_			:			Dict								=       randn_tensor(A   ,						generator=A   ,						device=A   ,						dtype=A       )
							else:
									lowercase_			:			Tuple								=       latents.to(device=A   ,						dtype=A       )

							# scale the initial noise by the standard deviation required by the scheduler
							lowercase_			:			List[str]								=       latents * self.scheduler.init_noise_sigma
							return latents




					def   A  (    self					:						Tuple   ,						A					:						torch.FloatTensor   ,						A					:						str = "pil"       )  ->  Optional[int]:
							if output_type not in ["pt", "np", "pil"]:
									raise ValueError(
									    F'''output_type={output_type} is not supported. Make sure to choose one of [\'pt\', \'np\', or \'pil\']'''       )

							# Equivalent to diffusers.VaeImageProcessor.denormalize
							lowercase_			:			Dict								=       (sample / 2 + 0.5).clamp(0   ,						1       )
							if output_type == "pt":
									return sample

							# Equivalent to diffusers.VaeImageProcessor.pt_to_numpy
							lowercase_			:			List[str]								=       sample.cpu().permute(0   ,						2   ,						3   ,						1       ).numpy()
							if output_type == "np":
									return sample

							# Output_type must be 'pil'
							lowercase_			:			List[Any]								=       self.numpy_to_pil(A       )
							return sample




					def   A  (    self					:						Optional[int]   ,						A					:						Any   ,						A					:						Union[str, Any]   ,						A					:						Optional[int]=None       )  ->  List[Any]:
							if self.unet.config.num_class_embeds is not None:
									if isinstance(A   ,						A       ):
											lowercase_			:			Optional[int]								=       torch.tensor(A   ,						dtype=torch.int       )
									elif isinstance(A   ,						A       ):
											assert batch_size == 1, "Batch size must be 1 if classes is an int"
											lowercase_			:			int								=       torch.tensor([class_labels]   ,						dtype=torch.int       )
									elif class_labels is None:
											# Randomly generate batch_size class labels
											# TODO: should use generator here? int analogue of randn_tensor is not exposed in ...utils
											lowercase_			:			Any								=       torch.randint(0   ,						self.unet.config.num_class_embeds   ,						size=(batch_size,)       )
									lowercase_			:			List[str]								=       class_labels.to(A       )
							else:
									lowercase_			:			Union[str, Any]								=       None
							return class_labels




					def   A  (    self					:						Dict   ,						A					:						Union[str, Any]   ,						A					:						Any   ,						A					:						Optional[int]   ,						A					:						Union[str, Any]   ,						A					:						Any   ,						A					:						int       )  ->  Union[str, Any]:
							if num_inference_steps is None and timesteps is None:
									raise ValueError('''Exactly one of `num_inference_steps` or `timesteps` must be supplied.'''       )

							if num_inference_steps is not None and timesteps is not None:
									logger.warning(
									    F'''Both `num_inference_steps`: {num_inference_steps} and `timesteps`: {timesteps} are supplied;'''
									    ''' `timesteps` will be used over `num_inference_steps`.'''       )

							if latents is not None:
									lowercase_			:			List[Any]								=       (batch_size, 3, img_size, img_size)
									if latents.shape != expected_shape:
											raise ValueError(F'''The shape of latents is {latents.shape} but is expected to be {expected_shape}.'''       )

							if (callback_steps is None) or (
							    callback_steps is not None and (not isinstance(A   ,						A       ) or callback_steps <= 0)
							):
									raise ValueError(
									    F'''`callback_steps` has to be a positive integer but is {callback_steps} of type'''
									    F''' {type(A       )}.'''       )






					@torch.no_grad()
					@replace_example_docstring(A       )
					def __call__(    self					:						Optional[Any]   ,						A					:						int = 1   ,						A					:						Optional[Union[torch.Tensor, List[int], int]] = None   ,						A					:						int = 1   ,						A					:						List[int] = None   ,						A					:						Optional[Union[torch.Generator, List[torch.Generator]]] = None   ,						A					:						Optional[torch.FloatTensor] = None   ,						A					:						Optional[str] = "pil"   ,						A					:						bool = True   ,						A					:						Optional[Callable[[int, int, torch.FloatTensor], None]] = None   ,						A					:						int = 1   ,						)  ->  Tuple:
							lowercase_			:			Dict								=       self.unet.config.sample_size
							lowercase_			:			Union[str, Any]								=       self._execution_device

							# 1. Check inputs
							self.check_inputs(A   ,						A   ,						A   ,						A   ,						A   ,						A       )

							# 2. Prepare image latents
							# Sample image latents x_0 ~ N(0, sigma_0^2 * I)
							lowercase_			:			Optional[int]								=       self.prepare_latents(
							    batch_size=A   ,						num_channels=self.unet.config.in_channels   ,						height=A   ,						width=A   ,						dtype=self.unet.dtype   ,						device=A   ,						generator=A   ,						latents=A   ,						)

							# 3. Handle class_labels for class-conditional models
							lowercase_			:			List[str]								=       self.prepare_class_labels(A   ,						A   ,						class_labels=A       )

							# 4. Prepare timesteps
							if timesteps is not None:
									self.scheduler.set_timesteps(timesteps=A   ,						device=A       )
									lowercase_			:			Optional[int]								=       self.scheduler.timesteps
									lowercase_			:			List[Any]								=       len(A       )
							else:
									self.scheduler.set_timesteps(A       )
									lowercase_			:			Any								=       self.scheduler.timesteps

							# 5. Denoising loop
							# Multistep sampling: implements Algorithm 1 in the paper
							with self.progress_bar(total=A       ) as progress_bar:
									for i, t in enumerate(A       ):
											lowercase_			:			List[str]								=       self.scheduler.scale_model_input(A   ,						A       )
											lowercase_			:			Optional[Any]								=       self.unet(A   ,						A   ,						class_labels=A   ,						return_dict=A       )[0]

											lowercase_			:			Tuple								=       self.scheduler.step(A   ,						A   ,						A   ,						generator=A       )[0]

											# call the callback, if provided
											progress_bar.update()
											if callback is not None and i % callback_steps == 0:
													callback(A   ,						A   ,						A       )

        # 6. Post-process image sample
							lowercase_			:			Union[str, Any]								=       self.postprocess_image(A   ,						output_type=A       )

							# Offload last model to CPU
							if hasattr(self   ,						'''final_offload_hook'''       ) and self.final_offload_hook is not None:
									self.final_offload_hook.offload()

							if not return_dict:
									return (image,)

							return ImagePipelineOutput(images=A       )



