



"""simple docstring"""


import importlib
import json
import os
from collections import OrderedDict
from typing import Dict, Optional, Union

# Build the list of all image processors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...image_processing_utils import ImageProcessingMixin
from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging
from .auto_factory import _LazyAutoMapping
from .configuration_auto import (
    CONFIG_MAPPING_NAMES,
    AutoConfig,
    model_type_to_module_name,
    replace_list_option_in_docstrings,
)


snake_case_				     =       logging.get_logger(__name__)

snake_case_				     =       OrderedDict(
    [
        ("""align""", """EfficientNetImageProcessor"""),
        ("""beit""", """BeitImageProcessor"""),
        ("""bit""", """BitImageProcessor"""),
        ("""blip""", """BlipImageProcessor"""),
        ("""blip-2""", """BlipImageProcessor"""),
        ("""bridgetower""", """BridgeTowerImageProcessor"""),
        ("""chinese_clip""", """ChineseCLIPImageProcessor"""),
        ("""clip""", """CLIPImageProcessor"""),
        ("""clipseg""", """ViTImageProcessor"""),
        ("""conditional_detr""", """ConditionalDetrImageProcessor"""),
        ("""convnext""", """ConvNextImageProcessor"""),
        ("""convnextv2""", """ConvNextImageProcessor"""),
        ("""cvt""", """ConvNextImageProcessor"""),
        ("""data2vec-vision""", """BeitImageProcessor"""),
        ("""deformable_detr""", """DeformableDetrImageProcessor"""),
        ("""deit""", """DeiTImageProcessor"""),
        ("""deta""", """DetaImageProcessor"""),
        ("""detr""", """DetrImageProcessor"""),
        ("""dinat""", """ViTImageProcessor"""),
        ("""donut-swin""", """DonutImageProcessor"""),
        ("""dpt""", """DPTImageProcessor"""),
        ("""efficientformer""", """EfficientFormerImageProcessor"""),
        ("""efficientnet""", """EfficientNetImageProcessor"""),
        ("""flava""", """FlavaImageProcessor"""),
        ("""focalnet""", """BitImageProcessor"""),
        ("""git""", """CLIPImageProcessor"""),
        ("""glpn""", """GLPNImageProcessor"""),
        ("""groupvit""", """CLIPImageProcessor"""),
        ("""imagegpt""", """ImageGPTImageProcessor"""),
        ("""instructblip""", """BlipImageProcessor"""),
        ("""layoutlmv2""", """LayoutLMv2ImageProcessor"""),
        ("""layoutlmv3""", """LayoutLMv3ImageProcessor"""),
        ("""levit""", """LevitImageProcessor"""),
        ("""mask2former""", """Mask2FormerImageProcessor"""),
        ("""maskformer""", """MaskFormerImageProcessor"""),
        ("""mgp-str""", """ViTImageProcessor"""),
        ("""mobilenet_v1""", """MobileNetV1ImageProcessor"""),
        ("""mobilenet_v2""", """MobileNetV2ImageProcessor"""),
        ("""mobilevit""", """MobileViTImageProcessor"""),
        ("""mobilevit""", """MobileViTImageProcessor"""),
        ("""mobilevitv2""", """MobileViTImageProcessor"""),
        ("""nat""", """ViTImageProcessor"""),
        ("""oneformer""", """OneFormerImageProcessor"""),
        ("""owlvit""", """OwlViTImageProcessor"""),
        ("""perceiver""", """PerceiverImageProcessor"""),
        ("""pix2struct""", """Pix2StructImageProcessor"""),
        ("""poolformer""", """PoolFormerImageProcessor"""),
        ("""regnet""", """ConvNextImageProcessor"""),
        ("""resnet""", """ConvNextImageProcessor"""),
        ("""sam""", """SamImageProcessor"""),
        ("""segformer""", """SegformerImageProcessor"""),
        ("""swiftformer""", """ViTImageProcessor"""),
        ("""swin""", """ViTImageProcessor"""),
        ("""swin2sr""", """Swin2SRImageProcessor"""),
        ("""swinv2""", """ViTImageProcessor"""),
        ("""table-transformer""", """DetrImageProcessor"""),
        ("""timesformer""", """VideoMAEImageProcessor"""),
        ("""tvlt""", """TvltImageProcessor"""),
        ("""upernet""", """SegformerImageProcessor"""),
        ("""van""", """ConvNextImageProcessor"""),
        ("""videomae""", """VideoMAEImageProcessor"""),
        ("""vilt""", """ViltImageProcessor"""),
        ("""vit""", """ViTImageProcessor"""),
        ("""vit_hybrid""", """ViTHybridImageProcessor"""),
        ("""vit_mae""", """ViTImageProcessor"""),
        ("""vit_msn""", """ViTImageProcessor"""),
        ("""xclip""", """CLIPImageProcessor"""),
        ("""yolos""", """YolosImageProcessor"""),
    ]
)

