




'''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    lowerCamelCase    (		_lowerCamelCase				,_lowerCamelCase				,_lowerCamelCase				,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 							UpperCAmelCase__       ( self			:   Any  )						->   int:
								torch.manual_seed(0  )
								__magic_name__							:	str    							=							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=lowerCamelCase_       ,						)
								__magic_name__							:	int    							=							PNDMScheduler(skip_prk_steps=lowerCamelCase_  )
								torch.manual_seed(0  )
								__magic_name__							:	int    							=							AutoencoderKL(
								    block_out_channels=[32, 64]       ,						in_channels=3       ,						out_channels=3       ,						down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']       ,						up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']       ,						latent_channels=4       ,						sample_size=128       ,						)
								torch.manual_seed(0  )
								__magic_name__							:	Union[str, Any]    							=							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       ,						)
								__magic_name__							:	Tuple    							=							CLIPTextModel(lowerCamelCase_  )
								__magic_name__							:	List[str]    							=							CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''  )

								__magic_name__							:	Optional[Any]    							=							{
								    '''unet''': unet,
								    '''scheduler''': scheduler,
								    '''vae''': vae,
								    '''text_encoder''': text_encoder,
								    '''tokenizer''': tokenizer,
								    '''safety_checker''': None,
								    '''feature_extractor''': None,
								}
								return components

			def 							UpperCAmelCase__       ( self			:   List[str]       ,						lowerCamelCase_			:   Any       ,						lowerCamelCase_			:   Optional[Any]=0  )						->   List[str]:
								# TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched
								__magic_name__							:	List[str]    							=							floats_tensor((1, 3, 32, 32)       ,						rng=random.Random(lowerCamelCase_  )  ).to(lowerCamelCase_  )
								__magic_name__							:	Dict    							=							image.cpu().permute(0       ,						2       ,						3       ,						1  )[0]
								__magic_name__							:	int    							=							Image.fromarray(np.uinta(lowerCamelCase_  )  ).convert('''RGB'''  ).resize((64, 64)  )
								__magic_name__							:	int    							=							Image.fromarray(np.uinta(image + 4  )  ).convert('''RGB'''  ).resize((64, 64)  )
								if str(lowerCamelCase_  ).startswith('''mps'''  ):
													__magic_name__							:	List[str]    							=							torch.manual_seed(lowerCamelCase_  )
								else:
													__magic_name__							:	List[Any]    							=							torch.Generator(device=lowerCamelCase_  ).manual_seed(lowerCamelCase_  )
								__magic_name__							:	Union[str, Any]    							=							{
								    '''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 							UpperCAmelCase__       ( self			:   int  )						->   Any:
								__magic_name__							:	int    							=							'''cpu'''  # ensure determinism for the device-dependent torch.Generator
								__magic_name__							:	Union[str, Any]    							=							self.get_dummy_components()
								__magic_name__							:	Any    							=							StableDiffusionInpaintPipeline(**lowerCamelCase_  )
								__magic_name__							:	int    							=							sd_pipe.to(lowerCamelCase_  )
								sd_pipe.set_progress_bar_config(disable=lowerCamelCase_  )

								__magic_name__							:	Optional[int]    							=							self.get_dummy_inputs(lowerCamelCase_  )
								__magic_name__							:	List[Any]    							=							sd_pipe(**lowerCamelCase_  ).images
								__magic_name__							:	Union[str, Any]    							=							image[0, -3:, -3:, -1]

								assert image.shape == (1, 64, 64, 3)
								__magic_name__							:	List[str]    							=							np.array([0.4_7_2_7, 0.5_7_3_5, 0.3_9_4_1, 0.5_4_4_6, 0.5_9_2_6, 0.4_3_9_4, 0.5_0_6_2, 0.4_6_5_4, 0.4_4_7_6]  )

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


			def 							UpperCAmelCase__       ( self			:   str  )						->   Dict:
								super().test_inference_batch_single_identical(expected_max_diff=3E-3  )






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






			'''simple docstring'''





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

			def 							UpperCAmelCase__       ( self			:   Union[str, Any]  )						->   Tuple:
								__magic_name__							:	str    							=							load_image(
								    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
								    '''/sd2-inpaint/init_image.png'''  )
								__magic_name__							:	Any    							=							load_image(
								    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png'''  )
								__magic_name__							:	Optional[int]    							=							load_numpy(
								    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint'''
								    '''/yellow_cat_sitting_on_a_park_bench.npy'''  )

								__magic_name__							:	Optional[Any]    							=							'''stabilityai/stable-diffusion-2-inpainting'''
								__magic_name__							:	Any    							=							StableDiffusionInpaintPipeline.from_pretrained(lowerCamelCase_       ,						safety_checker=lowerCamelCase_  )
								pipe.to(lowerCamelCase_  )
								pipe.set_progress_bar_config(disable=lowerCamelCase_  )
								pipe.enable_attention_slicing()

								__magic_name__							:	Any    							=							'''Face of a yellow cat, high resolution, sitting on a park bench'''

								__magic_name__							:	Union[str, Any]    							=							torch.manual_seed(0  )
								__magic_name__							:	str    							=							pipe(
								    prompt=lowerCamelCase_       ,						image=lowerCamelCase_       ,						mask_image=lowerCamelCase_       ,						generator=lowerCamelCase_       ,						output_type='''np'''       ,						)
								__magic_name__							:	Union[str, Any]    							=							output.images[0]

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

			def 							UpperCAmelCase__       ( self			:   List[Any]  )						->   List[Any]:
								__magic_name__							:	Optional[Any]    							=							load_image(
								    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
								    '''/sd2-inpaint/init_image.png'''  )
								__magic_name__							:	Optional[int]    							=							load_image(
								    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png'''  )
								__magic_name__							:	Optional[int]    							=							load_numpy(
								    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint'''
								    '''/yellow_cat_sitting_on_a_park_bench_fp16.npy'''  )

								__magic_name__							:	List[str]    							=							'''stabilityai/stable-diffusion-2-inpainting'''
								__magic_name__							:	Optional[int]    							=							StableDiffusionInpaintPipeline.from_pretrained(
								    lowerCamelCase_       ,						torch_dtype=torch.floataa       ,						safety_checker=lowerCamelCase_       ,						)
								pipe.to(lowerCamelCase_  )
								pipe.set_progress_bar_config(disable=lowerCamelCase_  )
								pipe.enable_attention_slicing()

								__magic_name__							:	Optional[Any]    							=							'''Face of a yellow cat, high resolution, sitting on a park bench'''

								__magic_name__							:	Optional[int]    							=							torch.manual_seed(0  )
								__magic_name__							:	Any    							=							pipe(
								    prompt=lowerCamelCase_       ,						image=lowerCamelCase_       ,						mask_image=lowerCamelCase_       ,						generator=lowerCamelCase_       ,						output_type='''np'''       ,						)
								__magic_name__							:	int    							=							output.images[0]

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


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

								__magic_name__							:	Optional[Any]    							=							load_image(
								    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
								    '''/sd2-inpaint/init_image.png'''  )
								__magic_name__							:	Any    							=							load_image(
								    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png'''  )

								__magic_name__							:	int    							=							'''stabilityai/stable-diffusion-2-inpainting'''
								__magic_name__							:	Dict    							=							PNDMScheduler.from_pretrained(lowerCamelCase_       ,						subfolder='''scheduler'''  )
								__magic_name__							:	str    							=							StableDiffusionInpaintPipeline.from_pretrained(
								    lowerCamelCase_       ,						safety_checker=lowerCamelCase_       ,						scheduler=lowerCamelCase_       ,						torch_dtype=torch.floataa       ,						)
								pipe.to(lowerCamelCase_  )
								pipe.set_progress_bar_config(disable=lowerCamelCase_  )
								pipe.enable_attention_slicing(1  )
								pipe.enable_sequential_cpu_offload()

								__magic_name__							:	str    							=							'''Face of a yellow cat, high resolution, sitting on a park bench'''

								__magic_name__							:	int    							=							torch.manual_seed(0  )
								__magic_name__							:	List[str]    							=							pipe(
								    prompt=lowerCamelCase_       ,						image=lowerCamelCase_       ,						mask_image=lowerCamelCase_       ,						generator=lowerCamelCase_       ,						num_inference_steps=2       ,						output_type='''np'''       ,						)

								__magic_name__							:	Dict    							=							torch.cuda.max_memory_allocated()
								# make sure that less than 2.65 GB is allocated
								assert mem_bytes < 2.6_5 * 10**9









from dataclasses import dataclass
from typing import Optional, Tuple

import torch
from torch import nn
from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel
from transformers.utils import ModelOutput


@dataclass
class    lowerCamelCase    (		_lowerCamelCase						):






			'''simple docstring'''





			UpperCamelCase__								=None
			UpperCamelCase__								=None
			UpperCamelCase__								=None
			UpperCamelCase__								=None






class    lowerCamelCase    (		_lowerCamelCase						):






			'''simple docstring'''





			def __init__( self			:   List[Any]       ,						lowerCamelCase_			:   Optional[Any]=1       ,						lowerCamelCase_			:   Any=0       ,						lowerCamelCase_			:   Dict=2       ,						lowerCamelCase_			:   Dict=512       ,						lowerCamelCase_			:   int="cls"       ,						lowerCamelCase_			:   Dict=False       ,						lowerCamelCase_			:   List[Any]=True       ,						**lowerCamelCase_			:   Optional[Any]       ,						)						->   Optional[int]:
								super().__init__(pad_token_id=lowerCamelCase_       ,						bos_token_id=lowerCamelCase_       ,						eos_token_id=lowerCamelCase_       ,						**lowerCamelCase_  )
								__magic_name__							:	Dict    							=							project_dim
								__magic_name__							:	int    							=							pooler_fn
								__magic_name__							:	str    							=							learn_encoder
								__magic_name__							:	Optional[int]    							=							use_attention_mask






class    lowerCamelCase    (		_lowerCamelCase						):






			'''simple docstring'''





			UpperCamelCase__								=[R'''pooler''', R'''logit_scale''']
			UpperCamelCase__								=[R'''position_ids''', R'''predictions.decoder.bias''']
			UpperCamelCase__								='''roberta'''
			UpperCamelCase__								=RobertaSeriesConfig

			def __init__( self			:   str       ,						lowerCamelCase_			:   Optional[Any]  )						->   Optional[Any]:
								super().__init__(lowerCamelCase_  )
								__magic_name__							:	Tuple    							=							XLMRobertaModel(lowerCamelCase_  )
								__magic_name__							:	Any    							=							nn.Linear(config.hidden_size       ,						config.project_dim  )
								__magic_name__							:	Optional[int]    							=							getattr(lowerCamelCase_       ,						'''has_pre_transformation'''       ,						lowerCamelCase_  )
								if self.has_pre_transformation:
													__magic_name__							:	List[Any]    							=							nn.Linear(config.hidden_size       ,						config.project_dim  )
													__magic_name__							:	Union[str, Any]    							=							nn.LayerNorm(config.hidden_size       ,						eps=config.layer_norm_eps  )
								self.post_init()


			def 							UpperCAmelCase__       ( self			:   Optional[Any]       ,						lowerCamelCase_			:   Optional[torch.Tensor] = None       ,						lowerCamelCase_			:   Optional[torch.Tensor] = None       ,						lowerCamelCase_			:   Optional[torch.Tensor] = None       ,						lowerCamelCase_			:   Optional[torch.Tensor] = None       ,						lowerCamelCase_			:   Optional[torch.Tensor] = None       ,						lowerCamelCase_			:   Optional[torch.Tensor] = None       ,						lowerCamelCase_			:   Optional[torch.Tensor] = None       ,						lowerCamelCase_			:   Optional[torch.Tensor] = None       ,						lowerCamelCase_			:   Optional[bool] = None       ,						lowerCamelCase_			:   Optional[bool] = None       ,						lowerCamelCase_			:   Optional[bool] = None       ,						)						->   List[Any]:
								__magic_name__							:	Optional[int]    							=							return_dict if return_dict is not None else self.config.use_return_dict

								__magic_name__							:	Any    							=							self.base_model(
								    input_ids=lowerCamelCase_       ,						attention_mask=lowerCamelCase_       ,						token_type_ids=lowerCamelCase_       ,						position_ids=lowerCamelCase_       ,						head_mask=lowerCamelCase_       ,						inputs_embeds=lowerCamelCase_       ,						encoder_hidden_states=lowerCamelCase_       ,						encoder_attention_mask=lowerCamelCase_       ,						output_attentions=lowerCamelCase_       ,						output_hidden_states=True if self.has_pre_transformation else output_hidden_states       ,						return_dict=lowerCamelCase_       ,						)

								if self.has_pre_transformation:
													__magic_name__							:	Any    							=							outputs['''hidden_states'''][-2]
													__magic_name__							:	Dict    							=							self.pre_LN(lowerCamelCase_  )
													__magic_name__							:	int    							=							self.transformation_pre(lowerCamelCase_  )

													return TransformationModelOutput(
													    projection_state=lowerCamelCase_       ,						last_hidden_state=outputs.last_hidden_state       ,						hidden_states=outputs.hidden_states       ,						attentions=outputs.attentions       ,						)
								else:
													__magic_name__							:	Union[str, Any]    							=							self.transformation(outputs.last_hidden_state  )
													return TransformationModelOutput(
													    projection_state=lowerCamelCase_       ,						last_hidden_state=outputs.last_hidden_state       ,						hidden_states=outputs.hidden_states       ,						attentions=outputs.attentions       ,						)



