
'''simple docstring'''





import unittest

from transformers import XLMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch

		from transformers import (
		    XLMForMultipleChoice,
		    XLMForQuestionAnswering,
		    XLMForQuestionAnsweringSimple,
		    XLMForSequenceClassification,
		    XLMForTokenClassification,
		    XLMModel,
		    XLMWithLMHeadModel,
		)
		from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST







class        lowerCAmelCase__      :

						def __init__(			self       ,							a       ,							a=13       ,							a=7       ,							a=True       ,							a=True       ,							a=True       ,							a=True       ,							a=True       ,							a=False       ,							a=False       ,							a=False       ,							a=2       ,							a=99       ,							a=0       ,							a=32       ,							a=5       ,							a=4       ,							a=0.1       ,							a=0.1       ,							a=5_12       ,							a=2       ,							a=0.02       ,							a=2       ,							a=4       ,							a="last"       ,							a=True       ,							a=None       ,							a=0       ,							)					->      Union[str, Any]:


								'''simple docstring'''

								_UpperCamelCase						    =	parent
								_UpperCamelCase						    =	batch_size
								_UpperCamelCase						    =	seq_length
								_UpperCamelCase						    =	is_training
								_UpperCamelCase						    =	use_input_lengths
								_UpperCamelCase						    =	use_token_type_ids
								_UpperCamelCase						    =	use_labels
								_UpperCamelCase						    =	gelu_activation
								_UpperCamelCase						    =	sinusoidal_embeddings
								_UpperCamelCase						    =	causal
								_UpperCamelCase						    =	asm
								_UpperCamelCase						    =	n_langs
								_UpperCamelCase						    =	vocab_size
								_UpperCamelCase						    =	n_special
								_UpperCamelCase						    =	hidden_size
								_UpperCamelCase						    =	num_hidden_layers
								_UpperCamelCase						    =	num_attention_heads
								_UpperCamelCase						    =	hidden_dropout_prob
								_UpperCamelCase						    =	attention_probs_dropout_prob
								_UpperCamelCase						    =	max_position_embeddings
								_UpperCamelCase						    =	type_sequence_label_size
								_UpperCamelCase						    =	initializer_range
								_UpperCamelCase						    =	num_labels
								_UpperCamelCase						    =	num_choices
								_UpperCamelCase						    =	summary_type
								_UpperCamelCase						    =	use_proj
								_UpperCamelCase						    =	scope
								_UpperCamelCase						    =	bos_token_id

						def  A_				(			self				)					->      Tuple:


								'''simple docstring'''

								_UpperCamelCase						    =	ids_tensor([self.batch_size, self.seq_length]       ,							self.vocab_size				)
								_UpperCamelCase						    =	random_attention_mask([self.batch_size, self.seq_length]				)

								_UpperCamelCase						    =	None
								if self.use_input_lengths:
										_UpperCamelCase						    =	(
										    ids_tensor([self.batch_size]       ,							vocab_size=2				) + self.seq_length - 2
										)  # small variation of seq_length

								_UpperCamelCase						    =	None
								if self.use_token_type_ids:
										_UpperCamelCase						    =	ids_tensor([self.batch_size, self.seq_length]       ,							self.n_langs				)

								_UpperCamelCase						    =	None
								_UpperCamelCase						    =	None
								_UpperCamelCase						    =	None
								if self.use_labels:
										_UpperCamelCase						    =	ids_tensor([self.batch_size]       ,							self.type_sequence_label_size				)
										_UpperCamelCase						    =	ids_tensor([self.batch_size, self.seq_length]       ,							self.num_labels				)
										_UpperCamelCase						    =	ids_tensor([self.batch_size]       ,							2				).float()
										_UpperCamelCase						    =	ids_tensor([self.batch_size]       ,							self.num_choices				)

								_UpperCamelCase						    =	self.get_config()

								return (
								    config,
								    input_ids,
								    token_type_ids,
								    input_lengths,
								    sequence_labels,
								    token_labels,
								    is_impossible_labels,
								    choice_labels,
								    input_mask,
								)

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


								'''simple docstring'''

								return XLMConfig(
								    vocab_size=self.vocab_size       ,							n_special=self.n_special       ,							emb_dim=self.hidden_size       ,							n_layers=self.num_hidden_layers       ,							n_heads=self.num_attention_heads       ,							dropout=self.hidden_dropout_prob       ,							attention_dropout=self.attention_probs_dropout_prob       ,							gelu_activation=self.gelu_activation       ,							sinusoidal_embeddings=self.sinusoidal_embeddings       ,							asm=self.asm       ,							causal=self.causal       ,							n_langs=self.n_langs       ,							max_position_embeddings=self.max_position_embeddings       ,							initializer_range=self.initializer_range       ,							summary_type=self.summary_type       ,							use_proj=self.use_proj       ,							num_labels=self.num_labels       ,							bos_token_id=self.bos_token_id       ,							)

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


								'''simple docstring'''

								_UpperCamelCase						    =	XLMModel(config=snake_case_				)
								model.to(snake_case_				)
								model.eval()
								_UpperCamelCase						    =	model(snake_case_       ,							lengths=snake_case_       ,							langs=snake_case_				)
								_UpperCamelCase						    =	model(snake_case_       ,							langs=snake_case_				)
								_UpperCamelCase						    =	model(snake_case_				)
								self.parent.assertEqual(result.last_hidden_state.shape       ,							(self.batch_size, self.seq_length, self.hidden_size)				)

						def  A_				(			self       ,							a       ,							a       ,							a       ,							a       ,							a       ,							a       ,							a       ,							a       ,							a       ,							)					->      List[str]:


								'''simple docstring'''

								_UpperCamelCase						    =	XLMWithLMHeadModel(snake_case_				)
								model.to(snake_case_				)
								model.eval()

								_UpperCamelCase						    =	model(snake_case_       ,							token_type_ids=snake_case_       ,							labels=snake_case_				)
								self.parent.assertEqual(result.loss.shape       ,							()				)
								self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.seq_length, self.vocab_size)				)

						def  A_				(			self       ,							a       ,							a       ,							a       ,							a       ,							a       ,							a       ,							a       ,							a       ,							a       ,							)					->      Optional[Any]:


								'''simple docstring'''

								_UpperCamelCase						    =	XLMForQuestionAnsweringSimple(snake_case_				)
								model.to(snake_case_				)
								model.eval()

								_UpperCamelCase						    =	model(snake_case_				)

								_UpperCamelCase						    =	model(snake_case_       ,							start_positions=snake_case_       ,							end_positions=snake_case_				)
								_UpperCamelCase						    =	outputs
								self.parent.assertEqual(result.start_logits.shape       ,							(self.batch_size, self.seq_length)				)
								self.parent.assertEqual(result.end_logits.shape       ,							(self.batch_size, self.seq_length)				)

						def  A_				(			self       ,							a       ,							a       ,							a       ,							a       ,							a       ,							a       ,							a       ,							a       ,							a       ,							)					->      Optional[int]:


								'''simple docstring'''

								_UpperCamelCase						    =	XLMForQuestionAnswering(snake_case_				)
								model.to(snake_case_				)
								model.eval()

								_UpperCamelCase						    =	model(snake_case_				)

								_UpperCamelCase						    =	model(
								    snake_case_       ,							start_positions=snake_case_       ,							end_positions=snake_case_       ,							cls_index=snake_case_       ,							is_impossible=snake_case_       ,							p_mask=snake_case_       ,							)

								_UpperCamelCase						    =	model(
								    snake_case_       ,							start_positions=snake_case_       ,							end_positions=snake_case_       ,							cls_index=snake_case_       ,							is_impossible=snake_case_       ,							)

								(_UpperCamelCase					)						    =	result_with_labels.to_tuple()

								_UpperCamelCase						    =	model(snake_case_       ,							start_positions=snake_case_       ,							end_positions=snake_case_				)

								(_UpperCamelCase					)						    =	result_with_labels.to_tuple()

								self.parent.assertEqual(result_with_labels.loss.shape       ,							()				)
								self.parent.assertEqual(result.start_top_log_probs.shape       ,							(self.batch_size, model.config.start_n_top)				)
								self.parent.assertEqual(result.start_top_index.shape       ,							(self.batch_size, model.config.start_n_top)				)
								self.parent.assertEqual(
								    result.end_top_log_probs.shape       ,							(self.batch_size, model.config.start_n_top * model.config.end_n_top)				)
								self.parent.assertEqual(
								    result.end_top_index.shape       ,							(self.batch_size, model.config.start_n_top * model.config.end_n_top)				)
								self.parent.assertEqual(result.cls_logits.shape       ,							(self.batch_size,)				)

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


								'''simple docstring'''

								_UpperCamelCase						    =	XLMForSequenceClassification(snake_case_				)
								model.to(snake_case_				)
								model.eval()

								_UpperCamelCase						    =	model(snake_case_				)
								_UpperCamelCase						    =	model(snake_case_       ,							labels=snake_case_				)
								self.parent.assertEqual(result.loss.shape       ,							()				)
								self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.type_sequence_label_size)				)

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


								'''simple docstring'''

								_UpperCamelCase						    =	self.num_labels
								_UpperCamelCase						    =	XLMForTokenClassification(snake_case_				)
								model.to(snake_case_				)
								model.eval()

								_UpperCamelCase						    =	model(snake_case_       ,							attention_mask=snake_case_       ,							labels=snake_case_				)
								self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.seq_length, self.num_labels)				)

						def  A_				(			self       ,							a       ,							a       ,							a       ,							a       ,							a       ,							a       ,							a       ,							a       ,							a       ,							)					->      str:


								'''simple docstring'''

								_UpperCamelCase						    =	self.num_choices
								_UpperCamelCase						    =	XLMForMultipleChoice(config=snake_case_				)
								model.to(snake_case_				)
								model.eval()
								_UpperCamelCase						    =	input_ids.unsqueeze(1				).expand(-1       ,							self.num_choices       ,							-1				).contiguous()
								_UpperCamelCase						    =	token_type_ids.unsqueeze(1				).expand(-1       ,							self.num_choices       ,							-1				).contiguous()
								_UpperCamelCase						    =	input_mask.unsqueeze(1				).expand(-1       ,							self.num_choices       ,							-1				).contiguous()
								_UpperCamelCase						    =	model(
								    snake_case_       ,							attention_mask=snake_case_       ,							token_type_ids=snake_case_       ,							labels=snake_case_       ,							)
								self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.num_choices)				)







						def  A_				(			self				)					->      int:


								'''simple docstring'''

								_UpperCamelCase						    =	self.prepare_config_and_inputs()
								(
								    _UpperCamelCase					
								)						    =	config_and_inputs
								_UpperCamelCase						    =	{"input_ids": input_ids, "token_type_ids": token_type_ids, "lengths": input_lengths}
								return config, inputs_dict







