



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

a__      :				Optional[Any]   	=			"\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   _lowerCAmelCase   (						A__						,  A__						,  A__=8	):
      lowercase__     =  height // scale_factor**2
      if height % scale_factor**2 != 0:
            new_height += 1
      lowercase__     =  width // scale_factor**2
      if width % scale_factor**2 != 0:
            new_width += 1
      return new_height * scale_factor, new_width * scale_factor



class       UpperCAmelCase__(							lowercase_	):

   '''simple docstring'''




   def __init__(						self  :			Any			,				lowerCAmelCase  :			UNetaDConditionModel			,				lowerCAmelCase  :			DDPMScheduler			,				lowerCAmelCase  :			VQModel			,				)	->				Optional[Any]:




         """simple docstring"""

         super().__init__()

         self.register_modules(
             unet=UpperCamelCase__			,				scheduler=UpperCamelCase__			,				movq=UpperCamelCase__			,				)
         lowercase__     =  2 ** (len(self.movq.config.block_out_channels) - 1)


   def 			UpperCAmelCase		(						self  :			Any			,				lowerCAmelCase  :			Tuple			,				lowerCAmelCase  :			Optional[int]			,				lowerCAmelCase  :			Tuple			,				lowerCAmelCase  :			List[Any]			,				lowerCAmelCase  :			List[str]			,				lowerCAmelCase  :			Any)	->				Optional[int]:




         """simple docstring"""

         if latents is None:
               lowercase__     =  randn_tensor(UpperCamelCase__			,				generator=UpperCamelCase__			,				device=UpperCamelCase__			,				dtype=UpperCamelCase__)
         else:
               if latents.shape != shape:
                     raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}''')
               lowercase__     =  latents.to(UpperCamelCase__)

         lowercase__     =  latents * scheduler.init_noise_sigma
         return latents


   def 			UpperCAmelCase		(						self  :			Union[str, Any]			,				lowerCAmelCase  :			Optional[int]=0)	->				Optional[int]:




         """simple docstring"""

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

         lowercase__     =  torch.device(f'''cuda:{gpu_id}''')

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


   def 			UpperCAmelCase		(						self  :			List[str]			,				lowerCAmelCase  :			str=0)	->				List[Any]:




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

         lowercase__     =  torch.device(f'''cuda:{gpu_id}''')

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

         lowercase__     =  None
         for cpu_offloaded_model in [self.unet, self.movq]:
               lowercase__,	lowercase__     =  cpu_offload_with_hook(UpperCamelCase__			,				UpperCamelCase__			,				prev_module_hook=UpperCamelCase__)

         # We'll offload the last model manually.
         lowercase__     =  hook


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




         """simple docstring"""

         if not hasattr(self.unet			,				'_hf_hook'):
               return self.device
         for module in self.unet.modules():
               if (
                   hasattr(UpperCamelCase__			,				'_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(UpperCamelCase__)
   def __call__(						self  :			Tuple			,				lowerCAmelCase  :			Union[torch.FloatTensor, List[torch.FloatTensor]]			,				lowerCAmelCase  :			Union[torch.FloatTensor, List[torch.FloatTensor]]			,				lowerCAmelCase  :			int = 5_12			,				lowerCAmelCase  :			int = 5_12			,				lowerCAmelCase  :			int = 1_00			,				lowerCAmelCase  :			float = 4.0			,				lowerCAmelCase  :			int = 1			,				lowerCAmelCase  :			Optional[Union[torch.Generator, List[torch.Generator]]] = None			,				lowerCAmelCase  :			Optional[torch.FloatTensor] = None			,				lowerCAmelCase  :			Optional[str] = "pil"			,				lowerCAmelCase  :			bool = True			,				)	->				str:




         """simple docstring"""

         lowercase__     =  self._execution_device

         lowercase__     =  guidance_scale > 1.0

         if isinstance(UpperCamelCase__			,				UpperCamelCase__):
               lowercase__     =  torch.cat(UpperCamelCase__			,				dim=0)
         lowercase__     =  image_embeds.shape[0] * num_images_per_prompt
         if isinstance(UpperCamelCase__			,				UpperCamelCase__):
               lowercase__     =  torch.cat(UpperCamelCase__			,				dim=0)

         if do_classifier_free_guidance:
               lowercase__     =  image_embeds.repeat_interleave(UpperCamelCase__			,				dim=0)
               lowercase__     =  negative_image_embeds.repeat_interleave(UpperCamelCase__			,				dim=0)

         lowercase__     =  torch.cat([negative_image_embeds, image_embeds]			,				dim=0).to(dtype=self.unet.dtype			,				device=UpperCamelCase__)

         self.scheduler.set_timesteps(UpperCamelCase__			,				device=UpperCamelCase__)
         lowercase__     =  self.scheduler.timesteps

         lowercase__     =  self.unet.config.in_channels

         lowercase__,	lowercase__     =  downscale_height_and_width(UpperCamelCase__			,				UpperCamelCase__			,				self.movq_scale_factor)

         # create initial latent
         lowercase__     =  self.prepare_latents(
             (batch_size, num_channels_latents, height, width)			,				image_embeds.dtype			,				UpperCamelCase__			,				UpperCamelCase__			,				UpperCamelCase__			,				self.scheduler			,				)

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

               lowercase__     =  {'image_embeds': image_embeds}
               lowercase__     =  self.unet(
                   sample=UpperCamelCase__			,				timestep=UpperCamelCase__			,				encoder_hidden_states=UpperCamelCase__			,				added_cond_kwargs=UpperCamelCase__			,				return_dict=UpperCamelCase__			,				)[0]

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

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

         if output_type == "pil":
               lowercase__     =  self.numpy_to_pil(UpperCamelCase__)

         if not return_dict:
               return (image,)

         return ImagePipelineOutput(images=UpperCamelCase__)





from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


a__      :				int   	=			"\\n@misc{wu2016googles,\n      title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n      author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n              and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n              Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n              Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n              Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n              and Jeffrey Dean},\n      year={2016},\n      eprint={1609.08144},\n      archivePrefix={arXiv},\n      primaryClass={cs.CL}\n}\n"

a__      :				Optional[Any]   	=			"\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe 'GLEU score'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore's range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n"

a__      :				Tuple   	=			"\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n    predictions (list of str): list of translations to score.\n        Each translation should be tokenized into a list of tokens.\n    references (list of list of str): list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\n    min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n    max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n    'google_bleu': google_bleu score\n\nExamples:\n    Example 1:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.44\n\n    Example 2:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n        ...          'heed', 'the', 'cat', 'commands']\n        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n        ...          'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.61\n\n    Example 3:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n        ...          'heed', 'the', 'cat', 'commands']\n        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n        ...          'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.53\n\n    Example 4:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n        ...          'heed', 'the', 'cat', 'commands']\n        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n        ...          'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.4\n"



@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,							_KWARGS_DESCRIPTION	)
class       UpperCAmelCase__(							datasets.Metric	):

   '''simple docstring'''




   def 			UpperCAmelCase		(						self  :			List[Any])	->				MetricInfo:




         """simple docstring"""

         return datasets.MetricInfo(
             description=_DESCRIPTION			,				citation=_CITATION			,				inputs_description=_KWARGS_DESCRIPTION			,				features=datasets.Features(
                 {
                     'predictions': datasets.Sequence(datasets.Value('string'			,				id='token')			,				id='sequence'),
                     'references': datasets.Sequence(
                         datasets.Sequence(datasets.Value('string'			,				id='token')			,				id='sequence')			,				id='references'),
                 })			,				)



   def 			UpperCAmelCase		(						self  :			int			,				lowerCAmelCase  :			List[List[List[str]]]			,				lowerCAmelCase  :			List[List[str]]			,				lowerCAmelCase  :			int = 1			,				lowerCAmelCase  :			int = 4			,				)	->				Dict[str, float]:




         """simple docstring"""

         return {
             "google_bleu": gleu_score.corpus_gleu(
                 list_of_references=lowerCAmelCase			,				hypotheses=lowerCAmelCase			,				min_len=lowerCAmelCase			,				max_len=lowerCAmelCase)
         }
