





'''simple docstring'''

import gc
import unittest

from parameterized import parameterized

from diffusers import FlaxUNetaDConditionModel
from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import load_hf_numpy, require_flax, slow


if is_flax_available():
      import jax
      import jax.numpy as jnp


@slow
@require_flax
class 					a_     (				unittest.TestCase       ):

    '''simple docstring'''


    def 			snake_case_(		self ,		A ,		A       )		->   List[Any]:
        return f'gaussian_noise_s={seed}_shape={"_".join([str(A       ) for s in shape]       )}.npy'


    def 			snake_case_(		self       )		->   List[Any]:
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()


    def 			snake_case_(		self ,		A=0 ,		A=(4, 4, 64, 64) ,		A=False       )		->   str:
        _SCREAMING_SNAKE_CASE									=			jnp.bfloataa if fpaa else jnp.floataa
        _SCREAMING_SNAKE_CASE									=			jnp.array(load_hf_numpy(self.get_file_format(A ,		A       )       ) ,		dtype=A       )
        return image


    def 			snake_case_(		self ,		A=False ,		A="CompVis/stable-diffusion-v1-4"       )		->   List[Any]:
        _SCREAMING_SNAKE_CASE									=			jnp.bfloataa if fpaa else jnp.floataa
        _SCREAMING_SNAKE_CASE									=			"""bf16""" if fpaa else None

        _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			FlaxUNetaDConditionModel.from_pretrained(
            A ,		subfolder="""unet""" ,		dtype=A ,		revision=A       )
        return model, params


    def 			snake_case_(		self ,		A=0 ,		A=(4, 77, 768) ,		A=False       )		->   Any:
        _SCREAMING_SNAKE_CASE									=			jnp.bfloataa if fpaa else jnp.floataa
        _SCREAMING_SNAKE_CASE									=			jnp.array(load_hf_numpy(self.get_file_format(A ,		A       )       ) ,		dtype=A       )
        return hidden_states


    @parameterized.expand(
        [
            # fmt: off
            [83, 4, [-0.2323, -0.1304, 0.0813, -0.3093, -0.0919, -0.1571, -0.1125, -0.5806]],
            [17, 0.55, [-0.0831, -0.2443, 0.0901, -0.0919, 0.3396, 0.0103, -0.3743, 0.0701]],
            [8, 0.89, [-0.4863, 0.0859, 0.0875, -0.1658, 0.9199, -0.0114, 0.4839, 0.4639]],
            [3, 1000, [-0.5649, 0.2402, -0.5518, 0.1248, 1.1328, -0.2443, -0.0325, -1.0078]],
            # fmt: on
        ]       )
    def 			snake_case_(		self ,		A ,		A ,		A       )		->   Union[str, Any]:
        _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			self.get_unet_model(model_id="""CompVis/stable-diffusion-v1-4""" ,		fpaa=A       )
        _SCREAMING_SNAKE_CASE									=			self.get_latents(A ,		fpaa=A       )
        _SCREAMING_SNAKE_CASE									=			self.get_encoder_hidden_states(A ,		fpaa=A       )

        _SCREAMING_SNAKE_CASE									=			model.apply(
            {"""params""": params} ,		A ,		jnp.array(A ,		dtype=jnp.intaa       ) ,		encoder_hidden_states=A ,		).sample

        assert sample.shape == latents.shape

        _SCREAMING_SNAKE_CASE									=			jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten())       ) ,		dtype=jnp.floataa       )
        _SCREAMING_SNAKE_CASE									=			jnp.array(A ,		dtype=jnp.floataa       )

        # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, in the same hardware
        assert jnp.allclose(A ,		A ,		atol=1e-2       )





    @parameterized.expand(
        [
            # fmt: off
            [83, 4, [0.1514, 0.0807, 0.1624, 0.1016, -0.1896, 0.0263, 0.0677, 0.2310]],
            [17, 0.55, [0.1164, -0.0216, 0.0170, 0.1589, -0.3120, 0.1005, -0.0581, -0.1458]],
            [8, 0.89, [-0.1758, -0.0169, 0.1004, -0.1411, 0.1312, 0.1103, -0.1996, 0.2139]],
            [3, 1000, [0.1214, 0.0352, -0.0731, -0.1562, -0.0994, -0.0906, -0.2340, -0.0539]],
            # fmt: on
        ]       )
    def 			snake_case_(		self ,		A ,		A ,		A       )		->   str:
        _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			self.get_unet_model(model_id="""stabilityai/stable-diffusion-2""" ,		fpaa=A       )
        _SCREAMING_SNAKE_CASE									=			self.get_latents(A ,		shape=(4, 4, 96, 96) ,		fpaa=A       )
        _SCREAMING_SNAKE_CASE									=			self.get_encoder_hidden_states(A ,		shape=(4, 77, 1024) ,		fpaa=A       )

        _SCREAMING_SNAKE_CASE									=			model.apply(
            {"""params""": params} ,		A ,		jnp.array(A ,		dtype=jnp.intaa       ) ,		encoder_hidden_states=A ,		).sample

        assert sample.shape == latents.shape

        _SCREAMING_SNAKE_CASE									=			jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten())       ) ,		dtype=jnp.floataa       )
        _SCREAMING_SNAKE_CASE									=			jnp.array(A ,		dtype=jnp.floataa       )

        # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, on the same hardware
        assert jnp.allclose(A ,		A ,		atol=1e-2       )










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


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

