





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


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

_SCREAMING_SNAKE_CASE       	=		"""
    Examples:
        ```py
        >>> import torch
        >>> import numpy as np

        >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline
        >>> from transformers import pipeline
        >>> from diffusers.utils import load_image


        >>> def make_hint(image, depth_estimator):
        ...     image = depth_estimator(image)[\"depth\"]
        ...     image = np.array(image)
        ...     image = image[:, :, None]
        ...     image = np.concatenate([image, image, image], axis=2)
        ...     detected_map = torch.from_numpy(image).float() / 255.0
        ...     hint = detected_map.permute(2, 0, 1)
        ...     return hint


        >>> depth_estimator = pipeline(\"depth-estimation\")

        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(
        ...     \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16
        ... )
        >>> pipe_prior = pipe_prior.to(\"cuda\")

        >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(
        ...     \"kandinsky-community/kandinsky-2-2-controlnet-depth\", torch_dtype=torch.float16
        ... )
        >>> pipe = pipe.to(\"cuda\")


        >>> img = load_image(
        ...     \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"
        ...     \"/kandinsky/cat.png\"
        ... ).resize((768, 768))

        >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to(\"cuda\")

        >>> prompt = \"A robot, 4k photo\"
        >>> negative_prior_prompt = \"lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature\"

        >>> generator = torch.Generator(device=\"cuda\").manual_seed(43)

        >>> image_emb, zero_image_emb = pipe_prior(
        ...     prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator
        ... ).to_tuple()

        >>> images = pipe(
        ...     image_embeds=image_emb,
        ...     negative_image_embeds=zero_image_emb,
        ...     hint=hint,
        ...     num_inference_steps=50,
        ...     generator=generator,
        ...     height=768,
        ...     width=768,
        ... ).images

        >>> images[0].save(\"robot_cat.png\")
        ```
"""


def 							SCREAMING_SNAKE_CASE__						(    __a   , __a   , __a=8   ):
	snake_case_		:			Optional[int]											=	height // scale_factor**2
	if height % scale_factor**2 != 0:
		new_height += 1
	snake_case_		:			str											=	width // scale_factor**2
	if width % scale_factor**2 != 0:
		new_width += 1
	return new_height * scale_factor, new_width * scale_factor


