





import gc
import random
import unittest

import numpy as np
import torch
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModel,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    floats_tensor,
    load_image,
    load_numpy,
    require_torch_gpu,
    skip_mps,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import (
    PipelineKarrasSchedulerTesterMixin,
    PipelineLatentTesterMixin,
    PipelineTesterMixin,
    assert_mean_pixel_difference,
)


enable_full_determinism()



class    _a     (				_lowerCAmelCase					,							_lowerCAmelCase					,							_lowerCAmelCase					,							unittest.TestCase							):






							"""simple docstring"""

							snake_case_							 =						StableUnCLIPImgaImgPipeline
							snake_case_							 =						TEXT_GUIDED_IMAGE_VARIATION_PARAMS
							snake_case_							 =						TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
							snake_case_							 =						frozenset(
							    []							)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
							snake_case_							 =						frozenset([]							)

							def      A_  (      self				:     Optional[Any]    )	->str:
													SCREAMING_SNAKE_CASE__     :				Optional[int]   =					32
													SCREAMING_SNAKE_CASE__     :				Tuple   =					embedder_hidden_size

													# image encoding components

													SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					CLIPImageProcessor(crop_size=32							,	size=32    )

													torch.manual_seed(0    )
													SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					CLIPVisionModelWithProjection(
													    CLIPVisionConfig(
													        hidden_size=_lowerCAmelCase							,	projection_dim=_lowerCAmelCase							,	num_hidden_layers=5							,	num_attention_heads=4							,	image_size=32							,	intermediate_size=37							,	patch_size=1							,	)    )

													# regular denoising components

													torch.manual_seed(0    )
													SCREAMING_SNAKE_CASE__     :				Optional[int]   =					StableUnCLIPImageNormalizer(embedding_dim=_lowerCAmelCase    )
													SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					DDPMScheduler(beta_schedule="squaredcos_cap_v2"    )

													torch.manual_seed(0    )
													SCREAMING_SNAKE_CASE__     :				Dict   =					CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"    )

													torch.manual_seed(0    )
													SCREAMING_SNAKE_CASE__     :				Any   =					CLIPTextModel(
													    CLIPTextConfig(
													        bos_token_id=0							,	eos_token_id=2							,	hidden_size=_lowerCAmelCase							,	projection_dim=32							,	intermediate_size=37							,	layer_norm_eps=1E-05							,	num_attention_heads=4							,	num_hidden_layers=5							,	pad_token_id=1							,	vocab_size=10_00							,	)    )

													torch.manual_seed(0    )
													SCREAMING_SNAKE_CASE__     :				List[str]   =					UNetaDConditionModel(
													    sample_size=32							,	in_channels=4							,	out_channels=4							,	down_block_types=("CrossAttnDownBlock2D", "DownBlock2D")							,	up_block_types=("UpBlock2D", "CrossAttnUpBlock2D")							,	block_out_channels=(32, 64)							,	attention_head_dim=(2, 4)							,	class_embed_type="projection"							,	projection_class_embeddings_input_dim=embedder_projection_dim * 2							,	cross_attention_dim=_lowerCAmelCase							,	layers_per_block=1							,	upcast_attention=_lowerCAmelCase							,	use_linear_projection=_lowerCAmelCase							,	)

													torch.manual_seed(0    )
													SCREAMING_SNAKE_CASE__     :				Optional[int]   =					DDIMScheduler(
													    beta_schedule="scaled_linear"							,	beta_start=0.0_0085							,	beta_end=0.012							,	prediction_type="v_prediction"							,	set_alpha_to_one=_lowerCAmelCase							,	steps_offset=1							,	)

													torch.manual_seed(0    )
													SCREAMING_SNAKE_CASE__     :				Optional[int]   =					AutoencoderKL()

													SCREAMING_SNAKE_CASE__     :				List[str]   =					{
													    # image encoding components
													    "feature_extractor": feature_extractor,
													    "image_encoder": image_encoder.eval(),
													    # image noising components
													    "image_normalizer": image_normalizer.eval(),
													    "image_noising_scheduler": image_noising_scheduler,
													    # regular denoising components
													    "tokenizer": tokenizer,
													    "text_encoder": text_encoder.eval(),
													    "unet": unet.eval(),
													    "scheduler": scheduler,
													    "vae": vae.eval(),
													}

													return components

							def      A_  (      self				:     List[Any]							,	a				:     int							,	a				:     Union[str, Any]=0							,	a				:     Optional[int]=True    )	->Tuple:







													if str(_lowerCAmelCase    ).startswith("mps"    ):
																			SCREAMING_SNAKE_CASE__     :				Any   =					torch.manual_seed(_lowerCAmelCase    )
													else:
																			SCREAMING_SNAKE_CASE__     :				str   =					torch.Generator(device=_lowerCAmelCase    ).manual_seed(_lowerCAmelCase    )

													SCREAMING_SNAKE_CASE__     :				str   =					floats_tensor((1, 3, 32, 32)							,	rng=random.Random(_lowerCAmelCase    )    ).to(_lowerCAmelCase    )

													if pil_image:
																			SCREAMING_SNAKE_CASE__     :				Dict   =					input_image * 0.5 + 0.5
																			SCREAMING_SNAKE_CASE__     :				Tuple   =					input_image.clamp(0							,	1    )
																			SCREAMING_SNAKE_CASE__     :				Dict   =					input_image.cpu().permute(0							,	2							,	3							,	1    ).float().numpy()
																			SCREAMING_SNAKE_CASE__     :				Tuple   =					DiffusionPipeline.numpy_to_pil(_lowerCAmelCase    )[0]

													return {
													    "prompt": "An anime racoon running a marathon",
													    "image": input_image,
													    "generator": generator,
													    "num_inference_steps": 2,
													    "output_type": "np",
													}

							@skip_mps
							def      A_  (      self				:     str    )	->Any:
													SCREAMING_SNAKE_CASE__     :				int   =					"cpu"  # ensure determinism for the device-dependent torch.Generator
													SCREAMING_SNAKE_CASE__     :				int   =					self.get_dummy_components()
													SCREAMING_SNAKE_CASE__     :				Any   =					StableUnCLIPImgaImgPipeline(**_lowerCAmelCase    )
													SCREAMING_SNAKE_CASE__     :				Tuple   =					sd_pipe.to(_lowerCAmelCase    )
													sd_pipe.set_progress_bar_config(disable=_lowerCAmelCase    )

													SCREAMING_SNAKE_CASE__     :				List[str]   =					self.get_dummy_inputs(_lowerCAmelCase    )
													inputs.update({"image_embeds": None}    )
													SCREAMING_SNAKE_CASE__     :				List[str]   =					sd_pipe(**_lowerCAmelCase    ).images
													SCREAMING_SNAKE_CASE__     :				List[str]   =					image[0, -3:, -3:, -1]

													assert image.shape == (1, 32, 32, 3)
													SCREAMING_SNAKE_CASE__     :				Dict   =					np.array([0.3872, 0.7224, 0.5601, 0.4741, 0.6872, 0.5814, 0.4636, 0.3867, 0.5078]    )

													assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1E-3

							def      A_  (      self				:     List[str]    )	->Optional[Any]:
													SCREAMING_SNAKE_CASE__     :				Dict   =					torch_device in ["cpu", "mps"]

													self._test_attention_slicing_forward_pass(test_max_difference=_lowerCAmelCase    )

							def      A_  (      self				:     Tuple    )	->Optional[Any]:
													SCREAMING_SNAKE_CASE__     :				Optional[int]   =					torch_device in ["cpu", "mps"]

													self._test_inference_batch_single_identical(test_max_difference=_lowerCAmelCase    )






							@unittest.skipIf(
							    torch_device != "cuda" or not is_xformers_available()							,	reason="XFormers attention is only available with CUDA and `xformers` installed"							,	)
							def      A_  (      self				:     int    )	->Tuple:
													self._test_xformers_attention_forwardGenerator_pass(test_max_difference=_lowerCAmelCase    )







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






							"""simple docstring"""

							def      A_  (      self				:     int    )	->List[Any]:
													super().tearDown()
													gc.collect()
													torch.cuda.empty_cache()

							def      A_  (      self				:     List[str]    )	->int:
													SCREAMING_SNAKE_CASE__     :				Optional[int]   =					load_image(
													    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png"    )

													SCREAMING_SNAKE_CASE__     :				Union[str, Any]   =					load_numpy(
													    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy"    )

													SCREAMING_SNAKE_CASE__     :				List[Any]   =					StableUnCLIPImgaImgPipeline.from_pretrained(
													    "fusing/stable-unclip-2-1-l-img2img"							,	torch_dtype=torch.floataa    )
													pipe.to(_lowerCAmelCase    )
													pipe.set_progress_bar_config(disable=_lowerCAmelCase    )
													# stable unclip will oom when integration tests are run on a V100,
													# so turn on memory savings
													pipe.enable_attention_slicing()
													pipe.enable_sequential_cpu_offload()

													SCREAMING_SNAKE_CASE__     :				Optional[int]   =					torch.Generator(device="cpu"    ).manual_seed(0    )
													SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					pipe(_lowerCAmelCase							,	"anime turle"							,	generator=_lowerCAmelCase							,	output_type="np"    )

													SCREAMING_SNAKE_CASE__     :				str   =					output.images[0]

													assert image.shape == (7_68, 7_68, 3)

													assert_mean_pixel_difference(_lowerCAmelCase							,	_lowerCAmelCase    )

							def      A_  (      self				:     str    )	->Tuple:
													SCREAMING_SNAKE_CASE__     :				int   =					load_image(
													    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png"    )

													SCREAMING_SNAKE_CASE__     :				Dict   =					load_numpy(
													    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy"    )

													SCREAMING_SNAKE_CASE__     :				int   =					StableUnCLIPImgaImgPipeline.from_pretrained(
													    "fusing/stable-unclip-2-1-h-img2img"							,	torch_dtype=torch.floataa    )
													pipe.to(_lowerCAmelCase    )
													pipe.set_progress_bar_config(disable=_lowerCAmelCase    )
													# stable unclip will oom when integration tests are run on a V100,
													# so turn on memory savings
													pipe.enable_attention_slicing()
													pipe.enable_sequential_cpu_offload()

													SCREAMING_SNAKE_CASE__     :				Any   =					torch.Generator(device="cpu"    ).manual_seed(0    )
													SCREAMING_SNAKE_CASE__     :				str   =					pipe(_lowerCAmelCase							,	"anime turle"							,	generator=_lowerCAmelCase							,	output_type="np"    )

													SCREAMING_SNAKE_CASE__     :				Any   =					output.images[0]

													assert image.shape == (7_68, 7_68, 3)

													assert_mean_pixel_difference(_lowerCAmelCase							,	_lowerCAmelCase    )






							def      A_  (      self				:     Dict    )	->List[str]:
													SCREAMING_SNAKE_CASE__     :				Any   =					load_image(
													    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png"    )

													torch.cuda.empty_cache()
													torch.cuda.reset_max_memory_allocated()
													torch.cuda.reset_peak_memory_stats()

													SCREAMING_SNAKE_CASE__     :				int   =					StableUnCLIPImgaImgPipeline.from_pretrained(
													    "fusing/stable-unclip-2-1-h-img2img"							,	torch_dtype=torch.floataa    )
													SCREAMING_SNAKE_CASE__     :				List[Any]   =					pipe.to(_lowerCAmelCase    )
													pipe.set_progress_bar_config(disable=_lowerCAmelCase    )
													pipe.enable_attention_slicing()
													pipe.enable_sequential_cpu_offload()

													SCREAMING_SNAKE_CASE__     :				Optional[Any]   =					pipe(
													    _lowerCAmelCase							,	"anime turtle"							,	num_inference_steps=2							,	output_type="np"							,	)

													SCREAMING_SNAKE_CASE__     :				Any   =					torch.cuda.max_memory_allocated()
													# make sure that less than 7 GB is allocated
													assert mem_bytes < 7 * 10**9






from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


__lowercase       :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"

__lowercase       :str       =  "\\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"

__lowercase       :List[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    _a     (				datasets.Metric							):






							"""simple docstring"""

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