




"""simple docstring"""






import copy
import inspect
import unittest

from transformers import PretrainedConfig, SwiftFormerConfig
from transformers.testing_utils import (
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
		import torch
		from torch import nn

		from transformers import SwiftFormerForImageClassification, SwiftFormerModel
		from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import ViTImageProcessor




class 				__lowercase			:







					'''simple docstring'''




					def __init__(						self	,			_UpperCAmelCase	,			_UpperCAmelCase=13	,			_UpperCAmelCase=3	,			_UpperCAmelCase=True	,			_UpperCAmelCase=True	,			_UpperCAmelCase=0.1	,			_UpperCAmelCase=0.1	,			_UpperCAmelCase=224	,			_UpperCAmelCase=1000	,			_UpperCAmelCase=[3, 3, 6, 4]	,			_UpperCAmelCase=[48, 56, 112, 220]	,			):
									__a :						Union[str, Any]			       =  parent
									__a :						str			       =  batch_size
									__a :						Dict			       =  num_channels
									__a :						List[Any]			       =  is_training
									__a :						int			       =  use_labels
									__a :						Tuple			       =  hidden_dropout_prob
									__a :						str			       =  attention_probs_dropout_prob
									__a :						Dict			       =  num_labels
									__a :						Union[str, Any]			       =  image_size
									__a :						Union[str, Any]			       =  layer_depths
									__a :						List[Any]			       =  embed_dims







					def  _lowerCamelCase		(						self     ):
									__a :						int			       =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

									__a :						Any			       =  None
									if self.use_labels:
													__a :						int			       =  ids_tensor([self.batch_size]	,			self.num_labels     )

									__a :						Tuple			       =  self.get_config()

									return config, pixel_values, labels







					def  _lowerCamelCase		(						self     ):
									return SwiftFormerConfig(
									    depths=self.layer_depths	,			embed_dims=self.embed_dims	,			mlp_ratio=4	,			downsamples=[True, True, True, True]	,			hidden_act='''gelu'''	,			num_labels=self.num_labels	,			down_patch_size=3	,			down_stride=2	,			down_pad=1	,			drop_rate=0.0	,			drop_path_rate=0.0	,			use_layer_scale=_UpperCAmelCase	,			layer_scale_init_value=1e-5	,			)







					def  _lowerCamelCase		(						self	,			_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase     ):
									__a :						List[Any]			       =  SwiftFormerModel(config=_UpperCAmelCase     )
									model.to(_UpperCAmelCase     )
									model.eval()
									__a :						List[str]			       =  model(_UpperCAmelCase     )
									self.parent.assertEqual(result.last_hidden_state.shape	,			(self.batch_size, self.embed_dims[-1], 7, 7)     )







					def  _lowerCamelCase		(						self	,			_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase     ):
									__a :						Union[str, Any]			       =  self.num_labels
									__a :						Dict			       =  SwiftFormerForImageClassification(_UpperCAmelCase     )
									model.to(_UpperCAmelCase     )
									model.eval()
									__a :						str			       =  model(_UpperCAmelCase	,			labels=_UpperCAmelCase     )
									self.parent.assertEqual(result.logits.shape	,			(self.batch_size, self.num_labels)     )

									__a :						Optional[int]			       =  SwiftFormerForImageClassification(_UpperCAmelCase     )
									model.to(_UpperCAmelCase     )
									model.eval()

									__a :						List[Any]			       =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )
									__a :						List[str]			       =  model(_UpperCAmelCase     )
									self.parent.assertEqual(result.logits.shape	,			(self.batch_size, self.num_labels)     )







					def  _lowerCamelCase		(						self     ):
									(__a) :						List[Any]			       =  self.prepare_config_and_inputs()
									__a :						int			       =  {'''pixel_values''': pixel_values}
									return config, inputs_dict






