from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
    import tensorflow as tf

    from transformers import TFCvtForImageClassification, TFCvtModel
    from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor


class 	lowerCamelCase_     (   UpperCAmelCase_ ):






    '''simple docstring'''






    def 			UpperCamelCase__   (	self)       ->	Any:
        __UpperCamelCase     :Union[str, Any]			  =		self.config_class(**self.inputs_dict)
        self.parent.assertTrue(hasattr(__lowercase , '''embed_dim'''))
        self.parent.assertTrue(hasattr(__lowercase , '''num_heads'''))


class 	lowerCamelCase_     :






    '''simple docstring'''






    def __init__(	self , __lowercase , __lowercase=13 , __lowercase=64 , __lowercase=3 , __lowercase=[16, 48, 96] , __lowercase=[1, 3, 6] , __lowercase=[1, 2, 10] , __lowercase=[7, 3, 3] , __lowercase=[4, 2, 2] , __lowercase=[2, 1, 1] , __lowercase=[2, 2, 2] , __lowercase=[False, False, True] , __lowercase=[0.0, 0.0, 0.0] , __lowercase=0.02 , __lowercase=1E-1_2 , __lowercase=True , __lowercase=True , __lowercase=2 , )       ->	Any:
        __UpperCamelCase     :Optional[Any]			  =		parent
        __UpperCamelCase     :Tuple			  =		batch_size
        __UpperCamelCase     :List[Any]			  =		image_size
        __UpperCamelCase     :str			  =		patch_sizes
        __UpperCamelCase     :Optional[Any]			  =		patch_stride
        __UpperCamelCase     :int			  =		patch_padding
        __UpperCamelCase     :int			  =		is_training
        __UpperCamelCase     :Optional[Any]			  =		use_labels
        __UpperCamelCase     :str			  =		num_labels
        __UpperCamelCase     :Tuple			  =		num_channels
        __UpperCamelCase     :Optional[Any]			  =		embed_dim
        __UpperCamelCase     :List[Any]			  =		num_heads
        __UpperCamelCase     :Dict			  =		stride_kv
        __UpperCamelCase     :Optional[Any]			  =		depth
        __UpperCamelCase     :Any			  =		cls_token
        __UpperCamelCase     :Dict			  =		attention_drop_rate
        __UpperCamelCase     :int			  =		initializer_range
        __UpperCamelCase     :str			  =		layer_norm_eps







    def 			UpperCamelCase__   (	self)       ->	List[Any]:
        __UpperCamelCase     :Dict			  =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

        __UpperCamelCase     :int			  =		None
        if self.use_labels:
            # create a random int32 tensor of given shape
            __UpperCamelCase     :Optional[Any]			  =		ids_tensor([self.batch_size] , self.num_labels)

        __UpperCamelCase     :Dict			  =		self.get_config()
        return config, pixel_values, labels







    def 			UpperCamelCase__   (	self)       ->	Optional[int]:
        return CvtConfig(
            image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , )







    def 			UpperCamelCase__   (	self , __lowercase , __lowercase , __lowercase)       ->	Dict:
        __UpperCamelCase     :Any			  =		TFCvtModel(config=__lowercase)
        __UpperCamelCase     :Optional[int]			  =		model(__lowercase , training=__lowercase)
        __UpperCamelCase     :List[Any]			  =		(self.image_size, self.image_size)
        __UpperCamelCase  ,       __UpperCamelCase     :Tuple			  =		image_size[0], image_size[1]
        for i in range(len(self.depth)):
            __UpperCamelCase     :Tuple			  =		floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1)
            __UpperCamelCase     :int			  =		floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1)
        self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width))







    def 			UpperCamelCase__   (	self , __lowercase , __lowercase , __lowercase)       ->	str:
        __UpperCamelCase     :List[str]			  =		self.num_labels
        __UpperCamelCase     :Any			  =		TFCvtForImageClassification(__lowercase)
        __UpperCamelCase     :int			  =		model(__lowercase , labels=__lowercase , training=__lowercase)
        self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels))







    def 			UpperCamelCase__   (	self)       ->	List[str]:
        __UpperCamelCase     :List[str]			  =		self.prepare_config_and_inputs()
        __UpperCamelCase  ,       __UpperCamelCase  ,       __UpperCamelCase     :List[str]			  =		config_and_inputs
        __UpperCamelCase     :List[Any]			  =		{'''pixel_values''': pixel_values}
        return config, inputs_dict


