




import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
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 transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
  from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor


class 							UpperCamelCase_       :

    '''simple docstring'''






    def __init__(     self :      Optional[int]   ,					UpperCAmelCase__ :      List[Any]   ,					UpperCAmelCase__ :      Any=13   ,					UpperCAmelCase__ :      List[Any]=32   ,					UpperCAmelCase__ :      Optional[int]=3   ,					UpperCAmelCase__ :      Optional[Any]=4   ,					UpperCAmelCase__ :      Dict=[10, 20, 30, 40]   ,					UpperCAmelCase__ :      Union[str, Any]=[2, 2, 3, 2]   ,					UpperCAmelCase__ :      Any=True   ,					UpperCAmelCase__ :      Any=True   ,					UpperCAmelCase__ :      Union[str, Any]=37   ,					UpperCAmelCase__ :      Union[str, Any]="gelu"   ,					UpperCAmelCase__ :      Any=10   ,					UpperCAmelCase__ :      List[Any]=0.02   ,					UpperCAmelCase__ :      List[str]=["stage2", "stage3", "stage4"]   ,					UpperCAmelCase__ :      Tuple=[2, 3, 4]   ,					UpperCAmelCase__ :      str=None   ,					)		->Optional[Any]:





           '''simple docstring'''

           A__ 					=       parent
           A__ 					=       batch_size
           A__ 					=       image_size
           A__ 					=       num_channels
           A__ 					=       num_stages
           A__ 					=       hidden_sizes
           A__ 					=       depths
           A__ 					=       is_training
           A__ 					=       use_labels
           A__ 					=       intermediate_size
           A__ 					=       hidden_act
           A__ 					=       num_labels
           A__ 					=       initializer_range
           A__ 					=       out_features
           A__ 					=       out_indices
           A__ 					=       scope


    def 			SCREAMING_SNAKE_CASE				(     self :      str)		->Tuple:





           '''simple docstring'''

           A__ 					=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

           A__ 					=       None
           if self.use_labels:
                  A__ 					=       ids_tensor([self.batch_size]   ,					self.num_labels)

           A__ 					=       self.get_config()

           return config, pixel_values, labels


    def 			SCREAMING_SNAKE_CASE				(     self :      Tuple)		->Any:





           '''simple docstring'''

           return ConvNextVaConfig(
               num_channels=self.num_channels   ,					hidden_sizes=self.hidden_sizes   ,					depths=self.depths   ,					num_stages=self.num_stages   ,					hidden_act=self.hidden_act   ,					is_decoder=UpperCAmelCase__   ,					initializer_range=self.initializer_range   ,					out_features=self.out_features   ,					out_indices=self.out_indices   ,					num_labels=self.num_labels   ,					)


    def 			SCREAMING_SNAKE_CASE				(     self :      List[str]   ,					UpperCAmelCase__ :      Any   ,					UpperCAmelCase__ :      str   ,					UpperCAmelCase__ :      str)		->List[str]:





           '''simple docstring'''

           A__ 					=       ConvNextVaModel(config=UpperCAmelCase__)
           model.to(UpperCAmelCase__)
           model.eval()
           A__ 					=       model(UpperCAmelCase__)
           # expected last hidden states: B, C, H // 32, W // 32
           self.parent.assertEqual(
               result.last_hidden_state.shape   ,					(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)   ,					)


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





           '''simple docstring'''

           A__ 					=       ConvNextVaForImageClassification(UpperCAmelCase__)
           model.to(UpperCAmelCase__)
           model.eval()
           A__ 					=       model(UpperCAmelCase__   ,					labels=UpperCAmelCase__)
           self.parent.assertEqual(result.logits.shape   ,					(self.batch_size, self.num_labels))


    def 			SCREAMING_SNAKE_CASE				(     self :      str   ,					UpperCAmelCase__ :      Tuple   ,					UpperCAmelCase__ :      Optional[Any]   ,					UpperCAmelCase__ :      str)		->str:





           '''simple docstring'''

           A__ 					=       ConvNextVaBackbone(config=UpperCAmelCase__)
           model.to(UpperCAmelCase__)
           model.eval()
           A__ 					=       model(UpperCAmelCase__)

           # verify hidden states
           self.parent.assertEqual(len(result.feature_maps)   ,					len(config.out_features))
           self.parent.assertListEqual(list(result.feature_maps[0].shape)   ,					[self.batch_size, self.hidden_sizes[1], 4, 4])

           # verify channels
           self.parent.assertEqual(len(model.channels)   ,					len(config.out_features))
           self.parent.assertListEqual(model.channels   ,					config.hidden_sizes[1:])

           # verify backbone works with out_features=None
           A__ 					=       None
           A__ 					=       ConvNextVaBackbone(config=UpperCAmelCase__)
           model.to(UpperCAmelCase__)
           model.eval()
           A__ 					=       model(UpperCAmelCase__)

           # verify feature maps
           self.parent.assertEqual(len(result.feature_maps)   ,					1)
           self.parent.assertListEqual(list(result.feature_maps[0].shape)   ,					[self.batch_size, self.hidden_sizes[-1], 1, 1])

           # verify channels
           self.parent.assertEqual(len(model.channels)   ,					1)
           self.parent.assertListEqual(model.channels   ,					[config.hidden_sizes[-1]])


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





           '''simple docstring'''

           A__ 					=       self.prepare_config_and_inputs()
           A__					,				A__					,				A__ 					=       config_and_inputs
           A__ 					=       {'''pixel_values''': pixel_values}
           return config, inputs_dict





    def 			SCREAMING_SNAKE_CASE				(     self :      List[Any])		->int:





           '''simple docstring'''

           A__ 					=       self.prepare_config_and_inputs()
           A__					,				A__					,				A__ 					=       config_and_inputs
           A__ 					=       {'''pixel_values''': pixel_values, '''labels''': labels}
           return config, inputs_dict


