





'''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, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow

from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()


class 					a_     (				snake_case_      ,    snake_case_      ,    snake_case_      ,    unittest.TestCase       ):

    '''simple docstring'''
    UpperCamelCase     = StableDiffusionInpaintPipeline
    UpperCamelCase     = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
    UpperCamelCase     = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
    UpperCamelCase     = frozenset(
        []       )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
    UpperCamelCase     = frozenset([]       )


    def 			snake_case_(		self       )		->   str:
        torch.manual_seed(0       )
        _SCREAMING_SNAKE_CASE									=			UNetaDConditionModel(
            block_out_channels=(32, 64) ,		layers_per_block=2 ,		sample_size=32 ,		in_channels=9 ,		out_channels=4 ,		down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") ,		up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") ,		cross_attention_dim=32 ,		attention_head_dim=(2, 4) ,		use_linear_projection=A ,		)
        _SCREAMING_SNAKE_CASE									=			PNDMScheduler(skip_prk_steps=A       )
        torch.manual_seed(0       )
        _SCREAMING_SNAKE_CASE									=			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 ,		sample_size=128 ,		)
        torch.manual_seed(0       )
        _SCREAMING_SNAKE_CASE									=			CLIPTextConfig(
            bos_token_id=0 ,		eos_token_id=2 ,		hidden_size=32 ,		intermediate_size=37 ,		layer_norm_eps=1e-05 ,		num_attention_heads=4 ,		num_hidden_layers=5 ,		pad_token_id=1 ,		vocab_size=1000 ,		hidden_act="""gelu""" ,		projection_dim=512 ,		)
        _SCREAMING_SNAKE_CASE									=			CLIPTextModel(A       )
        _SCREAMING_SNAKE_CASE									=			CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""       )

        _SCREAMING_SNAKE_CASE									=			{
            """unet""": unet,
            """scheduler""": scheduler,
            """vae""": vae,
            """text_encoder""": text_encoder,
            """tokenizer""": tokenizer,
            """safety_checker""": None,
            """feature_extractor""": None,
        }
        return components


    def 			snake_case_(		self ,		A ,		A=0       )		->   Optional[Any]:
        # TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched
        _SCREAMING_SNAKE_CASE									=			floats_tensor((1, 3, 32, 32) ,		rng=random.Random(A       )       ).to(A       )
        _SCREAMING_SNAKE_CASE									=			image.cpu().permute(0 ,		2 ,		3 ,		1       )[0]
        _SCREAMING_SNAKE_CASE									=			Image.fromarray(np.uinta(A       )       ).convert("""RGB"""       ).resize((64, 64)       )
        _SCREAMING_SNAKE_CASE									=			Image.fromarray(np.uinta(image + 4       )       ).convert("""RGB"""       ).resize((64, 64)       )
        if str(A       ).startswith("""mps"""       ):
            _SCREAMING_SNAKE_CASE									=			torch.manual_seed(A       )
        else:
            _SCREAMING_SNAKE_CASE									=			torch.Generator(device=A       ).manual_seed(A       )
        _SCREAMING_SNAKE_CASE									=			{
            """prompt""": """A painting of a squirrel eating a burger""",
            """image""": init_image,
            """mask_image""": mask_image,
            """generator""": generator,
            """num_inference_steps""": 2,
            """guidance_scale""": 6.0,
            """output_type""": """numpy""",
        }
        return inputs


    def 			snake_case_(		self       )		->   str:
        _SCREAMING_SNAKE_CASE									=			"""cpu"""  # ensure determinism for the device-dependent torch.Generator
        _SCREAMING_SNAKE_CASE									=			self.get_dummy_components()
        _SCREAMING_SNAKE_CASE									=			StableDiffusionInpaintPipeline(**A       )
        _SCREAMING_SNAKE_CASE									=			sd_pipe.to(A       )
        sd_pipe.set_progress_bar_config(disable=A       )

        _SCREAMING_SNAKE_CASE									=			self.get_dummy_inputs(A       )
        _SCREAMING_SNAKE_CASE									=			sd_pipe(**A       ).images
        _SCREAMING_SNAKE_CASE									=			image[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
        _SCREAMING_SNAKE_CASE									=			np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476]       )

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





    def 			snake_case_(		self       )		->   Any:
        super().test_inference_batch_single_identical(expected_max_diff=3e-3       )




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

    '''simple docstring'''


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


    def 			snake_case_(		self       )		->   List[str]:
        _SCREAMING_SNAKE_CASE									=			load_image(
            """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
            """/sd2-inpaint/init_image.png"""       )
        _SCREAMING_SNAKE_CASE									=			load_image(
            """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png"""       )
        _SCREAMING_SNAKE_CASE									=			load_numpy(
            """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint"""
            """/yellow_cat_sitting_on_a_park_bench.npy"""       )

        _SCREAMING_SNAKE_CASE									=			"""stabilityai/stable-diffusion-2-inpainting"""
        _SCREAMING_SNAKE_CASE									=			StableDiffusionInpaintPipeline.from_pretrained(A ,		safety_checker=A       )
        pipe.to(A       )
        pipe.set_progress_bar_config(disable=A       )
        pipe.enable_attention_slicing()

        _SCREAMING_SNAKE_CASE									=			"""Face of a yellow cat, high resolution, sitting on a park bench"""

        _SCREAMING_SNAKE_CASE									=			torch.manual_seed(0       )
        _SCREAMING_SNAKE_CASE									=			pipe(
            prompt=A ,		image=A ,		mask_image=A ,		generator=A ,		output_type="""np""" ,		)
        _SCREAMING_SNAKE_CASE									=			output.images[0]

        assert image.shape == (512, 512, 3)
        assert np.abs(expected_image - image       ).max() < 9e-3


    def 			snake_case_(		self       )		->   Any:
        _SCREAMING_SNAKE_CASE									=			load_image(
            """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
            """/sd2-inpaint/init_image.png"""       )
        _SCREAMING_SNAKE_CASE									=			load_image(
            """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png"""       )
        _SCREAMING_SNAKE_CASE									=			load_numpy(
            """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint"""
            """/yellow_cat_sitting_on_a_park_bench_fp16.npy"""       )

        _SCREAMING_SNAKE_CASE									=			"""stabilityai/stable-diffusion-2-inpainting"""
        _SCREAMING_SNAKE_CASE									=			StableDiffusionInpaintPipeline.from_pretrained(
            A ,		torch_dtype=torch.floataa ,		safety_checker=A ,		)
        pipe.to(A       )
        pipe.set_progress_bar_config(disable=A       )
        pipe.enable_attention_slicing()

        _SCREAMING_SNAKE_CASE									=			"""Face of a yellow cat, high resolution, sitting on a park bench"""

        _SCREAMING_SNAKE_CASE									=			torch.manual_seed(0       )
        _SCREAMING_SNAKE_CASE									=			pipe(
            prompt=A ,		image=A ,		mask_image=A ,		generator=A ,		output_type="""np""" ,		)
        _SCREAMING_SNAKE_CASE									=			output.images[0]

        assert image.shape == (512, 512, 3)
        assert np.abs(expected_image - image       ).max() < 5e-1





    def 			snake_case_(		self       )		->   int:
        torch.cuda.empty_cache()
        torch.cuda.reset_max_memory_allocated()
        torch.cuda.reset_peak_memory_stats()

        _SCREAMING_SNAKE_CASE									=			load_image(
            """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
            """/sd2-inpaint/init_image.png"""       )
        _SCREAMING_SNAKE_CASE									=			load_image(
            """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png"""       )

        _SCREAMING_SNAKE_CASE									=			"""stabilityai/stable-diffusion-2-inpainting"""
        _SCREAMING_SNAKE_CASE									=			PNDMScheduler.from_pretrained(A ,		subfolder="""scheduler"""       )
        _SCREAMING_SNAKE_CASE									=			StableDiffusionInpaintPipeline.from_pretrained(
            A ,		safety_checker=A ,		scheduler=A ,		torch_dtype=torch.floataa ,		)
        pipe.to(A       )
        pipe.set_progress_bar_config(disable=A       )
        pipe.enable_attention_slicing(1       )
        pipe.enable_sequential_cpu_offload()

        _SCREAMING_SNAKE_CASE									=			"""Face of a yellow cat, high resolution, sitting on a park bench"""

        _SCREAMING_SNAKE_CASE									=			torch.manual_seed(0       )
        _SCREAMING_SNAKE_CASE									=			pipe(
            prompt=A ,		image=A ,		mask_image=A ,		generator=A ,		num_inference_steps=2 ,		output_type="""np""" ,		)

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










'''simple docstring'''

import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowercase_					= logging.get_logger(__name__)

lowercase_					= {
    """BridgeTower/bridgetower-base""": """https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json""",
    """BridgeTower/bridgetower-base-itm-mlm""": (
        """https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json"""
    ),
}


class 					a_     (				snake_case_       ):

    '''simple docstring'''
    UpperCamelCase     = '''bridgetower_vision_model'''


    def __init__(		self ,		A=768 ,		A=12 ,		A=3 ,		A=16 ,		A=288 ,		A=1 ,		A=1e-05 ,		A=False ,		A=True ,		A=False ,		**A ,		)		->   Dict:
        super().__init__(**A       )
        _SCREAMING_SNAKE_CASE									=			hidden_size
        _SCREAMING_SNAKE_CASE									=			num_hidden_layers
        _SCREAMING_SNAKE_CASE									=			num_channels
        _SCREAMING_SNAKE_CASE									=			patch_size
        _SCREAMING_SNAKE_CASE									=			image_size
        _SCREAMING_SNAKE_CASE									=			initializer_factor
        _SCREAMING_SNAKE_CASE									=			layer_norm_eps
        _SCREAMING_SNAKE_CASE									=			stop_gradient
        _SCREAMING_SNAKE_CASE									=			share_layernorm
        _SCREAMING_SNAKE_CASE									=			remove_last_layer





    @classmethod
    def 			snake_case_(		cls ,		A ,		**A       )		->   "PretrainedConfig":
        _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			cls.get_config_dict(A ,		**A       )

        if config_dict.get("""model_type"""       ) == "bridgetower":
            _SCREAMING_SNAKE_CASE									=			config_dict["""text_config"""]

        if "model_type" in config_dict and hasattr(cls ,		"""model_type"""       ) and config_dict["model_type"] != cls.model_type:
            logger.warning(
                f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
                f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'       )

        return cls.from_dict(A ,		**A       )




class 					a_     (				snake_case_       ):

    '''simple docstring'''
    UpperCamelCase     = '''bridgetower_text_model'''


    def __init__(		self ,		A=5_0265 ,		A=768 ,		A=12 ,		A=12 ,		A=1 ,		A=3072 ,		A="gelu" ,		A=0.1 ,		A=0.1 ,		A=514 ,		A=1 ,		A=1e-05 ,		A=1 ,		A=0 ,		A=2 ,		A="absolute" ,		A=True ,		**A ,		)		->   Union[str, Any]:
        super().__init__(**A       )

        _SCREAMING_SNAKE_CASE									=			vocab_size
        _SCREAMING_SNAKE_CASE									=			hidden_size
        _SCREAMING_SNAKE_CASE									=			num_hidden_layers
        _SCREAMING_SNAKE_CASE									=			num_attention_heads
        _SCREAMING_SNAKE_CASE									=			hidden_act
        _SCREAMING_SNAKE_CASE									=			initializer_factor
        _SCREAMING_SNAKE_CASE									=			intermediate_size
        _SCREAMING_SNAKE_CASE									=			hidden_dropout_prob
        _SCREAMING_SNAKE_CASE									=			attention_probs_dropout_prob
        _SCREAMING_SNAKE_CASE									=			max_position_embeddings
        _SCREAMING_SNAKE_CASE									=			type_vocab_size
        _SCREAMING_SNAKE_CASE									=			layer_norm_eps
        _SCREAMING_SNAKE_CASE									=			position_embedding_type
        _SCREAMING_SNAKE_CASE									=			use_cache
        _SCREAMING_SNAKE_CASE									=			pad_token_id
        _SCREAMING_SNAKE_CASE									=			bos_token_id
        _SCREAMING_SNAKE_CASE									=			eos_token_id





    @classmethod
    def 			snake_case_(		cls ,		A ,		**A       )		->   "PretrainedConfig":
        _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			cls.get_config_dict(A ,		**A       )

        if config_dict.get("""model_type"""       ) == "bridgetower":
            _SCREAMING_SNAKE_CASE									=			config_dict["""text_config"""]

        if "model_type" in config_dict and hasattr(cls ,		"""model_type"""       ) and config_dict["model_type"] != cls.model_type:
            logger.warning(
                f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
                f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'       )

        return cls.from_dict(A ,		**A       )




class 					a_     (				snake_case_       ):

    '''simple docstring'''
    UpperCamelCase     = '''bridgetower'''


    def __init__(		self ,		A=True ,		A="gelu" ,		A=768 ,		A=1 ,		A=1e-05 ,		A=False ,		A="add" ,		A=12 ,		A=6 ,		A=False ,		A=False ,		A=None ,		A=None ,		**A ,		)		->   Tuple:
        # TODO: remove this once the Hub files are updated.
        _SCREAMING_SNAKE_CASE									=			kwargs.pop("""text_config_dict""" ,		A       )
        _SCREAMING_SNAKE_CASE									=			kwargs.pop("""vision_config_dict""" ,		A       )

        super().__init__(**A       )
        _SCREAMING_SNAKE_CASE									=			share_cross_modal_transformer_layers
        _SCREAMING_SNAKE_CASE									=			hidden_act
        _SCREAMING_SNAKE_CASE									=			hidden_size
        _SCREAMING_SNAKE_CASE									=			initializer_factor
        _SCREAMING_SNAKE_CASE									=			layer_norm_eps
        _SCREAMING_SNAKE_CASE									=			share_link_tower_layers
        _SCREAMING_SNAKE_CASE									=			link_tower_type
        _SCREAMING_SNAKE_CASE									=			num_attention_heads
        _SCREAMING_SNAKE_CASE									=			num_hidden_layers
        _SCREAMING_SNAKE_CASE									=			tie_word_embeddings
        _SCREAMING_SNAKE_CASE									=			init_layernorm_from_vision_encoder

        if text_config is None:
            _SCREAMING_SNAKE_CASE									=			{}
            logger.info("""`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values."""       )

        if vision_config is None:
            _SCREAMING_SNAKE_CASE									=			{}
            logger.info("""`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values."""       )

        _SCREAMING_SNAKE_CASE									=			BridgeTowerTextConfig(**A       )
        _SCREAMING_SNAKE_CASE									=			BridgeTowerVisionConfig(**A       )


    @classmethod
    def 			snake_case_(		cls ,		A ,		A ,		**A       )		->   int:
        return cls(text_config=text_config.to_dict() ,		vision_config=vision_config.to_dict() ,		**A       )





    def 			snake_case_(		self       )		->   List[Any]:
        _SCREAMING_SNAKE_CASE									=			copy.deepcopy(self.__dict__       )
        _SCREAMING_SNAKE_CASE									=			self.text_config.to_dict()
        _SCREAMING_SNAKE_CASE									=			self.vision_config.to_dict()
        _SCREAMING_SNAKE_CASE									=			self.__class__.model_type
        return output



