






'''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,
)


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

SCREAMING_SNAKE_CASE__      =   '''
    Examples:
        ```py
        >>> import torch
        >>> import numpy as np

        >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline
        >>> from transformers import pipeline
        >>> from diffusers.utils import load_image


        >>> def make_hint(image, depth_estimator):
        ...     image = depth_estimator(image)["depth"]
        ...     image = np.array(image)
        ...     image = image[:, :, None]
        ...     image = np.concatenate([image, image, image], axis=2)
        ...     detected_map = torch.from_numpy(image).float() / 255.0
        ...     hint = detected_map.permute(2, 0, 1)
        ...     return hint


        >>> depth_estimator = pipeline("depth-estimation")

        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(
        ...     "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16
        ... )
        >>> pipe_prior = pipe_prior.to("cuda")

        >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(
        ...     "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16
        ... )
        >>> pipe = pipe.to("cuda")


        >>> img = load_image(
        ...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
        ...     "/kandinsky/cat.png"
        ... ).resize((768, 768))

        >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")

        >>> prompt = "A robot, 4k photo"
        >>> 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"

        >>> generator = torch.Generator(device="cuda").manual_seed(43)

        >>> image_emb, zero_image_emb = pipe_prior(
        ...     prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator
        ... ).to_tuple()

        >>> images = pipe(
        ...     image_embeds=image_emb,
        ...     negative_image_embeds=zero_image_emb,
        ...     hint=hint,
        ...     num_inference_steps=50,
        ...     generator=generator,
        ...     height=768,
        ...     width=768,
        ... ).images

        >>> images[0].save("robot_cat.png")
        ```
