




"""simple docstring"""






import gc
import random
import unittest

import torch

from diffusers import (
    IFImgaImgPipeline,
    IFImgaImgSuperResolutionPipeline,
    IFInpaintingPipeline,
    IFInpaintingSuperResolutionPipeline,
    IFPipeline,
    IFSuperResolutionPipeline,
)
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
from . import IFPipelineTesterMixin






@skip_mps
class lowerCAmelCase__			(  lowercase,			lowercase,			unittest.TestCase		):






			'''simple docstring'''



			lowerCamelCase__   =    IFPipeline
			lowerCamelCase__   =    TEXT_TO_IMAGE_PARAMS - {"""width""", """height""", """latents"""}
			lowerCamelCase__   =    TEXT_TO_IMAGE_BATCH_PARAMS
			lowerCamelCase__   =    PipelineTesterMixin.required_optional_params - {"""latents"""}
			def       A_					(						self						):
							return self._get_dummy_components()
			def       A_					(						self						,   lowercase						,   lowercase=0						):
							if str(lowercase						).startswith('mps'						):
											_lowerCamelCase  :    List[str]					=					torch.manual_seed(lowercase						)
							else:
											_lowerCamelCase  :    Optional[Any]					=					torch.Generator(device=lowercase						).manual_seed(lowercase						)

							_lowerCamelCase  :    Optional[Any]					=					{
							    'prompt': 'A painting of a squirrel eating a burger',
							    'generator': generator,
							    'num_inference_steps': 2,
							    'output_type': 'numpy',
							}

							return inputs
			def       A_					(						self						):
							self._test_save_load_optional_components()
			@unittest.skipIf(torch_device != 'cuda'						,   reason='float16 requires CUDA'						)
			def       A_					(						self						):
							# Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
							super().test_save_load_floataa(expected_max_diff=1E-1						)
			def       A_					(						self						):
							self._test_attention_slicing_forward_pass(expected_max_diff=1E-2						)
			def       A_					(						self						):
							self._test_save_load_local()
			def       A_					(						self						):
							self._test_inference_batch_single_identical(
							    expected_max_diff=1E-2						,   )






			@unittest.skipIf(
			    torch_device != 'cuda' or not is_xformers_available()						,   reason='XFormers attention is only available with CUDA and `xformers` installed'						,   )
			def       A_					(						self						):
							self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3						)