@require_torch
class        lowerCAmelCase__      (   _snake_case		,	_snake_case		,	_snake_case		,	unittest.TestCase	):
						UpperCamelCase_							: Dict	=		(
						    (
						        XLMModel,
						        XLMWithLMHeadModel,
						        XLMForQuestionAnswering,
						        XLMForSequenceClassification,
						        XLMForQuestionAnsweringSimple,
						        XLMForTokenClassification,
						        XLMForMultipleChoice,
						    )
						    if is_torch_available()
						    else ()
						)
						UpperCamelCase_							: Union[str, Any]	=		(
						    (XLMWithLMHeadModel,) if is_torch_available() else ()
						)  # TODO (PVP): Check other models whether language generation is also applicable
						UpperCamelCase_							: Optional[int]	=		(
						    {
						        """feature-extraction""": XLMModel,
						        """fill-mask""": XLMWithLMHeadModel,
						        """question-answering""": XLMForQuestionAnsweringSimple,
						        """text-classification""": XLMForSequenceClassification,
						        """text-generation""": XLMWithLMHeadModel,
						        """token-classification""": XLMForTokenClassification,
						        """zero-shot""": XLMForSequenceClassification,
						    }
						    if is_torch_available()
						    else {}
						)

						def  A_				(			self       ,							a       ,							a       ,							a       ,							a       ,							a				)					->      int:


								'''simple docstring'''

								if (
								    pipeline_test_casse_name == "QAPipelineTests"
								    and tokenizer_name is not None
								    and not tokenizer_name.endswith("""Fast"""				)
								):
										# `QAPipelineTests` fails for a few models when the slower tokenizer are used.
										# (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
										# TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
										return True

								return False

						def  A_				(			self       ,							a       ,							a       ,							a=False				)					->      Dict:


								'''simple docstring'''

								_UpperCamelCase						    =	super()._prepare_for_class(snake_case_       ,							snake_case_       ,							return_labels=snake_case_				)

								if return_labels:
										if model_class.__name__ == "XLMForQuestionAnswering":
												_UpperCamelCase						    =	torch.zeros(
												    self.model_tester.batch_size       ,							dtype=torch.long       ,							device=snake_case_				)
												_UpperCamelCase						    =	torch.zeros(
												    self.model_tester.batch_size       ,							dtype=torch.long       ,							device=snake_case_				)

								return inputs_dict

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


								'''simple docstring'''

								_UpperCamelCase						    =	XLMModelTester(self				)
								_UpperCamelCase						    =	ConfigTester(self       ,							config_class=snake_case_       ,							emb_dim=37				)

						def  A_				(			self				)					->      Dict:


								'''simple docstring'''

								self.config_tester.run_common_tests()

						def  A_				(			self				)					->      Any:


								'''simple docstring'''

								_UpperCamelCase						    =	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_xlm_model(*snake_case_				)

						def  A_				(			self				)					->      Dict:


								'''simple docstring'''

								_UpperCamelCase						    =	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_xlm_lm_head(*snake_case_				)

						def  A_				(			self				)					->      int:


								'''simple docstring'''

								_UpperCamelCase						    =	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_xlm_simple_qa(*snake_case_				)

						def  A_				(			self				)					->      str:


								'''simple docstring'''

								_UpperCamelCase						    =	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_xlm_qa(*snake_case_				)

						def  A_				(			self				)					->      List[str]:


								'''simple docstring'''

								_UpperCamelCase						    =	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_xlm_sequence_classif(*snake_case_				)

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


								'''simple docstring'''

								_UpperCamelCase						    =	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_xlm_token_classif(*snake_case_				)

						def  A_				(			self				)					->      str:


								'''simple docstring'''

								_UpperCamelCase						    =	self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_xlm_for_multiple_choice(*snake_case_				)

						def  A_				(			self       ,							a       ,							a       ,							a       ,							a       ,							a       ,							a=False       ,							a=1				)					->      Optional[Any]:


								'''simple docstring'''

								self.assertIsInstance(snake_case_       ,							snake_case_				)
								self.assertListEqual(
								    [isinstance(snake_case_       ,							snake_case_				) for iter_attentions in attentions]       ,							[True] * len(snake_case_				)				)
								self.assertEqual(len(snake_case_				)       ,							(max_length - min_length) * num_beam_groups				)

								for idx, iter_attentions in enumerate(snake_case_				):
										# adds PAD dummy token
										_UpperCamelCase						    =	min_length + idx + 1
										_UpperCamelCase						    =	min_length + idx + 1

										_UpperCamelCase						    =	(
										    batch_size * num_beam_groups,
										    config.num_attention_heads,
										    tgt_len,
										    src_len,
										)
										# check attn size
										self.assertListEqual(
										    [layer_attention.shape for layer_attention in iter_attentions]       ,							[expected_shape] * len(snake_case_				)				)

						def  A_				(			self       ,							a       ,							a       ,							a       ,							a       ,							a       ,							a=False       ,							a=1				)					->      str:


								'''simple docstring'''

								self.assertIsInstance(snake_case_       ,							snake_case_				)
								self.assertListEqual(
								    [isinstance(snake_case_       ,							snake_case_				) for iter_hidden_states in hidden_states]       ,							[True] * len(snake_case_				)       ,							)
								self.assertEqual(len(snake_case_				)       ,							(max_length - min_length) * num_beam_groups				)

								for idx, iter_hidden_states in enumerate(snake_case_				):
										# adds PAD dummy token
										_UpperCamelCase						    =	min_length + idx + 1
										_UpperCamelCase						    =	(batch_size * num_beam_groups, seq_len, config.hidden_size)
										# check hidden size
										self.assertListEqual(
										    [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states]       ,							[expected_shape] * len(snake_case_				)       ,							)
								pass







						@slow
						def  A_				(			self				)					->      List[Any]:


								'''simple docstring'''

								for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										_UpperCamelCase						    =	XLMModel.from_pretrained(snake_case_				)
										self.assertIsNotNone(snake_case_				)







