





"""simple docstring"""





import random
import timeit
from functools import wraps
from typing import Callable, Optional

from ..configuration_utils import PretrainedConfig
from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING
from ..utils import is_pyanvml_available, is_tf_available, logging
from .benchmark_utils import (
    Benchmark,
    Memory,
    MemorySummary,
    measure_peak_memory_cpu,
    start_memory_tracing,
    stop_memory_tracing,
)


if is_tf_available():
							import tensorflow as tf
							from tensorflow.python.framework.errors_impl import ResourceExhaustedError

							from .benchmark_args_tf import TensorFlowBenchmarkArguments

if is_pyanvml_available():
							import pyanvml.pyanvml as nvml

_UpperCamelCase							=      logging.get_logger(__name__)



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							bool    ,						SCREAMING_SNAKE_CASE       :							bool   ):


							'''simple docstring'''







							def run_func(SCREAMING_SNAKE_CASE       :							str   ):
														@wraps(SCREAMING_SNAKE_CASE   )
														def run_in_eager_mode(*SCREAMING_SNAKE_CASE       :							str    ,						**SCREAMING_SNAKE_CASE       :							Any   ):
																					return func(*SCREAMING_SNAKE_CASE    ,						**SCREAMING_SNAKE_CASE   )

														@wraps(SCREAMING_SNAKE_CASE   )
														@tf.function(experimental_compile=SCREAMING_SNAKE_CASE   )
														def run_in_graph_mode(*SCREAMING_SNAKE_CASE       :							Tuple    ,						**SCREAMING_SNAKE_CASE       :							Any   ):
																					return func(*SCREAMING_SNAKE_CASE    ,						**SCREAMING_SNAKE_CASE   )

														if do_eager_mode is True:
																					if use_xla is not False:
																												raise ValueError(
																												    '''Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.'''   )
																					return run_in_eager_mode
														else:
																					return run_in_graph_mode

							return run_func



def 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							int    ,						SCREAMING_SNAKE_CASE       :							int    ,						SCREAMING_SNAKE_CASE       :							int   ):


							'''simple docstring'''







							__lowerCamelCase      :      str         =random.Random()
							__lowerCamelCase      :      Dict         =[rng.randint(0    ,						vocab_size - 1   ) for i in range(batch_size * sequence_length   )]
							return tf.constant(SCREAMING_SNAKE_CASE    ,						shape=(batch_size, sequence_length)    ,						dtype=tf.intaa   )