@require_tf
class 	lowerCamelCase_     (   UpperCAmelCase_						,	UpperCAmelCase_						,	unittest.TestCase ):






    '''simple docstring'''






    a__	:						str						=      (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
    a__	:						str						=      (
        {"""feature-extraction""": TFCvtModel, """image-classification""": TFCvtForImageClassification}
        if is_tf_available()
        else {}
    )
    a__	:						List[str]						=      False
    a__	:						str						=      False
    a__	:						List[Any]						=      False
    a__	:						List[Any]						=      False
    a__	:						Optional[int]						=      False







    def 			UpperCamelCase__   (	self)       ->	Tuple:
        __UpperCamelCase     :List[str]			  =		TFCvtModelTester(self)
        __UpperCamelCase     :List[str]			  =		TFCvtConfigTester(self , config_class=__lowercase , has_text_modality=__lowercase , hidden_size=37)







    def 			UpperCamelCase__   (	self)       ->	Union[str, Any]:
        self.config_tester.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()







    @unittest.skip(reason='''Cvt does not output attentions''')
    def 			UpperCamelCase__   (	self)       ->	Optional[Any]:
        pass







    @unittest.skip(reason='''Cvt does not use inputs_embeds''')
    def 			UpperCamelCase__   (	self)       ->	Any:
        pass







    @unittest.skip(reason='''Cvt does not support input and output embeddings''')
    def 			UpperCamelCase__   (	self)       ->	str:
        pass







    @unittest.skipIf(
        not is_tf_available() or len(tf.config.list_physical_devices('''GPU''')) == 0 , reason='''TF does not support backprop for grouped convolutions on CPU.''' , )
    def 			UpperCamelCase__   (	self)       ->	int:
        super().test_dataset_conversion()







    @unittest.skipIf(
        not is_tf_available() or len(tf.config.list_physical_devices('''GPU''')) == 0 , reason='''TF does not support backprop for grouped convolutions on CPU.''' , )
    @slow
    def 			UpperCamelCase__   (	self)       ->	List[str]:
        super().test_keras_fit()







    @unittest.skip(reason='''Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8''')
    def 			UpperCamelCase__   (	self)       ->	Tuple:
        __UpperCamelCase     :int			  =		tf.keras.mixed_precision.Policy('''mixed_float16''')
        tf.keras.mixed_precision.set_global_policy(__lowercase)
        super().test_keras_fit()
        tf.keras.mixed_precision.set_global_policy('''float32''')







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

        for model_class in self.all_model_classes:
            __UpperCamelCase     :Dict			  =		model_class(__lowercase)
            __UpperCamelCase     :Dict			  =		inspect.signature(model.call)
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            __UpperCamelCase     :Dict			  =		[*signature.parameters.keys()]

            __UpperCamelCase     :Optional[int]			  =		['''pixel_values''']
            self.assertListEqual(arg_names[:1] , __lowercase)







    def 			UpperCamelCase__   (	self)       ->	str:
        def check_hidden_states_output(__lowercase , __lowercase , __lowercase):
            __UpperCamelCase     :Tuple			  =		model_class(__lowercase)

            __UpperCamelCase     :Optional[int]			  =		model(**self._prepare_for_class(__lowercase , __lowercase))
            __UpperCamelCase     :List[Any]			  =		outputs.hidden_states

            __UpperCamelCase     :Any			  =		len(self.model_tester.depth)
            self.assertEqual(len(__lowercase) , __lowercase)

            # verify the first hidden states (first block)
            self.assertListEqual(
                list(hidden_states[0].shape[-3:]) , [
                    self.model_tester.embed_dim[0],
                    self.model_tester.image_size // 4,
                    self.model_tester.image_size // 4,
                ] , )

        __UpperCamelCase  ,       __UpperCamelCase     :str			  =		self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            __UpperCamelCase     :int			  =		True
            check_hidden_states_output(__lowercase , __lowercase , __lowercase)

            # check that output_hidden_states also work using config
            del inputs_dict["output_hidden_states"]
            __UpperCamelCase     :Optional[Any]			  =		True

            check_hidden_states_output(__lowercase , __lowercase , __lowercase)







    def 			UpperCamelCase__   (	self)       ->	Tuple:
        __UpperCamelCase     :Optional[int]			  =		self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__lowercase)







    def 			UpperCamelCase__   (	self)       ->	List[str]:
        __UpperCamelCase     :str			  =		self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__lowercase)







    @slow
    def 			UpperCamelCase__   (	self)       ->	Any:
        for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            __UpperCamelCase     :Optional[int]			  =		TFCvtModel.from_pretrained(__lowercase)
            self.assertIsNotNone(__lowercase)



