



import inspect
import unittest

from huggingface_hub import hf_hub_download

from transformers import ConvNextConfig, UperNetConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch

	from transformers import UperNetForSemanticSegmentation
	from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import AutoImageProcessor







class 				_a				:

			def __init__(self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_=13,   SCREAMING_SNAKE_CASE_=32,   SCREAMING_SNAKE_CASE_=3,   SCREAMING_SNAKE_CASE_=4,   SCREAMING_SNAKE_CASE_=[10, 20, 30, 40],   SCREAMING_SNAKE_CASE_=[2, 2, 3, 2],   SCREAMING_SNAKE_CASE_=True,   SCREAMING_SNAKE_CASE_=True,   SCREAMING_SNAKE_CASE_=37,   SCREAMING_SNAKE_CASE_="gelu",   SCREAMING_SNAKE_CASE_=10,   SCREAMING_SNAKE_CASE_=0.0_2,   SCREAMING_SNAKE_CASE_=["stage2", "stage3", "stage4"],   SCREAMING_SNAKE_CASE_=3,   SCREAMING_SNAKE_CASE_=None,   )       ->   List[Any]:
						UpperCAmelCase_:		Tuple							      =     parent
						UpperCAmelCase_:		int							      =     batch_size
						UpperCAmelCase_:		Union[str, Any]							      =     image_size
						UpperCAmelCase_:		int							      =     num_channels
						UpperCAmelCase_:		str							      =     num_stages
						UpperCAmelCase_:		int							      =     hidden_sizes
						UpperCAmelCase_:		Dict							      =     depths
						UpperCAmelCase_:		str							      =     is_training
						UpperCAmelCase_:		Any							      =     use_labels
						UpperCAmelCase_:		int							      =     intermediate_size
						UpperCAmelCase_:		Union[str, Any]							      =     hidden_act
						UpperCAmelCase_:		Union[str, Any]							      =     type_sequence_label_size
						UpperCAmelCase_:		int							      =     initializer_range
						UpperCAmelCase_:		Any							      =     out_features
						UpperCAmelCase_:		Tuple							      =     num_labels
						UpperCAmelCase_:		List[str]							      =     scope
						UpperCAmelCase_:		Optional[Any]							      =     num_stages

			def      __snake_case       (self					)       ->   str:
						UpperCAmelCase_:		List[str]							      =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

						UpperCAmelCase_:		List[str]							      =     None
						if self.use_labels:
									UpperCAmelCase_:		Optional[Any]							      =     ids_tensor([self.batch_size],   self.type_sequence_label_size					)

						UpperCAmelCase_:		Any							      =     self.get_config()

						return config, pixel_values, labels

			def      __snake_case       (self					)       ->   Optional[Any]:
						return ConvNextConfig(
						    num_channels=self.num_channels,   num_stages=self.num_stages,   hidden_sizes=self.hidden_sizes,   depths=self.depths,   is_training=self.is_training,   intermediate_size=self.intermediate_size,   hidden_act=self.hidden_act,   out_features=self.out_features,   )

			def      __snake_case       (self					)       ->   List[str]:
						return UperNetConfig(
						    backbone_config=self.get_backbone_config(),   hidden_size=512,   pool_scales=[1, 2, 3, 6],   use_auxiliary_head=SCREAMING_SNAKE_CASE_,   auxiliary_loss_weight=0.4,   auxiliary_in_channels=40,   auxiliary_channels=256,   auxiliary_num_convs=1,   auxiliary_concat_input=SCREAMING_SNAKE_CASE_,   loss_ignore_index=255,   num_labels=self.num_labels,   )

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)       ->   Union[str, Any]:
						UpperCAmelCase_:		Optional[int]							      =     UperNetForSemanticSegmentation(config=SCREAMING_SNAKE_CASE_					)
						model.to(SCREAMING_SNAKE_CASE_					)
						model.eval()
						UpperCAmelCase_:		Any							      =     model(SCREAMING_SNAKE_CASE_					)
						self.parent.assertEqual(
						    result.logits.shape,   (self.batch_size, self.num_labels, self.image_size, self.image_size)					)

			def      __snake_case       (self					)       ->   Optional[Any]:
						UpperCAmelCase_:		List[str]							      =     self.prepare_config_and_inputs()
						(
						    (
						    UpperCAmelCase_
						)      ,							(
						    UpperCAmelCase_
						)      ,							(
						    UpperCAmelCase_
						)      ,							
						):		List[Any]							      =     config_and_inputs
						UpperCAmelCase_:		List[Any]							      =     {"""pixel_values""": pixel_values}
						return config, inputs_dict







