




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


_lowerCamelCase      :  List[Any]      						=						logging.get_logger(__name__)  # pylint: disable=invalid-name

_lowerCamelCase      :  List[str]      						=						'''
    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 							_UpperCAmelCase  (UpperCamelCase_ : List[str]      ,    UpperCamelCase_ : Any      ,    UpperCamelCase_ : List[str]=8       ):
				'''simple docstring'''
				_lowerCAmelCase    :    Tuple										=      height // scale_factor**2
				if height % scale_factor**2 != 0:
								new_height += 1
				_lowerCAmelCase    :    Optional[int]										=      width // scale_factor**2
				if width % scale_factor**2 != 0:
								new_width += 1
				return new_height * scale_factor, new_width * scale_factor





class        __snake_case  (__UpperCAmelCase		):



				def __init__(      self      :		Dict		,	_UpperCAmelCase      :		UNetaDConditionModel		,	_UpperCAmelCase      :		DDPMScheduler		,	_UpperCAmelCase      :		VQModel		,	)  ->    List[Any]:





								'''simple docstring'''




								super().__init__()

								self.register_modules(
								    unet=__SCREAMING_SNAKE_CASE		,	scheduler=__SCREAMING_SNAKE_CASE		,	movq=__SCREAMING_SNAKE_CASE		,	)
								_lowerCAmelCase    :    Dict										=      2 ** (len(self.movq.config.block_out_channels      ) - 1)



				def       SCREAMING_SNAKE_CASE       (      self      :		Any		,	_UpperCAmelCase      :		Tuple		,	_UpperCAmelCase      :		Optional[Any]		,	_UpperCAmelCase      :		Tuple		,	_UpperCAmelCase      :		Tuple		,	_UpperCAmelCase      :		List[str]		,	_UpperCAmelCase      :		List[str]      )  ->    Tuple:





								'''simple docstring'''




								if latents is None:
												_lowerCAmelCase    :    Dict										=      randn_tensor(__SCREAMING_SNAKE_CASE		,	generator=__SCREAMING_SNAKE_CASE		,	device=__SCREAMING_SNAKE_CASE		,	dtype=__SCREAMING_SNAKE_CASE      )
								else:
												if latents.shape != shape:
																raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}"      )
												_lowerCAmelCase    :    str										=      latents.to(__SCREAMING_SNAKE_CASE      )

								_lowerCAmelCase    :    Dict										=      latents * scheduler.init_noise_sigma
								return latents



				def       SCREAMING_SNAKE_CASE       (      self      :		List[str]		,	_UpperCAmelCase      :		Optional[Any]=0      )  ->    List[Any]:





								'''simple docstring'''




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

								_lowerCAmelCase    :    Optional[Any]										=      torch.device(f"cuda:{gpu_id}"      )

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



				def       SCREAMING_SNAKE_CASE       (      self      :		int		,	_UpperCAmelCase      :		str=0      )  ->    Dict:





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

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

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

								_lowerCAmelCase    :    int										=      None
								for cpu_offloaded_model in [self.unet, self.movq]:
												_lowerCAmelCase					,    _lowerCAmelCase    :    Optional[int]										=      cpu_offload_with_hook(__SCREAMING_SNAKE_CASE		,	__SCREAMING_SNAKE_CASE		,	prev_module_hook=__SCREAMING_SNAKE_CASE      )

								# We'll offload the last model manually.
								_lowerCAmelCase    :    Optional[int]										=      hook



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





								'''simple docstring'''




								if not hasattr(self.unet		,	"""_hf_hook"""      ):
												return self.device
								for module in self.unet.modules():
												if (
												    hasattr(__SCREAMING_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(__SCREAMING_SNAKE_CASE      )
				def __call__(      self      :		str		,	_UpperCAmelCase      :		Union[torch.FloatTensor, List[torch.FloatTensor]]		,	_UpperCAmelCase      :		Union[torch.FloatTensor, List[torch.FloatTensor]]		,	_UpperCAmelCase      :		int = 512		,	_UpperCAmelCase      :		int = 512		,	_UpperCAmelCase      :		int = 100		,	_UpperCAmelCase      :		float = 4.0		,	_UpperCAmelCase      :		int = 1		,	_UpperCAmelCase      :		Optional[Union[torch.Generator, List[torch.Generator]]] = None		,	_UpperCAmelCase      :		Optional[torch.FloatTensor] = None		,	_UpperCAmelCase      :		Optional[str] = "pil"		,	_UpperCAmelCase      :		bool = True		,	)  ->    int:





								'''simple docstring'''




								_lowerCAmelCase    :    Optional[Any]										=      self._execution_device

								_lowerCAmelCase    :    int										=      guidance_scale > 1.0

								if isinstance(__SCREAMING_SNAKE_CASE		,	__SCREAMING_SNAKE_CASE      ):
												_lowerCAmelCase    :    Optional[int]										=      torch.cat(__SCREAMING_SNAKE_CASE		,	dim=0      )
								_lowerCAmelCase    :    Dict										=      image_embeds.shape[0] * num_images_per_prompt
								if isinstance(__SCREAMING_SNAKE_CASE		,	__SCREAMING_SNAKE_CASE      ):
												_lowerCAmelCase    :    Optional[Any]										=      torch.cat(__SCREAMING_SNAKE_CASE		,	dim=0      )

								if do_classifier_free_guidance:
												_lowerCAmelCase    :    List[Any]										=      image_embeds.repeat_interleave(__SCREAMING_SNAKE_CASE		,	dim=0      )
												_lowerCAmelCase    :    Any										=      negative_image_embeds.repeat_interleave(__SCREAMING_SNAKE_CASE		,	dim=0      )

								_lowerCAmelCase    :    Any										=      torch.cat([negative_image_embeds, image_embeds]		,	dim=0      ).to(dtype=self.unet.dtype		,	device=__SCREAMING_SNAKE_CASE      )

								self.scheduler.set_timesteps(__SCREAMING_SNAKE_CASE		,	device=__SCREAMING_SNAKE_CASE      )
								_lowerCAmelCase    :    Tuple										=      self.scheduler.timesteps

								_lowerCAmelCase    :    Union[str, Any]										=      self.unet.config.in_channels

								_lowerCAmelCase					,    _lowerCAmelCase    :    List[Any]										=      downscale_height_and_width(__SCREAMING_SNAKE_CASE		,	__SCREAMING_SNAKE_CASE		,	self.movq_scale_factor      )

								# create initial latent
								_lowerCAmelCase    :    Dict										=      self.prepare_latents(
								    (batch_size, num_channels_latents, height, width)		,	image_embeds.dtype		,	__SCREAMING_SNAKE_CASE		,	__SCREAMING_SNAKE_CASE		,	__SCREAMING_SNAKE_CASE		,	self.scheduler		,	)

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

												_lowerCAmelCase    :    Optional[Any]										=      {"""image_embeds""": image_embeds}
												_lowerCAmelCase    :    Union[str, Any]										=      self.unet(
												    sample=__SCREAMING_SNAKE_CASE		,	timestep=__SCREAMING_SNAKE_CASE		,	encoder_hidden_states=__SCREAMING_SNAKE_CASE		,	added_cond_kwargs=__SCREAMING_SNAKE_CASE		,	return_dict=__SCREAMING_SNAKE_CASE		,	)[0]

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

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

								if output_type == "pil":
												_lowerCAmelCase    :    Tuple										=      self.numpy_to_pil(__SCREAMING_SNAKE_CASE      )

								if not return_dict:
												return (image,)

								return ImagePipelineOutput(images=__SCREAMING_SNAKE_CASE      )







import logging

from transformers.configuration_utils import PretrainedConfig


_lowerCamelCase      :  Union[str, Any]      						=						logging.getLogger(__name__)
class        __snake_case  (_a		):
				lowerCAmelCase__				=     "masked_bert"



				def __init__(      self      :		Union[str, Any]		,	_UpperCAmelCase      :		Union[str, Any]=3_0522		,	_UpperCAmelCase      :		Optional[Any]=768		,	_UpperCAmelCase      :		List[Any]=12		,	_UpperCAmelCase      :		Dict=12		,	_UpperCAmelCase      :		List[str]=3072		,	_UpperCAmelCase      :		List[Any]="gelu"		,	_UpperCAmelCase      :		Optional[Any]=0.1		,	_UpperCAmelCase      :		Optional[Any]=0.1		,	_UpperCAmelCase      :		List[Any]=512		,	_UpperCAmelCase      :		int=2		,	_UpperCAmelCase      :		Optional[int]=0.02		,	_UpperCAmelCase      :		str=1E-12		,	_UpperCAmelCase      :		Tuple=0		,	_UpperCAmelCase      :		Dict="topK"		,	_UpperCAmelCase      :		List[str]="constant"		,	_UpperCAmelCase      :		Optional[Any]=0.0		,	**_UpperCAmelCase      :		str		,	)  ->    Tuple:





								'''simple docstring'''




								super().__init__(pad_token_id=_UpperCAmelCase		,	**_UpperCAmelCase      )

								_lowerCAmelCase    :    str										=      vocab_size
								_lowerCAmelCase    :    List[str]										=      hidden_size
								_lowerCAmelCase    :    Any										=      num_hidden_layers
								_lowerCAmelCase    :    Optional[Any]										=      num_attention_heads
								_lowerCAmelCase    :    Optional[Any]										=      hidden_act
								_lowerCAmelCase    :    Union[str, Any]										=      intermediate_size
								_lowerCAmelCase    :    Tuple										=      hidden_dropout_prob
								_lowerCAmelCase    :    Optional[int]										=      attention_probs_dropout_prob
								_lowerCAmelCase    :    str										=      max_position_embeddings
								_lowerCAmelCase    :    int										=      type_vocab_size
								_lowerCAmelCase    :    List[str]										=      initializer_range
								_lowerCAmelCase    :    Optional[Any]										=      layer_norm_eps
								_lowerCAmelCase    :    Tuple										=      pruning_method
								_lowerCAmelCase    :    str										=      mask_init
								_lowerCAmelCase    :    List[str]										=      mask_scale

