


import inspect
import math
import tempfile
import unittest

import numpy as np

from transformers import ViTMAEConfig
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 ViTMAEForPreTraining, ViTMAEModel
 from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import ViTImageProcessor






class _lowerCamelCase:
       def __init__(					self,      lowerCamelCase,      lowerCamelCase=13,      lowerCamelCase=30,      lowerCamelCase=2,      lowerCamelCase=3,      lowerCamelCase=True,      lowerCamelCase=True,      lowerCamelCase=32,      lowerCamelCase=5,      lowerCamelCase=4,      lowerCamelCase=37,      lowerCamelCase="gelu",      lowerCamelCase=0.1,      lowerCamelCase=0.1,      lowerCamelCase=10,      lowerCamelCase=0.0_2,      lowerCamelCase=3,      lowerCamelCase=0.6,      lowerCamelCase=None,      )       ->   int:




           """simple docstring"""

           _lowercase       :							str      		=		parent
           _lowercase       :							Union[str, Any]      		=		batch_size
           _lowercase       :							Dict      		=		image_size
           _lowercase       :							Optional[Any]      		=		patch_size
           _lowercase       :							List[Any]      		=		num_channels
           _lowercase       :							Union[str, Any]      		=		is_training
           _lowercase       :							Dict      		=		use_labels
           _lowercase       :							List[str]      		=		hidden_size
           _lowercase       :							Union[str, Any]      		=		num_hidden_layers
           _lowercase       :							List[str]      		=		num_attention_heads
           _lowercase       :							Tuple      		=		intermediate_size
           _lowercase       :							List[str]      		=		hidden_act
           _lowercase       :							Dict      		=		hidden_dropout_prob
           _lowercase       :							str      		=		attention_probs_dropout_prob
           _lowercase       :							List[str]      		=		type_sequence_label_size
           _lowercase       :							Union[str, Any]      		=		initializer_range
           _lowercase       :							int      		=		mask_ratio
           _lowercase       :							List[str]      		=		scope

           # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above
           # (we add 1 for the [CLS] token)
           _lowercase       :							str      		=		(image_size // patch_size) ** 2
           _lowercase       :							List[str]      		=		int(math.ceil((1 - mask_ratio) * (num_patches + 1)))
       def 			UpperCamelCase     (					self)       ->   Optional[Any]:




           """simple docstring"""

           _lowercase       :							Union[str, Any]      		=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

           _lowercase       :							int      		=		None
           if self.use_labels:
               _lowercase       :							List[Any]      		=		ids_tensor([self.batch_size],      self.type_sequence_label_size)

           _lowercase       :							Optional[int]      		=		self.get_config()

           return config, pixel_values, labels
       def 			UpperCamelCase     (					self)       ->   Optional[Any]:




           """simple docstring"""

           return ViTMAEConfig(
               image_size=self.image_size,      patch_size=self.patch_size,      num_channels=self.num_channels,      hidden_size=self.hidden_size,      num_hidden_layers=self.num_hidden_layers,      num_attention_heads=self.num_attention_heads,      intermediate_size=self.intermediate_size,      hidden_act=self.hidden_act,      hidden_dropout_prob=self.hidden_dropout_prob,      attention_probs_dropout_prob=self.attention_probs_dropout_prob,      is_decoder=lowerCamelCase,      initializer_range=self.initializer_range,      mask_ratio=self.mask_ratio,      )
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase)       ->   Dict:




           """simple docstring"""

           _lowercase       :							Tuple      		=		ViTMAEModel(config=lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase       :							Tuple      		=		model(lowerCamelCase)
           self.parent.assertEqual(result.last_hidden_state.shape,      (self.batch_size, self.seq_length, self.hidden_size))
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase)       ->   Union[str, Any]:




           """simple docstring"""

           _lowercase       :							List[Any]      		=		ViTMAEForPreTraining(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase       :							Optional[int]      		=		model(lowerCamelCase)
           _lowercase       :							int      		=		(self.image_size // self.patch_size) ** 2
           _lowercase       :							List[str]      		=		self.patch_size**2 * self.num_channels
           self.parent.assertEqual(result.logits.shape,      (self.batch_size, num_patches, expected_num_channels))

           # test greyscale images
           _lowercase       :							Tuple      		=		1
           _lowercase       :							Any      		=		ViTMAEForPreTraining(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase       :							Optional[Any]      		=		floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
           _lowercase       :							Dict      		=		model(lowerCamelCase)
           _lowercase       :							List[str]      		=		self.patch_size**2
           self.parent.assertEqual(result.logits.shape,      (self.batch_size, num_patches, expected_num_channels))




       def 			UpperCamelCase     (					self)       ->   List[str]:




           """simple docstring"""

           _lowercase       :							Dict      		=		self.prepare_config_and_inputs()
           _lowercase		,				_lowercase		,				_lowercase       :							Tuple      		=		config_and_inputs
           _lowercase       :							Any      		=		{'pixel_values': pixel_values}
           return config, inputs_dict






@require_torch
class _lowerCamelCase(						_a, _a, unittest.TestCase   ):
       lowercase_ :	Optional[Any]     =			(ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else ()
       lowercase_ :	str     =			{"""feature-extraction""": ViTMAEModel} if is_torch_available() else {}

       lowercase_ :	Optional[int]     =			False
       lowercase_ :	List[str]     =			False
       lowercase_ :	Dict     =			False
       lowercase_ :	List[str]     =			False
       def 			UpperCamelCase     (					self)       ->   int:




           """simple docstring"""

           _lowercase       :							List[Any]      		=		ViTMAEModelTester(self)
           _lowercase       :							Union[str, Any]      		=		ConfigTester(self,      config_class=lowerCamelCase,      has_text_modality=lowerCamelCase,      hidden_size=37)
       def 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

           self.config_tester.run_common_tests()
       @unittest.skip(reason='ViTMAE does not use inputs_embeds')
       def 			UpperCamelCase     (					self)       ->   Any:




           """simple docstring"""

           pass
       def 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Any      		=		self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               _lowercase       :							Union[str, Any]      		=		model_class(lowerCamelCase)
               self.assertIsInstance(model.get_input_embeddings(),      (nn.Module))
               _lowercase       :							str      		=		model.get_output_embeddings()
               self.assertTrue(x is None or isinstance(lowerCamelCase,      nn.Linear))
       def 			UpperCamelCase     (					self)       ->   List[Any]:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Dict      		=		self.model_tester.prepare_config_and_inputs_for_common()

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

               _lowercase       :							Optional[Any]      		=		['pixel_values']
               self.assertListEqual(arg_names[:1],      lowerCamelCase)
       def 			UpperCamelCase     (					self)       ->   Tuple:




           """simple docstring"""

           _lowercase       :							str      		=		self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowerCamelCase)
       def 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

           _lowercase       :							int      		=		self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_pretraining(*lowerCamelCase)
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase)       ->   Dict:




           """simple docstring"""

           np.random.seed(2)

           _lowercase       :							Optional[Any]      		=		int((pt_model.config.image_size // pt_model.config.patch_size) ** 2)
           _lowercase       :							Optional[int]      		=		np.random.uniform(size=(self.model_tester.batch_size, num_patches))
           _lowercase       :							List[str]      		=		torch.from_numpy(lowerCamelCase)

           # Add `noise` argument.
           # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument
           _lowercase       :							List[str]      		=		pt_noise

           super().check_pt_tf_models(lowerCamelCase,      lowerCamelCase,      lowerCamelCase)
       def 			UpperCamelCase     (					self)       ->   Any:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Tuple      		=		self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               _lowercase       :							Any      		=		model_class(lowerCamelCase)
               model.to(lowerCamelCase)
               model.eval()
               # make random mask reproducible
               torch.manual_seed(2)
               with torch.no_grad():
                   _lowercase       :							List[str]      		=		model(**self._prepare_for_class(lowerCamelCase,      lowerCamelCase))

               _lowercase       :							str      		=		outputs[0].cpu().numpy()
               _lowercase       :							List[str]      		=		0

               with tempfile.TemporaryDirectory() as tmpdirname:
                   model.save_pretrained(lowerCamelCase)
                   _lowercase       :							Tuple      		=		model_class.from_pretrained(lowerCamelCase)
                   model.to(lowerCamelCase)
                   # make random mask reproducible
                   torch.manual_seed(2)
                   with torch.no_grad():
                       _lowercase       :							Optional[int]      		=		model(**self._prepare_for_class(lowerCamelCase,      lowerCamelCase))

                   # Make sure we don't have nans
                   _lowercase       :							Tuple      		=		after_outputs[0].cpu().numpy()
                   _lowercase       :							List[Any]      		=		0
                   _lowercase       :							Any      		=		np.amax(np.abs(out_a - out_a))
                   self.assertLessEqual(lowerCamelCase,      1E-5)
       @unittest.skip(
           reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n    to get deterministic results.')
       def 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

           pass
       @unittest.skip(
           reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n    to get deterministic results.')
       def 			UpperCamelCase     (					self)       ->   List[str]:




           """simple docstring"""

           pass
       @unittest.skip(
           reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n    to get deterministic results.')
       def 			UpperCamelCase     (					self)       ->   Dict:




           """simple docstring"""

           pass
       @unittest.skip(reason='ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load')
       def 			UpperCamelCase     (					self)       ->   Optional[int]:




           """simple docstring"""

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




           """simple docstring"""

           pass




       @slow
       def 			UpperCamelCase     (					self)       ->   Union[str, Any]:




           """simple docstring"""

           for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _lowercase       :							Tuple      		=		ViTMAEModel.from_pretrained(lowerCamelCase)
               self.assertIsNotNone(lowerCamelCase)



def 				UpperCamelCase_(      )    ->						Tuple:
    _lowercase       :							int      		=		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
    return image






@require_torch
@require_vision
class _lowerCamelCase(						unittest.TestCase   ):
       @cached_property
       def 			UpperCamelCase     (					self)       ->   Optional[int]:




           """simple docstring"""

           return ViTImageProcessor.from_pretrained('facebook/vit-mae-base') if is_vision_available() else None




       @slow
       def 			UpperCamelCase     (					self)       ->   int:




           """simple docstring"""

           np.random.seed(2)

           _lowercase       :							Dict      		=		ViTMAEForPreTraining.from_pretrained('facebook/vit-mae-base').to(lowerCamelCase)

           _lowercase       :							int      		=		self.default_image_processor
           _lowercase       :							List[Any]      		=		prepare_img()
           _lowercase       :							List[Any]      		=		image_processor(images=lowerCamelCase,      return_tensors='pt').to(lowerCamelCase)

           # prepare a noise vector that will be also used for testing the TF model
           # (this way we can ensure that the PT and TF models operate on the same inputs)
           _lowercase       :							Optional[Any]      		=		ViTMAEConfig()
           _lowercase       :							Dict      		=		int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2)
           _lowercase       :							Dict      		=		np.random.uniform(size=(1, num_patches))

           # forward pass
           with torch.no_grad():
               _lowercase       :							List[Any]      		=		model(**lowerCamelCase,      noise=torch.from_numpy(lowerCamelCase).to(device=lowerCamelCase))

           # verify the logits
           _lowercase       :							Optional[Any]      		=		torch.Size((1, 1_96, 7_68))
           self.assertEqual(outputs.logits.shape,      lowerCamelCase)

           _lowercase       :							Any      		=		torch.tensor(
               [[-0.0_5_4_8, -1.7_0_2_3, -0.9_3_2_5], [0.3_7_2_1, -0.5_6_7_0, -0.2_2_3_3], [0.8_2_3_5, -1.3_8_7_8, -0.3_5_2_4]])

           self.assertTrue(torch.allclose(outputs.logits[0, :3, :3],      expected_slice.to(lowerCamelCase),      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 _lowerCamelCase(						unittest.TestCase   ):
       def 			UpperCamelCase     (					self)       ->   Optional[Any]:




           """simple docstring"""

           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()
       @property
       def 			UpperCamelCase     (					self)       ->   Optional[int]:




           """simple docstring"""

           _lowercase       :							Optional[Any]      		=		1
           _lowercase       :							Any      		=		3
           _lowercase       :							Tuple      		=		(32, 32)

           _lowercase       :							Tuple      		=		floats_tensor((batch_size, num_channels) + sizes,      rng=random.Random(0)).to(lowerCamelCase)
           return image
       @property
       def 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

           torch.manual_seed(0)
           _lowercase       :							Dict      		=		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 			UpperCamelCase     (					self)       ->   List[Any]:




           """simple docstring"""

           torch.manual_seed(0)
           _lowercase       :							str      		=		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 			UpperCamelCase     (					self)       ->   Optional[Any]:




           """simple docstring"""

           torch.manual_seed(0)
           _lowercase       :							Optional[int]      		=		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=50_06,      )
           return RobertaSeriesModelWithTransformation(lowerCamelCase)
       @property
       def 			UpperCamelCase     (					self)       ->   Optional[int]:




           """simple docstring"""

           def extract(*lowerCamelCase,      **lowerCamelCase):






               class _lowerCamelCase:
                      def __init__(					self)       ->   Optional[Any]:




                          """simple docstring"""

                          _lowercase       :							Optional[int]      		=		torch.ones([0])




                      def 			UpperCamelCase     (					self,      lowerCamelCase)       ->   int:




                          """simple docstring"""

                          self.pixel_values.to(lowerCamelCase)
                          return self


               return Out()

           return extract
       def 			UpperCamelCase     (					self)       ->   Tuple:




           """simple docstring"""

           _lowercase       :							Any      		=		'cpu'  # ensure determinism for the device-dependent torch.Generator
           _lowercase       :							List[Any]      		=		self.dummy_cond_unet
           _lowercase       :							Union[str, Any]      		=		PNDMScheduler(skip_prk_steps=lowerCamelCase)
           _lowercase       :							Optional[Any]      		=		self.dummy_vae
           _lowercase       :							List[Any]      		=		self.dummy_text_encoder
           _lowercase       :							Any      		=		XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta')
           _lowercase       :							Tuple      		=		77

           _lowercase       :							int      		=		self.dummy_image.to(lowerCamelCase)
           _lowercase       :							int      		=		init_image / 2 + 0.5

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

           _lowercase       :							Optional[Any]      		=		'A painting of a squirrel eating a burger'
           _lowercase       :							Dict      		=		torch.Generator(device=lowerCamelCase).manual_seed(0)
           _lowercase       :							Any      		=		alt_pipe(
               [prompt],      generator=lowerCamelCase,      guidance_scale=6.0,      num_inference_steps=2,      output_type='np',      image=lowerCamelCase,      )

           _lowercase       :							Optional[int]      		=		output.images

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

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

           assert image.shape == (1, 32, 32, 3)
           _lowercase       :							int      		=		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 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

           _lowercase       :							List[Any]      		=		self.dummy_cond_unet
           _lowercase       :							Tuple      		=		PNDMScheduler(skip_prk_steps=lowerCamelCase)
           _lowercase       :							str      		=		self.dummy_vae
           _lowercase       :							Optional[Any]      		=		self.dummy_text_encoder
           _lowercase       :							Optional[Any]      		=		XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta')
           _lowercase       :							Optional[Any]      		=		77

           _lowercase       :							str      		=		self.dummy_image.to(lowerCamelCase)

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

           # make sure here that pndm scheduler skips prk
           _lowercase       :							Union[str, Any]      		=		AltDiffusionImgaImgPipeline(
               unet=lowerCamelCase,      scheduler=lowerCamelCase,      vae=lowerCamelCase,      text_encoder=lowerCamelCase,      tokenizer=lowerCamelCase,      safety_checker=lowerCamelCase,      feature_extractor=self.dummy_extractor,      )
           _lowercase       :							List[str]      		=		VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor,      do_normalize=lowerCamelCase)
           _lowercase       :							Any      		=		alt_pipe.to(lowerCamelCase)
           alt_pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase       :							int      		=		'A painting of a squirrel eating a burger'
           _lowercase       :							Optional[Any]      		=		torch.manual_seed(0)
           _lowercase       :							Union[str, Any]      		=		alt_pipe(
               [prompt],      generator=lowerCamelCase,      num_inference_steps=2,      output_type='np',      image=lowerCamelCase,      ).images

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




       @unittest.skipIf(torch_device != 'cuda',      'This test requires a GPU')
       def 			UpperCamelCase     (					self)       ->   Optional[int]:




           """simple docstring"""

           _lowercase       :							int      		=		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
           _lowercase       :							str      		=		init_image.resize((7_60, 5_04))

           _lowercase       :							Optional[int]      		=		'BAAI/AltDiffusion'
           _lowercase       :							str      		=		AltDiffusionImgaImgPipeline.from_pretrained(
               lowerCamelCase,      safety_checker=lowerCamelCase,      )
           pipe.to(lowerCamelCase)
           pipe.set_progress_bar_config(disable=lowerCamelCase)
           pipe.enable_attention_slicing()

           _lowercase       :							List[str]      		=		'A fantasy landscape, trending on artstation'

           _lowercase       :							Any      		=		torch.manual_seed(0)
           _lowercase       :							Dict      		=		pipe(
               prompt=lowerCamelCase,      image=lowerCamelCase,      strength=0.7_5,      guidance_scale=7.5,      generator=lowerCamelCase,      output_type='np',      )
           _lowercase       :							List[str]      		=		output.images[0]

           _lowercase       :							Tuple      		=		image[2_55:2_58, 3_83:3_86, -1]

           assert image.shape == (5_04, 7_60, 3)
           _lowercase       :							Optional[Any]      		=		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 _lowerCamelCase(						unittest.TestCase   ):
       def 			UpperCamelCase     (					self)       ->   Optional[Any]:




           """simple docstring"""

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




       def 			UpperCamelCase     (					self)       ->   List[Any]:




           """simple docstring"""

           _lowercase       :							Union[str, Any]      		=		load_image(
               'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
               '/img2img/sketch-mountains-input.jpg')
           _lowercase       :							str      		=		init_image.resize((7_68, 5_12))
           _lowercase       :							Any      		=		load_numpy(
               'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy')

           _lowercase       :							str      		=		'BAAI/AltDiffusion'
           _lowercase       :							Optional[Any]      		=		AltDiffusionImgaImgPipeline.from_pretrained(
               lowerCamelCase,      safety_checker=lowerCamelCase,      )
           pipe.to(lowerCamelCase)
           pipe.set_progress_bar_config(disable=lowerCamelCase)
           pipe.enable_attention_slicing()

           _lowercase       :							int      		=		'A fantasy landscape, trending on artstation'

           _lowercase       :							List[Any]      		=		torch.manual_seed(0)
           _lowercase       :							int      		=		pipe(
               prompt=lowerCamelCase,      image=lowerCamelCase,      strength=0.7_5,      guidance_scale=7.5,      generator=lowerCamelCase,      output_type='np',      )
           _lowercase       :							Union[str, Any]      		=		output.images[0]

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


