






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		:       List[str]			     = logging.get_logger(__name__)  # pylint: disable=invalid-name

a		:       Optional[int]			     = "\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 				lowerCamelCase__      (    __lowerCamelCase			:     str  ,		__lowerCamelCase			:     Optional[Any]  ,		__lowerCamelCase			:     str=8		):
  __UpperCAmelCase							:	Optional[Any]           =  height // scale_factor**2
  if height % scale_factor**2 != 0:
    new_height += 1
  __UpperCAmelCase							:	Dict           =  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					:			List[Any]		,      __lowercase					:			UNetaDConditionModel		,      __lowercase					:			DDPMScheduler		,      __lowercase					:			VQModel		,      )							->      Optional[int]:
        super().__init__()

        self.register_modules(
            unet=__lowercase		,      scheduler=__lowercase		,      movq=__lowercase		,      )
        __UpperCAmelCase							:	int           =  2 ** (len(self.movq.config.block_out_channels					) - 1)
      def 	UpperCAmelCase      (      self					:			int		,      __lowercase					:			Optional[int]		,      __lowercase					:			int		,      __lowercase					:			Optional[int]		,      __lowercase					:			str		,      __lowercase					:			List[str]		,      __lowercase					:			str					)							->      Any:
        if latents is None:
          __UpperCAmelCase							:	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							:	int           =  latents * scheduler.init_noise_sigma
        return latents
      def 	UpperCAmelCase      (      self					:			Any		,      __lowercase					:			int=0					)							->      Tuple:
        if is_accelerate_available():
          from accelerate import cpu_offload
        else:
          raise ImportError("""Please install accelerate via `pip install accelerate`"""					)

        __UpperCAmelCase							:	Union[str, Any]           =  torch.device(f"""cuda:{gpu_id}"""					)

        __UpperCAmelCase							:	List[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					:			Union[str, Any]		,      __lowercase					:			Dict=0					)							->      str:
        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							:	Dict           =  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							:	str           =  None
        for cpu_offloaded_model in [self.unet, self.movq]:
          __UpperCAmelCase      , __UpperCAmelCase							:	Tuple           =  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					:			Optional[int]					)							->      int:
        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					:			int		,      __lowercase					:			Union[torch.FloatTensor, List[torch.FloatTensor]]		,      __lowercase					:			Union[torch.FloatTensor, List[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		,      )							->      List[Any]:
        __UpperCAmelCase							:	Union[str, Any]           =  self._execution_device

        __UpperCAmelCase							:	List[str]           =  guidance_scale > 1.0

        if isinstance(__lowercase		,      __lowercase					):
          __UpperCAmelCase							:	Any           =  torch.cat(__lowercase		,      dim=0					)
        __UpperCAmelCase							:	List[Any]           =  image_embeds.shape[0] * num_images_per_prompt
        if isinstance(__lowercase		,      __lowercase					):
          __UpperCAmelCase							:	List[str]           =  torch.cat(__lowercase		,      dim=0					)

        if do_classifier_free_guidance:
          __UpperCAmelCase							:	Any           =  image_embeds.repeat_interleave(__lowercase		,      dim=0					)
          __UpperCAmelCase							:	Tuple           =  negative_image_embeds.repeat_interleave(__lowercase		,      dim=0					)

        __UpperCAmelCase							:	List[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							:	str           =  self.scheduler.timesteps

        __UpperCAmelCase							:	Optional[Any]           =  self.unet.config.in_channels

        __UpperCAmelCase      , __UpperCAmelCase							:	Optional[int]           =  downscale_height_and_width(__lowercase		,      __lowercase		,      self.movq_scale_factor					)

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

          __UpperCAmelCase							:	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							:	Optional[int]           =  noise_pred.split(latents.shape[1]		,      dim=1					)
            __UpperCAmelCase      , __UpperCAmelCase							:	Tuple           =  noise_pred.chunk(2					)
            __UpperCAmelCase      , __UpperCAmelCase							:	Tuple           =  variance_pred.chunk(2					)
            __UpperCAmelCase							:	List[str]           =  noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
            __UpperCAmelCase							:	Optional[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							:	str           =  noise_pred.split(latents.shape[1]		,      dim=1					)

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

        if output_type == "pil":
          __UpperCAmelCase							:	Optional[int]           =  self.numpy_to_pil(__lowercase					)

        if not return_dict:
          return (image,)

        return ImagePipelineOutput(images=__lowercase					)










from ...configuration_utils import PretrainedConfig
from ...utils import logging


a		:       Optional[int]			     = logging.get_logger(__name__)

a		:       List[Any]			     = {
    "facebook/xglm-564M": "https://huggingface.co/facebook/xglm-564M/resolve/main/config.json",
    # See all XGLM models at https://huggingface.co/models?filter=xglm
}
class     a    ( lowercase__   ):



      """simple docstring"""


      a  : List[Any]							       =	'xglm'
      a  : str							       =	['past_key_values']

      a  : Any							       =	{
          'num_attention_heads': 'attention_heads',
          'hidden_size': 'd_model',
          'num_hidden_layers': 'num_layers',
      }
      def __init__(      self					:			Optional[int]		,      __lowercase					:			int=256008		,      __lowercase					:			Tuple=2048		,      __lowercase					:			List[Any]=1024		,      __lowercase					:			str=4096		,      __lowercase					:			Optional[Any]=24		,      __lowercase					:			Optional[int]=16		,      __lowercase					:			List[Any]="gelu"		,      __lowercase					:			str=0.1		,      __lowercase					:			Dict=0.1		,      __lowercase					:			Tuple=0.0		,      __lowercase					:			Optional[int]=0.0		,      __lowercase					:			Dict=0.02		,      __lowercase					:			Optional[int]=True		,      __lowercase					:			Any=True		,      __lowercase					:			Dict=2		,      __lowercase					:			Optional[Any]=1		,      __lowercase					:			List[Any]=0		,      __lowercase					:			Optional[Any]=2		,      **__lowercase					:			List[str]		,      )							->      Optional[int]:
        __UpperCAmelCase							:	List[str]           =  vocab_size
        __UpperCAmelCase							:	Optional[Any]           =  max_position_embeddings
        __UpperCAmelCase							:	Optional[Any]           =  d_model
        __UpperCAmelCase							:	str           =  ffn_dim
        __UpperCAmelCase							:	List[str]           =  num_layers
        __UpperCAmelCase							:	Dict           =  attention_heads
        __UpperCAmelCase							:	str           =  activation_function
        __UpperCAmelCase							:	Optional[Any]           =  dropout
        __UpperCAmelCase							:	Any           =  attention_dropout
        __UpperCAmelCase							:	int           =  activation_dropout
        __UpperCAmelCase							:	Tuple           =  layerdrop
        __UpperCAmelCase							:	Tuple           =  init_std
        __UpperCAmelCase							:	List[str]           =  scale_embedding  # scale factor will be sqrt(d_model) if True
        __UpperCAmelCase							:	Union[str, Any]           =  use_cache

        super().__init__(
            pad_token_id=__lowercase		,      bos_token_id=__lowercase		,      eos_token_id=__lowercase		,      decoder_start_token_id=__lowercase		,      **__lowercase		,      )