@require_torch
class 				_a				(   _lowerCAmelCase ,		_lowerCAmelCase ,		unittest.TestCase					):
			A      		=	(UperNetForSemanticSegmentation,) if is_torch_available() else ()
			A      		=	{'''image-segmentation''': UperNetForSemanticSegmentation} if is_torch_available() else {}
			A      		=	False
			A      		=	False
			A      		=	False
			A      		=	False
			A      		=	False
			A      		=	False

			def      __snake_case       (self					)       ->   Optional[Any]:
						UpperCAmelCase_:		List[str]							      =     UperNetModelTester(self					)
						UpperCAmelCase_:		List[str]							      =     ConfigTester(self,   config_class=SCREAMING_SNAKE_CASE_,   has_text_modality=SCREAMING_SNAKE_CASE_,   hidden_size=37					)

			def      __snake_case       (self					)       ->   List[str]:
						self.create_and_test_config_common_properties()
						self.config_tester.create_and_test_config_to_json_string()
						self.config_tester.create_and_test_config_to_json_file()
						self.config_tester.create_and_test_config_from_and_save_pretrained()
						self.config_tester.create_and_test_config_with_num_labels()
						self.config_tester.check_config_can_be_init_without_params()
						self.config_tester.check_config_arguments_init()

			def      __snake_case       (self					)       ->   Any:
						return

			def      __snake_case       (self					)       ->   Union[str, Any]:
						UpperCAmelCase_      ,							UpperCAmelCase_:		Dict							      =     self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									UpperCAmelCase_:		str							      =     model_class(SCREAMING_SNAKE_CASE_					)
									UpperCAmelCase_:		Union[str, Any]							      =     inspect.signature(model.forward					)
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									UpperCAmelCase_:		List[Any]							      =     [*signature.parameters.keys()]

									UpperCAmelCase_:		Dict							      =     ["""pixel_values"""]
									self.assertListEqual(arg_names[:1],   SCREAMING_SNAKE_CASE_					)

			def      __snake_case       (self					)       ->   Tuple:
						UpperCAmelCase_:		Union[str, Any]							      =     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE_					)

			@unittest.skip(reason="""UperNet does not use inputs_embeds"""					)
			def      __snake_case       (self					)       ->   Union[str, Any]:
						pass

			@unittest.skip(reason="""UperNet does not support input and output embeddings"""					)
			def      __snake_case       (self					)       ->   Dict:
						pass

			@unittest.skip(reason="""UperNet does not have a base model"""					)
			def      __snake_case       (self					)       ->   int:
						pass

			@unittest.skip(reason="""UperNet does not have a base model"""					)
			def      __snake_case       (self					)       ->   str:
						pass

			@require_torch_multi_gpu
			@unittest.skip(reason="""UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`"""					)
			def      __snake_case       (self					)       ->   Any:
						pass

			@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""					)
			def      __snake_case       (self					)       ->   Any:
						pass

			def      __snake_case       (self					)       ->   List[Any]:
						def check_hidden_states_output(SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					):
									UpperCAmelCase_:		Any							      =     model_class(SCREAMING_SNAKE_CASE_					)
									model.to(SCREAMING_SNAKE_CASE_					)
									model.eval()

									with torch.no_grad():
												UpperCAmelCase_:		int							      =     model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)					)

									UpperCAmelCase_:		int							      =     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

									UpperCAmelCase_:		int							      =     self.model_tester.num_stages
									self.assertEqual(len(SCREAMING_SNAKE_CASE_					),   expected_num_stages + 1					)

									# ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
									self.assertListEqual(
									    list(hidden_states[0].shape[-2:]					),   [self.model_tester.image_size // 4, self.model_tester.image_size // 4],   )

						UpperCAmelCase_      ,							UpperCAmelCase_:		Optional[Any]							      =     self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									UpperCAmelCase_:		Any							      =     True
									check_hidden_states_output(SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)

									# check that output_hidden_states also work using config
									del inputs_dict["output_hidden_states"]
									UpperCAmelCase_:		int							      =     True

									check_hidden_states_output(SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)

			def      __snake_case       (self					)       ->   List[str]:
						UpperCAmelCase_      ,							UpperCAmelCase_:		int							      =     self.model_tester.prepare_config_and_inputs_for_common()

						UpperCAmelCase_:		List[Any]							      =     _config_zero_init(SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		Optional[Any]							      =     _config_zero_init(configs_no_init.backbone_config					)
						for model_class in self.all_model_classes:
									UpperCAmelCase_:		Dict							      =     model_class(config=SCREAMING_SNAKE_CASE_					)
									for name, param in model.named_parameters():
												if param.requires_grad:
															self.assertIn(
															    ((param.data.mean() * 1E9).round() / 1E9).item(),   [0.0, 1.0],   msg=f'Parameter {name} of model {model_class} seems not properly initialized',   )

			@unittest.skip(reason="""UperNet does not have tied weights"""					)
			def      __snake_case       (self					)       ->   str:
						pass

			@slow
			def      __snake_case       (self					)       ->   Dict:
						for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									UpperCAmelCase_:		Any							      =     UperNetForSemanticSegmentation.from_pretrained(SCREAMING_SNAKE_CASE_					)
									self.assertIsNotNone(SCREAMING_SNAKE_CASE_					)







def  lowerCAmelCase_	():





			"""simple docstring"""


			UpperCAmelCase_:		List[str]							      =     hf_hub_download(
			    repo_id="""hf-internal-testing/fixtures_ade20k"""		,						repo_type="""dataset"""		,						filename="""ADE_val_00000001.jpg"""  )
			UpperCAmelCase_:		Dict							      =     Image.open(lowerCAmelCase__  ).convert("""RGB"""  )
			return image







@require_torch
@require_vision
@slow
class 				_a				(   unittest.TestCase					):

			def      __snake_case       (self					)       ->   Any:
						UpperCAmelCase_:		List[Any]							      =     AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny"""					)
						UpperCAmelCase_:		Any							      =     UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny"""					).to(SCREAMING_SNAKE_CASE_					)

						UpperCAmelCase_:		Dict							      =     prepare_img()
						UpperCAmelCase_:		str							      =     processor(images=SCREAMING_SNAKE_CASE_,   return_tensors="""pt"""					).to(SCREAMING_SNAKE_CASE_					)

						with torch.no_grad():
									UpperCAmelCase_:		str							      =     model(**SCREAMING_SNAKE_CASE_					)

						UpperCAmelCase_:		Union[str, Any]							      =     torch.Size((1, model.config.num_labels, 512, 512)					)
						self.assertEqual(outputs.logits.shape,   SCREAMING_SNAKE_CASE_					)

						UpperCAmelCase_:		Any							      =     torch.tensor(
						    [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]]					).to(SCREAMING_SNAKE_CASE_					)
						self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3],   SCREAMING_SNAKE_CASE_,   atol=1E-4					)					)

			def      __snake_case       (self					)       ->   Optional[int]:
						UpperCAmelCase_:		Any							      =     AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny"""					)
						UpperCAmelCase_:		Tuple							      =     UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny"""					).to(SCREAMING_SNAKE_CASE_					)

						UpperCAmelCase_:		List[str]							      =     prepare_img()
						UpperCAmelCase_:		Optional[Any]							      =     processor(images=SCREAMING_SNAKE_CASE_,   return_tensors="""pt"""					).to(SCREAMING_SNAKE_CASE_					)

						with torch.no_grad():
									UpperCAmelCase_:		List[str]							      =     model(**SCREAMING_SNAKE_CASE_					)

						UpperCAmelCase_:		List[str]							      =     torch.Size((1, model.config.num_labels, 512, 512)					)
						self.assertEqual(outputs.logits.shape,   SCREAMING_SNAKE_CASE_					)

						UpperCAmelCase_:		Optional[Any]							      =     torch.tensor(
						    [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]]					).to(SCREAMING_SNAKE_CASE_					)
						self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3],   SCREAMING_SNAKE_CASE_,   atol=1E-4					)					)