lowercase_					= """
    Examples:
        ```py
        >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline
        >>> import torch

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





def lowerCamelCase						(     __lowerCamelCase :    str					,       __lowerCamelCase :    Optional[Any]					,       __lowerCamelCase :    List[Any]=8    )						->Tuple:
    _SCREAMING_SNAKE_CASE									=			height // scale_factor**2
    if height % scale_factor**2 != 0:
        new_height += 1
    _SCREAMING_SNAKE_CASE									=			width // scale_factor**2
    if width % scale_factor**2 != 0:
        new_width += 1
    return new_height * scale_factor, new_width * scale_factor






class 					a_     (				snake_case_       ):

    '''simple docstring'''


    def __init__(		self ,		A ,		A ,		A ,		)		->   Union[str, Any]:
        super().__init__()

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


    def 			snake_case_(		self ,		A ,		A ,		A ,		A ,		A ,		A       )		->   Union[str, Any]:
        if latents is None:
            _SCREAMING_SNAKE_CASE									=			randn_tensor(A ,		generator=A ,		device=A ,		dtype=A       )
        else:
            if latents.shape != shape:
                raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}'       )
            _SCREAMING_SNAKE_CASE									=			latents.to(A       )

        _SCREAMING_SNAKE_CASE									=			latents * scheduler.init_noise_sigma
        return latents


    def 			snake_case_(		self ,		A=0       )		->   Dict:
        if is_accelerate_available():
            from accelerate import cpu_offload
        else:
            raise ImportError("""Please install accelerate via `pip install accelerate`"""       )

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

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


    def 			snake_case_(		self ,		A=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."""       )

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

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

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

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


    @property
    # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
    def 			snake_case_(		self       )		->   Tuple:
        if not hasattr(self.unet ,		"""_hf_hook"""       ):
            return self.device
        for module in self.unet.modules():
            if (
                hasattr(A ,		"""_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(A       )
    def __call__(		self ,		A ,		A ,		A = 512 ,		A = 512 ,		A = 100 ,		A = 4.0 ,		A = 1 ,		A = None ,		A = None ,		A = "pil" ,		A = True ,		)		->   List[str]:
        _SCREAMING_SNAKE_CASE									=			self._execution_device

        _SCREAMING_SNAKE_CASE									=			guidance_scale > 1.0

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

        if do_classifier_free_guidance:
            _SCREAMING_SNAKE_CASE									=			image_embeds.repeat_interleave(A ,		dim=0       )
            _SCREAMING_SNAKE_CASE									=			negative_image_embeds.repeat_interleave(A ,		dim=0       )

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

        self.scheduler.set_timesteps(A ,		device=A       )
        _SCREAMING_SNAKE_CASE									=			self.scheduler.timesteps

        _SCREAMING_SNAKE_CASE									=			self.unet.config.in_channels

        _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			downscale_height_and_width(A ,		A ,		self.movq_scale_factor       )

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

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

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

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

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

        if output_type == "pil":
            _SCREAMING_SNAKE_CASE									=			self.numpy_to_pil(A       )

        if not return_dict:
            return (image,)

        return ImagePipelineOutput(images=A       )