@slow
@require_torch_gpu
class lowerCAmelCase__			(  unittest.TestCase		):






			'''simple docstring'''



			def       A_					(						self						):
							# clean up the VRAM after each test
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()
			def       A_					(						self						):
							# if

							_lowerCamelCase  :    Any					=					IFPipeline.from_pretrained('DeepFloyd/IF-I-XL-v1.0'						,   variant='fp16'						,   torch_dtype=torch.floataa						)

							_lowerCamelCase  :    Union[str, Any]					=					IFSuperResolutionPipeline.from_pretrained(
							    'DeepFloyd/IF-II-L-v1.0'						,   variant='fp16'						,   torch_dtype=torch.floataa						,   text_encoder=lowercase						,   tokenizer=lowercase						)

							# pre compute text embeddings and remove T5 to save memory

							pipe_a.text_encoder.to('cuda'						)

							_lowerCamelCase,				_lowerCamelCase  :    Dict					=					pipe_a.encode_prompt('anime turtle'						,   device='cuda'						)

							del pipe_a.tokenizer
							del pipe_a.text_encoder
							gc.collect()

							_lowerCamelCase  :    Dict					=					None
							_lowerCamelCase  :    List[str]					=					None

							pipe_a.enable_model_cpu_offload()
							pipe_a.enable_model_cpu_offload()

							pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()						)
							pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()						)

							self._test_if(lowercase						,   lowercase						,   lowercase						,   lowercase						)

							pipe_a.remove_all_hooks()
							pipe_a.remove_all_hooks()

							# img2img

							_lowerCamelCase  :    Tuple					=					IFImgaImgPipeline(**pipe_a.components						)
							_lowerCamelCase  :    List[Any]					=					IFImgaImgSuperResolutionPipeline(**pipe_a.components						)

							pipe_a.enable_model_cpu_offload()
							pipe_a.enable_model_cpu_offload()

							pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()						)
							pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()						)

							self._test_if_imgaimg(lowercase						,   lowercase						,   lowercase						,   lowercase						)

							pipe_a.remove_all_hooks()
							pipe_a.remove_all_hooks()

							# inpainting

							_lowerCamelCase  :    Optional[Any]					=					IFInpaintingPipeline(**pipe_a.components						)
							_lowerCamelCase  :    Any					=					IFInpaintingSuperResolutionPipeline(**pipe_a.components						)

							pipe_a.enable_model_cpu_offload()
							pipe_a.enable_model_cpu_offload()

							pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()						)
							pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()						)

							self._test_if_inpainting(lowercase						,   lowercase						,   lowercase						,   lowercase						)
			def       A_					(						self						,   lowercase						,   lowercase						,   lowercase						,   lowercase						):
							# pipeline 1

							_start_torch_memory_measurement()

							_lowerCamelCase  :    List[Any]					=					torch.Generator(device='cpu'						).manual_seed(0						)
							_lowerCamelCase  :    Dict					=					pipe_a(
							    prompt_embeds=lowercase						,   negative_prompt_embeds=lowercase						,   num_inference_steps=2						,   generator=lowercase						,   output_type='np'						,   )

							_lowerCamelCase  :    Union[str, Any]					=					output.images[0]

							assert image.shape == (64, 64, 3)

							_lowerCamelCase  :    List[Any]					=					torch.cuda.max_memory_allocated()
							assert mem_bytes < 13 * 10**9

							_lowerCamelCase  :    int					=					load_numpy(
							    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy'						)
							assert_mean_pixel_difference(lowercase						,   lowercase						)

							# pipeline 2

							_start_torch_memory_measurement()

							_lowerCamelCase  :    List[str]					=					torch.Generator(device='cpu'						).manual_seed(0						)

							_lowerCamelCase  :    List[Any]					=					floats_tensor((1, 3, 64, 64)						,   rng=random.Random(0						)						).to(lowercase						)

							_lowerCamelCase  :    List[str]					=					pipe_a(
							    prompt_embeds=lowercase						,   negative_prompt_embeds=lowercase						,   image=lowercase						,   generator=lowercase						,   num_inference_steps=2						,   output_type='np'						,   )

							_lowerCamelCase  :    Any					=					output.images[0]

							assert image.shape == (256, 256, 3)

							_lowerCamelCase  :    Tuple					=					torch.cuda.max_memory_allocated()
							assert mem_bytes < 4 * 10**9

							_lowerCamelCase  :    Optional[Any]					=					load_numpy(
							    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy'						)
							assert_mean_pixel_difference(lowercase						,   lowercase						)
			def       A_					(						self						,   lowercase						,   lowercase						,   lowercase						,   lowercase						):
							# pipeline 1

							_start_torch_memory_measurement()

							_lowerCamelCase  :    Optional[int]					=					floats_tensor((1, 3, 64, 64)						,   rng=random.Random(0						)						).to(lowercase						)

							_lowerCamelCase  :    Any					=					torch.Generator(device='cpu'						).manual_seed(0						)

							_lowerCamelCase  :    List[Any]					=					pipe_a(
							    prompt_embeds=lowercase						,   negative_prompt_embeds=lowercase						,   image=lowercase						,   num_inference_steps=2						,   generator=lowercase						,   output_type='np'						,   )

							_lowerCamelCase  :    Tuple					=					output.images[0]

							assert image.shape == (64, 64, 3)

							_lowerCamelCase  :    List[str]					=					torch.cuda.max_memory_allocated()
							assert mem_bytes < 10 * 10**9

							_lowerCamelCase  :    Optional[int]					=					load_numpy(
							    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy'						)
							assert_mean_pixel_difference(lowercase						,   lowercase						)

							# pipeline 2

							_start_torch_memory_measurement()

							_lowerCamelCase  :    List[str]					=					torch.Generator(device='cpu'						).manual_seed(0						)

							_lowerCamelCase  :    List[str]					=					floats_tensor((1, 3, 256, 256)						,   rng=random.Random(0						)						).to(lowercase						)
							_lowerCamelCase  :    int					=					floats_tensor((1, 3, 64, 64)						,   rng=random.Random(0						)						).to(lowercase						)

							_lowerCamelCase  :    List[str]					=					pipe_a(
							    prompt_embeds=lowercase						,   negative_prompt_embeds=lowercase						,   image=lowercase						,   original_image=lowercase						,   generator=lowercase						,   num_inference_steps=2						,   output_type='np'						,   )

							_lowerCamelCase  :    List[Any]					=					output.images[0]

							assert image.shape == (256, 256, 3)

							_lowerCamelCase  :    List[str]					=					torch.cuda.max_memory_allocated()
							assert mem_bytes < 4 * 10**9

							_lowerCamelCase  :    List[Any]					=					load_numpy(
							    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy'						)
							assert_mean_pixel_difference(lowercase						,   lowercase						)






			def       A_					(						self						,   lowercase						,   lowercase						,   lowercase						,   lowercase						):
							# pipeline 1

							_start_torch_memory_measurement()

							_lowerCamelCase  :    Optional[Any]					=					floats_tensor((1, 3, 64, 64)						,   rng=random.Random(0						)						).to(lowercase						)
							_lowerCamelCase  :    Dict					=					floats_tensor((1, 3, 64, 64)						,   rng=random.Random(1						)						).to(lowercase						)

							_lowerCamelCase  :    List[Any]					=					torch.Generator(device='cpu'						).manual_seed(0						)
							_lowerCamelCase  :    Optional[Any]					=					pipe_a(
							    prompt_embeds=lowercase						,   negative_prompt_embeds=lowercase						,   image=lowercase						,   mask_image=lowercase						,   num_inference_steps=2						,   generator=lowercase						,   output_type='np'						,   )

							_lowerCamelCase  :    Dict					=					output.images[0]

							assert image.shape == (64, 64, 3)

							_lowerCamelCase  :    Tuple					=					torch.cuda.max_memory_allocated()
							assert mem_bytes < 10 * 10**9

							_lowerCamelCase  :    List[Any]					=					load_numpy(
							    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy'						)
							assert_mean_pixel_difference(lowercase						,   lowercase						)

							# pipeline 2

							_start_torch_memory_measurement()

							_lowerCamelCase  :    Dict					=					torch.Generator(device='cpu'						).manual_seed(0						)

							_lowerCamelCase  :    Dict					=					floats_tensor((1, 3, 64, 64)						,   rng=random.Random(0						)						).to(lowercase						)
							_lowerCamelCase  :    Union[str, Any]					=					floats_tensor((1, 3, 256, 256)						,   rng=random.Random(0						)						).to(lowercase						)
							_lowerCamelCase  :    List[str]					=					floats_tensor((1, 3, 256, 256)						,   rng=random.Random(1						)						).to(lowercase						)

							_lowerCamelCase  :    str					=					pipe_a(
							    prompt_embeds=lowercase						,   negative_prompt_embeds=lowercase						,   image=lowercase						,   mask_image=lowercase						,   original_image=lowercase						,   generator=lowercase						,   num_inference_steps=2						,   output_type='np'						,   )

							_lowerCamelCase  :    Dict					=					output.images[0]

							assert image.shape == (256, 256, 3)

							_lowerCamelCase  :    List[str]					=					torch.cuda.max_memory_allocated()
							assert mem_bytes < 4 * 10**9

							_lowerCamelCase  :    int					=					load_numpy(
							    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy'						)
							assert_mean_pixel_difference(lowercase						,   lowercase						)







def   _snake_case    (       ):
				torch.cuda.empty_cache()
				torch.cuda.reset_max_memory_allocated()
				torch.cuda.reset_peak_memory_stats()





"""simple docstring"""






from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


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

lowercase__  		=		"""\
The BLEU score has some undesirable properties when used for single
sentences, as it was designed to be a corpus measure. We therefore
use a slightly different score for our RL experiments which we call
the 'GLEU score'. For the GLEU score, we record all sub-sequences of
1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then
compute a recall, which is the ratio of the number of matching n-grams
to the number of total n-grams in the target (ground truth) sequence,
and a precision, which is the ratio of the number of matching n-grams
to the number of total n-grams in the generated output sequence. Then
GLEU score is simply the minimum of recall and precision. This GLEU
score's range is always between 0 (no matches) and 1 (all match) and
it is symmetrical when switching output and target. According to
our experiments, GLEU score correlates quite well with the BLEU
metric on a corpus level but does not have its drawbacks for our per
sentence reward objective.
"""

lowercase__  		=		"""\
Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.
Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching
tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.

Args:
    predictions (list of str): list of translations to score.
        Each translation should be tokenized into a list of tokens.
    references (list of list of str): list of lists of references for each translation.
        Each reference should be tokenized into a list of tokens.
    min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.
    max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.

Returns:
    'google_bleu': google_bleu score

Examples:
    Example 1:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
        >>> print(round(results[\"google_bleu\"], 2))
        0.44

    Example 2:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
        >>> print(round(results[\"google_bleu\"], 2))
        0.61

    Example 3:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)
        >>> print(round(results[\"google_bleu\"], 2))
        0.53

    Example 4:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)
        >>> print(round(results[\"google_bleu\"], 2))
        0.4
"""






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






			'''simple docstring'''



			def       A_					(						self						):
							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       A_					(						self						,   lowercase						,   lowercase						,   lowercase = 1						,   lowercase = 4						,   ):
							return {
							    "google_bleu": gleu_score.corpus_gleu(
							        list_of_references=lowercase						,   hypotheses=lowercase						,   min_len=lowercase						,   max_len=lowercase						)
							}