class SCREAMING_SNAKE_CASE_						(					snake_case_					):






						def __init__(      self      :      Tuple		,   _A      :      UNetaDConditionModel		,   _A      :      DDPMScheduler		,   _A      :      VQModel		,   )							->    List[str]:







							"""simple docstring"""


							super().__init__()

							self.register_modules(
							    unet=_A		,   scheduler=_A		,   movq=_A		,   )
							snake_case_		:			Tuple											=	2 ** (len(self.movq.config.block_out_channels	) - 1)






						def UpperCAmelCase_				(      self      :      Any		,   _A      :      Dict		,   _A      :      Optional[Any]		,   _A      :      Union[str, Any]		,   _A      :      Union[str, Any]		,   _A      :      Dict		,   _A      :      List[Any]	)							->    List[str]:







							"""simple docstring"""


							if latents is None:
								snake_case_		:			Optional[int]											=	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}"""	)
								snake_case_		:			List[str]											=	latents.to(_A	)

							snake_case_		:			Union[str, Any]											=	latents * scheduler.init_noise_sigma
							return latents






						def UpperCAmelCase_				(      self      :      List[str]		,   _A      :      List[str]=0	)							->    Optional[int]:







							"""simple docstring"""


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

							snake_case_		:			Optional[int]											=	torch.device(F"""cuda:{gpu_id}"""	)

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






						def UpperCAmelCase_				(      self      :      int		,   _A      :      List[str]=0	)							->    int:







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

							snake_case_		:			Union[str, Any]											=	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)

							snake_case_		:			str											=	None
							for cpu_offloaded_model in [self.unet, self.movq]:
								snake_case_		:			Optional[int]											=	cpu_offload_with_hook(_A		,   _A		,   prev_module_hook=_A	)

							# We'll offload the last model manually.
							snake_case_		:			Tuple											=	hook






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







							"""simple docstring"""


							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      :      str		,   _A      :      Union[torch.FloatTensor, List[torch.FloatTensor]]		,   _A      :      Union[torch.FloatTensor, List[torch.FloatTensor]]		,   _A      :      torch.FloatTensor		,   _A      :      int = 512		,   _A      :      int = 512		,   _A      :      int = 100		,   _A      :      float = 4.0		,   _A      :      int = 1		,   _A      :      Optional[Union[torch.Generator, List[torch.Generator]]] = None		,   _A      :      Optional[torch.FloatTensor] = None		,   _A      :      Optional[str] = "pil"		,   _A      :      bool = True		,   )							->    str:







							"""simple docstring"""


							snake_case_		:			Any											=	self._execution_device

							snake_case_		:			Tuple											=	guidance_scale > 1.0

							if isinstance(_A		,   _A	):
								snake_case_		:			int											=	torch.cat(_A		,   dim=0	)
							if isinstance(_A		,   _A	):
								snake_case_		:			Any											=	torch.cat(_A		,   dim=0	)
							if isinstance(_A		,   _A	):
								snake_case_		:			int											=	torch.cat(_A		,   dim=0	)

							snake_case_		:			Dict											=	image_embeds.shape[0] * num_images_per_prompt

							if do_classifier_free_guidance:
								snake_case_		:			int											=	image_embeds.repeat_interleave(_A		,   dim=0	)
								snake_case_		:			Optional[int]											=	negative_image_embeds.repeat_interleave(_A		,   dim=0	)
								snake_case_		:			int											=	hint.repeat_interleave(_A		,   dim=0	)

							snake_case_		:			Optional[Any]											=	torch.cat([negative_image_embeds, image_embeds]		,   dim=0	).to(dtype=self.unet.dtype		,   device=_A	)
							snake_case_		:			List[str]											=	torch.cat([hint, hint]		,   dim=0	).to(dtype=self.unet.dtype		,   device=_A	)
							self.scheduler.set_timesteps(_A		,   device=_A	)
							snake_case_		:			Tuple											=	self.scheduler.timesteps

							snake_case_		:			Union[str, Any]											=	self.movq.config.latent_channels

							snake_case_		:			Union[str, Any]											=	downscale_height_and_width(_A		,   _A		,   self.movq_scale_factor	)

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

								snake_case_		:			Optional[Any]											=	{'image_embeds': image_embeds, 'hint': hint}
								snake_case_		:			int											=	self.unet(
								    sample=_A		,   timestep=_A		,   encoder_hidden_states=_A		,   added_cond_kwargs=_A		,   return_dict=_A		,   )[0]

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

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

							if output_type == "pil":
								snake_case_		:			List[Any]											=	self.numpy_to_pil(_A	)

							if not return_dict:
								return (image,)

							return ImagePipelineOutput(images=_A	)








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 SCREAMING_SNAKE_CASE_						(					unittest.TestCase					):






						def __init__(      self      :      Dict		,   _A      :      List[str]		,   _A      :      Dict=13		,   _A      :      str=30		,   _A      :      Any=2		,   _A      :      Dict=3		,   _A      :      Optional[Any]=True		,   _A      :      Tuple=True		,   _A      :      List[str]=32		,   _A      :      int=5		,   _A      :      Optional[int]=4		,   _A      :      Dict=37		,   _A      :      Tuple="gelu"		,   _A      :      Dict=0.1		,   _A      :      str=0.1		,   _A      :      int=10		,   _A      :      Union[str, Any]=0.0_2		,   )							->    int:







							"""simple docstring"""


							snake_case_		:			int											=	parent
							snake_case_		:			str											=	batch_size
							snake_case_		:			List[str]											=	image_size
							snake_case_		:			Tuple											=	patch_size
							snake_case_		:			str											=	num_channels
							snake_case_		:			List[str]											=	is_training
							snake_case_		:			List[str]											=	use_labels
							snake_case_		:			str											=	hidden_size
							snake_case_		:			Union[str, Any]											=	num_hidden_layers
							snake_case_		:			Any											=	num_attention_heads
							snake_case_		:			List[Any]											=	intermediate_size
							snake_case_		:			Any											=	hidden_act
							snake_case_		:			List[Any]											=	hidden_dropout_prob
							snake_case_		:			List[Any]											=	attention_probs_dropout_prob
							snake_case_		:			Tuple											=	type_sequence_label_size
							snake_case_		:			Any											=	initializer_range

							# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
							snake_case_		:			Tuple											=	(image_size // patch_size) ** 2
							snake_case_		:			List[Any]											=	num_patches + 1






						def UpperCAmelCase_				(      self      :      Dict	)							->    List[str]:







							"""simple docstring"""


							snake_case_		:			int											=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

							snake_case_		:			Optional[Any]											=	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=_A		,   initializer_range=self.initializer_range		,   )

							return config, pixel_values






						def UpperCAmelCase_				(      self      :      int		,   _A      :      Union[str, Any]		,   _A      :      List[Any]	)							->    Dict:







							"""simple docstring"""


							snake_case_		:			Union[str, Any]											=	FlaxViTModel(config=_A	)
							snake_case_		:			Optional[Any]											=	model(_A	)
							# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
							snake_case_		:			Union[str, Any]											=	(self.image_size, self.image_size)
							snake_case_		:			int											=	(self.patch_size, self.patch_size)
							snake_case_		:			Optional[Any]											=	(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 UpperCAmelCase_				(      self      :      str		,   _A      :      Any		,   _A      :      List[str]	)							->    Dict:







							"""simple docstring"""


							snake_case_		:			Dict											=	self.type_sequence_label_size
							snake_case_		:			Any											=	FlaxViTForImageClassification(config=_A	)
							snake_case_		:			Optional[int]											=	model(_A	)
							self.parent.assertEqual(result.logits.shape		,   (self.batch_size, self.type_sequence_label_size)	)

							# test greyscale images
							snake_case_		:			List[str]											=	1
							snake_case_		:			Dict											=	FlaxViTForImageClassification(_A	)

							snake_case_		:			Optional[int]											=	floats_tensor([self.batch_size, 1, self.image_size, self.image_size]	)
							snake_case_		:			Any											=	model(_A	)






						def UpperCAmelCase_				(      self      :      Any	)							->    Any:







							"""simple docstring"""


							snake_case_		:			Tuple											=	self.prepare_config_and_inputs()
							(
							    (
							    snake_case_
							)						,(
							    snake_case_
							)						,
							)		:			Any											=	config_and_inputs
							snake_case_		:			Tuple											=	{'pixel_values': pixel_values}
							return config, inputs_dict
@require_flax
class SCREAMING_SNAKE_CASE_						(					snake_case_       ,				unittest.TestCase					):
						__magic_name__:			Tuple       =       (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else ()






						def UpperCAmelCase_				(      self      :      List[str]	)							->    None:







							"""simple docstring"""


							snake_case_		:			Union[str, Any]											=	FlaxViTModelTester(self	)
							snake_case_		:			Any											=	ConfigTester(self		,   config_class=_A		,   has_text_modality=_A		,   hidden_size=37	)






						def UpperCAmelCase_				(      self      :      Any	)							->    Dict:







							"""simple docstring"""


							self.config_tester.run_common_tests()






						def UpperCAmelCase_				(      self      :      Any	)							->    Optional[Any]:







							"""simple docstring"""


							snake_case_		:			str											=	self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_A	)






						def UpperCAmelCase_				(      self      :      List[Any]	)							->    Union[str, Any]:







							"""simple docstring"""


							snake_case_		:			Tuple											=	self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*_A	)






						def UpperCAmelCase_				(      self      :      int	)							->    List[str]:







							"""simple docstring"""


							snake_case_						,snake_case_		:			Tuple											=	self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
								snake_case_		:			str											=	model_class(_A	)
								snake_case_		:			Dict											=	inspect.signature(model.__call__	)
								# signature.parameters is an OrderedDict => so arg_names order is deterministic
								snake_case_		:			Optional[Any]											=	[*signature.parameters.keys()]

								snake_case_		:			Dict											=	['pixel_values']
								self.assertListEqual(arg_names[:1]		,   _A	)






						def UpperCAmelCase_				(      self      :      Optional[Any]	)							->    str:







							"""simple docstring"""


							snake_case_						,snake_case_		:			Optional[int]											=	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_		:			Dict											=	self._prepare_for_class(_A		,   _A	)
									snake_case_		:			Tuple											=	model_class(_A	)

									@jax.jit
									def model_jitted(_A      :      Optional[int]		,   **_A      :      Any	):
										return model(pixel_values=_A		,   **_A	)

									with self.subTest('JIT Enabled'	):
										snake_case_		:			Optional[Any]											=	model_jitted(**_A	).to_tuple()

									with self.subTest('JIT Disabled'	):
										with jax.disable_jit():
											snake_case_		:			Optional[Any]											=	model_jitted(**_A	).to_tuple()

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






						@slow
						def UpperCAmelCase_				(      self      :      List[str]	)							->    Any:







							"""simple docstring"""


							for model_class_name in self.all_model_classes:
								snake_case_		:			List[Any]											=	model_class_name.from_pretrained('google/vit-base-patch16-224'	)
								snake_case_		:			Optional[Any]											=	model(np.ones((1, 3, 224, 224)	)	)
								self.assertIsNotNone(_A	)

