





'''simple docstring'''



from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

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       =     "\n    Examples:\n        ```py\n        >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\n        >>> from diffusers.utils import load_image\n        >>> import torch\n\n        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n        ...     \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16\n        ... )\n        >>> pipe_prior.to(\"cuda\")\n\n        >>> prompt = \"A red cartoon frog, 4k\"\n        >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\n\n        >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\n        ...     \"kandinsky-community/kandinsky-2-2-decoder\", torch_dtype=torch.float16\n        ... )\n        >>> pipe.to(\"cuda\")\n\n        >>> init_image = load_image(\n        ...     \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\n        ...     \"/kandinsky/frog.png\"\n        ... )\n\n        >>> image = pipe(\n        ...     image=init_image,\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=zero_image_emb,\n        ...     height=768,\n        ...     width=768,\n        ...     num_inference_steps=100,\n        ...     strength=0.2,\n        ... ).images\n\n        >>> image[0].save(\"red_frog.png\")\n        ```\n"




def  _lowerCAmelCase    (					lowerCamelCase_      :	List[Any]		,							lowerCamelCase_      :	Any		,							lowerCamelCase_      :	int=8					):
			__lowercase					    =				height // scale_factor**2
			if height % scale_factor**2 != 0:
						new_height += 1
			__lowercase					    =				width // scale_factor**2
			if width % scale_factor**2 != 0:
						new_width += 1
			return new_height * scale_factor, new_width * scale_factor




def  _lowerCAmelCase    (					lowerCamelCase_      :	Dict		,							lowerCamelCase_      :	List[Any]=5_1_2		,							lowerCamelCase_      :	int=5_1_2					):
			__lowercase					    =				pil_image.resize((w, h)		,							resample=Image.BICUBIC		,							reducing_gap=1					)
			__lowercase					    =				np.array(pil_image.convert('''RGB'''					)					)
			__lowercase					    =				arr.astype(np.floataa					) / 1_27.5 - 1
			__lowercase					    =				np.transpose(UpperCamelCase_		,							[2, 0, 1]					)
			__lowercase					    =				torch.from_numpy(UpperCamelCase_					).unsqueeze(0					)
			return image