@require_torch
class        lowerCAmelCase__      (   unittest.TestCase	):

						@slow
						def  A_				(			self				)					->      Union[str, Any]:


								'''simple docstring'''

								_UpperCamelCase						    =	XLMWithLMHeadModel.from_pretrained("""xlm-mlm-en-2048"""				)
								model.to(snake_case_				)
								_UpperCamelCase						    =	torch.tensor([[14, 4_47]]       ,							dtype=torch.long       ,							device=snake_case_				)  # the president
								_UpperCamelCase						    =	[
								    14,
								    4_47,
								    14,
								    4_47,
								    14,
								    4_47,
								    14,
								    4_47,
								    14,
								    4_47,
								    14,
								    4_47,
								    14,
								    4_47,
								    14,
								    4_47,
								    14,
								    4_47,
								    14,
								    4_47,
								]  # the president the president the president the president the president the president the president the president the president the president
								# TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference
								_UpperCamelCase						    =	model.generate(snake_case_       ,							do_sample=snake_case_				)
								self.assertListEqual(output_ids[0].cpu().numpy().tolist()       ,							snake_case_				)





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	):
						UpperCamelCase_							: List[Any]	=		StableDiffusionInpaintPipeline
						UpperCamelCase_							: int	=		TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
						UpperCamelCase_							: Union[str, Any]	=		TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
						UpperCamelCase_							: Tuple	=		frozenset(
						    []	)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
						UpperCamelCase_							: int	=		frozenset([]	)

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


								'''simple docstring'''

								torch.manual_seed(0				)
								_UpperCamelCase						    =	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       ,							)
								_UpperCamelCase						    =	PNDMScheduler(skip_prk_steps=a				)
								torch.manual_seed(0				)
								_UpperCamelCase						    =	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=1_28       ,							)
								torch.manual_seed(0				)
								_UpperCamelCase						    =	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=10_00       ,							hidden_act="""gelu"""       ,							projection_dim=5_12       ,							)
								_UpperCamelCase						    =	CLIPTextModel(a				)
								_UpperCamelCase						    =	CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""				)

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

						def  A_				(			self       ,							a       ,							a=0				)					->      List[Any]:


								'''simple docstring'''

								_UpperCamelCase						    =	floats_tensor((1, 3, 32, 32)       ,							rng=random.Random(a				)				).to(a				)
								_UpperCamelCase						    =	image.cpu().permute(0       ,							2       ,							3       ,							1				)[0]
								_UpperCamelCase						    =	Image.fromarray(np.uinta(a				)				).convert("""RGB"""				).resize((64, 64)				)
								_UpperCamelCase						    =	Image.fromarray(np.uinta(image + 4				)				).convert("""RGB"""				).resize((64, 64)				)
								if str(a				).startswith("""mps"""				):
										_UpperCamelCase						    =	torch.manual_seed(a				)
								else:
										_UpperCamelCase						    =	torch.Generator(device=a				).manual_seed(a				)
								_UpperCamelCase						    =	{
								    """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  A_				(			self				)					->      Dict:


								'''simple docstring'''

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

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

								assert image.shape == (1, 64, 64, 3)
								_UpperCamelCase						    =	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  A_				(			self				)					->      Tuple:


								'''simple docstring'''

								super().test_inference_batch_single_identical(expected_max_diff=3e-3				)







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

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


								'''simple docstring'''

								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()

						def  A_				(			self				)					->      Dict:


								'''simple docstring'''

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

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

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

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

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

						def  A_				(			self				)					->      str:


								'''simple docstring'''

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

								_UpperCamelCase						    =	"""stabilityai/stable-diffusion-2-inpainting"""
								_UpperCamelCase						    =	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()

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

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

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







						def  A_				(			self				)					->      Dict:


								'''simple docstring'''

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

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

								_UpperCamelCase						    =	"""stabilityai/stable-diffusion-2-inpainting"""
								_UpperCamelCase						    =	PNDMScheduler.from_pretrained(a       ,							subfolder="""scheduler"""				)
								_UpperCamelCase						    =	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()

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

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

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