snake_case_				     =       _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES)

def  _lowerCAmelCase      (   lowercase_						):
						for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items():
												if class_name in extractors:
																		UpperCAmelCase             = model_type_to_module_name(lowercase_						)

																		UpperCAmelCase             = importlib.import_module(F""".{module_name}"""		,	'transformers.models'						)
																		try:
																								return getattr(lowercase_		,	lowercase_						)
																		except AttributeError:
																								continue

						for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items():
												if getattr(lowercase_		,	'__name__'		,	lowercase_						) == class_name:
																		return extractor

    # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
    # init and we return the proper dummy to get an appropriate error message.
						UpperCAmelCase             = importlib.import_module('transformers'						)
						if hasattr(lowercase_		,	lowercase_						):
												return getattr(lowercase_		,	lowercase_						)

						return None

def  _lowerCAmelCase      (   lowercase_		,	lowercase_ = None		,	lowercase_ = False		,	lowercase_ = False		,	lowercase_ = None		,	lowercase_ = None		,	lowercase_ = None		,	lowercase_ = False		,	**lowercase_		,	):
						UpperCAmelCase             = get_file_from_repo(
						    lowercase_		,	lowercase_		,	cache_dir=lowercase_		,	force_download=lowercase_		,	resume_download=lowercase_		,	proxies=lowercase_		,	use_auth_token=lowercase_		,	revision=lowercase_		,	local_files_only=lowercase_		,	)
						if resolved_config_file is None:
												logger.info(
												    'Could not locate the image processor configuration file, will try to use the model config instead.'						)
												return {}

						with open(lowercase_		,	encoding='utf-8'						) as reader:
												return json.load(lowercase_						)