'''







def     lowercase__ (      __UpperCamelCase		,						__UpperCamelCase		,						__UpperCamelCase=8    )-> List[str]:
      UpperCamelCase				  =					height // scale_factor**2
      if height % scale_factor**2 != 0:
            new_height += 1
      UpperCamelCase				  =					width // scale_factor**2
      if width % scale_factor**2 != 0:
            new_width += 1
      return new_height * scale_factor, new_width * scale_factor






class 				a_						(			lowerCamelCase				):

  def __init__(      self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		)  ->      Tuple:



        """simple docstring"""






        super().__init__()

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

  def   A__						(      self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE      )  ->      Optional[Any]:



        """simple docstring"""






        if latents is None:
              UpperCamelCase				  =					randn_tensor(UpperCAmelCase__			,		generator=UpperCAmelCase__			,		device=UpperCAmelCase__			,		dtype=UpperCAmelCase__      )
        else:
              if latents.shape != shape:
                    raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}"      )
              UpperCamelCase				  =					latents.to(UpperCAmelCase__      )

        UpperCamelCase				  =					latents * scheduler.init_noise_sigma
        return latents

  def   A__						(      self			,		_SCREAMING_SNAKE_CASE=0      )  ->      Union[str, Any]:



        """simple docstring"""






        if is_accelerate_available():
              from accelerate import cpu_offload
        else:
              raise ImportError("""Please install accelerate via `pip install accelerate`"""      )

        UpperCamelCase				  =					torch.device(F"cuda:{gpu_id}"      )

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

  def   A__						(      self			,		_SCREAMING_SNAKE_CASE=0      )  ->      Tuple:



        """simple docstring"""






        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."""      )

        UpperCamelCase				  =					torch.device(F"cuda:{gpu_id}"      )

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

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

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

  @property
  # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
  def   A__						(      self      )  ->      List[Any]:



        """simple docstring"""






        if not hasattr(self.unet			,		"""_hf_hook"""      ):
              return self.device
        for module in self.unet.modules():
              if (
                  hasattr(UpperCAmelCase__			,		"""_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(UpperCAmelCase__      )
  def __call__(      self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE = 512			,		_SCREAMING_SNAKE_CASE = 512			,		_SCREAMING_SNAKE_CASE = 100			,		_SCREAMING_SNAKE_CASE = 4.0			,		_SCREAMING_SNAKE_CASE = 1			,		_SCREAMING_SNAKE_CASE = None			,		_SCREAMING_SNAKE_CASE = None			,		_SCREAMING_SNAKE_CASE = "pil"			,		_SCREAMING_SNAKE_CASE = True			,		)  ->      Optional[int]:



        """simple docstring"""






        UpperCamelCase				  =					self._execution_device

        UpperCamelCase				  =					guidance_scale > 1.0

        if isinstance(UpperCAmelCase__			,		UpperCAmelCase__      ):
              UpperCamelCase				  =					torch.cat(UpperCAmelCase__			,		dim=0      )
        if isinstance(UpperCAmelCase__			,		UpperCAmelCase__      ):
              UpperCamelCase				  =					torch.cat(UpperCAmelCase__			,		dim=0      )
        if isinstance(UpperCAmelCase__			,		UpperCAmelCase__      ):
              UpperCamelCase				  =					torch.cat(UpperCAmelCase__			,		dim=0      )

        UpperCamelCase				  =					image_embeds.shape[0] * num_images_per_prompt

        if do_classifier_free_guidance:
              UpperCamelCase				  =					image_embeds.repeat_interleave(UpperCAmelCase__			,		dim=0      )
              UpperCamelCase				  =					negative_image_embeds.repeat_interleave(UpperCAmelCase__			,		dim=0      )
              UpperCamelCase				  =					hint.repeat_interleave(UpperCAmelCase__			,		dim=0      )

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

        UpperCamelCase				  =					self.movq.config.latent_channels

        UpperCamelCase  ,UpperCamelCase				  =					downscale_height_and_width(UpperCAmelCase__			,		UpperCAmelCase__			,		self.movq_scale_factor      )

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

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

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

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

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

        if output_type == "pil":
              UpperCamelCase				  =					self.numpy_to_pil(UpperCAmelCase__      )

        if not return_dict:
              return (image,)

        return ImagePipelineOutput(images=UpperCAmelCase__      )




"""simple docstring"""







import importlib.util
import json
import os
import warnings
from dataclasses import dataclass, field

import torch

from ..training_args import TrainingArguments
from ..utils import cached_property, is_sagemaker_dp_enabled, logging


a__				:							Union[str, Any]						=     logging.get_logger(__name__)




def    UpperCAmelCase__       ():




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE						   =				os.getenv("SM_HP_MP_PARAMETERS"  ,						"{}"   )
					try:
										# Parse it and check the field "partitions" is included, it is required for model parallel.
										__SCREAMING_SNAKE_CASE						   =				json.loads(lowerCAmelCase_   )
										if "partitions" not in smp_options:
															return False
					except json.JSONDecodeError:
										return False

					# Get the sagemaker specific framework parameters from mpi_options variable.
					__SCREAMING_SNAKE_CASE						   =				os.getenv("SM_FRAMEWORK_PARAMS"  ,						"{}"   )
					try:
										# Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
										__SCREAMING_SNAKE_CASE						   =				json.loads(lowerCAmelCase_   )
										if not mpi_options.get("sagemaker_mpi_enabled"  ,						lowerCAmelCase_   ):
															return False
					except json.JSONDecodeError:
										return False
					# Lastly, check if the `smdistributed` module is present.
					return importlib.util.find_spec("smdistributed"   ) is not None


if is_sagemaker_model_parallel_available():
		import smdistributed.modelparallel.torch as smp

		smp.init()




@dataclass
class  UpperCamelCase_	( UpperCamelCase):

	"""simple docstring"""





	snake_case__				:  str    					=			field(
	    default=""			,  metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"}			,  )




	def   UpperCAmelCase_      ( self			:				List[str]   )       ->	Any:
						super().__post_init__()
						warnings.warn(
						    "`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use "
						    "`TrainingArguments` instead."			,			UpperCAmelCase__			,			)




	@cached_property
	def   UpperCAmelCase_      ( self			:				List[str]   )       ->	"torch.device":
						logger.info("PyTorch: setting up devices"   )
						if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1:
											logger.warning(
											    "torch.distributed process group is initialized, but local_rank == -1. "
											    "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch"   )
						if self.no_cuda:
											__SCREAMING_SNAKE_CASE						   =				torch.device("cpu"   )
											__SCREAMING_SNAKE_CASE						   =				0
						elif is_sagemaker_model_parallel_available():
											__SCREAMING_SNAKE_CASE						   =				smp.local_rank()
											__SCREAMING_SNAKE_CASE						   =				torch.device("cuda"			,			UpperCAmelCase__   )
											__SCREAMING_SNAKE_CASE						   =				1
						elif is_sagemaker_dp_enabled():
											import smdistributed.dataparallel.torch.torch_smddp  # noqa: F401

											torch.distributed.init_process_group(backend="smddp"			,			timeout=self.ddp_timeout_delta   )
											__SCREAMING_SNAKE_CASE						   =				int(os.getenv("SMDATAPARALLEL_LOCAL_RANK"   )   )
											__SCREAMING_SNAKE_CASE						   =				torch.device("cuda"			,			self.local_rank   )
											__SCREAMING_SNAKE_CASE						   =				1
						elif self.local_rank == -1:
											# if n_gpu is > 1 we'll use nn.DataParallel.
											# If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
											# Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will
											# trigger an error that a device index is missing. Index 0 takes into account the
											# GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0`
											# will use the first GPU in that env, i.e. GPU#1
											__SCREAMING_SNAKE_CASE						   =				torch.device("cuda:0" if torch.cuda.is_available() else "cpu"   )
											# Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at
											# the default value.
											__SCREAMING_SNAKE_CASE						   =				torch.cuda.device_count()
						else:
											# Here, we'll use torch.distributed.
											# Initializes the distributed backend which will take care of synchronizing nodes/GPUs
											if not torch.distributed.is_initialized():
																torch.distributed.init_process_group(backend="nccl"			,			timeout=self.ddp_timeout_delta   )
											__SCREAMING_SNAKE_CASE						   =				torch.device("cuda"			,			self.local_rank   )
											__SCREAMING_SNAKE_CASE						   =				1

						if device.type == "cuda":
											torch.cuda.set_device(UpperCAmelCase__   )

						return device




	@property
	def   UpperCAmelCase_      ( self			:				Dict   )       ->	Any:
						if is_sagemaker_model_parallel_available():
											return smp.dp_size()

						return super().world_size




	@property
	def   UpperCAmelCase_      ( self			:				Union[str, Any]   )       ->	List[Any]:
						return not is_sagemaker_model_parallel_available()




	@property
	def   UpperCAmelCase_      ( self			:				Tuple   )       ->	int:
						return False