class 				__lowercase							(   snake_case__    ):







	'''simple docstring'''

	def __init__(self  ,_lowerCamelCase  ,_lowerCamelCase  ,_lowerCamelCase  ,)				->				Any:







				'''simple docstring'''





				super().__init__()

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


	def     _UpperCAmelCase  (self  ,_lowerCamelCase  ,_lowerCamelCase  ,_lowerCamelCase			)				->				Optional[Any]:







				'''simple docstring'''





				__lowercase					    =				min(int(num_inference_steps * strength			)  ,__snake_case			)

				__lowercase					    =				max(num_inference_steps - init_timestep  ,0			)
				__lowercase					    =				self.scheduler.timesteps[t_start:]

				return timesteps, num_inference_steps - t_start


	def     _UpperCAmelCase  (self  ,_lowerCamelCase  ,_lowerCamelCase  ,_lowerCamelCase  ,_lowerCamelCase  ,_lowerCamelCase  ,_lowerCamelCase  ,_lowerCamelCase=None			)				->				Any:







				'''simple docstring'''





				if not isinstance(__snake_case  ,(torch.Tensor, PIL.Image.Image, list)			):
							raise ValueError(
							    f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(__snake_case			)}"			)

				__lowercase					    =				image.to(device=__snake_case  ,dtype=__snake_case			)

				__lowercase					    =				batch_size * num_images_per_prompt

				if image.shape[1] == 4:
							__lowercase					    =				image

				else:
							if isinstance(__snake_case  ,__snake_case			) and len(__snake_case			) != batch_size:
										raise ValueError(
										    f"You have passed a list of generators of length {len(__snake_case			)}, but requested an effective batch"
										    f" size of {batch_size}. Make sure the batch size matches the length of the generators."			)

							elif isinstance(__snake_case  ,__snake_case			):
										__lowercase					    =				[
										    self.movq.encode(image[i : i + 1]			).latent_dist.sample(generator[i]			) for i in range(__snake_case			)
										]
										__lowercase					    =				torch.cat(__snake_case  ,dim=0			)
							else:
										__lowercase					    =				self.movq.encode(__snake_case			).latent_dist.sample(__snake_case			)

							__lowercase					    =				self.movq.config.scaling_factor * init_latents

				__lowercase					    =				torch.cat([init_latents]  ,dim=0			)

				__lowercase					    =				init_latents.shape
				__lowercase					    =				randn_tensor(__snake_case  ,generator=__snake_case  ,device=__snake_case  ,dtype=__snake_case			)

				# get latents
				__lowercase					    =				self.scheduler.add_noise(__snake_case  ,__snake_case  ,__snake_case			)

				__lowercase					    =				init_latents

				return latents


	def     _UpperCAmelCase  (self  ,_lowerCamelCase=0			)				->				Tuple:







				'''simple docstring'''





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

				__lowercase					    =				torch.device(f"cuda:{gpu_id}"			)

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


	def     _UpperCAmelCase  (self  ,_lowerCamelCase=0			)				->				List[str]:







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

				__lowercase					    =				torch.device(f"cuda:{gpu_id}"			)

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

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

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


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







				'''simple docstring'''





				if not hasattr(self.unet  ,'''_hf_hook'''			):
							return self.device
				for module in self.unet.modules():
							if (
							    hasattr(__snake_case  ,'''_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(__snake_case			)
	def __call__(self  ,_lowerCamelCase  ,_lowerCamelCase  ,_lowerCamelCase  ,_lowerCamelCase = 512  ,_lowerCamelCase = 512  ,_lowerCamelCase = 100  ,_lowerCamelCase = 4.0  ,_lowerCamelCase = 0.3  ,_lowerCamelCase = 1  ,_lowerCamelCase = None  ,_lowerCamelCase = "pil"  ,_lowerCamelCase = True  ,)				->				Dict:







				'''simple docstring'''





				__lowercase					    =				self._execution_device

				__lowercase					    =				guidance_scale > 1.0

				if isinstance(__snake_case  ,__snake_case			):
							__lowercase					    =				torch.cat(__snake_case  ,dim=0			)
				__lowercase					    =				image_embeds.shape[0]
				if isinstance(__snake_case  ,__snake_case			):
							__lowercase					    =				torch.cat(__snake_case  ,dim=0			)

				if do_classifier_free_guidance:
							__lowercase					    =				image_embeds.repeat_interleave(__snake_case  ,dim=0			)
							__lowercase					    =				negative_image_embeds.repeat_interleave(__snake_case  ,dim=0			)

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

				if not isinstance(__snake_case  ,__snake_case			):
							__lowercase					    =				[image]
				if not all(isinstance(__snake_case  ,(PIL.Image.Image, torch.Tensor)			) for i in image			):
							raise ValueError(
							    f"Input is in incorrect format: {[type(__snake_case			) for i in image]}. Currently, we only support  PIL image and pytorch tensor"			)

				__lowercase					    =				torch.cat([prepare_image(__snake_case  ,__snake_case  ,__snake_case			) for i in image]  ,dim=0			)
				__lowercase					    =				image.to(dtype=image_embeds.dtype  ,device=__snake_case			)

				__lowercase					    =				self.movq.encode(__snake_case			)['''latents''']
				__lowercase					    =				latents.repeat_interleave(__snake_case  ,dim=0			)
				self.scheduler.set_timesteps(__snake_case  ,device=__snake_case			)
				__lowercase    ,		__lowercase					    =				self.get_timesteps(__snake_case  ,__snake_case  ,__snake_case			)
				__lowercase					    =				timesteps[:1].repeat(batch_size * num_images_per_prompt			)
				__lowercase    ,		__lowercase					    =				downscale_height_and_width(__snake_case  ,__snake_case  ,self.movq_scale_factor			)
				__lowercase					    =				self.prepare_latents(
				    __snake_case  ,__snake_case  ,__snake_case  ,__snake_case  ,image_embeds.dtype  ,__snake_case  ,__snake_case			)
				for i, t in enumerate(self.progress_bar(__snake_case			)			):
							# expand the latents if we are doing classifier free guidance
							__lowercase					    =				torch.cat([latents] * 2			) if do_classifier_free_guidance else latents

							__lowercase					    =				{'''image_embeds''': image_embeds}
							__lowercase					    =				self.unet(
							    sample=__snake_case  ,timestep=__snake_case  ,encoder_hidden_states=__snake_case  ,added_cond_kwargs=__snake_case  ,return_dict=__snake_case  ,)[0]

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

							# compute the previous noisy sample x_t -> x_t-1
							__lowercase					    =				self.scheduler.step(
							    __snake_case  ,__snake_case  ,__snake_case  ,generator=__snake_case  ,)[0]

				# post-processing
				__lowercase					    =				self.movq.decode(__snake_case  ,force_not_quantize=__snake_case			)['''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"]:
							__lowercase					    =				image * 0.5 + 0.5
							__lowercase					    =				image.clamp(0  ,1			)
							__lowercase					    =				image.cpu().permute(0  ,2  ,3  ,1			).float().numpy()

				if output_type == "pil":
							__lowercase					    =				self.numpy_to_pil(__snake_case			)

				if not return_dict:
							return (image,)

				return ImagePipelineOutput(images=__snake_case			)









import inspect
import unittest

import numpy as np

from transformers import ViTConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
 import jax

 from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel

class     A__   (       unittest.TestCase      ):







    """simple docstring"""

    def __init__(			self     ,   __snake_case     ,   __snake_case=1_3     ,   __snake_case=3_0     ,   __snake_case=2     ,   __snake_case=3     ,   __snake_case=True     ,   __snake_case=True     ,   __snake_case=3_2     ,   __snake_case=5     ,   __snake_case=4     ,   __snake_case=3_7     ,   __snake_case="gelu"     ,   __snake_case=0.1     ,   __snake_case=0.1     ,   __snake_case=1_0     ,   __snake_case=0.02     ,   ):
         snake_case											=							parent
         snake_case											=							batch_size
         snake_case											=							image_size
         snake_case											=							patch_size
         snake_case											=							num_channels
         snake_case											=							is_training
         snake_case											=							use_labels
         snake_case											=							hidden_size
         snake_case											=							num_hidden_layers
         snake_case											=							num_attention_heads
         snake_case											=							intermediate_size
         snake_case											=							hidden_act
         snake_case											=							hidden_dropout_prob
         snake_case											=							attention_probs_dropout_prob
         snake_case											=							type_sequence_label_size
         snake_case											=							initializer_range

         # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
         snake_case											=							(image_size // patch_size) ** 2
         snake_case											=							num_patches + 1
    def 						a_     (			self       ):
         snake_case											=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

         snake_case											=							ViTConfig(
             image_size=self.image_size     ,   patch_size=self.patch_size     ,   num_channels=self.num_channels     ,   hidden_size=self.hidden_size     ,   num_hidden_layers=self.num_hidden_layers     ,   num_attention_heads=self.num_attention_heads     ,   intermediate_size=self.intermediate_size     ,   hidden_act=self.hidden_act     ,   hidden_dropout_prob=self.hidden_dropout_prob     ,   attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,   is_decoder=__snake_case     ,   initializer_range=self.initializer_range     ,   )

         return config, pixel_values
    def 						a_     (			self     ,   __snake_case     ,   __snake_case       ):
         snake_case											=							FlaxViTModel(config=__snake_case       )
         snake_case											=							model(__snake_case       )
         # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
         snake_case											=							(self.image_size, self.image_size)
         snake_case											=							(self.patch_size, self.patch_size)
         snake_case											=							(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
         self.parent.assertEqual(result.last_hidden_state.shape     ,   (self.batch_size, num_patches + 1, self.hidden_size)       )
    def 						a_     (			self     ,   __snake_case     ,   __snake_case       ):
         snake_case											=							self.type_sequence_label_size
         snake_case											=							FlaxViTForImageClassification(config=__snake_case       )
         snake_case											=							model(__snake_case       )
         self.parent.assertEqual(result.logits.shape     ,   (self.batch_size, self.type_sequence_label_size)       )

         # test greyscale images
         snake_case											=							1
         snake_case											=							FlaxViTForImageClassification(__snake_case       )

         snake_case											=							floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
         snake_case											=							model(__snake_case       )




    def 						a_     (			self       ):
         snake_case											=							self.prepare_config_and_inputs()
         (
             (
             snake_case
         )					,    (
             snake_case
         )					,    
         )											=							config_and_inputs
         snake_case											=							{'''pixel_values''': pixel_values}
         return config, inputs_dict






@require_flax
class     A__   (       snake_case__			,   unittest.TestCase      ):







    """simple docstring"""

    __magic_name__         =						(FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else ()
    def 						a_     (			self       ):
         snake_case											=							FlaxViTModelTester(self       )
         snake_case											=							ConfigTester(self     ,   config_class=__snake_case     ,   has_text_modality=__snake_case     ,   hidden_size=3_7       )
    def 						a_     (			self       ):
         self.config_tester.run_common_tests()
    def 						a_     (			self       ):
         snake_case											=							self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__snake_case       )
    def 						a_     (			self       ):
         snake_case											=							self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__snake_case       )
    def 						a_     (			self       ):
         snake_case					,    snake_case											=							self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              snake_case											=							model_class(__snake_case       )
              snake_case											=							inspect.signature(model.__call__       )
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              snake_case											=							[*signature.parameters.keys()]

              snake_case											=							['''pixel_values''']
              self.assertListEqual(arg_names[:1]     ,   __snake_case       )
    def 						a_     (			self       ):
         snake_case					,    snake_case											=							self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              with self.subTest(model_class.__name__       ):
                   snake_case											=							self._prepare_for_class(__snake_case     ,   __snake_case       )
                   snake_case											=							model_class(__snake_case       )

                   @jax.jit
                   def model_jitted(__snake_case     ,   **__snake_case       ):
                        return model(pixel_values=__snake_case     ,   **__snake_case       )

                   with self.subTest('''JIT Enabled'''       ):
                        snake_case											=							model_jitted(**__snake_case       ).to_tuple()

                   with self.subTest('''JIT Disabled'''       ):
                        with jax.disable_jit():
                             snake_case											=							model_jitted(**__snake_case       ).to_tuple()

                   self.assertEqual(len(__snake_case       )     ,   len(__snake_case       )       )
                   for jitted_output, output in zip(__snake_case     ,   __snake_case       ):
                        self.assertEqual(jitted_output.shape     ,   output.shape       )




    @slow
    def 						a_     (			self       ):
         for model_class_name in self.all_model_classes:
              snake_case											=							model_class_name.from_pretrained('''google/vit-base-patch16-224'''       )
              snake_case											=							model(np.ones((1, 3, 2_2_4, 2_2_4)       )       )
              self.assertIsNotNone(__snake_case       )