class       A_			:



						"""simple docstring"""






						def __init__(					self :int					)				->			str:
												raise EnvironmentError(
												    'AutoImageProcessor is designed to be instantiated '
												    'using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.'					)






						@classmethod
						@replace_list_option_in_docstrings(lowercase_					)
						def 	UpperCAmelCase__     (					cls :str   ,  lowercase_ :Dict   ,  **lowercase_ :Any					)				->			str:
												UpperCAmelCase             = kwargs.pop('config'   ,  lowercase_					)
												UpperCAmelCase             = kwargs.pop('trust_remote_code'   ,  lowercase_					)
												UpperCAmelCase             = True

												UpperCAmelCase      ,    UpperCAmelCase             = ImageProcessingMixin.get_image_processor_dict(lowercase_   ,  **lowercase_					)
												UpperCAmelCase             = config_dict.get('image_processor_type'   ,  lowercase_					)
												UpperCAmelCase             = None
												if "AutoImageProcessor" in config_dict.get('auto_map'   ,  {}					):
																		UpperCAmelCase             = config_dict['auto_map']['AutoImageProcessor']

												# If we still don't have the image processor class, check if we're loading from a previous feature extractor config
												# and if so, infer the image processor class from there.
												if image_processor_class is None and image_processor_auto_map is None:
																		UpperCAmelCase             = config_dict.pop('feature_extractor_type'   ,  lowercase_					)
																		if feature_extractor_class is not None:
																								logger.warning(
																								    'Could not find image processor class in the image processor config or the model config. Loading'
																								    ' based on pattern matching with the model\'s feature extractor configuration.'					)
																								UpperCAmelCase             = feature_extractor_class.replace('FeatureExtractor'   ,  'ImageProcessor'					)
																		if "AutoFeatureExtractor" in config_dict.get('auto_map'   ,  {}					):
																								UpperCAmelCase             = config_dict['auto_map']['AutoFeatureExtractor']
																								UpperCAmelCase             = feature_extractor_auto_map.replace('FeatureExtractor'   ,  'ImageProcessor'					)
																								logger.warning(
																								    'Could not find image processor auto map in the image processor config or the model config.'
																								    ' Loading based on pattern matching with the model\'s feature extractor configuration.'					)

        # If we don't find the image processor class in the image processor config, let's try the model config.
												if image_processor_class is None and image_processor_auto_map is None:
																		if not isinstance(lowercase_   ,  lowercase_					):
																								UpperCAmelCase             = AutoConfig.from_pretrained(lowercase_   ,  **lowercase_					)
																		# It could be in `config.image_processor_type``
																		UpperCAmelCase             = getattr(lowercase_   ,  'image_processor_type'   ,  lowercase_					)
																		if hasattr(lowercase_   ,  'auto_map'					) and "AutoImageProcessor" in config.auto_map:
																								UpperCAmelCase             = config.auto_map['AutoImageProcessor']

												if image_processor_class is not None:
																		UpperCAmelCase             = image_processor_class_from_name(lowercase_					)

												UpperCAmelCase             = image_processor_auto_map is not None
												UpperCAmelCase             = image_processor_class is not None or type(lowercase_					) in IMAGE_PROCESSOR_MAPPING
												UpperCAmelCase             = resolve_trust_remote_code(
												    lowercase_   ,  lowercase_   ,  lowercase_   ,  lowercase_					)

												if has_remote_code and trust_remote_code:
																		UpperCAmelCase             = get_class_from_dynamic_module(
																		    lowercase_   ,  lowercase_   ,  **lowercase_					)
																		UpperCAmelCase             = kwargs.pop('code_revision'   ,  lowercase_					)
																		if os.path.isdir(lowercase_					):
																								image_processor_class.register_for_auto_class()
																		return image_processor_class.from_dict(lowercase_   ,  **lowercase_					)
												elif image_processor_class is not None:
																		return image_processor_class.from_dict(lowercase_   ,  **lowercase_					)
												# Last try: we use the IMAGE_PROCESSOR_MAPPING.
												elif type(lowercase_					) in IMAGE_PROCESSOR_MAPPING:
																		UpperCAmelCase             = IMAGE_PROCESSOR_MAPPING[type(lowercase_					)]
																		return image_processor_class.from_dict(lowercase_   ,  **lowercase_					)

												raise ValueError(
												    f"""Unrecognized image processor in {pretrained_model_name_or_path}. Should have a """
												    f"""`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following """
												    f"""`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys()					)}"""					)






						@staticmethod
						def 	UpperCAmelCase__     (					lowercase_ :Optional[Any]   ,  lowercase_ :Any					)				->			Any:
												IMAGE_PROCESSOR_MAPPING.register(lowercase_   ,  lowercase_					)











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   A(						unittest.TestCase   ):



 '''simple docstring'''


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

       """simple docstring"""






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

 @property
 def 				a__ (				self					:  int  )   ->	int:

       """simple docstring"""






       lowerCamelCase_		     =    1
       lowerCamelCase_		     =    3
       lowerCamelCase_		     =    (32, 32)

       lowerCamelCase_		     =    floats_tensor((batch_size, num_channels) + sizes						,							rng=random.Random(0  )  ).to(A_  )
       return image

 @property
 def 				a__ (				self					:  Any  )   ->	List[Any]:

       """simple docstring"""






       torch.manual_seed(0  )
       lowerCamelCase_		     =    UNetaDConditionModel(
           block_out_channels=(32, 32, 64)						,							layers_per_block=2						,							sample_size=32						,							in_channels=7						,							out_channels=4						,							down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D', 'CrossAttnDownBlock2D')						,							up_block_types=('CrossAttnUpBlock2D', 'CrossAttnUpBlock2D', 'UpBlock2D')						,							cross_attention_dim=32						,							attention_head_dim=8						,							use_linear_projection=A_						,							only_cross_attention=(True, True, False)						,							num_class_embeds=100						,							)
       return model

 @property
 def 				a__ (				self					:  Optional[int]  )   ->	Optional[int]:

       """simple docstring"""






       torch.manual_seed(0  )
       lowerCamelCase_		     =    AutoencoderKL(
           block_out_channels=[32, 32, 64]						,							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 				a__ (				self					:  Union[str, Any]  )   ->	Union[str, Any]:

       """simple docstring"""






       torch.manual_seed(0  )
       lowerCamelCase_		     =    CLIPTextConfig(
           bos_token_id=0						,							eos_token_id=2						,							hidden_size=32						,							intermediate_size=37						,							layer_norm_eps=1E-05						,							num_attention_heads=4						,							num_hidden_layers=5						,							pad_token_id=1						,							vocab_size=1000						,							hidden_act='gelu'						,							projection_dim=512						,							)
       return CLIPTextModel(A_  )

 def 				a__ (				self					:  Optional[int]  )   ->	List[str]:

       """simple docstring"""






       lowerCamelCase_		     =    'cpu'  # ensure determinism for the device-dependent torch.Generator
       lowerCamelCase_		     =    self.dummy_cond_unet_upscale
       lowerCamelCase_		     =    DDPMScheduler()
       lowerCamelCase_		     =    DDIMScheduler(prediction_type='v_prediction'  )
       lowerCamelCase_		     =    self.dummy_vae
       lowerCamelCase_		     =    self.dummy_text_encoder
       lowerCamelCase_		     =    CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'  )

       lowerCamelCase_		     =    self.dummy_image.cpu().permute(0						,							2						,							3						,							1  )[0]
       lowerCamelCase_		     =    Image.fromarray(np.uinta(A_  )  ).convert('RGB'  ).resize((64, 64)  )

       # make sure here that pndm scheduler skips prk
       lowerCamelCase_		     =    StableDiffusionUpscalePipeline(
           unet=A_						,							low_res_scheduler=A_						,							scheduler=A_						,							vae=A_						,							text_encoder=A_						,							tokenizer=A_						,							max_noise_level=350						,							)
       lowerCamelCase_		     =    sd_pipe.to(A_  )
       sd_pipe.set_progress_bar_config(disable=A_  )

       lowerCamelCase_		     =    'A painting of a squirrel eating a burger'
       lowerCamelCase_		     =    torch.Generator(device=A_  ).manual_seed(0  )
       lowerCamelCase_		     =    sd_pipe(
           [prompt]						,							image=A_						,							generator=A_						,							guidance_scale=6.0						,							noise_level=20						,							num_inference_steps=2						,							output_type='np'						,							)

       lowerCamelCase_		     =    output.images

       lowerCamelCase_		     =    torch.Generator(device=A_  ).manual_seed(0  )
       lowerCamelCase_		     =    sd_pipe(
           [prompt]						,							image=A_						,							generator=A_						,							guidance_scale=6.0						,							noise_level=20						,							num_inference_steps=2						,							output_type='np'						,							return_dict=A_						,							)[0]

       lowerCamelCase_		     =    image[0, -3:, -3:, -1]
       lowerCamelCase_		     =    image_from_tuple[0, -3:, -3:, -1]

       lowerCamelCase_		     =    low_res_image.size[0] * 4
       assert image.shape == (1, expected_height_width, expected_height_width, 3)
       lowerCamelCase_		     =    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 				a__ (				self					:  List[Any]  )   ->	int:

       """simple docstring"""






       lowerCamelCase_		     =    'cpu'  # ensure determinism for the device-dependent torch.Generator
       lowerCamelCase_		     =    self.dummy_cond_unet_upscale
       lowerCamelCase_		     =    DDPMScheduler()
       lowerCamelCase_		     =    DDIMScheduler(prediction_type='v_prediction'  )
       lowerCamelCase_		     =    self.dummy_vae
       lowerCamelCase_		     =    self.dummy_text_encoder
       lowerCamelCase_		     =    CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'  )

       lowerCamelCase_		     =    self.dummy_image.cpu().permute(0						,							2						,							3						,							1  )[0]
       lowerCamelCase_		     =    Image.fromarray(np.uinta(A_  )  ).convert('RGB'  ).resize((64, 64)  )

       # make sure here that pndm scheduler skips prk
       lowerCamelCase_		     =    StableDiffusionUpscalePipeline(
           unet=A_						,							low_res_scheduler=A_						,							scheduler=A_						,							vae=A_						,							text_encoder=A_						,							tokenizer=A_						,							max_noise_level=350						,							)
       lowerCamelCase_		     =    sd_pipe.to(A_  )
       sd_pipe.set_progress_bar_config(disable=A_  )

       lowerCamelCase_		     =    'A painting of a squirrel eating a burger'
       lowerCamelCase_		     =    sd_pipe(
           2 * [prompt]						,							image=2 * [low_res_image]						,							guidance_scale=6.0						,							noise_level=20						,							num_inference_steps=2						,							output_type='np'						,							)
       lowerCamelCase_		     =    output.images
       assert image.shape[0] == 2

       lowerCamelCase_		     =    torch.Generator(device=A_  ).manual_seed(0  )
       lowerCamelCase_		     =    sd_pipe(
           [prompt]						,							image=A_						,							generator=A_						,							num_images_per_prompt=2						,							guidance_scale=6.0						,							noise_level=20						,							num_inference_steps=2						,							output_type='np'						,							)
       lowerCamelCase_		     =    output.images
       assert image.shape[0] == 2





 @unittest.skipIf(torch_device != 'cuda'						,							'This test requires a GPU'  )
 def 				a__ (				self					:  List[Any]  )   ->	str:

       """simple docstring"""






       lowerCamelCase_		     =    self.dummy_cond_unet_upscale
       lowerCamelCase_		     =    DDPMScheduler()
       lowerCamelCase_		     =    DDIMScheduler(prediction_type='v_prediction'  )
       lowerCamelCase_		     =    self.dummy_vae
       lowerCamelCase_		     =    self.dummy_text_encoder
       lowerCamelCase_		     =    CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'  )

       lowerCamelCase_		     =    self.dummy_image.cpu().permute(0						,							2						,							3						,							1  )[0]
       lowerCamelCase_		     =    Image.fromarray(np.uinta(A_  )  ).convert('RGB'  ).resize((64, 64)  )

       # put models in fp16, except vae as it overflows in fp16
       lowerCamelCase_		     =    unet.half()
       lowerCamelCase_		     =    text_encoder.half()

       # make sure here that pndm scheduler skips prk
       lowerCamelCase_		     =    StableDiffusionUpscalePipeline(
           unet=A_						,							low_res_scheduler=A_						,							scheduler=A_						,							vae=A_						,							text_encoder=A_						,							tokenizer=A_						,							max_noise_level=350						,							)
       lowerCamelCase_		     =    sd_pipe.to(A_  )
       sd_pipe.set_progress_bar_config(disable=A_  )

       lowerCamelCase_		     =    'A painting of a squirrel eating a burger'
       lowerCamelCase_		     =    torch.manual_seed(0  )
       lowerCamelCase_		     =    sd_pipe(
           [prompt]						,							image=A_						,							generator=A_						,							num_inference_steps=2						,							output_type='np'						,							).images

       lowerCamelCase_		     =    low_res_image.size[0] * 4
       assert image.shape == (1, expected_height_width, expected_height_width, 3)







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



 '''simple docstring'''


 def 				a__ (				self					:  Tuple  )   ->	str:

       """simple docstring"""






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

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

       """simple docstring"""






       lowerCamelCase_		     =    load_image(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
           '/sd2-upscale/low_res_cat.png'  )
       lowerCamelCase_		     =    load_numpy(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'
           '/upsampled_cat.npy'  )

       lowerCamelCase_		     =    'stabilityai/stable-diffusion-x4-upscaler'
       lowerCamelCase_		     =    StableDiffusionUpscalePipeline.from_pretrained(A_  )
       pipe.to(A_  )
       pipe.set_progress_bar_config(disable=A_  )
       pipe.enable_attention_slicing()

       lowerCamelCase_		     =    'a cat sitting on a park bench'

       lowerCamelCase_		     =    torch.manual_seed(0  )
       lowerCamelCase_		     =    pipe(
           prompt=A_						,							image=A_						,							generator=A_						,							output_type='np'						,							)
       lowerCamelCase_		     =    output.images[0]

       assert image.shape == (512, 512, 3)
       assert np.abs(expected_image - image  ).max() < 1E-3

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

       """simple docstring"""






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

       lowerCamelCase_		     =    'stabilityai/stable-diffusion-x4-upscaler'
       lowerCamelCase_		     =    StableDiffusionUpscalePipeline.from_pretrained(
           A_						,							torch_dtype=torch.floataa						,							)
       pipe.to(A_  )
       pipe.set_progress_bar_config(disable=A_  )
       pipe.enable_attention_slicing()

       lowerCamelCase_		     =    'a cat sitting on a park bench'

       lowerCamelCase_		     =    torch.manual_seed(0  )
       lowerCamelCase_		     =    pipe(
           prompt=A_						,							image=A_						,							generator=A_						,							output_type='np'						,							)
       lowerCamelCase_		     =    output.images[0]

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





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

       """simple docstring"""






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

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

       lowerCamelCase_		     =    'stabilityai/stable-diffusion-x4-upscaler'
       lowerCamelCase_		     =    StableDiffusionUpscalePipeline.from_pretrained(
           A_						,							torch_dtype=torch.floataa						,							)
       pipe.to(A_  )
       pipe.set_progress_bar_config(disable=A_  )
       pipe.enable_attention_slicing(1  )
       pipe.enable_sequential_cpu_offload()

       lowerCamelCase_		     =    'a cat sitting on a park bench'

       lowerCamelCase_		     =    torch.manual_seed(0  )
       lowerCamelCase_		     =    pipe(
           prompt=A_						,							image=A_						,							generator=A_						,							num_inference_steps=5						,							output_type='np'						,							)

       lowerCamelCase_		     =    torch.cuda.max_memory_allocated()
       # make sure that less than 2.9 GB is allocated
       assert mem_bytes < 2.9 * 10**9