@require_torch
class 				__lowercase			(			_UpperCamelCase   ,      _UpperCamelCase   ,      unittest.TestCase							):







					'''simple docstring'''




					__lowerCAmelCase  =  (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else ()
					__lowerCAmelCase  =  (
					    {'''feature-extraction''': SwiftFormerModel, '''image-classification''': SwiftFormerForImageClassification}
					    if is_torch_available()
					    else {}
					)

					__lowerCAmelCase  =  False
					__lowerCAmelCase  =  False
					__lowerCAmelCase  =  False
					__lowerCAmelCase  =  False
					__lowerCAmelCase  =  False







					def  _lowerCamelCase		(						self     ):
									__a :						str			       =  SwiftFormerModelTester(self     )
									__a :						List[Any]			       =  ConfigTester(
									    self	,			config_class=_UpperCAmelCase	,			has_text_modality=_UpperCAmelCase	,			hidden_size=37	,			num_attention_heads=12	,			num_hidden_layers=12	,			)







					def  _lowerCamelCase		(						self     ):
									self.config_tester.run_common_tests()







					@unittest.skip(reason='''SwiftFormer does not use inputs_embeds'''     )
					def  _lowerCamelCase		(						self     ):
									pass







					def  _lowerCamelCase		(						self     ):
									__a :						Dict			       =  self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
													__a :						List[str]			       =  model_class(_UpperCAmelCase     )
													__a :						int			       =  model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(_UpperCAmelCase	,			nn.Linear     )     )







					def  _lowerCamelCase		(						self     ):
									__a :						str			       =  self.model_tester.prepare_config_and_inputs_for_common()

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

													__a :						Union[str, Any]			       =  ['''pixel_values''']
													self.assertListEqual(arg_names[:1]	,			_UpperCAmelCase     )







					def  _lowerCamelCase		(						self     ):
									__a :						Optional[Any]			       =  self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_UpperCAmelCase     )







					def  _lowerCamelCase		(						self     ):
									__a :						Dict			       =  self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase     )







					@slow
					def  _lowerCamelCase		(						self     ):
									for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													__a :						List[Any]			       =  SwiftFormerModel.from_pretrained(_UpperCAmelCase     )
													self.assertIsNotNone(_UpperCAmelCase     )







					@unittest.skip(reason='''SwiftFormer does not output attentions'''     )
					def  _lowerCamelCase		(						self     ):
									pass







					def  _lowerCamelCase		(						self     ):
									def check_hidden_states_output(_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase     ):
													__a :						Optional[Any]			       =  model_class(_UpperCAmelCase     )
													model.to(_UpperCAmelCase     )
													model.eval()

													with torch.no_grad():
																	__a :						List[Any]			       =  model(**self._prepare_for_class(_UpperCAmelCase	,			_UpperCAmelCase     )     )

													__a :						List[Any]			       =  outputs.hidden_states

													__a :						Any			       =  8
													self.assertEqual(len(_UpperCAmelCase     )	,			_UpperCAmelCase     )  # TODO

													# SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width)
													# with the width and height being successively divided by 2, after every 2 blocks
													for i in range(len(_UpperCAmelCase     )     ):
																	self.assertEqual(
																	    hidden_states[i].shape	,			torch.Size(
																	        [
																	            self.model_tester.batch_size,
																	            self.model_tester.embed_dims[i // 2],
																	            (self.model_tester.image_size // 4) // 2 ** (i // 2),
																	            (self.model_tester.image_size // 4) // 2 ** (i // 2),
																	        ]     )	,			)

									__a :						List[Any]			       =  self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
													__a :						Tuple			       =  True
													check_hidden_states_output(_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase     )

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

													check_hidden_states_output(_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase     )







					def  _lowerCamelCase		(						self     ):
									def _config_zero_init(_UpperCAmelCase     ):
													__a :						Any			       =  copy.deepcopy(_UpperCAmelCase     )
													for key in configs_no_init.__dict__.keys():
																	if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key:
																					setattr(_UpperCAmelCase	,			_UpperCAmelCase	,			1e-1_0     )
																	if isinstance(getattr(_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase     )	,			_UpperCAmelCase     ):
																					__a :						Optional[int]			       =  _config_zero_init(getattr(_UpperCAmelCase	,			_UpperCAmelCase     )     )
																					setattr(_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase     )
													return configs_no_init

									__a :						Union[str, Any]			       =  self.model_tester.prepare_config_and_inputs_for_common()

									__a :						Tuple			       =  _config_zero_init(_UpperCAmelCase     )
									for model_class in self.all_model_classes:
													__a :						List[str]			       =  model_class(config=_UpperCAmelCase     )
													for name, param in model.named_parameters():
																	if param.requires_grad:
																					self.assertIn(
																					    ((param.data.mean() * 1e9) / 1e9).round().item()	,			[0.0, 1.0]	,			msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""	,			)







					@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''     )
					def  _lowerCamelCase		(						self     ):
									pass






def     __A      (			)		->		Union[str, Any]:
				__a :						Optional[Any]			       =  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
				return image






@require_torch
@require_vision
class 				__lowercase			(			unittest.TestCase							):







					'''simple docstring'''




					@cached_property
					def  _lowerCamelCase		(						self     ):
									return ViTImageProcessor.from_pretrained('''MBZUAI/swiftformer-xs'''     ) if is_vision_available() else None







					@slow
					def  _lowerCamelCase		(						self     ):
									__a :						int			       =  SwiftFormerForImageClassification.from_pretrained('''MBZUAI/swiftformer-xs'''     ).to(_UpperCAmelCase     )

									__a :						List[Any]			       =  self.default_image_processor
									__a :						List[Any]			       =  prepare_img()
									__a :						Optional[Any]			       =  image_processor(images=_UpperCAmelCase	,			return_tensors='''pt'''     ).to(_UpperCAmelCase     )

									# forward pass
									with torch.no_grad():
													__a :						Optional[Any]			       =  model(**_UpperCAmelCase     )

									# verify the logits
									__a :						Any			       =  torch.Size((1, 1000)     )
									self.assertEqual(outputs.logits.shape	,			_UpperCAmelCase     )

									__a :						str			       =  torch.tensor([[-2.1_7_0_3e0_0, 2.1_1_0_7e0_0, -2.0_8_1_1e0_0]]     ).to(_UpperCAmelCase     )
									self.assertTrue(torch.allclose(outputs.logits[0, :3]	,			_UpperCAmelCase	,			atol=1e-4     )     )






"""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,
    EulerAncestralDiscreteScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionInstructPixaPixPipeline,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.utils import floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()




class 				__lowercase			(			_UpperCamelCase   ,      _UpperCamelCase   ,      _UpperCamelCase   ,      unittest.TestCase							):







					'''simple docstring'''




					__lowerCAmelCase  =  StableDiffusionInstructPixaPixPipeline
					__lowerCAmelCase  =  TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width''', '''cross_attention_kwargs'''}
					__lowerCAmelCase  =  TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
					__lowerCAmelCase  =  IMAGE_TO_IMAGE_IMAGE_PARAMS
					__lowerCAmelCase  =  IMAGE_TO_IMAGE_IMAGE_PARAMS







					def  _lowerCamelCase		(						self     ):
									torch.manual_seed(0     )
									__a :						Optional[Any]			       =  UNetaDConditionModel(
									    block_out_channels=(32, 64)	,			layers_per_block=2	,			sample_size=32	,			in_channels=8	,			out_channels=4	,			down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')	,			up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')	,			cross_attention_dim=32	,			)
									__a :						List[str]			       =  PNDMScheduler(skip_prk_steps=_UpperCAmelCase     )
									torch.manual_seed(0     )
									__a :						int			       =  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	,			)
									torch.manual_seed(0     )
									__a :						str			       =  CLIPTextConfig(
									    bos_token_id=0	,			eos_token_id=2	,			hidden_size=32	,			intermediate_size=37	,			layer_norm_eps=1e-0_5	,			num_attention_heads=4	,			num_hidden_layers=5	,			pad_token_id=1	,			vocab_size=1000	,			)
									__a :						Optional[int]			       =  CLIPTextModel(_UpperCAmelCase     )
									__a :						str			       =  CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''     )

									__a :						Union[str, Any]			       =  {
									    '''unet''': unet,
									    '''scheduler''': scheduler,
									    '''vae''': vae,
									    '''text_encoder''': text_encoder,
									    '''tokenizer''': tokenizer,
									    '''safety_checker''': None,
									    '''feature_extractor''': None,
									}
									return components







					def  _lowerCamelCase		(						self	,			_UpperCAmelCase	,			_UpperCAmelCase=0     ):
									__a :						Any			       =  floats_tensor((1, 3, 32, 32)	,			rng=random.Random(_UpperCAmelCase     )     ).to(_UpperCAmelCase     )
									__a :						Optional[Any]			       =  image.cpu().permute(0	,			2	,			3	,			1     )[0]
									__a :						Tuple			       =  Image.fromarray(np.uinta(_UpperCAmelCase     )     ).convert('''RGB'''     )
									if str(_UpperCAmelCase     ).startswith('''mps'''     ):
													__a :						Union[str, Any]			       =  torch.manual_seed(_UpperCAmelCase     )
									else:
													__a :						Union[str, Any]			       =  torch.Generator(device=_UpperCAmelCase     ).manual_seed(_UpperCAmelCase     )
									__a :						Union[str, Any]			       =  {
									    '''prompt''': '''A painting of a squirrel eating a burger''',
									    '''image''': image,
									    '''generator''': generator,
									    '''num_inference_steps''': 2,
									    '''guidance_scale''': 6.0,
									    '''image_guidance_scale''': 1,
									    '''output_type''': '''numpy''',
									}
									return inputs







					def  _lowerCamelCase		(						self     ):
									__a :						List[Any]			       =  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
									__a :						Dict			       =  self.get_dummy_components()
									__a :						Any			       =  StableDiffusionInstructPixaPixPipeline(**_UpperCAmelCase     )
									__a :						int			       =  sd_pipe.to(_UpperCAmelCase     )
									sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase     )

									__a :						Union[str, Any]			       =  self.get_dummy_inputs(_UpperCAmelCase     )
									__a :						str			       =  sd_pipe(**_UpperCAmelCase     ).images
									__a :						List[Any]			       =  image[0, -3:, -3:, -1]
									assert image.shape == (1, 32, 32, 3)
									__a :						Optional[int]			       =  np.array([0.7_5_2_6, 0.3_7_5_0, 0.4_5_4_7, 0.6_1_1_7, 0.5_8_6_6, 0.5_0_1_6, 0.4_3_2_7, 0.5_6_4_2, 0.4_8_1_5]     )

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







					def  _lowerCamelCase		(						self     ):
									__a :						Dict			       =  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
									__a :						Optional[Any]			       =  self.get_dummy_components()
									__a :						Dict			       =  StableDiffusionInstructPixaPixPipeline(**_UpperCAmelCase     )
									__a :						List[Any]			       =  sd_pipe.to(_UpperCAmelCase     )
									sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase     )

									__a :						Dict			       =  self.get_dummy_inputs(_UpperCAmelCase     )
									__a :						Union[str, Any]			       =  '''french fries'''
									__a :						str			       =  sd_pipe(**_UpperCAmelCase	,			negative_prompt=_UpperCAmelCase     )
									__a :						Dict			       =  output.images
									__a :						Optional[int]			       =  image[0, -3:, -3:, -1]

									assert image.shape == (1, 32, 32, 3)
									__a :						Tuple			       =  np.array([0.7_5_1_1, 0.3_6_4_2, 0.4_5_5_3, 0.6_2_3_6, 0.5_7_9_7, 0.5_0_1_3, 0.4_3_4_3, 0.5_6_1_1, 0.4_8_3_1]     )

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







					def  _lowerCamelCase		(						self     ):
									__a :						Union[str, Any]			       =  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
									__a :						Dict			       =  self.get_dummy_components()
									__a :						str			       =  StableDiffusionInstructPixaPixPipeline(**_UpperCAmelCase     )
									__a :						Optional[int]			       =  sd_pipe.to(_UpperCAmelCase     )
									sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase     )

									__a :						Union[str, Any]			       =  self.get_dummy_inputs(_UpperCAmelCase     )
									__a :						List[str]			       =  [inputs['''prompt''']] * 2

									__a :						Optional[Any]			       =  np.array(inputs['''image''']     ).astype(np.floataa     ) / 2_5_5.0
									__a :						Optional[Any]			       =  torch.from_numpy(_UpperCAmelCase     ).unsqueeze(0     ).to(_UpperCAmelCase     )
									__a :						Tuple			       =  image / 2 + 0.5
									__a :						str			       =  image.permute(0	,			3	,			1	,			2     )
									__a :						List[str]			       =  image.repeat(2	,			1	,			1	,			1     )

									__a :						int			       =  sd_pipe(**_UpperCAmelCase     ).images
									__a :						Optional[Any]			       =  image[-1, -3:, -3:, -1]

									assert image.shape == (2, 32, 32, 3)
									__a :						List[str]			       =  np.array([0.5_8_1_2, 0.5_7_4_8, 0.5_2_2_2, 0.5_9_0_8, 0.5_6_9_5, 0.7_1_7_4, 0.6_8_0_4, 0.5_5_2_3, 0.5_5_7_9]     )

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







					def  _lowerCamelCase		(						self     ):
									__a :						Dict			       =  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
									__a :						List[str]			       =  self.get_dummy_components()
									__a :						Union[str, Any]			       =  EulerAncestralDiscreteScheduler(
									    beta_start=0.0_0_0_8_5	,			beta_end=0.0_1_2	,			beta_schedule='''scaled_linear'''     )
									__a :						str			       =  StableDiffusionInstructPixaPixPipeline(**_UpperCAmelCase     )
									__a :						List[str]			       =  sd_pipe.to(_UpperCAmelCase     )
									sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase     )

									__a :						Dict			       =  self.get_dummy_inputs(_UpperCAmelCase     )
									__a :						Any			       =  sd_pipe(**_UpperCAmelCase     ).images
									__a :						Dict			       =  image[0, -3:, -3:, -1]

									__a :						Optional[int]			       =  [round(_UpperCAmelCase	,			4     ) for x in image_slice.flatten().tolist()]
									print(''','''.join([str(_UpperCAmelCase     ) for x in slice]     )     )

									assert image.shape == (1, 32, 32, 3)
									__a :						int			       =  np.array([0.7_4_1_7, 0.3_8_4_2, 0.4_7_3_2, 0.5_7_7_6, 0.5_8_9_1, 0.5_1_3_9, 0.4_0_5_2, 0.5_6_7_3, 0.4_9_8_6]     )

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







					def  _lowerCamelCase		(						self     ):
									super().test_inference_batch_single_identical(expected_max_diff=3e-3     )







					def  _lowerCamelCase		(						self     ):
									__a :						Any			       =  self.get_dummy_components()
									__a :						Optional[Any]			       =  StableDiffusionInstructPixaPixPipeline(**_UpperCAmelCase     )
									__a :						Any			       =  VaeImageProcessor(do_resize=_UpperCAmelCase	,			do_normalize=_UpperCAmelCase     )
									__a :						Dict			       =  pipe.to(_UpperCAmelCase     )
									pipe.set_progress_bar_config(disable=_UpperCAmelCase     )

									__a :						str			       =  pipe(**self.get_dummy_inputs_by_type(_UpperCAmelCase	,			input_image_type='''pt'''     )     )[0]

									__a :						List[Any]			       =  components['''vae''']
									__a :						List[Any]			       =  self.get_dummy_inputs_by_type(_UpperCAmelCase	,			input_image_type='''pt'''     )

									for image_param in self.image_latents_params:
													if image_param in inputs.keys():
																	__a :						Optional[Any]			       =  vae.encode(inputs[image_param]     ).latent_dist.mode()

									__a :						str			       =  pipe(**_UpperCAmelCase     )[0]

									__a :						Union[str, Any]			       =  np.abs(out - out_latents_inputs     ).max()
									self.assertLess(_UpperCAmelCase	,			1e-4	,			'''passing latents as image input generate different result from passing image'''     )






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







					'''simple docstring'''




					def  _lowerCamelCase		(						self     ):
									super().tearDown()
									gc.collect()
									torch.cuda.empty_cache()







					def  _lowerCamelCase		(						self	,			_UpperCAmelCase=0     ):
									__a :						List[str]			       =  torch.manual_seed(_UpperCAmelCase     )
									__a :						str			       =  load_image(
									    '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg'''     )
									__a :						List[str]			       =  {
									    '''prompt''': '''turn him into a cyborg''',
									    '''image''': image,
									    '''generator''': generator,
									    '''num_inference_steps''': 3,
									    '''guidance_scale''': 7.5,
									    '''image_guidance_scale''': 1.0,
									    '''output_type''': '''numpy''',
									}
									return inputs







					def  _lowerCamelCase		(						self     ):
									__a :						List[str]			       =  StableDiffusionInstructPixaPixPipeline.from_pretrained(
									    '''timbrooks/instruct-pix2pix'''	,			safety_checker=_UpperCAmelCase     )
									pipe.to(_UpperCAmelCase     )
									pipe.set_progress_bar_config(disable=_UpperCAmelCase     )
									pipe.enable_attention_slicing()

									__a :						str			       =  self.get_inputs()
									__a :						Optional[Any]			       =  pipe(**_UpperCAmelCase     ).images
									__a :						List[str]			       =  image[0, -3:, -3:, -1].flatten()

									assert image.shape == (1, 512, 512, 3)
									__a :						Tuple			       =  np.array([0.5_9_0_2, 0.6_0_1_5, 0.6_0_2_7, 0.5_9_8_3, 0.6_0_9_2, 0.6_0_6_1, 0.5_7_6_5, 0.5_7_8_5, 0.5_5_5_5]     )

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







					def  _lowerCamelCase		(						self     ):
									__a :						Tuple			       =  StableDiffusionInstructPixaPixPipeline.from_pretrained(
									    '''timbrooks/instruct-pix2pix'''	,			safety_checker=_UpperCAmelCase     )
									__a :						Optional[int]			       =  LMSDiscreteScheduler.from_config(pipe.scheduler.config     )
									pipe.to(_UpperCAmelCase     )
									pipe.set_progress_bar_config(disable=_UpperCAmelCase     )
									pipe.enable_attention_slicing()

									__a :						List[str]			       =  self.get_inputs()
									__a :						Optional[int]			       =  pipe(**_UpperCAmelCase     ).images
									__a :						Optional[Any]			       =  image[0, -3:, -3:, -1].flatten()

									assert image.shape == (1, 512, 512, 3)
									__a :						Tuple			       =  np.array([0.6_5_7_8, 0.6_8_1_7, 0.6_9_7_2, 0.6_7_6_1, 0.6_8_5_6, 0.6_9_1_6, 0.6_4_2_8, 0.6_5_1_6, 0.6_3_0_1]     )

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







					def  _lowerCamelCase		(						self     ):
									__a :						List[Any]			       =  StableDiffusionInstructPixaPixPipeline.from_pretrained(
									    '''timbrooks/instruct-pix2pix'''	,			safety_checker=_UpperCAmelCase     )
									__a :						Optional[int]			       =  DDIMScheduler.from_config(pipe.scheduler.config     )
									pipe.to(_UpperCAmelCase     )
									pipe.set_progress_bar_config(disable=_UpperCAmelCase     )
									pipe.enable_attention_slicing()

									__a :						List[str]			       =  self.get_inputs()
									__a :						str			       =  pipe(**_UpperCAmelCase     ).images
									__a :						Optional[int]			       =  image[0, -3:, -3:, -1].flatten()

									assert image.shape == (1, 512, 512, 3)
									__a :						Any			       =  np.array([0.3_8_2_8, 0.3_8_3_4, 0.3_8_1_8, 0.3_7_9_2, 0.3_8_6_5, 0.3_7_5_2, 0.3_7_9_2, 0.3_8_4_7, 0.3_7_5_3]     )

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







					def  _lowerCamelCase		(						self     ):
									__a :						Dict			       =  0

									def callback_fn(_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase     ) -> None:
													__a :						Optional[Any]			       =  True
													nonlocal number_of_steps
													number_of_steps += 1
													if step == 1:
																	__a :						Optional[int]			       =  latents.detach().cpu().numpy()
																	assert latents.shape == (1, 4, 64, 64)
																	__a :						int			       =  latents[0, -3:, -3:, -1]
																	__a :						int			       =  np.array([-0.2_4_6_3, -0.4_6_4_4, -0.9_7_5_6, 1.5_1_7_6, 1.4_4_1_4, 0.7_8_6_6, 0.9_8_9_7, 0.8_5_2_1, 0.7_9_8_3]     )

																	assert np.abs(latents_slice.flatten() - expected_slice     ).max() < 5e-2
													elif step == 2:
																	__a :						Union[str, Any]			       =  latents.detach().cpu().numpy()
																	assert latents.shape == (1, 4, 64, 64)
																	__a :						List[str]			       =  latents[0, -3:, -3:, -1]
																	__a :						Tuple			       =  np.array([-0.2_6_4_4, -0.4_6_2_6, -0.9_6_5_3, 1.5_1_7_6, 1.4_5_5_1, 0.7_6_8_6, 0.9_8_0_5, 0.8_4_5_2, 0.8_1_1_5]     )

																	assert np.abs(latents_slice.flatten() - expected_slice     ).max() < 5e-2

									__a :						Union[str, Any]			       =  False

									__a :						Optional[int]			       =  StableDiffusionInstructPixaPixPipeline.from_pretrained(
									    '''timbrooks/instruct-pix2pix'''	,			safety_checker=_UpperCAmelCase	,			torch_dtype=torch.floataa     )
									__a :						Optional[int]			       =  pipe.to(_UpperCAmelCase     )
									pipe.set_progress_bar_config(disable=_UpperCAmelCase     )
									pipe.enable_attention_slicing()

									__a :						str			       =  self.get_inputs()
									pipe(**_UpperCAmelCase	,			callback=_UpperCAmelCase	,			callback_steps=1     )
									assert callback_fn.has_been_called
									assert number_of_steps == 3







					def  _lowerCamelCase		(						self     ):
									torch.cuda.empty_cache()
									torch.cuda.reset_max_memory_allocated()
									torch.cuda.reset_peak_memory_stats()

									__a :						Any			       =  StableDiffusionInstructPixaPixPipeline.from_pretrained(
									    '''timbrooks/instruct-pix2pix'''	,			safety_checker=_UpperCAmelCase	,			torch_dtype=torch.floataa     )
									__a :						Optional[int]			       =  pipe.to(_UpperCAmelCase     )
									pipe.set_progress_bar_config(disable=_UpperCAmelCase     )
									pipe.enable_attention_slicing(1     )
									pipe.enable_sequential_cpu_offload()

									__a :						List[Any]			       =  self.get_inputs()
									__a :						Tuple			       =  pipe(**_UpperCAmelCase     )

									__a :						List[str]			       =  torch.cuda.max_memory_allocated()
									# make sure that less than 2.2 GB is allocated
									assert mem_bytes < 2.2 * 10**9







					def  _lowerCamelCase		(						self     ):
									__a :						List[Any]			       =  self.get_inputs()
									# resize to resolution that is divisible by 8 but not 16 or 32
									__a :						str			       =  inputs['''image'''].resize((504, 504)     )

									__a :						Tuple			       =  '''timbrooks/instruct-pix2pix'''
									__a :						Any			       =  StableDiffusionInstructPixaPixPipeline.from_pretrained(
									    _UpperCAmelCase	,			safety_checker=_UpperCAmelCase	,			)
									pipe.to(_UpperCAmelCase     )
									pipe.set_progress_bar_config(disable=_UpperCAmelCase     )
									pipe.enable_attention_slicing()

									__a :						List[Any]			       =  pipe(**_UpperCAmelCase     )
									__a :						int			       =  output.images[0]

									__a :						Optional[int]			       =  image[255:258, 383:386, -1]

									assert image.shape == (504, 504, 3)
									__a :						Union[str, Any]			       =  np.array([0.2_7_2_6, 0.2_5_2_9, 0.2_6_6_4, 0.2_6_5_5, 0.2_6_4_1, 0.2_6_4_2, 0.2_5_9_1, 0.2_6_4_9, 0.2_5_9_0]     )

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