class 		SCREAMING_SNAKE_CASE_							(    snake_case__   ):
				"""simple docstring"""
				__snake_case   :       TensorFlowBenchmarkArguments
				__snake_case   :       PretrainedConfig
				__snake_case   :       str	 =		"TensorFlow"




				@property
				def 					__lowercase  (     self  :Dict			):
											return tf.__version__




				def 					__lowercase  (     self  :Tuple						,    __lowercase  :str						,    __lowercase  :int						,    __lowercase  :int			):
											# initialize GPU on separate process
											__lowerCamelCase      :      List[Any]         =self.args.strategy
											if strategy is None:
																		raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''			)
											__lowerCamelCase      :      List[str]         =self._prepare_inference_func(__lowercase						,    __lowercase						,    __lowercase			)
											return self._measure_speed(_inference			)




				def 					__lowercase  (     self  :List[str]						,    __lowercase  :str						,    __lowercase  :int						,    __lowercase  :int			):
											__lowerCamelCase      :      str         =self.args.strategy
											if strategy is None:
																		raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''			)
											__lowerCamelCase      :      Tuple         =self._prepare_train_func(__lowercase						,    __lowercase						,    __lowercase			)
											return self._measure_speed(_train			)




				def 					__lowercase  (     self  :Dict						,    __lowercase  :str						,    __lowercase  :int						,    __lowercase  :int			):
											# initialize GPU on separate process
											if self.args.is_gpu:
																		tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]						,    __lowercase			)
											__lowerCamelCase      :      List[str]         =self.args.strategy
											if strategy is None:
																		raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''			)
											__lowerCamelCase      :      Any         =self._prepare_inference_func(__lowercase						,    __lowercase						,    __lowercase			)
											return self._measure_memory(_inference			)




				def 					__lowercase  (     self  :Any						,    __lowercase  :str						,    __lowercase  :int						,    __lowercase  :int			):
											if self.args.is_gpu:
																		tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]						,    __lowercase			)
											__lowerCamelCase      :      List[str]         =self.args.strategy
											if strategy is None:
																		raise ValueError('''A device strategy has to be initialized before using TensorFlow.'''			)

											__lowerCamelCase      :      Optional[Any]         =self._prepare_train_func(__lowercase						,    __lowercase						,    __lowercase			)
											return self._measure_memory(_train			)




				def 					__lowercase  (     self  :Union[str, Any]						,    __lowercase  :str						,    __lowercase  :int						,    __lowercase  :int			):
											__lowerCamelCase      :      Optional[Any]         =self.config_dict[model_name]

											if self.args.fpaa:
																		raise NotImplementedError('''Mixed precision is currently not supported.'''			)

											__lowerCamelCase      :      int         =(
											    hasattr(__lowercase						,    '''architectures'''			)
											    and isinstance(config.architectures						,    __lowercase			)
											    and len(config.architectures			) > 0
											)
											if not self.args.only_pretrain_model and has_model_class_in_config:
																		try:
																									__lowerCamelCase      :      Dict         ='''TF''' + config.architectures[0]  # prepend 'TF' for tensorflow model
																									__lowerCamelCase      :      List[str]         =__import__('''transformers'''						,    fromlist=[model_class]			)
																									__lowerCamelCase      :      List[str]         =getattr(__lowercase						,    __lowercase			)
																									__lowerCamelCase      :      List[str]         =model_cls(__lowercase			)
																		except ImportError:
																									raise ImportError(
																									    f'{model_class} does not exist. If you just want to test the pretrained model, you might want to'
																									    ''' set `--only_pretrain_model` or `args.only_pretrain_model=True`.'''			)
											else:
																		__lowerCamelCase      :      Dict         =TF_MODEL_MAPPING[config.__class__](__lowercase			)

											# encoder-decoder has vocab size saved differently
											__lowerCamelCase      :      int         =config.vocab_size if hasattr(__lowercase						,    '''vocab_size'''			) else config.encoder.vocab_size
											__lowerCamelCase      :      List[Any]         =random_input_ids(__lowercase						,    __lowercase						,    __lowercase			)

											@run_with_tf_optimizations(self.args.eager_mode						,    self.args.use_xla			)
											def encoder_decoder_forward():
																		return model(__lowercase						,    decoder_input_ids=__lowercase						,    training=__lowercase			)

											@run_with_tf_optimizations(self.args.eager_mode						,    self.args.use_xla			)
											def encoder_forward():
																		return model(__lowercase						,    training=__lowercase			)

											__lowerCamelCase      :      Tuple         =encoder_decoder_forward if config.is_encoder_decoder else encoder_forward

											return _inference




				def 					__lowercase  (     self  :str						,    __lowercase  :str						,    __lowercase  :int						,    __lowercase  :int			):
											__lowerCamelCase      :      List[str]         =self.config_dict[model_name]

											if self.args.eager_mode is not False:
																		raise ValueError('''Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.'''			)

											if self.args.fpaa:
																		raise NotImplementedError('''Mixed precision is currently not supported.'''			)

											__lowerCamelCase      :      str         =(
											    hasattr(__lowercase						,    '''architectures'''			)
											    and isinstance(config.architectures						,    __lowercase			)
											    and len(config.architectures			) > 0
											)
											if not self.args.only_pretrain_model and has_model_class_in_config:
																		try:
																									__lowerCamelCase      :      int         ='''TF''' + config.architectures[0]  # prepend 'TF' for tensorflow model
																									__lowerCamelCase      :      Union[str, Any]         =__import__('''transformers'''						,    fromlist=[model_class]			)
																									__lowerCamelCase      :      List[Any]         =getattr(__lowercase						,    __lowercase			)
																									__lowerCamelCase      :      List[str]         =model_cls(__lowercase			)
																		except ImportError:
																									raise ImportError(
																									    f'{model_class} does not exist. If you just want to test the pretrained model, you might want to'
																									    ''' set `--only_pretrain_model` or `args.only_pretrain_model=True`.'''			)
											else:
																		__lowerCamelCase      :      str         =TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](__lowercase			)

											# encoder-decoder has vocab size saved differently
											__lowerCamelCase      :      Any         =config.vocab_size if hasattr(__lowercase						,    '''vocab_size'''			) else config.encoder.vocab_size
											__lowerCamelCase      :      Tuple         =random_input_ids(__lowercase						,    __lowercase						,    __lowercase			)

											@run_with_tf_optimizations(self.args.eager_mode						,    self.args.use_xla			)
											def encoder_decoder_train():
																		__lowerCamelCase      :      Optional[Any]         =model(__lowercase						,    decoder_input_ids=__lowercase						,    labels=__lowercase						,    training=__lowercase			)[0]
																		__lowerCamelCase      :      Any         =tf.gradients(__lowercase						,    model.trainable_variables			)
																		return gradients

											@run_with_tf_optimizations(self.args.eager_mode						,    self.args.use_xla			)
											def encoder_train():
																		__lowerCamelCase      :      Optional[Any]         =model(__lowercase						,    labels=__lowercase						,    training=__lowercase			)[0]
																		__lowerCamelCase      :      List[Any]         =tf.gradients(__lowercase						,    model.trainable_variables			)
																		return gradients

											__lowerCamelCase      :      List[Any]         =encoder_decoder_train if config.is_encoder_decoder else encoder_train

											return _train




				def 					__lowercase  (     self  :Optional[Any]						,    __lowercase  :Tuple			):
											with self.args.strategy.scope():
																		try:
																									if self.args.is_tpu or self.args.use_xla:
																																# run additional 10 times to stabilize compilation for tpu
																																logger.info('''Do inference on TPU. Running model 5 times to stabilize compilation'''			)
																																timeit.repeat(__lowercase						,    repeat=1						,    number=5			)

																									# as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average
																									__lowerCamelCase      :      List[Any]         =timeit.repeat(
																									    __lowercase						,    repeat=self.args.repeat						,    number=10						,    )

																									return min(__lowercase			) / 10.0
																		except ResourceExhaustedError as e:
																									self.print_fn(f'Doesn\'t fit on GPU. {e}'			)




				def 					__lowercase  (     self  :List[str]						,    __lowercase  :Callable[[], None]			):
											logger.info(
											    '''Note that TensorFlow allocates more memory than '''
											    '''it might need to speed up computation. '''
											    '''The memory reported here corresponds to the memory '''
											    '''reported by `nvidia-smi`, which can vary depending '''
											    '''on total available memory on the GPU that is used.'''			)
											with self.args.strategy.scope():
																		try:
																									if self.args.trace_memory_line_by_line:
																																if not self.args.eager_mode:
																																							raise ValueError(
																																							    '''`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory'''
																																							    ''' consumption line by line.'''			)
																																__lowerCamelCase      :      List[str]         =start_memory_tracing('''transformers'''			)

																									if self.args.is_tpu:
																																# tpu
																																raise NotImplementedError(
																																    '''Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking'''
																																    ''' with `args.memory=False`'''			)
																									elif self.args.is_gpu:
																																# gpu
																																if not is_pyanvml_available():
																																							logger.warning(
																																							    '''py3nvml not installed, we won\'t log GPU memory usage. '''
																																							    '''Install py3nvml (pip install py3nvml) to log information about GPU.'''			)
																																							__lowerCamelCase      :      Optional[int]         ='''N/A'''
																																else:
																																							logger.info(
																																							    '''Measuring total GPU usage on GPU device. Make sure to not have additional processes'''
																																							    ''' running on the same GPU.'''			)
																																							# init nvml
																																							nvml.nvmlInit()
																																							func()
																																							__lowerCamelCase      :      Any         =nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx			)
																																							__lowerCamelCase      :      List[str]         =nvml.nvmlDeviceGetMemoryInfo(__lowercase			)
																																							__lowerCamelCase      :      Dict         =meminfo.used
																																							__lowerCamelCase      :      List[Any]         =Memory(__lowercase			)
																																							# shutdown nvml
																																							nvml.nvmlShutdown()
																									else:
																																# cpu
																																if self.args.trace_memory_line_by_line:
																																							logger.info(
																																							    '''When enabling line by line tracing, the max peak memory for CPU is inaccurate in'''
																																							    ''' TensorFlow.'''			)
																																							__lowerCamelCase      :      Dict         =None
																																else:
																																							__lowerCamelCase      :      Optional[Any]         =measure_peak_memory_cpu(__lowercase			)
																																							__lowerCamelCase      :      Any         =Memory(__lowercase			) if isinstance(__lowercase						,    __lowercase			) else memory_bytes
																									if self.args.trace_memory_line_by_line:
																																__lowerCamelCase      :      Dict         =stop_memory_tracing(__lowercase			)
																																if memory is None:
																																							__lowerCamelCase      :      str         =summary.total
																									else:
																																__lowerCamelCase      :      str         =None

																									return memory, summary
																		except ResourceExhaustedError as e:
																									self.print_fn(f'Doesn\'t fit on GPU. {e}'			)
																									return "N/A", None