@require_torch
class 							UpperCamelCase_       (					UpperCAmelCase__						,   UpperCAmelCase__						,   unittest.TestCase	):

    '''simple docstring'''






    UpperCAmelCase__				    = (
        (
            ConvNextVaModel,
            ConvNextVaForImageClassification,
            ConvNextVaBackbone,
        )
        if is_torch_available()
        else ()
    )
    UpperCAmelCase__				    = (
        {'''feature-extraction''': ConvNextVaModel, '''image-classification''': ConvNextVaForImageClassification}
        if is_torch_available()
        else {}
    )

    UpperCAmelCase__				    = False
    UpperCAmelCase__				    = False
    UpperCAmelCase__				    = False
    UpperCAmelCase__				    = False
    UpperCAmelCase__				    = False


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





           '''simple docstring'''

           A__ 					=       ConvNextVaModelTester(self)
           A__ 					=       ConfigTester(self   ,					config_class=UpperCAmelCase__   ,					has_text_modality=UpperCAmelCase__   ,					hidden_size=37)


    def 			SCREAMING_SNAKE_CASE				(     self :      str)		->Tuple:





           '''simple docstring'''

           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 			SCREAMING_SNAKE_CASE				(     self :      int)		->Any:





           '''simple docstring'''

           return


    @unittest.skip(reason='''ConvNextV2 does not use inputs_embeds''')
    def 			SCREAMING_SNAKE_CASE				(     self :      Tuple)		->Optional[Any]:





           '''simple docstring'''

           pass


    @unittest.skip(reason='''ConvNextV2 does not support input and output embeddings''')
    def 			SCREAMING_SNAKE_CASE				(     self :      Optional[Any])		->Any:





           '''simple docstring'''

           pass


    @unittest.skip(reason='''ConvNextV2 does not use feedforward chunking''')
    def 			SCREAMING_SNAKE_CASE				(     self :      Dict)		->Optional[int]:





           '''simple docstring'''

           pass


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





           '''simple docstring'''

           if not self.model_tester.is_training:
                  return

           for model_class in self.all_model_classes:
                  A__					,				A__ 					=       self.model_tester.prepare_config_and_inputs_with_labels()
                  A__ 					=       True

                  if model_class.__name__ in [
                      *get_values(UpperCAmelCase__),
                      *get_values(UpperCAmelCase__),
                  ]:
                         continue

                  A__ 					=       model_class(UpperCAmelCase__)
                  model.to(UpperCAmelCase__)
                  model.train()
                  A__ 					=       self._prepare_for_class(UpperCAmelCase__   ,					UpperCAmelCase__   ,					return_labels=UpperCAmelCase__)
                  A__ 					=       model(**UpperCAmelCase__).loss
                  loss.backward()


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





           '''simple docstring'''

           if not self.model_tester.is_training:
                  return

           for model_class in self.all_model_classes:
                  A__					,				A__ 					=       self.model_tester.prepare_config_and_inputs_with_labels()
                  A__ 					=       False
                  A__ 					=       True

                  if (
                      model_class.__name__
                      in [*get_values(UpperCAmelCase__), *get_values(UpperCAmelCase__)]
                      or not model_class.supports_gradient_checkpointing
                  ):
                         continue

                  A__ 					=       model_class(UpperCAmelCase__)
                  model.to(UpperCAmelCase__)
                  model.gradient_checkpointing_enable()
                  model.train()
                  A__ 					=       self._prepare_for_class(UpperCAmelCase__   ,					UpperCAmelCase__   ,					return_labels=UpperCAmelCase__)
                  A__ 					=       model(**UpperCAmelCase__).loss
                  loss.backward()


    def 			SCREAMING_SNAKE_CASE				(     self :      Any)		->int:





           '''simple docstring'''

           A__					,				A__ 					=       self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                  A__ 					=       model_class(UpperCAmelCase__)
                  A__ 					=       inspect.signature(model.forward)
                  # signature.parameters is an OrderedDict => so arg_names order is deterministic
                  A__ 					=       [*signature.parameters.keys()]

                  A__ 					=       ['''pixel_values''']
                  self.assertListEqual(arg_names[:1]   ,					UpperCAmelCase__)


    def 			SCREAMING_SNAKE_CASE				(     self :      Any)		->Dict:





           '''simple docstring'''

           A__ 					=       self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCAmelCase__)


    def 			SCREAMING_SNAKE_CASE				(     self :      Optional[Any])		->Dict:





           '''simple docstring'''

           def check_hidden_states_output(UpperCAmelCase__ :      List[str]   ,					UpperCAmelCase__ :      Dict   ,					UpperCAmelCase__ :      List[Any]):
                  A__ 					=       model_class(UpperCAmelCase__)
                  model.to(UpperCAmelCase__)
                  model.eval()

                  with torch.no_grad():
                         A__ 					=       model(**self._prepare_for_class(UpperCAmelCase__   ,					UpperCAmelCase__))

                  A__ 					=       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                  A__ 					=       self.model_tester.num_stages
                  self.assertEqual(len(UpperCAmelCase__)   ,					expected_num_stages + 1)

                  # ConvNextV2'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]   ,					)

           A__					,				A__ 					=       self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                  A__ 					=       True
                  check_hidden_states_output(UpperCAmelCase__   ,					UpperCAmelCase__   ,					UpperCAmelCase__)

                  # check that output_hidden_states also work using config
                  del inputs_dict["output_hidden_states"]
                  A__ 					=       True

                  check_hidden_states_output(UpperCAmelCase__   ,					UpperCAmelCase__   ,					UpperCAmelCase__)


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





           '''simple docstring'''

           A__ 					=       self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__)





    @slow
    def 			SCREAMING_SNAKE_CASE				(     self :      List[str])		->Optional[Any]:





           '''simple docstring'''

           for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  A__ 					=       ConvNextVaModel.from_pretrained(UpperCAmelCase__)
                  self.assertIsNotNone(UpperCAmelCase__)







