





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        >>> 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__       (    SCREAMING_SNAKE_CASE_   :      List[str]				,	SCREAMING_SNAKE_CASE_   :      Optional[int]				,	SCREAMING_SNAKE_CASE_   :      List[Any]=8						)  ->  int:






   """simple docstring"""







   _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 			__UpperCamelCase    (							A__    ):





     def __init__(     self				,							_UpperCamelCase				,							_UpperCamelCase				,							_UpperCamelCase				,							):
        super().__init__()

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





     def 		UpperCamelCase(     self				,							_UpperCamelCase				,							_UpperCamelCase				,							_UpperCamelCase				,							_UpperCamelCase				,							_UpperCamelCase				,							_UpperCamelCase					):
        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 		UpperCamelCase(     self				,							_UpperCamelCase=0					):
        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 		UpperCamelCase(     self				,							_UpperCamelCase=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.'''					)

        _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 		UpperCamelCase(     self					):
        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				,							_UpperCamelCase				,							_UpperCamelCase				,							_UpperCamelCase = 512				,							_UpperCamelCase = 512				,							_UpperCamelCase = 100				,							_UpperCamelCase = 4.0				,							_UpperCamelCase = 1				,							_UpperCamelCase = None				,							_UpperCamelCase = None				,							_UpperCamelCase = "pil"				,							_UpperCamelCase = True				,							):
        _UpperCAmelCase           =   self._execution_device

        _UpperCAmelCase           =   guidance_scale > 1.0

        if isinstance(_UpperCamelCase				,							_UpperCamelCase					):
           _UpperCAmelCase           =   torch.cat(_UpperCamelCase				,							dim=0					)
        _UpperCAmelCase           =   image_embeds.shape[0] * num_images_per_prompt
        if isinstance(_UpperCamelCase				,							_UpperCamelCase					):
           _UpperCAmelCase           =   torch.cat(_UpperCamelCase				,							dim=0					)

        if do_classifier_free_guidance:
           _UpperCAmelCase           =   image_embeds.repeat_interleave(_UpperCamelCase				,							dim=0					)
           _UpperCAmelCase           =   negative_image_embeds.repeat_interleave(_UpperCamelCase				,							dim=0					)

        _UpperCAmelCase           =   torch.cat([negative_image_embeds, image_embeds]				,							dim=0					).to(dtype=self.unet.dtype				,							device=_UpperCamelCase					)

        self.scheduler.set_timesteps(_UpperCamelCase				,							device=_UpperCamelCase					)
        _UpperCAmelCase           =   self.scheduler.timesteps

        _UpperCAmelCase           =   self.unet.config.in_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}
           _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					)


from typing import Any

import numpy as np





def 	__a     (      A__			:  np.ndarray       ):
    return np.array_equal(A__			,  matrix.conjugate().T       )





def 	__a     (      A__			:  np.ndarray			,  A__			:  np.ndarray       ):
    SCREAMING_SNAKE_CASE										=   v.conjugate().T
    SCREAMING_SNAKE_CASE										=   v_star.dot(A__       )
    assert isinstance(A__			,  np.ndarray       )
    return (v_star_dot.dot(A__       )) / (v_star.dot(A__       ))





def 	__a     (      ):
    SCREAMING_SNAKE_CASE										=   np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]]       )
    SCREAMING_SNAKE_CASE										=   np.array([[1], [2], [3]]       )
    assert is_hermitian(A__       ), F"{a} is not hermitian."
    print(rayleigh_quotient(A__			,  A__       )       )

    SCREAMING_SNAKE_CASE										=   np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]]       )
    assert is_hermitian(A__       ), F"{a} is not hermitian."
    assert rayleigh_quotient(A__			,  A__       ) == float(3       )


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    tests()