

"""simple docstring"""


import unittest

from transformers import PegasusTokenizer, PegasusTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin


__A						   =			get_tests_dir("fixtures/test_sentencepiece_no_bos.model")





@require_sentencepiece
@require_tokenizers
class     snake_case	(				__snake_case,							unittest.TestCase  ):
				SCREAMING_SNAKE_CASE_   :      List[Any]         =  PegasusTokenizer
				SCREAMING_SNAKE_CASE_   :      str         =  PegasusTokenizerFast
				SCREAMING_SNAKE_CASE_   :      Optional[Any]         =  True
				SCREAMING_SNAKE_CASE_   :      str         =  True

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



						'''simple docstring'''


						super().setUp()

						# We have a SentencePiece fixture for testing
						__lowerCAmelCase:       Optional[int]          =			PegasusTokenizer(UpperCamelCase__)
						tokenizer.save_pretrained(self.tmpdirname)

				@cached_property
				def 							lowercase_     (	self							:				str)->   Union[str, Any]:



						'''simple docstring'''


						return PegasusTokenizer.from_pretrained("google/pegasus-large")

				def 							lowercase_     (	self							:				Optional[int]     ,  **UpperCamelCase__							:				str)->   PegasusTokenizer:



						'''simple docstring'''


						return PegasusTokenizer.from_pretrained(self.tmpdirname     ,  **UpperCamelCase__)

				def 							lowercase_     (	self							:				Tuple     ,  UpperCamelCase__							:				List[Any])->   Union[str, Any]:



						'''simple docstring'''


						return ("This is a test", "This is a test")

				def 							lowercase_     (	self							:				Tuple)->   Any:



						'''simple docstring'''


						__lowerCAmelCase:       Union[str, Any]          =			"</s>"
						__lowerCAmelCase:       Optional[Any]          =			1

						self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCamelCase__)     ,  UpperCamelCase__)
						self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCamelCase__)     ,  UpperCamelCase__)

				def 							lowercase_     (	self							:				Optional[int])->   Union[str, Any]:



						'''simple docstring'''


						__lowerCAmelCase:       List[Any]          =			list(self.get_tokenizer().get_vocab().keys())

						self.assertEqual(vocab_keys[0]     ,  "<pad>")
						self.assertEqual(vocab_keys[1]     ,  "</s>")
						self.assertEqual(vocab_keys[-1]     ,  "v")
						self.assertEqual(len(UpperCamelCase__)     ,  1_1_0_3)

				def 							lowercase_     (	self							:				int)->   Optional[int]:



						'''simple docstring'''


						self.assertEqual(self.get_tokenizer().vocab_size     ,  1_1_0_3)

				def 							lowercase_     (	self							:				Tuple)->   str:



						'''simple docstring'''


						__lowerCAmelCase:       str          =			self.rust_tokenizer_class.from_pretrained(self.tmpdirname)
						__lowerCAmelCase:       Dict          =			self.tokenizer_class.from_pretrained(self.tmpdirname)
						__lowerCAmelCase:       Optional[int]          =			(
						    "Let's see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important"
						    " </s> <pad> <pad> <pad>"
						)
						__lowerCAmelCase:       Dict          =			rust_tokenizer([raw_input_str]     ,  return_tensors=UpperCamelCase__     ,  add_special_tokens=UpperCamelCase__).input_ids[0]
						__lowerCAmelCase:       Optional[Any]          =			py_tokenizer([raw_input_str]     ,  return_tensors=UpperCamelCase__     ,  add_special_tokens=UpperCamelCase__).input_ids[0]
						self.assertListEqual(UpperCamelCase__     ,  UpperCamelCase__)

				def 							lowercase_     (	self							:				int)->   int:



						'''simple docstring'''


						__lowerCAmelCase:       List[Any]          =			self._large_tokenizer
						# <mask_1> masks whole sentence while <mask_2> masks single word
						__lowerCAmelCase:       str          =			"<mask_1> To ensure a <mask_2> flow of bank resolutions."
						__lowerCAmelCase:       Optional[int]          =			[2, 4_1_3, 6_1_5, 1_1_4, 3, 1_9_7_1, 1_1_3, 1_6_7_9, 1_0_7_1_0, 1_0_7, 1]
						__lowerCAmelCase:       str          =			tokenizer([raw_input_str]     ,  return_tensors=UpperCamelCase__).input_ids[0]
						self.assertListEqual(UpperCamelCase__     ,  UpperCamelCase__)

				def 							lowercase_     (	self							:				int)->   Dict:



						'''simple docstring'''


						__lowerCAmelCase:       Dict          =			self._large_tokenizer
						# The tracebacks for the following asserts are **better** without messages or self.assertEqual
						assert tokenizer.vocab_size == 9_6_1_0_3
						assert tokenizer.pad_token_id == 0
						assert tokenizer.eos_token_id == 1
						assert tokenizer.offset == 1_0_3
						assert tokenizer.unk_token_id == tokenizer.offset + 2 == 1_0_5
						assert tokenizer.unk_token == "<unk>"
						assert tokenizer.model_max_length == 1_0_2_4
						__lowerCAmelCase:       Tuple          =			"To ensure a smooth flow of bank resolutions."
						__lowerCAmelCase:       Dict          =			[4_1_3, 6_1_5, 1_1_4, 2_2_9_1, 1_9_7_1, 1_1_3, 1_6_7_9, 1_0_7_1_0, 1_0_7, 1]
						__lowerCAmelCase:       Any          =			tokenizer([raw_input_str]     ,  return_tensors=UpperCamelCase__).input_ids[0]
						self.assertListEqual(UpperCamelCase__     ,  UpperCamelCase__)
						assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3]) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"]

				@require_torch
				def 							lowercase_     (	self							:				List[str])->   List[str]:



						'''simple docstring'''


						__lowerCAmelCase:       Optional[Any]          =			["This is going to be way too long." * 1_5_0, "short example"]
						__lowerCAmelCase:       Tuple          =			["not super long but more than 5 tokens", "tiny"]
						__lowerCAmelCase:       List[Any]          =			self._large_tokenizer(UpperCamelCase__     ,  padding=UpperCamelCase__     ,  truncation=UpperCamelCase__     ,  return_tensors="pt")
						__lowerCAmelCase:       List[str]          =			self._large_tokenizer(
						    text_target=UpperCamelCase__     ,  max_length=5     ,  padding=UpperCamelCase__     ,  truncation=UpperCamelCase__     ,  return_tensors="pt")

						assert batch.input_ids.shape == (2, 1_0_2_4)
						assert batch.attention_mask.shape == (2, 1_0_2_4)
						assert targets["input_ids"].shape == (2, 5)
						assert len(UpperCamelCase__) == 2  # input_ids, attention_mask.




				@slow
				def 							lowercase_     (	self							:				Dict)->   List[Any]:



						'''simple docstring'''


						__lowerCAmelCase:       Optional[int]          =			{"input_ids": [[3_8_9_7_9, 1_4_3, 1_8_4_8_5, 6_0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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}  # noqa: E501
						# fmt: on

						self.tokenizer_integration_test_util(
						    expected_encoding=UpperCamelCase__     ,  model_name="google/bigbird-pegasus-large-arxiv"     ,  revision="ba85d0851d708441f91440d509690f1ab6353415"     ,  )





@require_sentencepiece
@require_tokenizers
class     snake_case	(				__snake_case,							unittest.TestCase  ):
				SCREAMING_SNAKE_CASE_   :      Any         =  PegasusTokenizer
				SCREAMING_SNAKE_CASE_   :      Union[str, Any]         =  PegasusTokenizerFast
				SCREAMING_SNAKE_CASE_   :      Dict         =  True
				SCREAMING_SNAKE_CASE_   :      Optional[int]         =  True

				def 							lowercase_     (	self							:				Optional[Any])->   Optional[Any]:



						'''simple docstring'''


						super().setUp()

						# We have a SentencePiece fixture for testing
						__lowerCAmelCase:       Optional[int]          =			PegasusTokenizer(UpperCamelCase__     ,  offset=0     ,  mask_token_sent=UpperCamelCase__     ,  mask_token="[MASK]")
						tokenizer.save_pretrained(self.tmpdirname)

				@cached_property
				def 							lowercase_     (	self							:				Dict)->   Union[str, Any]:



						'''simple docstring'''


						return PegasusTokenizer.from_pretrained("google/bigbird-pegasus-large-arxiv")

				def 							lowercase_     (	self							:				Dict     ,  **UpperCamelCase__							:				int)->   PegasusTokenizer:



						'''simple docstring'''


						return PegasusTokenizer.from_pretrained(self.tmpdirname     ,  **UpperCamelCase__)

				def 							lowercase_     (	self							:				str     ,  UpperCamelCase__							:				int)->   Any:



						'''simple docstring'''


						return ("This is a test", "This is a test")

				def 							lowercase_     (	self							:				int)->   Optional[Any]:



						'''simple docstring'''


						__lowerCAmelCase:       Tuple          =			self.rust_tokenizer_class.from_pretrained(self.tmpdirname)
						__lowerCAmelCase:       List[Any]          =			self.tokenizer_class.from_pretrained(self.tmpdirname)
						__lowerCAmelCase:       Dict          =			(
						    "Let's see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>"
						    " <pad> <pad> <pad>"
						)
						__lowerCAmelCase:       Optional[Any]          =			rust_tokenizer([raw_input_str]     ,  return_tensors=UpperCamelCase__     ,  add_special_tokens=UpperCamelCase__).input_ids[0]
						__lowerCAmelCase:       Tuple          =			py_tokenizer([raw_input_str]     ,  return_tensors=UpperCamelCase__     ,  add_special_tokens=UpperCamelCase__).input_ids[0]
						self.assertListEqual(UpperCamelCase__     ,  UpperCamelCase__)

				@require_torch
				def 							lowercase_     (	self							:				str)->   int:



						'''simple docstring'''


						__lowerCAmelCase:       Any          =			["This is going to be way too long." * 1_0_0_0, "short example"]
						__lowerCAmelCase:       Tuple          =			["not super long but more than 5 tokens", "tiny"]
						__lowerCAmelCase:       str          =			self._large_tokenizer(UpperCamelCase__     ,  padding=UpperCamelCase__     ,  truncation=UpperCamelCase__     ,  return_tensors="pt")
						__lowerCAmelCase:       Optional[int]          =			self._large_tokenizer(
						    text_target=UpperCamelCase__     ,  max_length=5     ,  padding=UpperCamelCase__     ,  truncation=UpperCamelCase__     ,  return_tensors="pt")

						assert batch.input_ids.shape == (2, 4_0_9_6)
						assert batch.attention_mask.shape == (2, 4_0_9_6)
						assert targets["input_ids"].shape == (2, 5)
						assert len(UpperCamelCase__) == 2  # input_ids, attention_mask.




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



						'''simple docstring'''


						__lowerCAmelCase:       Tuple          =			(
						    "This is an example string that is used to test the original TF implementation against the HF"
						    " implementation"
						)

						__lowerCAmelCase:       Union[str, Any]          =			self._large_tokenizer(UpperCamelCase__).input_ids

						self.assertListEqual(
						    UpperCamelCase__     ,  [1_8_2, 1_1_7, 1_4_2, 5_8_7, 4_2_1_1, 1_2_0, 1_1_7, 2_6_3, 1_1_2, 8_0_4, 1_0_9, 8_5_6, 2_5_0_1_6, 3_1_3_7, 4_6_4, 1_0_9, 2_6_9_5_5, 3_1_3_7, 1]     ,  )





"""simple docstring"""


import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()





class     snake_case	(				unittest.TestCase  ):

				def 							lowercase_     (	self							:				Optional[int])->   int:



						'''simple docstring'''


						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()

				@property
				def 							lowercase_     (	self							:				int)->   str:



						'''simple docstring'''


						__lowerCAmelCase:       str          =			1
						__lowerCAmelCase:       Union[str, Any]          =			3
						__lowerCAmelCase:       Union[str, Any]          =			(3_2, 3_2)

						__lowerCAmelCase:       Union[str, Any]          =			floats_tensor((batch_size, num_channels) + sizes     ,  rng=random.Random(0)).to(UpperCamelCase__)
						return image

				@property
				def 							lowercase_     (	self							:				Tuple)->   str:



						'''simple docstring'''


						torch.manual_seed(0)
						__lowerCAmelCase:       Optional[Any]          =			UNetaDConditionModel(
						    block_out_channels=(3_2, 3_2, 6_4)     ,  layers_per_block=2     ,  sample_size=3_2     ,  in_channels=7     ,  out_channels=4     ,  down_block_types=("DownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D")     ,  up_block_types=("CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "UpBlock2D")     ,  cross_attention_dim=3_2     ,  attention_head_dim=8     ,  use_linear_projection=UpperCamelCase__     ,  only_cross_attention=(True, True, False)     ,  num_class_embeds=1_0_0     ,  )
						return model

				@property
				def 							lowercase_     (	self							:				Any)->   Optional[Any]:



						'''simple docstring'''


						torch.manual_seed(0)
						__lowerCAmelCase:       Tuple          =			AutoencoderKL(
						    block_out_channels=[3_2, 3_2, 6_4]     ,  in_channels=3     ,  out_channels=3     ,  down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D"]     ,  up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"]     ,  latent_channels=4     ,  )
						return model

				@property
				def 							lowercase_     (	self							:				Any)->   Optional[Any]:



						'''simple docstring'''


						torch.manual_seed(0)
						__lowerCAmelCase:       List[str]          =			CLIPTextConfig(
						    bos_token_id=0     ,  eos_token_id=2     ,  hidden_size=3_2     ,  intermediate_size=3_7     ,  layer_norm_eps=1e-05     ,  num_attention_heads=4     ,  num_hidden_layers=5     ,  pad_token_id=1     ,  vocab_size=1_0_0_0     ,  hidden_act="gelu"     ,  projection_dim=5_1_2     ,  )
						return CLIPTextModel(UpperCamelCase__)

				def 							lowercase_     (	self							:				List[str])->   Dict:



						'''simple docstring'''


						__lowerCAmelCase:       Tuple          =			"cpu"  # ensure determinism for the device-dependent torch.Generator
						__lowerCAmelCase:       int          =			self.dummy_cond_unet_upscale
						__lowerCAmelCase:       int          =			DDPMScheduler()
						__lowerCAmelCase:       List[str]          =			DDIMScheduler(prediction_type="v_prediction")
						__lowerCAmelCase:       Tuple          =			self.dummy_vae
						__lowerCAmelCase:       Optional[Any]          =			self.dummy_text_encoder
						__lowerCAmelCase:       Any          =			CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")

						__lowerCAmelCase:       Tuple          =			self.dummy_image.cpu().permute(0     ,  2     ,  3     ,  1)[0]
						__lowerCAmelCase:       List[Any]          =			Image.fromarray(np.uinta(UpperCamelCase__)).convert("RGB").resize((6_4, 6_4))

						# make sure here that pndm scheduler skips prk
						__lowerCAmelCase:       Optional[int]          =			StableDiffusionUpscalePipeline(
						    unet=UpperCamelCase__     ,  low_res_scheduler=UpperCamelCase__     ,  scheduler=UpperCamelCase__     ,  vae=UpperCamelCase__     ,  text_encoder=UpperCamelCase__     ,  tokenizer=UpperCamelCase__     ,  max_noise_level=3_5_0     ,  )
						__lowerCAmelCase:       Tuple          =			sd_pipe.to(UpperCamelCase__)
						sd_pipe.set_progress_bar_config(disable=UpperCamelCase__)

						__lowerCAmelCase:       Any          =			"A painting of a squirrel eating a burger"
						__lowerCAmelCase:       str          =			torch.Generator(device=UpperCamelCase__).manual_seed(0)
						__lowerCAmelCase:       Optional[int]          =			sd_pipe(
						    [prompt]     ,  image=UpperCamelCase__     ,  generator=UpperCamelCase__     ,  guidance_scale=6.0     ,  noise_level=2_0     ,  num_inference_steps=2     ,  output_type="np"     ,  )

						__lowerCAmelCase:       List[str]          =			output.images

						__lowerCAmelCase:       Union[str, Any]          =			torch.Generator(device=UpperCamelCase__).manual_seed(0)
						__lowerCAmelCase:       List[str]          =			sd_pipe(
						    [prompt]     ,  image=UpperCamelCase__     ,  generator=UpperCamelCase__     ,  guidance_scale=6.0     ,  noise_level=2_0     ,  num_inference_steps=2     ,  output_type="np"     ,  return_dict=UpperCamelCase__     ,  )[0]

						__lowerCAmelCase:       int          =			image[0, -3:, -3:, -1]
						__lowerCAmelCase:       Dict          =			image_from_tuple[0, -3:, -3:, -1]

						__lowerCAmelCase:       Dict          =			low_res_image.size[0] * 4
						assert image.shape == (1, expected_height_width, expected_height_width, 3)
						__lowerCAmelCase:       List[Any]          =			np.array([0.3113, 0.3910, 0.4272, 0.4859, 0.5061, 0.4652, 0.5362, 0.5715, 0.5661])

						assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
						assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2

				def 							lowercase_     (	self							:				List[str])->   Optional[Any]:



						'''simple docstring'''


						__lowerCAmelCase:       Union[str, Any]          =			"cpu"  # ensure determinism for the device-dependent torch.Generator
						__lowerCAmelCase:       Dict          =			self.dummy_cond_unet_upscale
						__lowerCAmelCase:       List[str]          =			DDPMScheduler()
						__lowerCAmelCase:       Union[str, Any]          =			DDIMScheduler(prediction_type="v_prediction")
						__lowerCAmelCase:       Optional[int]          =			self.dummy_vae
						__lowerCAmelCase:       List[Any]          =			self.dummy_text_encoder
						__lowerCAmelCase:       Optional[int]          =			CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")

						__lowerCAmelCase:       List[Any]          =			self.dummy_image.cpu().permute(0     ,  2     ,  3     ,  1)[0]
						__lowerCAmelCase:       str          =			Image.fromarray(np.uinta(UpperCamelCase__)).convert("RGB").resize((6_4, 6_4))

						# make sure here that pndm scheduler skips prk
						__lowerCAmelCase:       Optional[int]          =			StableDiffusionUpscalePipeline(
						    unet=UpperCamelCase__     ,  low_res_scheduler=UpperCamelCase__     ,  scheduler=UpperCamelCase__     ,  vae=UpperCamelCase__     ,  text_encoder=UpperCamelCase__     ,  tokenizer=UpperCamelCase__     ,  max_noise_level=3_5_0     ,  )
						__lowerCAmelCase:       Optional[int]          =			sd_pipe.to(UpperCamelCase__)
						sd_pipe.set_progress_bar_config(disable=UpperCamelCase__)

						__lowerCAmelCase:       List[str]          =			"A painting of a squirrel eating a burger"
						__lowerCAmelCase:       List[Any]          =			sd_pipe(
						    2 * [prompt]     ,  image=2 * [low_res_image]     ,  guidance_scale=6.0     ,  noise_level=2_0     ,  num_inference_steps=2     ,  output_type="np"     ,  )
						__lowerCAmelCase:       List[Any]          =			output.images
						assert image.shape[0] == 2

						__lowerCAmelCase:       Dict          =			torch.Generator(device=UpperCamelCase__).manual_seed(0)
						__lowerCAmelCase:       Optional[Any]          =			sd_pipe(
						    [prompt]     ,  image=UpperCamelCase__     ,  generator=UpperCamelCase__     ,  num_images_per_prompt=2     ,  guidance_scale=6.0     ,  noise_level=2_0     ,  num_inference_steps=2     ,  output_type="np"     ,  )
						__lowerCAmelCase:       List[Any]          =			output.images
						assert image.shape[0] == 2




				@unittest.skipIf(torch_device != "cuda"     ,  "This test requires a GPU")
				def 							lowercase_     (	self							:				Tuple)->   Any:



						'''simple docstring'''


						__lowerCAmelCase:       Union[str, Any]          =			self.dummy_cond_unet_upscale
						__lowerCAmelCase:       int          =			DDPMScheduler()
						__lowerCAmelCase:       int          =			DDIMScheduler(prediction_type="v_prediction")
						__lowerCAmelCase:       Dict          =			self.dummy_vae
						__lowerCAmelCase:       int          =			self.dummy_text_encoder
						__lowerCAmelCase:       List[Any]          =			CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")

						__lowerCAmelCase:       List[Any]          =			self.dummy_image.cpu().permute(0     ,  2     ,  3     ,  1)[0]
						__lowerCAmelCase:       Optional[int]          =			Image.fromarray(np.uinta(UpperCamelCase__)).convert("RGB").resize((6_4, 6_4))

						# put models in fp16, except vae as it overflows in fp16
						__lowerCAmelCase:       List[Any]          =			unet.half()
						__lowerCAmelCase:       List[str]          =			text_encoder.half()

						# make sure here that pndm scheduler skips prk
						__lowerCAmelCase:       List[Any]          =			StableDiffusionUpscalePipeline(
						    unet=UpperCamelCase__     ,  low_res_scheduler=UpperCamelCase__     ,  scheduler=UpperCamelCase__     ,  vae=UpperCamelCase__     ,  text_encoder=UpperCamelCase__     ,  tokenizer=UpperCamelCase__     ,  max_noise_level=3_5_0     ,  )
						__lowerCAmelCase:       str          =			sd_pipe.to(UpperCamelCase__)
						sd_pipe.set_progress_bar_config(disable=UpperCamelCase__)

						__lowerCAmelCase:       Optional[Any]          =			"A painting of a squirrel eating a burger"
						__lowerCAmelCase:       str          =			torch.manual_seed(0)
						__lowerCAmelCase:       Dict          =			sd_pipe(
						    [prompt]     ,  image=UpperCamelCase__     ,  generator=UpperCamelCase__     ,  num_inference_steps=2     ,  output_type="np"     ,  ).images

						__lowerCAmelCase:       Optional[Any]          =			low_res_image.size[0] * 4
						assert image.shape == (1, expected_height_width, expected_height_width, 3)





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

				def 							lowercase_     (	self							:				Tuple)->   Tuple:



						'''simple docstring'''


						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()

				def 							lowercase_     (	self							:				List[Any])->   Tuple:



						'''simple docstring'''


						__lowerCAmelCase:       Dict          =			load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
						    "/sd2-upscale/low_res_cat.png")
						__lowerCAmelCase:       Optional[Any]          =			load_numpy(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
						    "/upsampled_cat.npy")

						__lowerCAmelCase:       str          =			"stabilityai/stable-diffusion-x4-upscaler"
						__lowerCAmelCase:       Optional[int]          =			StableDiffusionUpscalePipeline.from_pretrained(UpperCamelCase__)
						pipe.to(UpperCamelCase__)
						pipe.set_progress_bar_config(disable=UpperCamelCase__)
						pipe.enable_attention_slicing()

						__lowerCAmelCase:       Tuple          =			"a cat sitting on a park bench"

						__lowerCAmelCase:       int          =			torch.manual_seed(0)
						__lowerCAmelCase:       List[Any]          =			pipe(
						    prompt=UpperCamelCase__     ,  image=UpperCamelCase__     ,  generator=UpperCamelCase__     ,  output_type="np"     ,  )
						__lowerCAmelCase:       Dict          =			output.images[0]

						assert image.shape == (5_1_2, 5_1_2, 3)
						assert np.abs(expected_image - image).max() < 1e-3

				def 							lowercase_     (	self							:				Optional[int])->   Any:



						'''simple docstring'''


						__lowerCAmelCase:       Dict          =			load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
						    "/sd2-upscale/low_res_cat.png")
						__lowerCAmelCase:       Tuple          =			load_numpy(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
						    "/upsampled_cat_fp16.npy")

						__lowerCAmelCase:       Optional[Any]          =			"stabilityai/stable-diffusion-x4-upscaler"
						__lowerCAmelCase:       Tuple          =			StableDiffusionUpscalePipeline.from_pretrained(
						    UpperCamelCase__     ,  torch_dtype=torch.floataa     ,  )
						pipe.to(UpperCamelCase__)
						pipe.set_progress_bar_config(disable=UpperCamelCase__)
						pipe.enable_attention_slicing()

						__lowerCAmelCase:       str          =			"a cat sitting on a park bench"

						__lowerCAmelCase:       List[str]          =			torch.manual_seed(0)
						__lowerCAmelCase:       Optional[Any]          =			pipe(
						    prompt=UpperCamelCase__     ,  image=UpperCamelCase__     ,  generator=UpperCamelCase__     ,  output_type="np"     ,  )
						__lowerCAmelCase:       Union[str, Any]          =			output.images[0]

						assert image.shape == (5_1_2, 5_1_2, 3)
						assert np.abs(expected_image - image).max() < 5e-1




				def 							lowercase_     (	self							:				Optional[int])->   Dict:



						'''simple docstring'''


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

						__lowerCAmelCase:       Tuple          =			load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
						    "/sd2-upscale/low_res_cat.png")

						__lowerCAmelCase:       Union[str, Any]          =			"stabilityai/stable-diffusion-x4-upscaler"
						__lowerCAmelCase:       Any          =			StableDiffusionUpscalePipeline.from_pretrained(
						    UpperCamelCase__     ,  torch_dtype=torch.floataa     ,  )
						pipe.to(UpperCamelCase__)
						pipe.set_progress_bar_config(disable=UpperCamelCase__)
						pipe.enable_attention_slicing(1)
						pipe.enable_sequential_cpu_offload()

						__lowerCAmelCase:       int          =			"a cat sitting on a park bench"

						__lowerCAmelCase:       Dict          =			torch.manual_seed(0)
						__lowerCAmelCase:       Dict          =			pipe(
						    prompt=UpperCamelCase__     ,  image=UpperCamelCase__     ,  generator=UpperCamelCase__     ,  num_inference_steps=5     ,  output_type="np"     ,  )

						__lowerCAmelCase:       Optional[int]          =			torch.cuda.max_memory_allocated()
						# make sure that less than 2.9 GB is allocated
						assert mem_bytes < 2.9 * 1_0**9