import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
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					):

			def      __snake_case       (self					)       ->   Optional[Any]:
						# clean up the VRAM after each test
						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()

			@property
			def      __snake_case       (self					)       ->   int:
						UpperCAmelCase_:		str							      =     1
						UpperCAmelCase_:		Optional[int]							      =     3
						UpperCAmelCase_:		Optional[Any]							      =     (32, 32)

						UpperCAmelCase_:		int							      =     floats_tensor((batch_size, num_channels) + sizes,   rng=random.Random(0					)					).to(SCREAMING_SNAKE_CASE_					)
						return image

			@property
			def      __snake_case       (self					)       ->   str:
						torch.manual_seed(0					)
						UpperCAmelCase_:		Optional[int]							      =     UNetaDConditionModel(
						    block_out_channels=(32, 64),   layers_per_block=2,   sample_size=32,   in_channels=4,   out_channels=4,   down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D"""),   up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D"""),   cross_attention_dim=32,   )
						return model

			@property
			def      __snake_case       (self					)       ->   Optional[int]:
						torch.manual_seed(0					)
						UpperCAmelCase_:		Union[str, Any]							      =     AutoencoderKL(
						    block_out_channels=[32, 64],   in_channels=3,   out_channels=3,   down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""],   up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""],   latent_channels=4,   )
						return model

			@property
			def      __snake_case       (self					)       ->   Tuple:
						torch.manual_seed(0					)
						UpperCAmelCase_:		List[Any]							      =     RobertaSeriesConfig(
						    hidden_size=32,   project_dim=32,   intermediate_size=37,   layer_norm_eps=1E-05,   num_attention_heads=4,   num_hidden_layers=5,   pad_token_id=1,   vocab_size=5006,   )
						return RobertaSeriesModelWithTransformation(SCREAMING_SNAKE_CASE_					)

			@property
			def      __snake_case       (self					)       ->   Union[str, Any]:
						def extract(*SCREAMING_SNAKE_CASE_,   **SCREAMING_SNAKE_CASE_					):







									class 				_a				:

												def __init__(self					)       ->   Tuple:
															UpperCAmelCase_:		Any							      =     torch.ones([0]					)

												def      __snake_case       (self,   SCREAMING_SNAKE_CASE_					)       ->   List[Any]:
															self.pixel_values.to(SCREAMING_SNAKE_CASE_					)
															return self






									return Out()

						return extract

			def      __snake_case       (self					)       ->   int:
						UpperCAmelCase_:		List[str]							      =     """cpu"""  # ensure determinism for the device-dependent torch.Generator
						UpperCAmelCase_:		Union[str, Any]							      =     self.dummy_cond_unet
						UpperCAmelCase_:		Any							      =     PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		List[Any]							      =     self.dummy_vae
						UpperCAmelCase_:		int							      =     self.dummy_text_encoder
						UpperCAmelCase_:		int							      =     XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""					)
						UpperCAmelCase_:		Tuple							      =     77

						UpperCAmelCase_:		Tuple							      =     self.dummy_image.to(SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		str							      =     init_image / 2 + 0.5

						# make sure here that pndm scheduler skips prk
						UpperCAmelCase_:		List[Any]							      =     AltDiffusionImgaImgPipeline(
						    unet=SCREAMING_SNAKE_CASE_,   scheduler=SCREAMING_SNAKE_CASE_,   vae=SCREAMING_SNAKE_CASE_,   text_encoder=SCREAMING_SNAKE_CASE_,   tokenizer=SCREAMING_SNAKE_CASE_,   safety_checker=SCREAMING_SNAKE_CASE_,   feature_extractor=self.dummy_extractor,   )
						UpperCAmelCase_:		Dict							      =     VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor,   do_normalize=SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		Optional[int]							      =     alt_pipe.to(SCREAMING_SNAKE_CASE_					)
						alt_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_					)

						UpperCAmelCase_:		str							      =     """A painting of a squirrel eating a burger"""
						UpperCAmelCase_:		List[str]							      =     torch.Generator(device=SCREAMING_SNAKE_CASE_					).manual_seed(0					)
						UpperCAmelCase_:		Optional[int]							      =     alt_pipe(
						    [prompt],   generator=SCREAMING_SNAKE_CASE_,   guidance_scale=6.0,   num_inference_steps=2,   output_type="""np""",   image=SCREAMING_SNAKE_CASE_,   )

						UpperCAmelCase_:		List[str]							      =     output.images

						UpperCAmelCase_:		Optional[Any]							      =     torch.Generator(device=SCREAMING_SNAKE_CASE_					).manual_seed(0					)
						UpperCAmelCase_:		Any							      =     alt_pipe(
						    [prompt],   generator=SCREAMING_SNAKE_CASE_,   guidance_scale=6.0,   num_inference_steps=2,   output_type="""np""",   image=SCREAMING_SNAKE_CASE_,   return_dict=SCREAMING_SNAKE_CASE_,   )[0]

						UpperCAmelCase_:		List[str]							      =     image[0, -3:, -3:, -1]
						UpperCAmelCase_:		str							      =     image_from_tuple[0, -3:, -3:, -1]

						assert image.shape == (1, 32, 32, 3)
						UpperCAmelCase_:		Tuple							      =     np.array([0.4_4_2_7, 0.3_7_3_1, 0.4_2_4_9, 0.4_9_4_1, 0.4_5_4_6, 0.4_1_4_8, 0.4_1_9_3, 0.4_6_6_6, 0.4_4_9_9]					)

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

			@unittest.skipIf(torch_device != """cuda""",   """This test requires a GPU"""					)
			def      __snake_case       (self					)       ->   str:
						UpperCAmelCase_:		List[Any]							      =     self.dummy_cond_unet
						UpperCAmelCase_:		List[Any]							      =     PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		Any							      =     self.dummy_vae
						UpperCAmelCase_:		Optional[Any]							      =     self.dummy_text_encoder
						UpperCAmelCase_:		Dict							      =     XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""					)
						UpperCAmelCase_:		Union[str, Any]							      =     77

						UpperCAmelCase_:		Tuple							      =     self.dummy_image.to(SCREAMING_SNAKE_CASE_					)

						# put models in fp16
						UpperCAmelCase_:		Optional[Any]							      =     unet.half()
						UpperCAmelCase_:		Any							      =     vae.half()
						UpperCAmelCase_:		str							      =     bert.half()

						# make sure here that pndm scheduler skips prk
						UpperCAmelCase_:		Optional[int]							      =     AltDiffusionImgaImgPipeline(
						    unet=SCREAMING_SNAKE_CASE_,   scheduler=SCREAMING_SNAKE_CASE_,   vae=SCREAMING_SNAKE_CASE_,   text_encoder=SCREAMING_SNAKE_CASE_,   tokenizer=SCREAMING_SNAKE_CASE_,   safety_checker=SCREAMING_SNAKE_CASE_,   feature_extractor=self.dummy_extractor,   )
						UpperCAmelCase_:		Optional[Any]							      =     VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor,   do_normalize=SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		Any							      =     alt_pipe.to(SCREAMING_SNAKE_CASE_					)
						alt_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_					)

						UpperCAmelCase_:		Any							      =     """A painting of a squirrel eating a burger"""
						UpperCAmelCase_:		Optional[Any]							      =     torch.manual_seed(0					)
						UpperCAmelCase_:		Optional[int]							      =     alt_pipe(
						    [prompt],   generator=SCREAMING_SNAKE_CASE_,   num_inference_steps=2,   output_type="""np""",   image=SCREAMING_SNAKE_CASE_,   ).images

						assert image.shape == (1, 32, 32, 3)

			@unittest.skipIf(torch_device != """cuda""",   """This test requires a GPU"""					)
			def      __snake_case       (self					)       ->   Tuple:
						UpperCAmelCase_:		Optional[Any]							      =     load_image(
						    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
						    """/img2img/sketch-mountains-input.jpg"""					)
						# resize to resolution that is divisible by 8 but not 16 or 32
						UpperCAmelCase_:		List[Any]							      =     init_image.resize((760, 504)					)

						UpperCAmelCase_:		Tuple							      =     """BAAI/AltDiffusion"""
						UpperCAmelCase_:		Tuple							      =     AltDiffusionImgaImgPipeline.from_pretrained(
						    SCREAMING_SNAKE_CASE_,   safety_checker=SCREAMING_SNAKE_CASE_,   )
						pipe.to(SCREAMING_SNAKE_CASE_					)
						pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_					)
						pipe.enable_attention_slicing()

						UpperCAmelCase_:		Tuple							      =     """A fantasy landscape, trending on artstation"""

						UpperCAmelCase_:		Optional[int]							      =     torch.manual_seed(0					)
						UpperCAmelCase_:		int							      =     pipe(
						    prompt=SCREAMING_SNAKE_CASE_,   image=SCREAMING_SNAKE_CASE_,   strength=0.7_5,   guidance_scale=7.5,   generator=SCREAMING_SNAKE_CASE_,   output_type="""np""",   )
						UpperCAmelCase_:		Dict							      =     output.images[0]

						UpperCAmelCase_:		Tuple							      =     image[255:258, 383:386, -1]

						assert image.shape == (504, 760, 3)
						UpperCAmelCase_:		str							      =     np.array([0.9_3_5_8, 0.9_3_9_7, 0.9_5_9_9, 0.9_9_0_1, 1.0_0_0_0, 1.0_0_0_0, 0.9_8_8_2, 1.0_0_0_0, 1.0_0_0_0]					)

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







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

			def      __snake_case       (self					)       ->   int:
						# clean up the VRAM after each test
						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()

			def      __snake_case       (self					)       ->   Union[str, Any]:
						UpperCAmelCase_:		Optional[Any]							      =     load_image(
						    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
						    """/img2img/sketch-mountains-input.jpg"""					)
						UpperCAmelCase_:		Optional[Any]							      =     init_image.resize((768, 512)					)
						UpperCAmelCase_:		Union[str, Any]							      =     load_numpy(
						    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"""					)

						UpperCAmelCase_:		List[str]							      =     """BAAI/AltDiffusion"""
						UpperCAmelCase_:		int							      =     AltDiffusionImgaImgPipeline.from_pretrained(
						    SCREAMING_SNAKE_CASE_,   safety_checker=SCREAMING_SNAKE_CASE_,   )
						pipe.to(SCREAMING_SNAKE_CASE_					)
						pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_					)
						pipe.enable_attention_slicing()

						UpperCAmelCase_:		Dict							      =     """A fantasy landscape, trending on artstation"""

						UpperCAmelCase_:		int							      =     torch.manual_seed(0					)
						UpperCAmelCase_:		int							      =     pipe(
						    prompt=SCREAMING_SNAKE_CASE_,   image=SCREAMING_SNAKE_CASE_,   strength=0.7_5,   guidance_scale=7.5,   generator=SCREAMING_SNAKE_CASE_,   output_type="""np""",   )
						UpperCAmelCase_:		Dict							      =     output.images[0]

						assert image.shape == (512, 768, 3)
						# img2img is flaky across GPUs even in fp32, so using MAE here
						assert np.abs(expected_image - image					).max() < 1E-2