def lowerCamelCase  (   ):
    '''simple docstring'''







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


@require_tf
@require_vision
class 	lowerCamelCase_     (   unittest.TestCase ):






    '''simple docstring'''






    @cached_property
    def 			UpperCamelCase__   (	self)       ->	Dict:
        return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0])







    @slow
    def 			UpperCamelCase__   (	self)       ->	List[str]:
        __UpperCamelCase     :List[str]			  =		TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0])

        __UpperCamelCase     :Optional[Any]			  =		self.default_image_processor
        __UpperCamelCase     :Tuple			  =		prepare_img()
        __UpperCamelCase     :Dict			  =		image_processor(images=__lowercase , return_tensors='''tf''')

        # forward pass
        __UpperCamelCase     :str			  =		model(**__lowercase)

        # verify the logits
        __UpperCamelCase     :List[str]			  =		tf.TensorShape((1, 1_000))
        self.assertEqual(outputs.logits.shape , __lowercase)

        __UpperCamelCase     :Dict			  =		tf.constant([0.92_85, 0.90_15, -0.31_50])
        self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , __lowercase , atol=1E-4))






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 	lowerCamelCase_     (   UpperCAmelCase_						,	UpperCAmelCase_						,	UpperCAmelCase_						,	unittest.TestCase ):






    '''simple docstring'''






    a__	:						int						=      StableUnCLIPImgaImgPipeline
    a__	:						Optional[int]						=      TEXT_GUIDED_IMAGE_VARIATION_PARAMS
    a__	:						Union[str, Any]						=      TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
    a__	:						Optional[Any]						=      frozenset(
        [] )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
    a__	:						int						=      frozenset([] )







    def 			UpperCamelCase__   (	self)       ->	Tuple:
        __UpperCamelCase     :Tuple			  =		32
        __UpperCamelCase     :Optional[int]			  =		embedder_hidden_size

        # image encoding components

        __UpperCamelCase     :Union[str, Any]			  =		CLIPImageProcessor(crop_size=32 , size=32)

        torch.manual_seed(0)
        __UpperCamelCase     :Union[str, Any]			  =		CLIPVisionModelWithProjection(
            CLIPVisionConfig(
                hidden_size=__lowercase , projection_dim=__lowercase , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ))

        # regular denoising components

        torch.manual_seed(0)
        __UpperCamelCase     :str			  =		StableUnCLIPImageNormalizer(embedding_dim=__lowercase)
        __UpperCamelCase     :Optional[int]			  =		DDPMScheduler(beta_schedule='''squaredcos_cap_v2''')

        torch.manual_seed(0)
        __UpperCamelCase     :Union[str, Any]			  =		CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''')

        torch.manual_seed(0)
        __UpperCamelCase     :Dict			  =		CLIPTextModel(
            CLIPTextConfig(
                bos_token_id=0 , eos_token_id=2 , hidden_size=__lowercase , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ))

        torch.manual_seed(0)
        __UpperCamelCase     :List[Any]			  =		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=__lowercase , layers_per_block=1 , upcast_attention=__lowercase , use_linear_projection=__lowercase , )

        torch.manual_seed(0)
        __UpperCamelCase     :Tuple			  =		DDIMScheduler(
            beta_schedule='''scaled_linear''' , beta_start=0.0_00_85 , beta_end=0.0_12 , prediction_type='''v_prediction''' , set_alpha_to_one=__lowercase , steps_offset=1 , )

        torch.manual_seed(0)
        __UpperCamelCase     :List[str]			  =		AutoencoderKL()

        __UpperCamelCase     :Tuple			  =		{
            # 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 , __lowercase , __lowercase=0 , __lowercase=True)       ->	str:
        if str(__lowercase).startswith('''mps'''):
            __UpperCamelCase     :Union[str, Any]			  =		torch.manual_seed(__lowercase)
        else:
            __UpperCamelCase     :int			  =		torch.Generator(device=__lowercase).manual_seed(__lowercase)

        __UpperCamelCase     :int			  =		floats_tensor((1, 3, 32, 32) , rng=random.Random(__lowercase)).to(__lowercase)

        if pil_image:
            __UpperCamelCase     :List[Any]			  =		input_image * 0.5 + 0.5
            __UpperCamelCase     :Optional[Any]			  =		input_image.clamp(0 , 1)
            __UpperCamelCase     :int			  =		input_image.cpu().permute(0 , 2 , 3 , 1).float().numpy()
            __UpperCamelCase     :Optional[Any]			  =		DiffusionPipeline.numpy_to_pil(__lowercase)[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)       ->	Union[str, Any]:
        __UpperCamelCase     :Dict			  =		'''cpu'''  # ensure determinism for the device-dependent torch.Generator
        __UpperCamelCase     :Tuple			  =		self.get_dummy_components()
        __UpperCamelCase     :Any			  =		StableUnCLIPImgaImgPipeline(**__lowercase)
        __UpperCamelCase     :Optional[Any]			  =		sd_pipe.to(__lowercase)
        sd_pipe.set_progress_bar_config(disable=__lowercase)

        __UpperCamelCase     :List[Any]			  =		self.get_dummy_inputs(__lowercase)
        inputs.update({'''image_embeds''': None})
        __UpperCamelCase     :Any			  =		sd_pipe(**__lowercase).images
        __UpperCamelCase     :List[str]			  =		image[0, -3:, -3:, -1]

        assert image.shape == (1, 32, 32, 3)
        __UpperCamelCase     :List[Any]			  =		np.array([0.38_72, 0.72_24, 0.56_01, 0.47_41, 0.68_72, 0.58_14, 0.46_36, 0.38_67, 0.50_78])

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







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

        self._test_attention_slicing_forward_pass(test_max_difference=__lowercase)







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

        self._test_inference_batch_single_identical(test_max_difference=__lowercase)







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


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






    '''simple docstring'''






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







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

        __UpperCamelCase     :Any			  =		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''')

        __UpperCamelCase     :List[Any]			  =		StableUnCLIPImgaImgPipeline.from_pretrained(
            '''fusing/stable-unclip-2-1-l-img2img''' , torch_dtype=torch.floataa)
        pipe.to(__lowercase)
        pipe.set_progress_bar_config(disable=__lowercase)
        # 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()

        __UpperCamelCase     :int			  =		torch.Generator(device='''cpu''').manual_seed(0)
        __UpperCamelCase     :Dict			  =		pipe(__lowercase , '''anime turle''' , generator=__lowercase , output_type='''np''')

        __UpperCamelCase     :Dict			  =		output.images[0]

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

        assert_mean_pixel_difference(__lowercase , __lowercase)







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

        __UpperCamelCase     :Any			  =		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''')

        __UpperCamelCase     :Any			  =		StableUnCLIPImgaImgPipeline.from_pretrained(
            '''fusing/stable-unclip-2-1-h-img2img''' , torch_dtype=torch.floataa)
        pipe.to(__lowercase)
        pipe.set_progress_bar_config(disable=__lowercase)
        # 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()

        __UpperCamelCase     :int			  =		torch.Generator(device='''cpu''').manual_seed(0)
        __UpperCamelCase     :Optional[int]			  =		pipe(__lowercase , '''anime turle''' , generator=__lowercase , output_type='''np''')

        __UpperCamelCase     :List[Any]			  =		output.images[0]

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

        assert_mean_pixel_difference(__lowercase , __lowercase)







    def 			UpperCamelCase__   (	self)       ->	List[str]:
        __UpperCamelCase     :Dict			  =		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()

        __UpperCamelCase     :List[Any]			  =		StableUnCLIPImgaImgPipeline.from_pretrained(
            '''fusing/stable-unclip-2-1-h-img2img''' , torch_dtype=torch.floataa)
        __UpperCamelCase     :Union[str, Any]			  =		pipe.to(__lowercase)
        pipe.set_progress_bar_config(disable=__lowercase)
        pipe.enable_attention_slicing()
        pipe.enable_sequential_cpu_offload()

        __UpperCamelCase     :Optional[Any]			  =		pipe(
            __lowercase , '''anime turtle''' , num_inference_steps=2 , output_type='''np''' , )

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





