



"""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			:			str										=						logging.get_logger(__name__)  # pylint: disable=invalid-name

_lowercase			:			List[Any]										=						"""
    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 					snake_case__       (		__lowerCamelCase							,		__lowerCamelCase							,		__lowerCamelCase=8     ):
			"""simple docstring"""
			lowerCamelCase__		:		Any		     =height // scale_factor**2
			if height % scale_factor**2 != 0:
						new_height += 1
			lowerCamelCase__		:		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     (				lowerCAmelCase_       ):


					'''simple docstring'''





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

								self.register_modules(
								    unet=__lowerCAmelCase,  scheduler=__lowerCAmelCase,  movq=__lowerCAmelCase,  )
								lowerCamelCase__		:		Any		     =2 ** (len(self.movq.config.block_out_channels					) - 1)



					def 		snake_case	(	self							:  List[Any],  lowerCamelCase							:  List[str],  lowerCamelCase							:  Any,  lowerCamelCase							:  List[Any],  lowerCamelCase							:  Dict,  lowerCamelCase							:  Dict,  lowerCamelCase							:  Optional[Any]					)-> Optional[int]:



								if latents is None:
											lowerCamelCase__		:		Tuple		     =randn_tensor(__lowerCAmelCase,  generator=__lowerCAmelCase,  device=__lowerCAmelCase,  dtype=__lowerCAmelCase					)
								else:
											if latents.shape != shape:
														raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {shape}'''					)
											lowerCamelCase__		:		List[Any]		     =latents.to(__lowerCAmelCase					)

								lowerCamelCase__		:		Optional[Any]		     =latents * scheduler.init_noise_sigma
								return latents



					def 		snake_case	(	self							:  Union[str, Any],  lowerCamelCase							:  str=0					)-> Dict:



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

								lowerCamelCase__		:		List[str]		     =torch.device(F'''cuda:{gpu_id}'''					)

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



					def 		snake_case	(	self							:  Dict,  lowerCamelCase							:  Optional[Any]=0					)-> Dict:



								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__		:		Dict		     =torch.device(F'''cuda:{gpu_id}'''					)

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

								lowerCamelCase__		:		List[str]		     =None
								for cpu_offloaded_model in [self.unet, self.movq]:
											lowerCamelCase__     ,       lowerCamelCase__		:		Optional[Any]		     =cpu_offload_with_hook(__lowerCAmelCase,  __lowerCAmelCase,  prev_module_hook=__lowerCAmelCase					)

								# We'll offload the last model manually.
								lowerCamelCase__		:		Any		     =hook



					@property
					# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
					def 		snake_case	(	self							:  Dict					)-> Any:



								if not hasattr(self.unet,  '''_hf_hook'''					):
											return self.device
								for module in self.unet.modules():
											if (
											    hasattr(__lowerCAmelCase,  '''_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(__lowerCAmelCase					)
					def __call__(	self							:  Tuple,  lowerCamelCase							:  List[str],  lowerCamelCase							:  Any,  lowerCamelCase							:  Optional[int],  lowerCamelCase							:  List[Any] = 512,  lowerCamelCase							:  Dict = 512,  lowerCamelCase							:  List[str] = 100,  lowerCamelCase							:  int = 4.0,  lowerCamelCase							:  Optional[int] = 1,  lowerCamelCase							:  Optional[Any] = None,  lowerCamelCase							:  Optional[int] = None,  lowerCamelCase							:  Union[str, Any] = "pil",  lowerCamelCase							:  int = True,  )-> List[Any]:
								lowerCamelCase__		:		Any		     =self._execution_device

								lowerCamelCase__		:		Dict		     =guidance_scale > 1.0

								if isinstance(__lowerCAmelCase,  __lowerCAmelCase					):
											lowerCamelCase__		:		str		     =torch.cat(__lowerCAmelCase,  dim=0					)
								if isinstance(__lowerCAmelCase,  __lowerCAmelCase					):
											lowerCamelCase__		:		Tuple		     =torch.cat(__lowerCAmelCase,  dim=0					)
								if isinstance(__lowerCAmelCase,  __lowerCAmelCase					):
											lowerCamelCase__		:		List[str]		     =torch.cat(__lowerCAmelCase,  dim=0					)

								lowerCamelCase__		:		Union[str, Any]		     =image_embeds.shape[0] * num_images_per_prompt

								if do_classifier_free_guidance:
											lowerCamelCase__		:		Optional[int]		     =image_embeds.repeat_interleave(__lowerCAmelCase,  dim=0					)
											lowerCamelCase__		:		List[str]		     =negative_image_embeds.repeat_interleave(__lowerCAmelCase,  dim=0					)
											lowerCamelCase__		:		int		     =hint.repeat_interleave(__lowerCAmelCase,  dim=0					)

								lowerCamelCase__		:		Any		     =torch.cat([negative_image_embeds, image_embeds],  dim=0					).to(dtype=self.unet.dtype,  device=__lowerCAmelCase					)
								lowerCamelCase__		:		int		     =torch.cat([hint, hint],  dim=0					).to(dtype=self.unet.dtype,  device=__lowerCAmelCase					)
								self.scheduler.set_timesteps(__lowerCAmelCase,  device=__lowerCAmelCase					)
								lowerCamelCase__		:		List[str]		     =self.scheduler.timesteps

								lowerCamelCase__		:		List[str]		     =self.movq.config.latent_channels

								lowerCamelCase__     ,       lowerCamelCase__		:		Union[str, Any]		     =downscale_height_and_width(__lowerCAmelCase,  __lowerCAmelCase,  self.movq_scale_factor					)

								# create initial latent
								lowerCamelCase__		:		str		     =self.prepare_latents(
								    (batch_size, num_channels_latents, height, width),  image_embeds.dtype,  __lowerCAmelCase,  __lowerCAmelCase,  __lowerCAmelCase,  self.scheduler,  )

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

											lowerCamelCase__		:		Optional[Any]		     ={'''image_embeds''': image_embeds, '''hint''': hint}
											lowerCamelCase__		:		List[str]		     =self.unet(
											    sample=__lowerCAmelCase,  timestep=__lowerCAmelCase,  encoder_hidden_states=__lowerCAmelCase,  added_cond_kwargs=__lowerCAmelCase,  return_dict=__lowerCAmelCase,  )[0]

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

											# compute the previous noisy sample x_t -> x_t-1
											lowerCamelCase__		:		Any		     =self.scheduler.step(
											    __lowerCAmelCase,  __lowerCAmelCase,  __lowerCAmelCase,  generator=__lowerCAmelCase,  )[0]
								# post-processing
								lowerCamelCase__		:		List[str]		     =self.movq.decode(__lowerCAmelCase,  force_not_quantize=__lowerCAmelCase					)['''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__		:		Optional[Any]		     =image * 0.5 + 0.5
											lowerCamelCase__		:		Dict		     =image.clamp(0,  1					)
											lowerCamelCase__		:		Any		     =image.cpu().permute(0,  2,  3,  1					).float().numpy()

								if output_type == "pil":
											lowerCamelCase__		:		Union[str, Any]		     =self.numpy_to_pil(__lowerCAmelCase					)

								if not return_dict:
											return (image,)

								return ImagePipelineOutput(images=__lowerCAmelCase					)









"""simple docstring"""






import copy

from ...configuration_utils import PretrainedConfig
from ...utils import add_start_docstrings


_lowercase			:			Tuple										=						r"\n    [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and\n    can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.\n\n    Args:\n        title_sep (`str`, *optional*, defaults to  `\" / \"`):\n            Separator inserted between the title and the text of the retrieved document when calling [`RagRetriever`].\n        doc_sep (`str`, *optional*, defaults to  `\" // \"`):\n            Separator inserted between the text of the retrieved document and the original input when calling\n            [`RagRetriever`].\n        n_docs (`int`, *optional*, defaults to 5):\n            Number of documents to retrieve.\n        max_combined_length (`int`, *optional*, defaults to 300):\n            Max length of contextualized input returned by [`~RagRetriever.__call__`].\n        retrieval_vector_size (`int`, *optional*, defaults to 768):\n            Dimensionality of the document embeddings indexed by [`RagRetriever`].\n        retrieval_batch_size (`int`, *optional*, defaults to 8):\n            Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated\n            [`RagRetriever`].\n        dataset (`str`, *optional*, defaults to `\"wiki_dpr\"`):\n            A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids\n            using `datasets.list_datasets()`).\n        dataset_split (`str`, *optional*, defaults to `\"train\"`)\n            Which split of the `dataset` to load.\n        index_name (`str`, *optional*, defaults to `\"compressed\"`)\n            The index name of the index associated with the `dataset`. One can choose between `\"legacy\"`, `\"exact\"` and\n            `\"compressed\"`.\n        index_path (`str`, *optional*)\n            The path to the serialized faiss index on disk.\n        passages_path (`str`, *optional*):\n            A path to text passages compatible with the faiss index. Required if using\n            [`~models.rag.retrieval_rag.LegacyIndex`]\n        use_dummy_dataset (`bool`, *optional*, defaults to `False`)\n            Whether to load a \"dummy\" variant of the dataset specified by `dataset`.\n        label_smoothing (`float`, *optional*, defaults to 0.0):\n            Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing\n            in the loss calculation. If set to 0, no label smoothing is performed.\n        do_marginalize (`bool`, *optional*, defaults to `False`):\n            If `True`, the logits are marginalized over all documents by making use of\n            `torch.nn.functional.log_softmax`.\n        reduce_loss (`bool`, *optional*, defaults to `False`):\n            Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation.\n        do_deduplication (`bool`, *optional*, defaults to `True`):\n            Whether or not to deduplicate the generations from different context documents for a given input. Has to be\n            set to `False` if used while training with distributed backend.\n        exclude_bos_score (`bool`, *optional*, defaults to `False`):\n            Whether or not to disregard the BOS token when computing the loss.\n        output_retrieved(`bool`, *optional*, defaults to `False`):\n            If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and\n            `context_attention_mask` are returned. See returned tensors for more detail.\n        use_cache (`bool`, *optional*, defaults to `True`):\n            Whether or not the model should return the last key/values attentions (not used by all models).\n        forced_eos_token_id (`int`, *optional*):\n            The id of the token to force as the last generated token when `max_length` is reached. Usually set to\n            `eos_token_id`.\n"

@add_start_docstrings(lowerCAmelCase_       )
class 	__SCREAMING_SNAKE_CASE     (				lowerCAmelCase_       ):


					'''simple docstring'''





					_a             =							'rag'
					_a             =							True



					def __init__(	self							:  Optional[int],  lowerCamelCase							:  Union[str, Any]=None,  lowerCamelCase							:  Union[str, Any]=True,  lowerCamelCase							:  Dict=None,  lowerCamelCase							:  Optional[Any]=None,  lowerCamelCase							:  Any=None,  lowerCamelCase							:  List[Any]=None,  lowerCamelCase							:  Optional[Any]=None,  lowerCamelCase							:  Any=" / ",  lowerCamelCase							:  Union[str, Any]=" // ",  lowerCamelCase							:  List[Any]=5,  lowerCamelCase							:  int=300,  lowerCamelCase							:  Optional[Any]=768,  lowerCamelCase							:  Optional[Any]=8,  lowerCamelCase							:  Tuple="wiki_dpr",  lowerCamelCase							:  Tuple="train",  lowerCamelCase							:  Union[str, Any]="compressed",  lowerCamelCase							:  List[str]=None,  lowerCamelCase							:  Any=None,  lowerCamelCase							:  Union[str, Any]=False,  lowerCamelCase							:  Dict=False,  lowerCamelCase							:  Optional[int]=0.0,  lowerCamelCase							:  Any=True,  lowerCamelCase							:  Dict=False,  lowerCamelCase							:  Tuple=False,  lowerCamelCase							:  List[str]=False,  lowerCamelCase							:  List[Any]=True,  lowerCamelCase							:  Optional[Any]=None,  **lowerCamelCase							:  str,  )-> List[Any]:
								super().__init__(
								    bos_token_id=lowerCamelCase,  pad_token_id=lowerCamelCase,  eos_token_id=lowerCamelCase,  decoder_start_token_id=lowerCamelCase,  forced_eos_token_id=lowerCamelCase,  is_encoder_decoder=lowerCamelCase,  prefix=lowerCamelCase,  vocab_size=lowerCamelCase,  **lowerCamelCase,  )
								assert (
								    "question_encoder" in kwargs and "generator" in kwargs
								), "Config has to be initialized with question_encoder and generator config"
								lowerCamelCase__		:		Tuple		     =kwargs.pop('''question_encoder'''					)
								lowerCamelCase__		:		int		     =question_encoder_config.pop('''model_type'''					)
								lowerCamelCase__		:		Dict		     =kwargs.pop('''generator'''					)
								lowerCamelCase__		:		Tuple		     =decoder_config.pop('''model_type'''					)

								from ..auto.configuration_auto import AutoConfig

								lowerCamelCase__		:		Tuple		     =AutoConfig.for_model(lowerCamelCase,  **lowerCamelCase					)
								lowerCamelCase__		:		Dict		     =AutoConfig.for_model(lowerCamelCase,  **lowerCamelCase					)

								lowerCamelCase__		:		Any		     =reduce_loss
								lowerCamelCase__		:		Tuple		     =label_smoothing
								lowerCamelCase__		:		List[str]		     =exclude_bos_score
								lowerCamelCase__		:		Dict		     =do_marginalize

								lowerCamelCase__		:		Union[str, Any]		     =title_sep
								lowerCamelCase__		:		Dict		     =doc_sep
								lowerCamelCase__		:		List[Any]		     =n_docs
								lowerCamelCase__		:		List[str]		     =max_combined_length

								lowerCamelCase__		:		List[Any]		     =dataset
								lowerCamelCase__		:		int		     =dataset_split
								lowerCamelCase__		:		List[Any]		     =index_name

								lowerCamelCase__		:		int		     =retrieval_vector_size
								lowerCamelCase__		:		Dict		     =retrieval_batch_size
								lowerCamelCase__		:		str		     =passages_path
								lowerCamelCase__		:		Any		     =index_path
								lowerCamelCase__		:		List[Any]		     =use_dummy_dataset

								lowerCamelCase__		:		Optional[int]		     =output_retrieved

								lowerCamelCase__		:		List[str]		     =do_deduplication

								lowerCamelCase__		:		Tuple		     =use_cache

								if self.forced_eos_token_id is None:
											lowerCamelCase__		:		int		     =getattr(self.generator,  '''forced_eos_token_id''',  lowerCamelCase					)



					@classmethod
					def 		snake_case	(	cls							:  List[str],  lowerCamelCase							:  PretrainedConfig,  lowerCamelCase							:  PretrainedConfig,  **lowerCamelCase							:  int					)-> PretrainedConfig:
								return cls(question_encoder=question_encoder_config.to_dict(),  generator=generator_config.to_dict(),  **lowerCamelCase					)




					def 		snake_case	(	self							:  Optional[int]					)-> int:
								lowerCamelCase__		:		Union[str, Any]		     =copy.deepcopy(self.__dict__					)
								lowerCamelCase__		:		Optional[int]		     =self.question_encoder.to_dict()
								lowerCamelCase__		:		Tuple		     =self.generator.to_dict()
								lowerCamelCase__		:		Optional[Any]		     =self.__class__.model_type
								return output




