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


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

_a		       =							'\n    Examples:\n        ```py\n        >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline\n        >>> import torch\n\n        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-prior")\n        >>> pipe_prior.to("cuda")\n        >>> prompt = "red cat, 4k photo"\n        >>> out = pipe_prior(prompt)\n        >>> image_emb = out.image_embeds\n        >>> zero_image_emb = out.negative_image_embeds\n        >>> pipe = KandinskyV22Pipeline.from_pretrained("kandinsky-community/kandinsky-2-2-decoder")\n        >>> pipe.to("cuda")\n        >>> image = pipe(\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=zero_image_emb,\n        ...     height=768,\n        ...     width=768,\n        ...     num_inference_steps=50,\n        ... ).images\n        >>> image[0].save("cat.png")\n        ```\n'







def 	__a     (		__lowerCamelCase,		__lowerCamelCase,		__lowerCamelCase=8  ):
   UpperCAmelCase_					:					Union[str, Any]			     =    height // scale_factor**2
   if height % scale_factor**2 != 0:
      new_height += 1
   UpperCAmelCase_					:					Tuple			     =    width // scale_factor**2
   if width % scale_factor**2 != 0:
      new_width += 1
   return new_height * scale_factor, new_width * scale_factor


class A_	(lowercase__      ):




  '''simple docstring'''







  def __init__(		self				,   lowercase_				,   lowercase_				,   lowercase_				,   ):

     """simple docstring"""
     super().__init__()

     self.register_modules(
         unet=lowercase_				,   scheduler=lowercase_				,   movq=lowercase_				,   )
     UpperCAmelCase_					:					Union[str, Any]			     =    2 ** (len(self.movq.config.block_out_channels  ) - 1)







  def        UpperCamelCase__					(		self				,   lowercase_				,   lowercase_				,   lowercase_				,   lowercase_				,   lowercase_				,   lowercase_  ):

     """simple docstring"""
     if latents is None:
        UpperCAmelCase_					:					List[Any]			     =    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}"""  )
        UpperCAmelCase_					:					int			     =    latents.to(lowercase_  )

     UpperCAmelCase_					:					List[Any]			     =    latents * scheduler.init_noise_sigma
     return latents







  def        UpperCamelCase__					(		self				,   lowercase_=0  ):

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

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

     UpperCAmelCase_					:					Optional[Any]			     =    [
         self.unet,
         self.movq,
     ]
     for cpu_offloaded_model in models:
        if cpu_offloaded_model is not None:
           cpu_offload(lowercase_				,   lowercase_  )







  def        UpperCamelCase__					(		self				,   lowercase_=0  ):

     """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_					:					Tuple			     =    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)

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

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







  @property
  # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     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				,   lowercase_				,   lowercase_				,   lowercase_ = 512				,   lowercase_ = 512				,   lowercase_ = 100				,   lowercase_ = 4.0				,   lowercase_ = 1				,   lowercase_ = None				,   lowercase_ = None				,   lowercase_ = "pil"				,   lowercase_ = True				,   ):

     """simple docstring"""
     UpperCAmelCase_					:					Optional[Any]			     =    self._execution_device

     UpperCAmelCase_					:					Dict			     =    guidance_scale > 1.0

     if isinstance(lowercase_				,   lowercase_  ):
        UpperCAmelCase_					:					Optional[int]			     =    torch.cat(lowercase_				,   dim=0  )
     UpperCAmelCase_					:					List[str]			     =    image_embeds.shape[0] * num_images_per_prompt
     if isinstance(lowercase_				,   lowercase_  ):
        UpperCAmelCase_					:					Any			     =    torch.cat(lowercase_				,   dim=0  )

     if do_classifier_free_guidance:
        UpperCAmelCase_					:					Optional[Any]			     =    image_embeds.repeat_interleave(lowercase_				,   dim=0  )
        UpperCAmelCase_					:					Tuple			     =    negative_image_embeds.repeat_interleave(lowercase_				,   dim=0  )

     UpperCAmelCase_					:					Union[str, Any]			     =    torch.cat([negative_image_embeds, image_embeds]				,   dim=0  ).to(dtype=self.unet.dtype				,   device=lowercase_  )

     self.scheduler.set_timesteps(lowercase_				,   device=lowercase_  )
     UpperCAmelCase_					:					Any			     =    self.scheduler.timesteps

     UpperCAmelCase_					:					List[Any]			     =    self.unet.config.in_channels

     UpperCAmelCase_     ,   UpperCAmelCase_					:					Optional[Any]			     =    downscale_height_and_width(lowercase_				,   lowercase_				,   self.movq_scale_factor  )

     # create initial latent
     UpperCAmelCase_					:					str			     =    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
        UpperCAmelCase_					:					Union[str, Any]			     =    torch.cat([latents] * 2  ) if do_classifier_free_guidance else latents

        UpperCAmelCase_					:					Union[str, Any]			     =    {"image_embeds": image_embeds}
        UpperCAmelCase_					:					Optional[Any]			     =    self.unet(
            sample=lowercase_				,   timestep=lowercase_				,   encoder_hidden_states=lowercase_				,   added_cond_kwargs=lowercase_				,   return_dict=lowercase_				,   )[0]

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

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

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

     if not return_dict:
        return (image,)

     return ImagePipelineOutput(images=lowercase_  )




from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


A     :	List[str]    = logging.get_logger(__name__)

A     :	Optional[int]    = {
    'facebook/levit-128S': 'https://huggingface.co/facebook/levit-128S/resolve/main/config.json',
    # See all LeViT models at https://huggingface.co/models?filter=levit
}







class 			__A( a			):
				snake_case_						   =    '''levit'''




				def __init__(     self		,     _snake_case=224		,     _snake_case=3		,     _snake_case=3		,     _snake_case=2		,     _snake_case=1		,     _snake_case=16		,     _snake_case=[128, 256, 384]		,     _snake_case=[4, 8, 12]		,     _snake_case=[4, 4, 4]		,     _snake_case=[16, 16, 16]		,     _snake_case=0		,     _snake_case=[2, 2, 2]		,     _snake_case=[2, 2, 2]		,     _snake_case=0.02		,     **_snake_case		,     )    ->      Optional[Any]:


								'''simple docstring'''




								super().__init__(**_snake_case				)
								__a										=    image_size
								__a										=    num_channels
								__a										=    kernel_size
								__a										=    stride
								__a										=    padding
								__a										=    hidden_sizes
								__a										=    num_attention_heads
								__a										=    depths
								__a										=    key_dim
								__a										=    drop_path_rate
								__a										=    patch_size
								__a										=    attention_ratio
								__a										=    mlp_ratio
								__a										=    initializer_range
								__a										=    [
								    ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],
								    ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],
								]







class 			__A( a			):
				snake_case_						   =    version.parse('''1.11'''			)




				@property
				def 				SCREAMING_SNAKE_CASE_		(     self				)    ->      Mapping[str, Mapping[int, str]]:


								'''simple docstring'''




								return OrderedDict(
								    [
								        ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
								    ]				)




				@property
				def 				SCREAMING_SNAKE_CASE_		(     self				)    ->      float:


								'''simple docstring'''




								return 1E-4