"""simple docstring"""





from typing import List, Optional, Union

import torch

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


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

_UpperCamelCase							=      '\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 				lowerCAmelCase_			(      SCREAMING_SNAKE_CASE       :							Any    ,						SCREAMING_SNAKE_CASE       :							Tuple    ,						SCREAMING_SNAKE_CASE       :							Tuple=8   ):


							'''simple docstring'''







							__lowerCamelCase      :      Tuple         =height // scale_factor**2
							if height % scale_factor**2 != 0:
														new_height += 1
							__lowerCamelCase      :      Tuple         =width // scale_factor**2
							if width % scale_factor**2 != 0:
														new_width += 1
							return new_height * scale_factor, new_width * scale_factor
class 		SCREAMING_SNAKE_CASE_							(    snake_case__   ):
				"""simple docstring"""




				def __init__(     self  :Union[str, Any]						,    __lowercase  :UNetaDConditionModel						,    __lowercase  :DDPMScheduler						,    __lowercase  :VQModel						,    ):
											super().__init__()

											self.register_modules(
											    unet=__lowercase						,    scheduler=__lowercase						,    movq=__lowercase						,    )
											__lowerCamelCase      :      Any         =2 ** (len(self.movq.config.block_out_channels			) - 1)




				def 					__lowercase  (     self  :int						,    __lowercase  :Tuple						,    __lowercase  :Dict						,    __lowercase  :str						,    __lowercase  :Dict						,    __lowercase  :Union[str, Any]						,    __lowercase  :Dict			):
											if latents is None:
																		__lowerCamelCase      :      str         =randn_tensor(__lowercase						,    generator=__lowercase						,    device=__lowercase						,    dtype=__lowercase			)
											else:
																		if latents.shape != shape:
																									raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}'			)
																		__lowerCamelCase      :      str         =latents.to(__lowercase			)

											__lowerCamelCase      :      Any         =latents * scheduler.init_noise_sigma
											return latents




				def 					__lowercase  (     self  :Dict						,    __lowercase  :Any=0			):
											if is_accelerate_available():
																		from accelerate import cpu_offload
											else:
																		raise ImportError('''Please install accelerate via `pip install accelerate`'''			)

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

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




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

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

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

											__lowerCamelCase      :      Optional[Any]         =None
											for cpu_offloaded_model in [self.unet, self.movq]:
																		__lowerCamelCase    ,						__lowerCamelCase      :      Union[str, Any]         =cpu_offload_with_hook(__lowercase						,    __lowercase						,    prev_module_hook=__lowercase			)

											# We'll offload the last model manually.
											__lowerCamelCase      :      Dict         =hook




				@property
				# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
				def 					__lowercase  (     self  :Tuple			):
											if not hasattr(self.unet						,    '''_hf_hook'''			):
																		return self.device
											for module in self.unet.modules():
																		if (
																		    hasattr(__lowercase						,    '''_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(__lowercase			)
				def __call__(     self  :Union[str, Any]						,    __lowercase  :Union[torch.FloatTensor, List[torch.FloatTensor]]						,    __lowercase  :Union[torch.FloatTensor, List[torch.FloatTensor]]						,    __lowercase  :torch.FloatTensor						,    __lowercase  :int = 512						,    __lowercase  :int = 512						,    __lowercase  :int = 100						,    __lowercase  :float = 4.0						,    __lowercase  :int = 1						,    __lowercase  :Optional[Union[torch.Generator, List[torch.Generator]]] = None						,    __lowercase  :Optional[torch.FloatTensor] = None						,    __lowercase  :Optional[str] = "pil"						,    __lowercase  :bool = True						,    ):
											__lowerCamelCase      :      Any         =self._execution_device

											__lowerCamelCase      :      Dict         =guidance_scale > 1.0

											if isinstance(__lowercase						,    __lowercase			):
																		__lowerCamelCase      :      Any         =torch.cat(__lowercase						,    dim=0			)
											if isinstance(__lowercase						,    __lowercase			):
																		__lowerCamelCase      :      Dict         =torch.cat(__lowercase						,    dim=0			)
											if isinstance(__lowercase						,    __lowercase			):
																		__lowerCamelCase      :      Dict         =torch.cat(__lowercase						,    dim=0			)

											__lowerCamelCase      :      List[Any]         =image_embeds.shape[0] * num_images_per_prompt

											if do_classifier_free_guidance:
																		__lowerCamelCase      :      Optional[int]         =image_embeds.repeat_interleave(__lowercase						,    dim=0			)
																		__lowerCamelCase      :      Any         =negative_image_embeds.repeat_interleave(__lowercase						,    dim=0			)
																		__lowerCamelCase      :      List[Any]         =hint.repeat_interleave(__lowercase						,    dim=0			)

											__lowerCamelCase      :      List[str]         =torch.cat([negative_image_embeds, image_embeds]						,    dim=0			).to(dtype=self.unet.dtype						,    device=__lowercase			)
											__lowerCamelCase      :      List[str]         =torch.cat([hint, hint]						,    dim=0			).to(dtype=self.unet.dtype						,    device=__lowercase			)
											self.scheduler.set_timesteps(__lowercase						,    device=__lowercase			)
											__lowerCamelCase      :      str         =self.scheduler.timesteps

											__lowerCamelCase      :      Tuple         =self.movq.config.latent_channels

											__lowerCamelCase    ,						__lowerCamelCase      :      List[str]         =downscale_height_and_width(__lowercase						,    __lowercase						,    self.movq_scale_factor			)

											# create initial latent
											__lowerCamelCase      :      Optional[int]         =self.prepare_latents(
											    (batch_size, num_channels_latents, height, width)						,    image_embeds.dtype						,    __lowercase						,    __lowercase						,    __lowercase						,    self.scheduler						,    )

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

																		__lowerCamelCase      :      List[Any]         ={'''image_embeds''': image_embeds, '''hint''': hint}
																		__lowerCamelCase      :      Union[str, Any]         =self.unet(
																		    sample=__lowercase						,    timestep=__lowercase						,    encoder_hidden_states=__lowercase						,    added_cond_kwargs=__lowercase						,    return_dict=__lowercase						,    )[0]

																		if do_classifier_free_guidance:
																									__lowerCamelCase    ,						__lowerCamelCase      :      Dict         =noise_pred.split(latents.shape[1]						,    dim=1			)
																									__lowerCamelCase    ,						__lowerCamelCase      :      int         =noise_pred.chunk(2			)
																									__lowerCamelCase    ,						__lowerCamelCase      :      Tuple         =variance_pred.chunk(2			)
																									__lowerCamelCase      :      Tuple         =noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
																									__lowerCamelCase      :      Any         =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"]
																		):
																									__lowerCamelCase    ,						__lowerCamelCase      :      Any         =noise_pred.split(latents.shape[1]						,    dim=1			)

																		# compute the previous noisy sample x_t -> x_t-1
																		__lowerCamelCase      :      Tuple         =self.scheduler.step(
																		    __lowercase						,    __lowercase						,    __lowercase						,    generator=__lowercase						,    )[0]
											# post-processing
											__lowerCamelCase      :      List[str]         =self.movq.decode(__lowercase						,    force_not_quantize=__lowercase			)['''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"]:
																		__lowerCamelCase      :      List[str]         =image * 0.5 + 0.5
																		__lowerCamelCase      :      Optional[int]         =image.clamp(0						,    1			)
																		__lowerCamelCase      :      Union[str, Any]         =image.cpu().permute(0						,    2						,    3						,    1			).float().numpy()

											if output_type == "pil":
																		__lowerCamelCase      :      Optional[Any]         =self.numpy_to_pil(__lowercase			)

											if not return_dict:
																		return (image,)

											return ImagePipelineOutput(images=__lowercase			)




