


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


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

UpperCamelCase__    					=      '''
    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 					a__       (					lowerCAmelCase__  ,					lowerCAmelCase__  ,					lowerCAmelCase__=8						)    ->	str:
    UpperCAmelCase__			:		Optional[int]													=				height // scale_factor**2
    if height % scale_factor**2 != 0:
        new_height += 1
    UpperCAmelCase__			:		Any													=				width // scale_factor**2
    if width % scale_factor**2 != 0:
        new_width += 1
    return new_height * scale_factor, new_width * scale_factor







class 			lowerCamelCase_   (	__a      ):






      def __init__(					self				:    Optional[int]						,						_A				:    UNetaDConditionModel						,						_A				:    DDPMScheduler						,						_A				:    VQModel						,						):


          '''simple docstring'''


          super().__init__()

          self.register_modules(
              unet=_A						,						scheduler=_A						,						movq=_A						,						)
          UpperCAmelCase__			:		List[Any]													=				2 ** (len(self.movq.config.block_out_channels ) - 1)






      def lowercase_							(					self				:    List[str]						,						_A				:    Tuple						,						_A				:    Union[str, Any]						,						_A				:    List[str]						,						_A				:    Optional[Any]						,						_A				:    Any						,						_A				:    List[Any] ):


          '''simple docstring'''


          if latents is None:
              UpperCAmelCase__			:		Dict													=				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}""" )
              UpperCAmelCase__			:		Dict													=				latents.to(_A )

          UpperCAmelCase__			:		Tuple													=				latents * scheduler.init_noise_sigma
          return latents






      def lowercase_							(					self				:    Any						,						_A				:    Optional[int]=0 ):


          '''simple docstring'''


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

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

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






      def lowercase_							(					self				:    Tuple						,						_A				:    Optional[int]=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__			:		Optional[int]													=				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)

          UpperCAmelCase__			:		List[Any]													=				None
          for cpu_offloaded_model in [self.unet, self.movq]:
              UpperCAmelCase__						,						UpperCAmelCase__			:		Union[str, Any]													=				cpu_offload_with_hook(_A						,						_A						,						prev_module_hook=_A )

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






      @property
      # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
      def lowercase_							(					self				:    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				:    Tuple						,						_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						,						):


          '''simple docstring'''


          UpperCAmelCase__			:		Any													=				self._execution_device

          UpperCAmelCase__			:		Optional[int]													=				guidance_scale > 1.0

          if isinstance(_A						,						_A ):
              UpperCAmelCase__			:		List[Any]													=				torch.cat(_A						,						dim=0 )
          if isinstance(_A						,						_A ):
              UpperCAmelCase__			:		List[str]													=				torch.cat(_A						,						dim=0 )
          if isinstance(_A						,						_A ):
              UpperCAmelCase__			:		Optional[int]													=				torch.cat(_A						,						dim=0 )

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

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

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

          UpperCAmelCase__			:		Optional[Any]													=				self.movq.config.latent_channels

          UpperCAmelCase__						,						UpperCAmelCase__			:		str													=				downscale_height_and_width(_A						,						_A						,						self.movq_scale_factor )

          # create initial latent
          UpperCAmelCase__			:		Optional[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
              UpperCAmelCase__			:		int													=				torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents

              UpperCAmelCase__			:		List[str]													=				{'''image_embeds''': image_embeds, '''hint''': hint}
              UpperCAmelCase__			:		int													=				self.unet(
                  sample=_A						,						timestep=_A						,						encoder_hidden_states=_A						,						added_cond_kwargs=_A						,						return_dict=_A						,						)[0]

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

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

          if output_type == "pil":
              UpperCAmelCase__			:		Any													=				self.numpy_to_pil(_A )

          if not return_dict:
              return (image,)

          return ImagePipelineOutput(images=_A )




'''simple docstring'''
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


UpperCamelCase__    					=      logging.get_logger(__name__)

UpperCamelCase__    					=      '''▁'''

UpperCamelCase__    					=      {'''vocab_file''': '''sentencepiece.bpe.model'''}

UpperCamelCase__    					=      {
    '''vocab_file''': {
        '''facebook/xglm-564M''': '''https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model''',
    }
}

UpperCamelCase__    					=      {
    '''facebook/xglm-564M''': 2_0_4_8,
}




class 			lowerCamelCase_   (	__a      ):
      lowerCAmelCase__		     =     VOCAB_FILES_NAMES
      lowerCAmelCase__		     =     PRETRAINED_VOCAB_FILES_MAP
      lowerCAmelCase__		     =     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      lowerCAmelCase__		     =     ['input_ids', 'attention_mask']






      def __init__(					self				:    Optional[int]						,						_A				:    Optional[Any]						,						_A				:    Optional[Any]="<s>"						,						_A				:    List[str]="</s>"						,						_A				:    Optional[Any]="</s>"						,						_A				:    List[str]="<s>"						,						_A				:    Tuple="<unk>"						,						_A				:    List[str]="<pad>"						,						_A				:    Optional[Dict[str, Any]] = None						,						**_A				:    Union[str, Any]						,						):


          '''simple docstring'''


          UpperCAmelCase__			:		str													=				{} if sp_model_kwargs is None else sp_model_kwargs

          # Compatibility with the original tokenizer
          UpperCAmelCase__			:		Optional[int]													=				7
          UpperCAmelCase__			:		Optional[int]													=				[f"""<madeupword{i}>""" for i in range(self.num_madeup_words )]

          UpperCAmelCase__			:		Tuple													=				kwargs.get('''additional_special_tokens'''						,						[] )
          kwargs["additional_special_tokens"] += [
              word for word in madeup_words if word not in kwargs["additional_special_tokens"]
          ]

          super().__init__(
              bos_token=_A						,						eos_token=_A						,						unk_token=_A						,						sep_token=_A						,						cls_token=_A						,						pad_token=_A						,						sp_model_kwargs=self.sp_model_kwargs						,						**_A						,						)

          UpperCAmelCase__			:		Any													=				spm.SentencePieceProcessor(**self.sp_model_kwargs )
          self.sp_model.Load(str(_A ) )
          UpperCAmelCase__			:		List[str]													=				vocab_file

          # Original fairseq vocab and spm vocab must be "aligned":
          # Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
          # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
          # fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
          # spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

          # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
          UpperCAmelCase__			:		Any													=				1

          # Mimic fairseq token-to-id alignment for the first 4 token
          UpperCAmelCase__			:		Any													=				{'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3}

          UpperCAmelCase__			:		int													=				len(self.sp_model )
          UpperCAmelCase__			:		Optional[int]													=				{f"""<madeupword{i}>""": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words )}
          self.fairseq_tokens_to_ids.update(_A )

          UpperCAmelCase__			:		Tuple													=				{v: k for k, v in self.fairseq_tokens_to_ids.items()}






      def __getstate__(					self				:    Any ):


          '''simple docstring'''


          UpperCAmelCase__			:		Dict													=				self.__dict__.copy()
          UpperCAmelCase__			:		Optional[int]													=				None
          UpperCAmelCase__			:		Optional[Any]													=				self.sp_model.serialized_model_proto()
          return state






      def __setstate__(					self				:    Union[str, Any]						,						_A				:    int ):


          '''simple docstring'''


          UpperCAmelCase__			:		List[Any]													=				d

          # for backward compatibility
          if not hasattr(self						,						'''sp_model_kwargs''' ):
              UpperCAmelCase__			:		Dict													=				{}

          UpperCAmelCase__			:		str													=				spm.SentencePieceProcessor(**self.sp_model_kwargs )
          self.sp_model.LoadFromSerializedProto(self.sp_model_proto )






      def lowercase_							(					self				:    Any						,						_A				:    List[int]						,						_A				:    Optional[List[int]] = None ):


          '''simple docstring'''


          if token_ids_a is None:
              return [self.sep_token_id] + token_ids_a
          UpperCAmelCase__			:		Dict													=				[self.sep_token_id]
          return sep + token_ids_a + sep + sep + token_ids_a






      def lowercase_							(					self				:    str						,						_A				:    List[int]						,						_A				:    Optional[List[int]] = None						,						_A				:    bool = False ):


          '''simple docstring'''


          if already_has_special_tokens:
              return super().get_special_tokens_mask(
                  token_ids_a=_A						,						token_ids_a=_A						,						already_has_special_tokens=_A )

          if token_ids_a is None:
              return [1] + ([0] * len(_A ))
          return [1] + ([0] * len(_A )) + [1, 1] + ([0] * len(_A ))






      def lowercase_							(					self				:    Any						,						_A				:    List[int]						,						_A				:    Optional[List[int]] = None ):


          '''simple docstring'''


          UpperCAmelCase__			:		Optional[int]													=				[self.sep_token_id]

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






      @property
      def lowercase_							(					self				:    Any ):


          '''simple docstring'''


          return len(self.sp_model ) + self.fairseq_offset + self.num_madeup_words






      def lowercase_							(					self				:    Union[str, Any] ):


          '''simple docstring'''


          UpperCAmelCase__			:		str													=				{self.convert_ids_to_tokens(_A ): i for i in range(self.vocab_size )}
          vocab.update(self.added_tokens_encoder )
          return vocab






      def lowercase_							(					self				:    Optional[Any]						,						_A				:    str ):


          '''simple docstring'''


          return self.sp_model.encode(_A						,						out_type=_A )






      def lowercase_							(					self				:    List[str]						,						_A				:    List[Any] ):


          '''simple docstring'''


          if token in self.fairseq_tokens_to_ids:
              return self.fairseq_tokens_to_ids[token]
          UpperCAmelCase__			:		Union[str, Any]													=				self.sp_model.PieceToId(_A )

          # Need to return unknown token if the SP model returned 0
          return spm_id + self.fairseq_offset if spm_id else self.unk_token_id






      def lowercase_							(					self				:    List[Any]						,						_A				:    str ):


          '''simple docstring'''


          if index in self.fairseq_ids_to_tokens:
              return self.fairseq_ids_to_tokens[index]
          return self.sp_model.IdToPiece(index - self.fairseq_offset )






      def lowercase_							(					self				:    int						,						_A				:    Optional[int] ):


          '''simple docstring'''


          UpperCAmelCase__			:		List[str]													=				''''''.join(_A ).replace(_A						,						''' ''' ).strip()
          return out_string






      def lowercase_							(					self				:    Any						,						_A				:    str						,						_A				:    Optional[str] = None ):


          '''simple docstring'''


          if not os.path.isdir(_A ):
              logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" )
              return
          UpperCAmelCase__			:		List[str]													=				os.path.join(
              _A						,						(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )

          if os.path.abspath(self.vocab_file ) != os.path.abspath(_A ) and os.path.isfile(self.vocab_file ):
              copyfile(self.vocab_file						,						_A )
          elif not os.path.isfile(self.vocab_file ):
              with open(_A						,						'''wb''' ) as fi:
                  UpperCAmelCase__			:		List[Any]													=				self.sp_model.serialized_model_proto()
                  fi.write(_A )

          return (out_vocab_file,)
