



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


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

_lowerCAmelCase    : List[str]							=							"\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 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						Dict						,  SCREAMING_SNAKE_CASE__     :						Tuple						,  SCREAMING_SNAKE_CASE__     :						Tuple=8    )  ->       Optional[int]:





     '''simple docstring'''

     _UpperCAmelCase      :     Any        =   height // scale_factor**2
     if height % scale_factor**2 != 0:
          new_height += 1
     _UpperCAmelCase      :     List[Any]        =   width // scale_factor**2
     if width % scale_factor**2 != 0:
          new_width += 1
     return new_height * scale_factor, new_width * scale_factor






class      UpperCAmelCase_  (    _UpperCamelCase						):



      def __init__(					self					:     List[Any]					,     A					:     UNetaDConditionModel					,     A					:     DDPMScheduler					,     A					:     VQModel					,     ):
           super().__init__()

           self.register_modules(
               unet=A					,     scheduler=A					,     movq=A					,     )
           _UpperCAmelCase      :     Optional[Any]        =   2 ** (len(self.movq.config.block_out_channels						) - 1)



      def 						snake_case_ (					self					:     int					,     A					:     List[str]					,     A					:     Tuple					,     A					:     Dict					,     A					:     Any					,     A					:     Optional[int]					,     A					:     List[Any]						):
           if latents is None:
                _UpperCAmelCase      :     int        =   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      :     Union[str, Any]        =   latents.to(A						)

           _UpperCAmelCase      :     List[str]        =   latents * scheduler.init_noise_sigma
           return latents



      def 						snake_case_ (					self					:     Dict					,     A					:     Union[str, Any]=0						):
           if is_accelerate_available():
                from accelerate import cpu_offload
           else:
                raise ImportError("Please install accelerate via `pip install accelerate`"						)

           _UpperCAmelCase      :     List[Any]        =   torch.device(f'cuda:{gpu_id}'						)

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



      def 						snake_case_ (					self					:     int					,     A					:     str=0						):
           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      :     str        =   None
           for cpu_offloaded_model in [self.unet, self.movq]:
                _UpperCAmelCase      :     List[str]        =   cpu_offload_with_hook(A					,     A					,     prev_module_hook=A						)

           # We'll offload the last model manually.
           _UpperCAmelCase      :     str        =   hook



      @property
      # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
      def 						snake_case_ (					self					:     Optional[Any]						):
           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					:     Optional[Any]					,     A					:     Union[torch.FloatTensor, List[torch.FloatTensor]]					,     A					:     Union[torch.FloatTensor, List[torch.FloatTensor]]					,     A					:     int = 5_1_2					,     A					:     int = 5_1_2					,     A					:     int = 1_0_0					,     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					,     ):
           _UpperCAmelCase      :     Optional[Any]        =   self._execution_device

           _UpperCAmelCase      :     str        =   guidance_scale > 1.0

           if isinstance(A					,     A						):
                _UpperCAmelCase      :     Tuple        =   torch.cat(A					,     dim=0						)
           _UpperCAmelCase      :     Union[str, Any]        =   image_embeds.shape[0] * num_images_per_prompt
           if isinstance(A					,     A						):
                _UpperCAmelCase      :     List[Any]        =   torch.cat(A					,     dim=0						)

           if do_classifier_free_guidance:
                _UpperCAmelCase      :     Union[str, Any]        =   image_embeds.repeat_interleave(A					,     dim=0						)
                _UpperCAmelCase      :     List[Any]        =   negative_image_embeds.repeat_interleave(A					,     dim=0						)

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

           self.scheduler.set_timesteps(A					,     device=A						)
           _UpperCAmelCase      :     List[str]        =   self.scheduler.timesteps

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

           _UpperCAmelCase      :     Dict        =   downscale_height_and_width(A					,     A					,     self.movq_scale_factor						)

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

                _UpperCAmelCase      :     Any        =   {"image_embeds": image_embeds}
                _UpperCAmelCase      :     Dict        =   self.unet(
                    sample=A					,     timestep=A					,     encoder_hidden_states=A					,     added_cond_kwargs=A					,     return_dict=A					,     )[0]

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

                # compute the previous noisy sample x_t -> x_t-1
                _UpperCAmelCase      :     Optional[Any]        =   self.scheduler.step(
                    A					,     A					,     A					,     generator=A					,     )[0]
           # post-processing
           _UpperCAmelCase      :     Union[str, 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      :     str        =   image * 0.5 + 0.5
                _UpperCAmelCase      :     Dict        =   image.clamp(0					,     1						)
                _UpperCAmelCase      :     Dict        =   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"""




from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


_lowerCAmelCase    : Tuple							=							"\\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"

_lowerCAmelCase    : Optional[int]							=							"\\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"

_lowerCAmelCase    : Any							=							"\\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						):



      def 						snake_case_ (					self					:     List[str]						):
           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 						snake_case_ (					self					:     str					,     A					:     List[List[List[str]]]					,     A					:     List[List[str]]					,     A					:     int = 1					,     A					:     int = 4					,     ):
           return {
               "google_bleu": gleu_score.corpus_gleu(
                   list_of_references=A					,     hypotheses=A					,     min_len=A					,     max_len=A						)
           }