def SCREAMING_SNAKE_CASE							(			)  ->			Optional[Any]:



       """simple docstring"""

       A__ 					=       Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
       return image


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

    '''simple docstring'''






    @cached_property
    def 			SCREAMING_SNAKE_CASE				(     self :      Optional[int])		->int:





           '''simple docstring'''

           return AutoImageProcessor.from_pretrained('''facebook/convnextv2-tiny-1k-224''') if is_vision_available() else None





    @slow
    def 			SCREAMING_SNAKE_CASE				(     self :      Tuple)		->Optional[int]:





           '''simple docstring'''

           A__ 					=       ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224''').to(UpperCAmelCase__)

           A__ 					=       self.default_image_processor
           A__ 					=       prepare_img()
           A__ 					=       preprocessor(images=UpperCAmelCase__   ,					return_tensors='''pt''').to(UpperCAmelCase__)

           # forward pass
           with torch.no_grad():
                  A__ 					=       model(**UpperCAmelCase__)

           # verify the logits
           A__ 					=       torch.Size((1, 1_000))
           self.assertEqual(outputs.logits.shape   ,					UpperCAmelCase__)

           A__ 					=       torch.tensor([0.9996, 0.1966, -0.4386]).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 transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModel,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    floats_tensor,
    load_image,
    load_numpy,
    require_torch_gpu,
    skip_mps,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import (
    PipelineKarrasSchedulerTesterMixin,
    PipelineLatentTesterMixin,
    PipelineTesterMixin,
    assert_mean_pixel_difference,
)


enable_full_determinism()





class  __lowercase    (	__magic_name__							,				__magic_name__							,				__magic_name__							,				unittest.TestCase			):
   _a    						=   StableUnCLIPImgaImgPipeline
   _a    						=   TEXT_GUIDED_IMAGE_VARIATION_PARAMS
   _a    						=   TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
   _a    						=   frozenset(
       []			)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
   _a    						=   frozenset([]			)







   def 		UpperCamelCase__      (						self   )					->     List[str]:
     __a								=       32
     __a								=       embedder_hidden_size

     # image encoding components

     __a								=       CLIPImageProcessor(crop_size=32   ,				size=32   )

     torch.manual_seed(0   )
     __a								=       CLIPVisionModelWithProjection(
         CLIPVisionConfig(
             hidden_size=UpperCamelCase   ,				projection_dim=UpperCamelCase   ,				num_hidden_layers=5   ,				num_attention_heads=4   ,				image_size=32   ,				intermediate_size=37   ,				patch_size=1   ,				)   )

     # regular denoising components

     torch.manual_seed(0   )
     __a								=       StableUnCLIPImageNormalizer(embedding_dim=UpperCamelCase   )
     __a								=       DDPMScheduler(beta_schedule='squaredcos_cap_v2'   )

     torch.manual_seed(0   )
     __a								=       CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'   )

     torch.manual_seed(0   )
     __a								=       CLIPTextModel(
         CLIPTextConfig(
             bos_token_id=0   ,				eos_token_id=2   ,				hidden_size=UpperCamelCase   ,				projection_dim=32   ,				intermediate_size=37   ,				layer_norm_eps=1e-05   ,				num_attention_heads=4   ,				num_hidden_layers=5   ,				pad_token_id=1   ,				vocab_size=1000   ,				)   )

     torch.manual_seed(0   )
     __a								=       UNetaDConditionModel(
         sample_size=32   ,				in_channels=4   ,				out_channels=4   ,				down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D')   ,				up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D')   ,				block_out_channels=(32, 64)   ,				attention_head_dim=(2, 4)   ,				class_embed_type='projection'   ,				projection_class_embeddings_input_dim=embedder_projection_dim * 2   ,				cross_attention_dim=UpperCamelCase   ,				layers_per_block=1   ,				upcast_attention=UpperCamelCase   ,				use_linear_projection=UpperCamelCase   ,				)

     torch.manual_seed(0   )
     __a								=       DDIMScheduler(
         beta_schedule='scaled_linear'   ,				beta_start=0.00_085   ,				beta_end=0.012   ,				prediction_type='v_prediction'   ,				set_alpha_to_one=UpperCamelCase   ,				steps_offset=1   ,				)

     torch.manual_seed(0   )
     __a								=       AutoencoderKL()

     __a								=       {
         # image encoding components
         'feature_extractor': feature_extractor,
         'image_encoder': image_encoder.eval(),
         # image noising components
         'image_normalizer': image_normalizer.eval(),
         'image_noising_scheduler': image_noising_scheduler,
         # regular denoising components
         'tokenizer': tokenizer,
         'text_encoder': text_encoder.eval(),
         'unet': unet.eval(),
         'scheduler': scheduler,
         'vae': vae.eval(),
     }

     return components







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   ,				UpperCamelCase=0   ,				UpperCamelCase=True   )					->     Dict:
     if str(UpperCamelCase   ).startswith('mps'   ):
       __a								=       torch.manual_seed(UpperCamelCase   )
     else:
       __a								=       torch.Generator(device=UpperCamelCase   ).manual_seed(UpperCamelCase   )

     __a								=       floats_tensor((1, 3, 32, 32)   ,				rng=random.Random(UpperCamelCase   )   ).to(UpperCamelCase   )

     if pil_image:
       __a								=       input_image * 0.5 + 0.5
       __a								=       input_image.clamp(0   ,				1   )
       __a								=       input_image.cpu().permute(0   ,				2   ,				3   ,				1   ).float().numpy()
       __a								=       DiffusionPipeline.numpy_to_pil(UpperCamelCase   )[0]

     return {
         "prompt": "An anime racoon running a marathon",
         "image": input_image,
         "generator": generator,
         "num_inference_steps": 2,
         "output_type": "np",
     }







   @skip_mps
   def 		UpperCamelCase__      (						self   )					->     int:
     __a								=       'cpu'  # ensure determinism for the device-dependent torch.Generator
     __a								=       self.get_dummy_components()
     __a								=       StableUnCLIPImgaImgPipeline(**UpperCamelCase   )
     __a								=       sd_pipe.to(UpperCamelCase   )
     sd_pipe.set_progress_bar_config(disable=UpperCamelCase   )

     __a								=       self.get_dummy_inputs(UpperCamelCase   )
     inputs.update({'image_embeds': None}   )
     __a								=       sd_pipe(**UpperCamelCase   ).images
     __a								=       image[0, -3:, -3:, -1]

     assert image.shape == (1, 32, 32, 3)
     __a								=       np.array([0.3_872, 0.7_224, 0.5_601, 0.4_741, 0.6_872, 0.5_814, 0.4_636, 0.3_867, 0.5_078]   )

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







   def 		UpperCamelCase__      (						self   )					->     Any:
     __a								=       torch_device in ['cpu', 'mps']

     self._test_attention_slicing_forward_pass(test_max_difference=UpperCamelCase   )







   def 		UpperCamelCase__      (						self   )					->     Union[str, Any]:
     __a								=       torch_device in ['cpu', 'mps']

     self._test_inference_batch_single_identical(test_max_difference=UpperCamelCase   )







   @unittest.skipIf(
       torch_device != 'cuda' or not is_xformers_available()   ,				reason='XFormers attention is only available with CUDA and `xformers` installed'   ,				)
   def 		UpperCamelCase__      (						self   )					->     Optional[Any]:
     self._test_xformers_attention_forwardGenerator_pass(test_max_difference=UpperCamelCase   )





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







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







   def 		UpperCamelCase__      (						self   )					->     str:
     __a								=       load_image(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png'   )

     __a								=       load_numpy(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy'   )

     __a								=       StableUnCLIPImgaImgPipeline.from_pretrained(
         'fusing/stable-unclip-2-1-l-img2img'   ,				torch_dtype=torch.floataa   )
     pipe.to(UpperCamelCase   )
     pipe.set_progress_bar_config(disable=UpperCamelCase   )
     # stable unclip will oom when integration tests are run on a V100,
     # so turn on memory savings
     pipe.enable_attention_slicing()
     pipe.enable_sequential_cpu_offload()

     __a								=       torch.Generator(device='cpu'   ).manual_seed(0   )
     __a								=       pipe(UpperCamelCase   ,				'anime turle'   ,				generator=UpperCamelCase   ,				output_type='np'   )

     __a								=       output.images[0]

     assert image.shape == (768, 768, 3)

     assert_mean_pixel_difference(UpperCamelCase   ,				UpperCamelCase   )







   def 		UpperCamelCase__      (						self   )					->     Optional[int]:
     __a								=       load_image(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png'   )

     __a								=       load_numpy(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy'   )

     __a								=       StableUnCLIPImgaImgPipeline.from_pretrained(
         'fusing/stable-unclip-2-1-h-img2img'   ,				torch_dtype=torch.floataa   )
     pipe.to(UpperCamelCase   )
     pipe.set_progress_bar_config(disable=UpperCamelCase   )
     # stable unclip will oom when integration tests are run on a V100,
     # so turn on memory savings
     pipe.enable_attention_slicing()
     pipe.enable_sequential_cpu_offload()

     __a								=       torch.Generator(device='cpu'   ).manual_seed(0   )
     __a								=       pipe(UpperCamelCase   ,				'anime turle'   ,				generator=UpperCamelCase   ,				output_type='np'   )

     __a								=       output.images[0]

     assert image.shape == (768, 768, 3)

     assert_mean_pixel_difference(UpperCamelCase   ,				UpperCamelCase   )







   def 		UpperCamelCase__      (						self   )					->     Union[str, Any]:
     __a								=       load_image(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png'   )

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

     __a								=       StableUnCLIPImgaImgPipeline.from_pretrained(
         'fusing/stable-unclip-2-1-h-img2img'   ,				torch_dtype=torch.floataa   )
     __a								=       pipe.to(UpperCamelCase   )
     pipe.set_progress_bar_config(disable=UpperCamelCase   )
     pipe.enable_attention_slicing()
     pipe.enable_sequential_cpu_offload()

     __a								=       pipe(
         UpperCamelCase   ,				'anime turtle'   ,				num_inference_steps=2   ,				output_type='np'   ,				)

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



