
"""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					(       _lowercase  ,					_lowercase  ,					_lowercase  ,					unittest.TestCase   ):




			"""simple docstring"""







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




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







								"""simple docstring"""
								torch.manual_seed(0						)
								A_								=    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=_snake_case							, )
								A_								=    PNDMScheduler(skip_prk_steps=_snake_case						)
								torch.manual_seed(0						)
								A_								=    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						)
								A_								=    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=1_000							, hidden_act="gelu"							, projection_dim=512							, )
								A_								=    CLIPTextModel(_snake_case						)
								A_								=    CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"						)

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




			def   lowerCamelCase__  (					self    :       Optional[Any]							, _snake_case    :       str							, _snake_case    :       Optional[Any]=0						)   ->			Union[str, Any]:







								"""simple docstring"""
								# TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched
								A_								=    floats_tensor((1, 3, 32, 32)							, rng=random.Random(_snake_case						)						).to(_snake_case						)
								A_								=    image.cpu().permute(0							, 2							, 3							, 1						)[0]
								A_								=    Image.fromarray(np.uinta(_snake_case						)						).convert("RGB"						).resize((64, 64)						)
								A_								=    Image.fromarray(np.uinta(image + 4						)						).convert("RGB"						).resize((64, 64)						)
								if str(_snake_case						).startswith("mps"						):
													A_								=    torch.manual_seed(_snake_case						)
								else:
													A_								=    torch.Generator(device=_snake_case						).manual_seed(_snake_case						)
								A_								=    {
								    "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   lowerCamelCase__  (					self    :       Dict						)   ->			Optional[int]:







								"""simple docstring"""
								A_								=    "cpu"  # ensure determinism for the device-dependent torch.Generator
								A_								=    self.get_dummy_components()
								A_								=    StableDiffusionInpaintPipeline(**_snake_case						)
								A_								=    sd_pipe.to(_snake_case						)
								sd_pipe.set_progress_bar_config(disable=_snake_case						)

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

								assert image.shape == (1, 64, 64, 3)
								A_								=    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   lowerCamelCase__  (					self    :       Tuple						)   ->			Optional[int]:







								"""simple docstring"""
								super().test_inference_batch_single_identical(expected_max_diff=3e-3						)





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




			"""simple docstring"""







			def   lowerCamelCase__  (					self    :       Tuple						)   ->			str:







								"""simple docstring"""
								# clean up the VRAM after each test
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()




			def   lowerCamelCase__  (					self    :       Tuple						)   ->			List[str]:







								"""simple docstring"""
								A_								=    load_image(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
								    "/sd2-inpaint/init_image.png"						)
								A_								=    load_image(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png"						)
								A_								=    load_numpy(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint"
								    "/yellow_cat_sitting_on_a_park_bench.npy"						)

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

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

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

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




			def   lowerCamelCase__  (					self    :       Optional[int]						)   ->			int:







								"""simple docstring"""
								A_								=    load_image(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
								    "/sd2-inpaint/init_image.png"						)
								A_								=    load_image(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png"						)
								A_								=    load_numpy(
								    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint"
								    "/yellow_cat_sitting_on_a_park_bench_fp16.npy"						)

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

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

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

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






			def   lowerCamelCase__  (					self    :       Optional[int]						)   ->			Optional[int]:







								"""simple docstring"""
								torch.cuda.empty_cache()
								torch.cuda.reset_max_memory_allocated()
								torch.cuda.reset_peak_memory_stats()

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

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

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

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

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






"""simple docstring"""





import shutil
import tempfile
import unittest
from unittest.mock import patch

from transformers import (
    DefaultFlowCallback,
    IntervalStrategy,
    PrinterCallback,
    ProgressCallback,
    Trainer,
    TrainerCallback,
    TrainingArguments,
    is_torch_available,
)
from transformers.testing_utils import require_torch


if is_torch_available():
		from transformers.trainer import DEFAULT_CALLBACKS

		from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel



class __lowerCAmelCase					(       _lowercase   ):




			"""simple docstring"""







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







								"""simple docstring"""
								A_								=    []




			def   lowerCamelCase__  (					self    :       Tuple							, _snake_case    :       List[str]							, _snake_case    :       Optional[int]							, _snake_case    :       Optional[int]							, **_snake_case    :       str						)   ->			int:







								"""simple docstring"""
								self.events.append("on_init_end"						)




			def   lowerCamelCase__  (					self    :       Dict							, _snake_case    :       Union[str, Any]							, _snake_case    :       List[Any]							, _snake_case    :       Tuple							, **_snake_case    :       Tuple						)   ->			List[str]:







								"""simple docstring"""
								self.events.append("on_train_begin"						)




			def   lowerCamelCase__  (					self    :       List[Any]							, _snake_case    :       Any							, _snake_case    :       Optional[Any]							, _snake_case    :       Tuple							, **_snake_case    :       Optional[int]						)   ->			str:







								"""simple docstring"""
								self.events.append("on_train_end"						)




			def   lowerCamelCase__  (					self    :       Dict							, _snake_case    :       str							, _snake_case    :       List[Any]							, _snake_case    :       str							, **_snake_case    :       Optional[int]						)   ->			Dict:







								"""simple docstring"""
								self.events.append("on_epoch_begin"						)




			def   lowerCamelCase__  (					self    :       Optional[int]							, _snake_case    :       Optional[int]							, _snake_case    :       Any							, _snake_case    :       Optional[Any]							, **_snake_case    :       Optional[Any]						)   ->			str:







								"""simple docstring"""
								self.events.append("on_epoch_end"						)




			def   lowerCamelCase__  (					self    :       List[Any]							, _snake_case    :       List[str]							, _snake_case    :       str							, _snake_case    :       Optional[Any]							, **_snake_case    :       Optional[int]						)   ->			List[str]:







								"""simple docstring"""
								self.events.append("on_step_begin"						)




			def   lowerCamelCase__  (					self    :       Optional[Any]							, _snake_case    :       Union[str, Any]							, _snake_case    :       Optional[Any]							, _snake_case    :       Any							, **_snake_case    :       Union[str, Any]						)   ->			List[str]:







								"""simple docstring"""
								self.events.append("on_step_end"						)




			def   lowerCamelCase__  (					self    :       Tuple							, _snake_case    :       Dict							, _snake_case    :       Dict							, _snake_case    :       Union[str, Any]							, **_snake_case    :       List[str]						)   ->			Optional[int]:







								"""simple docstring"""
								self.events.append("on_evaluate"						)




			def   lowerCamelCase__  (					self    :       Optional[int]							, _snake_case    :       Optional[Any]							, _snake_case    :       int							, _snake_case    :       int							, **_snake_case    :       List[Any]						)   ->			List[str]:







								"""simple docstring"""
								self.events.append("on_predict"						)




			def   lowerCamelCase__  (					self    :       List[str]							, _snake_case    :       Union[str, Any]							, _snake_case    :       List[str]							, _snake_case    :       Optional[Any]							, **_snake_case    :       List[Any]						)   ->			Union[str, Any]:







								"""simple docstring"""
								self.events.append("on_save"						)




			def   lowerCamelCase__  (					self    :       Dict							, _snake_case    :       Dict							, _snake_case    :       List[Any]							, _snake_case    :       Optional[int]							, **_snake_case    :       Dict						)   ->			str:







								"""simple docstring"""
								self.events.append("on_log"						)






			def   lowerCamelCase__  (					self    :       Tuple							, _snake_case    :       Optional[Any]							, _snake_case    :       str							, _snake_case    :       int							, **_snake_case    :       List[Any]						)   ->			int:







								"""simple docstring"""
								self.events.append("on_prediction_step"						)





@require_torch
class __lowerCAmelCase					(       unittest.TestCase   ):




			"""simple docstring"""







			def   lowerCamelCase__  (					self    :       Union[str, Any]						)   ->			Dict:







								"""simple docstring"""
								A_								=    tempfile.mkdtemp()




			def   lowerCamelCase__  (					self    :       str						)   ->			Tuple:







								"""simple docstring"""
								shutil.rmtree(self.output_dir						)




			def   lowerCamelCase__  (					self    :       List[str]							, _snake_case    :       Any=0							, _snake_case    :       Optional[int]=0							, _snake_case    :       int=64							, _snake_case    :       Optional[int]=64							, _snake_case    :       List[Any]=None							, _snake_case    :       List[Any]=False							, **_snake_case    :       Optional[int]						)   ->			List[Any]:







								"""simple docstring"""
								# disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure
								# its set to False since the tests later on depend on its value.
								A_								=    RegressionDataset(length=_snake_case						)
								A_								=    RegressionDataset(length=_snake_case						)
								A_								=    RegressionModelConfig(a=_snake_case							, b=_snake_case						)
								A_								=    RegressionPreTrainedModel(_snake_case						)

								A_								=    TrainingArguments(self.output_dir							, disable_tqdm=_snake_case							, report_to=[]							, **_snake_case						)
								return Trainer(
								    _snake_case							, _snake_case							, train_dataset=_snake_case							, eval_dataset=_snake_case							, callbacks=_snake_case							, )




			def   lowerCamelCase__  (					self    :       List[Any]							, _snake_case    :       Optional[Any]							, _snake_case    :       List[Any]						)   ->			Union[str, Any]:







								"""simple docstring"""
								self.assertEqual(len(_snake_case						)							, len(_snake_case						)						)

								# Order doesn't matter
								A_								=    sorted(_snake_case							, key=lambda _snake_case						: cb.__name__ if isinstance(_snake_case							, _snake_case						) else cb.__class__.__name__						)
								A_								=    sorted(_snake_case							, key=lambda _snake_case						: cb.__name__ if isinstance(_snake_case							, _snake_case						) else cb.__class__.__name__						)

								for cba, cba in zip(_snake_case							, _snake_case						):
													if isinstance(_snake_case							, _snake_case						) and isinstance(_snake_case							, _snake_case						):
																		self.assertEqual(_snake_case							, _snake_case						)
													elif isinstance(_snake_case							, _snake_case						) and not isinstance(_snake_case							, _snake_case						):
																		self.assertEqual(_snake_case							, cba.__class__						)
													elif not isinstance(_snake_case							, _snake_case						) and isinstance(_snake_case							, _snake_case						):
																		self.assertEqual(cba.__class__							, _snake_case						)
													else:
																		self.assertEqual(_snake_case							, _snake_case						)




			def   lowerCamelCase__  (					self    :       List[Any]							, _snake_case    :       Union[str, Any]						)   ->			Optional[Any]:







								"""simple docstring"""
								A_								=    ["on_init_end", "on_train_begin"]
								A_								=    0
								A_								=    len(trainer.get_eval_dataloader()						)
								A_								=    ["on_prediction_step"] * len(trainer.get_eval_dataloader()						) + ["on_log", "on_evaluate"]
								for _ in range(trainer.state.num_train_epochs						):
													expected_events.append("on_epoch_begin"						)
													for _ in range(_snake_case						):
																		step += 1
																		expected_events += ["on_step_begin", "on_step_end"]
																		if step % trainer.args.logging_steps == 0:
																							expected_events.append("on_log"						)
																		if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0:
																							expected_events += evaluation_events.copy()
																		if step % trainer.args.save_steps == 0:
																							expected_events.append("on_save"						)
													expected_events.append("on_epoch_end"						)
													if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH:
																		expected_events += evaluation_events.copy()
								expected_events += ["on_log", "on_train_end"]
								return expected_events




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







								"""simple docstring"""
								A_								=    self.get_trainer()
								A_								=    DEFAULT_CALLBACKS.copy() + [ProgressCallback]
								self.check_callbacks_equality(trainer.callback_handler.callbacks							, _snake_case						)

								# Callbacks passed at init are added to the default callbacks
								A_								=    self.get_trainer(callbacks=[MyTestTrainerCallback]						)
								expected_callbacks.append(_snake_case						)
								self.check_callbacks_equality(trainer.callback_handler.callbacks							, _snake_case						)

								# TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback
								A_								=    self.get_trainer(disable_tqdm=_snake_case						)
								A_								=    DEFAULT_CALLBACKS.copy() + [PrinterCallback]
								self.check_callbacks_equality(trainer.callback_handler.callbacks							, _snake_case						)




			def   lowerCamelCase__  (					self    :       Optional[Any]						)   ->			List[Any]:







								"""simple docstring"""
								A_								=    DEFAULT_CALLBACKS.copy() + [ProgressCallback]
								A_								=    self.get_trainer()

								# We can add, pop, or remove by class name
								trainer.remove_callback(_snake_case						)
								expected_callbacks.remove(_snake_case						)
								self.check_callbacks_equality(trainer.callback_handler.callbacks							, _snake_case						)

								A_								=    self.get_trainer()
								A_								=    trainer.pop_callback(_snake_case						)
								self.assertEqual(cb.__class__							, _snake_case						)
								self.check_callbacks_equality(trainer.callback_handler.callbacks							, _snake_case						)

								trainer.add_callback(_snake_case						)
								expected_callbacks.insert(0							, _snake_case						)
								self.check_callbacks_equality(trainer.callback_handler.callbacks							, _snake_case						)

								# We can also add, pop, or remove by instance
								A_								=    self.get_trainer()
								A_								=    trainer.callback_handler.callbacks[0]
								trainer.remove_callback(_snake_case						)
								expected_callbacks.remove(_snake_case						)
								self.check_callbacks_equality(trainer.callback_handler.callbacks							, _snake_case						)

								A_								=    self.get_trainer()
								A_								=    trainer.callback_handler.callbacks[0]
								A_								=    trainer.pop_callback(_snake_case						)
								self.assertEqual(_snake_case							, _snake_case						)
								self.check_callbacks_equality(trainer.callback_handler.callbacks							, _snake_case						)

								trainer.add_callback(_snake_case						)
								expected_callbacks.insert(0							, _snake_case						)
								self.check_callbacks_equality(trainer.callback_handler.callbacks							, _snake_case						)






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







								"""simple docstring"""
								import warnings

								# XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested
								warnings.simplefilter(action="ignore"							, category=_snake_case						)

								A_								=    self.get_trainer(callbacks=[MyTestTrainerCallback]						)
								trainer.train()
								A_								=    trainer.callback_handler.callbacks[-2].events
								self.assertEqual(_snake_case							, self.get_expected_events(_snake_case						)						)

								# Independent log/save/eval
								A_								=    self.get_trainer(callbacks=[MyTestTrainerCallback]							, logging_steps=5						)
								trainer.train()
								A_								=    trainer.callback_handler.callbacks[-2].events
								self.assertEqual(_snake_case							, self.get_expected_events(_snake_case						)						)

								A_								=    self.get_trainer(callbacks=[MyTestTrainerCallback]							, save_steps=5						)
								trainer.train()
								A_								=    trainer.callback_handler.callbacks[-2].events
								self.assertEqual(_snake_case							, self.get_expected_events(_snake_case						)						)

								A_								=    self.get_trainer(callbacks=[MyTestTrainerCallback]							, eval_steps=5							, evaluation_strategy="steps"						)
								trainer.train()
								A_								=    trainer.callback_handler.callbacks[-2].events
								self.assertEqual(_snake_case							, self.get_expected_events(_snake_case						)						)

								A_								=    self.get_trainer(callbacks=[MyTestTrainerCallback]							, evaluation_strategy="epoch"						)
								trainer.train()
								A_								=    trainer.callback_handler.callbacks[-2].events
								self.assertEqual(_snake_case							, self.get_expected_events(_snake_case						)						)

								# A bit of everything
								A_								=    self.get_trainer(
								    callbacks=[MyTestTrainerCallback]							, logging_steps=3							, save_steps=10							, eval_steps=5							, evaluation_strategy="steps"							, )
								trainer.train()
								A_								=    trainer.callback_handler.callbacks[-2].events
								self.assertEqual(_snake_case							, self.get_expected_events(_snake_case						)						)

								# warning should be emitted for duplicated callbacks
								with patch("transformers.trainer_callback.logger.warning"						) as warn_mock:
													A_								=    self.get_trainer(
													    callbacks=[MyTestTrainerCallback, MyTestTrainerCallback]							, )
													assert str(_snake_case						) in warn_mock.call_args[0][0]




