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


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

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







def 	__a     (		__lowerCamelCase,		__lowerCamelCase,		__lowerCamelCase=8  ):
   UpperCAmelCase_					:					Union[str, Any]			     =    height // scale_factor**2
   if height % scale_factor**2 != 0:
      new_height += 1
   UpperCAmelCase_					:					Tuple			     =    width // scale_factor**2
   if width % scale_factor**2 != 0:
      new_width += 1
   return new_height * scale_factor, new_width * scale_factor


class A_	(lowercase__      ):




  '''simple docstring'''







  def __init__(		self				,   lowercase_				,   lowercase_				,   lowercase_				,   ):

     """simple docstring"""
     super().__init__()

     self.register_modules(
         unet=lowercase_				,   scheduler=lowercase_				,   movq=lowercase_				,   )
     UpperCAmelCase_					:					Union[str, Any]			     =    2 ** (len(self.movq.config.block_out_channels  ) - 1)







  def        UpperCamelCase__					(		self				,   lowercase_				,   lowercase_				,   lowercase_				,   lowercase_				,   lowercase_				,   lowercase_  ):

     """simple docstring"""
     if latents is None:
        UpperCAmelCase_					:					List[Any]			     =    randn_tensor(lowercase_				,   generator=lowercase_				,   device=lowercase_				,   dtype=lowercase_  )
     else:
        if latents.shape != shape:
           raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}"""  )
        UpperCAmelCase_					:					int			     =    latents.to(lowercase_  )

     UpperCAmelCase_					:					List[Any]			     =    latents * scheduler.init_noise_sigma
     return latents







  def        UpperCamelCase__					(		self				,   lowercase_=0  ):

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

     UpperCAmelCase_					:					Dict			     =    torch.device(F"""cuda:{gpu_id}"""  )

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







  def        UpperCamelCase__					(		self				,   lowercase_=0  ):

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

     UpperCAmelCase_					:					Tuple			     =    torch.device(F"""cuda:{gpu_id}"""  )

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

     UpperCAmelCase_					:					Union[str, Any]			     =    None
     for cpu_offloaded_model in [self.unet, self.movq]:
        UpperCAmelCase_     ,   UpperCAmelCase_					:					int			     =    cpu_offload_with_hook(lowercase_				,   lowercase_				,   prev_module_hook=lowercase_  )

     # We'll offload the last model manually.
     UpperCAmelCase_					:					Dict			     =    hook







  @property
  # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
  def        UpperCamelCase__					(		self  ):

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

     """simple docstring"""
     UpperCAmelCase_					:					Optional[Any]			     =    self._execution_device

     UpperCAmelCase_					:					Dict			     =    guidance_scale > 1.0

     if isinstance(lowercase_				,   lowercase_  ):
        UpperCAmelCase_					:					Optional[int]			     =    torch.cat(lowercase_				,   dim=0  )
     UpperCAmelCase_					:					List[str]			     =    image_embeds.shape[0] * num_images_per_prompt
     if isinstance(lowercase_				,   lowercase_  ):
        UpperCAmelCase_					:					Any			     =    torch.cat(lowercase_				,   dim=0  )

     if do_classifier_free_guidance:
        UpperCAmelCase_					:					Optional[Any]			     =    image_embeds.repeat_interleave(lowercase_				,   dim=0  )
        UpperCAmelCase_					:					Tuple			     =    negative_image_embeds.repeat_interleave(lowercase_				,   dim=0  )

     UpperCAmelCase_					:					Union[str, Any]			     =    torch.cat([negative_image_embeds, image_embeds]				,   dim=0  ).to(dtype=self.unet.dtype				,   device=lowercase_  )

     self.scheduler.set_timesteps(lowercase_				,   device=lowercase_  )
     UpperCAmelCase_					:					Any			     =    self.scheduler.timesteps

     UpperCAmelCase_					:					List[Any]			     =    self.unet.config.in_channels

     UpperCAmelCase_     ,   UpperCAmelCase_					:					Optional[Any]			     =    downscale_height_and_width(lowercase_				,   lowercase_				,   self.movq_scale_factor  )

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

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

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

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

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

     if output_type == "pil":
        UpperCAmelCase_					:					Tuple			     =    self.numpy_to_pil(lowercase_  )

     if not return_dict:
        return (image,)

     return ImagePipelineOutput(images=lowercase_  )




"""simple docstring"""





import os
from shutil import copyfile
from typing import List, Optional, Tuple

from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
    from .tokenization_fnet import FNetTokenizer
else:
    _a		       =							None

_a		       =							logging.get_logger(__name__)
_a		       =							{'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'}

_a		       =							{
    'vocab_file': {
        'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/spiece.model',
        'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/spiece.model',
    },
    'tokenizer_file': {
        'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json',
        'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json',
    },
}

_a		       =							{
    'google/fnet-base': 512,
    'google/fnet-large': 512,
}

_a		       =							'▁'


class A_	(lowercase__      ):




  '''simple docstring'''
  SCREAMING_SNAKE_CASE__			:						List[str]       =		VOCAB_FILES_NAMES
  SCREAMING_SNAKE_CASE__			:						Tuple       =		PRETRAINED_VOCAB_FILES_MAP
  SCREAMING_SNAKE_CASE__			:						Any       =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  SCREAMING_SNAKE_CASE__			:						Union[str, Any]       =		["""input_ids""", """token_type_ids"""]
  SCREAMING_SNAKE_CASE__			:						Tuple       =		FNetTokenizer







  def __init__(		self				,   lowercase_=None				,   lowercase_=None				,   lowercase_=False				,   lowercase_=True				,   lowercase_=True				,   lowercase_="<unk>"				,   lowercase_="[SEP]"				,   lowercase_="<pad>"				,   lowercase_="[CLS]"				,   lowercase_="[MASK]"				,   **lowercase_				,   ):

     """simple docstring"""
     # Mask token behave like a normal word, i.e. include the space before it and
     # is included in the raw text, there should be a match in a non-normalized sentence.
     UpperCAmelCase_					:					int			     =    (
         AddedToken(lowercase_				,   lstrip=lowercase_				,   rstrip=lowercase_				,   normalized=lowercase_  )
         if isinstance(lowercase_				,   lowercase_  )
         else mask_token
     )

     super().__init__(
         lowercase_				,   tokenizer_file=lowercase_				,   do_lower_case=lowercase_				,   remove_space=lowercase_				,   keep_accents=lowercase_				,   unk_token=lowercase_				,   sep_token=lowercase_				,   pad_token=lowercase_				,   cls_token=lowercase_				,   mask_token=lowercase_				,   **lowercase_				,   )

     UpperCAmelCase_					:					Any			     =    do_lower_case
     UpperCAmelCase_					:					Tuple			     =    remove_space
     UpperCAmelCase_					:					str			     =    keep_accents
     UpperCAmelCase_					:					Any			     =    vocab_file
     UpperCAmelCase_					:					List[Any]			     =    False if not self.vocab_file else True







  def        UpperCamelCase__					(		self				,   lowercase_				,   lowercase_ = None  ):

     """simple docstring"""
     UpperCAmelCase_					:					Tuple			     =    [self.sep_token_id]
     UpperCAmelCase_					:					Any			     =    [self.cls_token_id]
     if token_ids_a is None:
        return cls + token_ids_a + sep
     return cls + token_ids_a + sep + token_ids_a + sep







  def        UpperCamelCase__					(		self				,   lowercase_				,   lowercase_ = None  ):

     """simple docstring"""
     UpperCAmelCase_					:					Any			     =    [self.sep_token_id]
     UpperCAmelCase_					:					Any			     =    [self.cls_token_id]

     if token_ids_a is None:
        return len(cls + token_ids_a + sep  ) * [0]
     return len(cls + token_ids_a + sep  ) * [0] + len(token_ids_a + sep  ) * [1]







  def        UpperCamelCase__					(		self				,   lowercase_				,   lowercase_ = None  ):

     """simple docstring"""
     if not os.path.isdir(lowercase_  ):
        logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""  )
        return
     UpperCAmelCase_					:					List[str]			     =    os.path.join(
         lowercase_				,   (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]  )

     if os.path.abspath(self.vocab_file  ) != os.path.abspath(lowercase_  ):
        copyfile(self.vocab_file				,   lowercase_  )

     return (out_vocab_file,)


