



"""simple docstring"""







import unittest

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

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
							import torch

							from transformers import (
							    LayoutLMForMaskedLM,
							    LayoutLMForQuestionAnswering,
							    LayoutLMForSequenceClassification,
							    LayoutLMForTokenClassification,
							    LayoutLMModel,
							)






class   UpperCAmelCase__		:



		def __init__(			self	:     List[str]   ,				snake_case	:     Any   ,				snake_case	:     Tuple=13   ,				snake_case	:     Dict=7   ,				snake_case	:     int=True   ,				snake_case	:     Union[str, Any]=True   ,				snake_case	:     List[Any]=True   ,				snake_case	:     int=True   ,				snake_case	:     Union[str, Any]=99   ,				snake_case	:     int=32   ,				snake_case	:     str=5   ,				snake_case	:     Optional[Any]=4   ,				snake_case	:     List[str]=37   ,				snake_case	:     Any="gelu"   ,				snake_case	:     Union[str, Any]=0.1   ,				snake_case	:     Tuple=0.1   ,				snake_case	:     Any=512   ,				snake_case	:     Dict=16   ,				snake_case	:     str=2   ,				snake_case	:     int=0.02   ,				snake_case	:     List[Any]=3   ,				snake_case	:     Union[str, Any]=4   ,				snake_case	:     int=None   ,				snake_case	:     Tuple=1_000   ,				)      ->    Union[str, Any]:






									'''simple docstring'''

									A    =       parent
									A    =       batch_size
									A    =       seq_length
									A    =       is_training
									A    =       use_input_mask
									A    =       use_token_type_ids
									A    =       use_labels
									A    =       vocab_size
									A    =       hidden_size
									A    =       num_hidden_layers
									A    =       num_attention_heads
									A    =       intermediate_size
									A    =       hidden_act
									A    =       hidden_dropout_prob
									A    =       attention_probs_dropout_prob
									A    =       max_position_embeddings
									A    =       type_vocab_size
									A    =       type_sequence_label_size
									A    =       initializer_range
									A    =       num_labels
									A    =       num_choices
									A    =       scope
									A    =       range_bbox



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






									'''simple docstring'''

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

									A    =       ids_tensor([self.batch_size, self.seq_length, 4]   ,				self.range_bbox					)
									# Ensure that bbox is legal
									for i in range(bbox.shape[0]					):
																for j in range(bbox.shape[1]					):
																							if bbox[i, j, 3] < bbox[i, j, 1]:
																														A    =       bbox[i, j, 3]
																														A    =       bbox[i, j, 1]
																														A    =       t
																							if bbox[i, j, 2] < bbox[i, j, 0]:
																														A    =       bbox[i, j, 2]
																														A    =       bbox[i, j, 0]
																														A    =       t

									A    =       None
									if self.use_input_mask:
																A    =       ids_tensor([self.batch_size, self.seq_length]   ,				vocab_size=2					)

									A    =       None
									if self.use_token_type_ids:
																A    =       ids_tensor([self.batch_size, self.seq_length]   ,				self.type_vocab_size					)

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

									A    =       self.get_config()

									return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels



		def        A_		(			self	:     Tuple					)      ->    int:






									'''simple docstring'''

									return LayoutLMConfig(
									    vocab_size=self.vocab_size   ,				hidden_size=self.hidden_size   ,				num_hidden_layers=self.num_hidden_layers   ,				num_attention_heads=self.num_attention_heads   ,				intermediate_size=self.intermediate_size   ,				hidden_act=self.hidden_act   ,				hidden_dropout_prob=self.hidden_dropout_prob   ,				attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,				max_position_embeddings=self.max_position_embeddings   ,				type_vocab_size=self.type_vocab_size   ,				initializer_range=self.initializer_range   ,				)



		def        A_		(			self	:     List[str]   ,				snake_case	:     Optional[Any]   ,				snake_case	:     List[Any]   ,				snake_case	:     Tuple   ,				snake_case	:     str   ,				snake_case	:     Any   ,				snake_case	:     int   ,				snake_case	:     Dict   ,				snake_case	:     List[str]					)      ->    Any:






									'''simple docstring'''

									A    =       LayoutLMModel(config=_lowerCamelCase					)
									model.to(_lowerCamelCase					)
									model.eval()
									A    =       model(_lowerCamelCase   ,				_lowerCamelCase   ,				attention_mask=_lowerCamelCase   ,				token_type_ids=_lowerCamelCase					)
									A    =       model(_lowerCamelCase   ,				_lowerCamelCase   ,				token_type_ids=_lowerCamelCase					)
									A    =       model(_lowerCamelCase   ,				_lowerCamelCase					)
									self.parent.assertEqual(result.last_hidden_state.shape   ,				(self.batch_size, self.seq_length, self.hidden_size)					)
									self.parent.assertEqual(result.pooler_output.shape   ,				(self.batch_size, self.hidden_size)					)



		def        A_		(			self	:     List[Any]   ,				snake_case	:     List[Any]   ,				snake_case	:     Tuple   ,				snake_case	:     Dict   ,				snake_case	:     str   ,				snake_case	:     int   ,				snake_case	:     List[str]   ,				snake_case	:     Any   ,				snake_case	:     Any					)      ->    Dict:






									'''simple docstring'''

									A    =       LayoutLMForMaskedLM(config=_lowerCamelCase					)
									model.to(_lowerCamelCase					)
									model.eval()
									A    =       model(_lowerCamelCase   ,				_lowerCamelCase   ,				attention_mask=_lowerCamelCase   ,				token_type_ids=_lowerCamelCase   ,				labels=_lowerCamelCase					)
									self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.seq_length, self.vocab_size)					)



		def        A_		(			self	:     Tuple   ,				snake_case	:     str   ,				snake_case	:     Any   ,				snake_case	:     int   ,				snake_case	:     Union[str, Any]   ,				snake_case	:     List[str]   ,				snake_case	:     str   ,				snake_case	:     int   ,				snake_case	:     Any					)      ->    Optional[Any]:






									'''simple docstring'''

									A    =       self.num_labels
									A    =       LayoutLMForSequenceClassification(_lowerCamelCase					)
									model.to(_lowerCamelCase					)
									model.eval()
									A    =       model(
									    _lowerCamelCase   ,				_lowerCamelCase   ,				attention_mask=_lowerCamelCase   ,				token_type_ids=_lowerCamelCase   ,				labels=_lowerCamelCase					)
									self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.num_labels)					)



		def        A_		(			self	:     Any   ,				snake_case	:     Dict   ,				snake_case	:     Optional[Any]   ,				snake_case	:     int   ,				snake_case	:     Tuple   ,				snake_case	:     List[str]   ,				snake_case	:     Optional[int]   ,				snake_case	:     Dict   ,				snake_case	:     Optional[Any]					)      ->    str:






									'''simple docstring'''

									A    =       self.num_labels
									A    =       LayoutLMForTokenClassification(config=_lowerCamelCase					)
									model.to(_lowerCamelCase					)
									model.eval()
									A    =       model(_lowerCamelCase   ,				_lowerCamelCase   ,				attention_mask=_lowerCamelCase   ,				token_type_ids=_lowerCamelCase   ,				labels=_lowerCamelCase					)
									self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.seq_length, self.num_labels)					)



		def        A_		(			self	:     Optional[int]   ,				snake_case	:     List[str]   ,				snake_case	:     Dict   ,				snake_case	:     List[Any]   ,				snake_case	:     Optional[Any]   ,				snake_case	:     int   ,				snake_case	:     Tuple   ,				snake_case	:     Dict   ,				snake_case	:     Optional[int]					)      ->    Optional[int]:






									'''simple docstring'''

									A    =       LayoutLMForQuestionAnswering(config=_lowerCamelCase					)
									model.to(_lowerCamelCase					)
									model.eval()
									A    =       model(
									    _lowerCamelCase   ,				bbox=_lowerCamelCase   ,				attention_mask=_lowerCamelCase   ,				token_type_ids=_lowerCamelCase   ,				start_positions=_lowerCamelCase   ,				end_positions=_lowerCamelCase   ,				)
									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	:     List[str]					)      ->    Optional[int]:






									'''simple docstring'''

									A    =       self.prepare_config_and_inputs()
									(
									    A							
									)    =       config_and_inputs
									A    =       {
									    '''input_ids''': input_ids,
									    '''bbox''': bbox,
									    '''token_type_ids''': token_type_ids,
									    '''attention_mask''': input_mask,
									}
									return config, inputs_dict






@require_torch
class   UpperCAmelCase__		(   a__ ,a__ ,unittest.TestCase  ):
		lowerCAmelCase_							:						Tuple							=  (
		    (
		        LayoutLMModel,
		        LayoutLMForMaskedLM,
		        LayoutLMForSequenceClassification,
		        LayoutLMForTokenClassification,
		        LayoutLMForQuestionAnswering,
		    )
		    if is_torch_available()
		    else None
		)
		lowerCAmelCase_							:						Tuple							=  (
		    {
		        'document-question-answering': LayoutLMForQuestionAnswering,
		        'feature-extraction': LayoutLMModel,
		        'fill-mask': LayoutLMForMaskedLM,
		        'text-classification': LayoutLMForSequenceClassification,
		        'token-classification': LayoutLMForTokenClassification,
		        'zero-shot': LayoutLMForSequenceClassification,
		    }
		    if is_torch_available()
		    else {}
		)
		lowerCAmelCase_							:						Optional[int]							=  True



		def        A_		(			self	:     Dict					)      ->    int:






									'''simple docstring'''

									A    =       LayoutLMModelTester(self					)
									A    =       ConfigTester(self   ,				config_class=_lowerCamelCase   ,				hidden_size=37					)



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






									'''simple docstring'''

									self.config_tester.run_common_tests()



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






									'''simple docstring'''

									A    =       self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_lowerCamelCase					)



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






									'''simple docstring'''

									A    =       self.model_tester.prepare_config_and_inputs()
									for type in ["absolute", "relative_key", "relative_key_query"]:
																A    =       type
																self.model_tester.create_and_check_model(*_lowerCamelCase					)



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






									'''simple docstring'''

									A    =       self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_masked_lm(*_lowerCamelCase					)



		def        A_		(			self	:     int					)      ->    str:






									'''simple docstring'''

									A    =       self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_sequence_classification(*_lowerCamelCase					)



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






									'''simple docstring'''

									A    =       self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_token_classification(*_lowerCamelCase					)



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






									'''simple docstring'''

									A    =       self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_question_answering(*_lowerCamelCase					)



		@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'					)
		def        A_		(			self	:     List[Any]					)      ->    str:






									'''simple docstring'''

									pass



def 	lowerCAmelCase__      (  )			->				List[str]:
							A    =       torch.tensor([[101,1019,1014,1016,1037,12849,4747,1004,14246,2278,5439,4524,5002,2930,2193,2930,4341,3208,1005,1055,2171,2848,11300,3531,102],[101,4070,4034,7020,1024,3058,1015,1013,2861,1013,6070,19274,2772,6205,27814,16147,16147,4343,2047,10283,10969,14389,1012,2338,102]]					,   device=a__      )  # noqa: E231
							A    =       torch.tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],]					,   device=a__      )  # noqa: E231
							A    =       torch.tensor([[[0,0,0,0],[423,237,440,251],[427,272,441,287],[419,115,437,129],[961,885,992,912],[256,38,330,58],[256,38,330,58],[336,42,353,57],[360,39,401,56],[360,39,401,56],[411,39,471,59],[479,41,528,59],[533,39,630,60],[67,113,134,131],[141,115,209,132],[68,149,133,166],[141,149,187,164],[195,148,287,165],[195,148,287,165],[195,148,287,165],[295,148,349,165],[441,149,492,166],[497,149,546,164],[64,201,125,218],[1000,1000,1000,1000]],[[0,0,0,0],[662,150,754,166],[665,199,742,211],[519,213,554,228],[519,213,554,228],[134,433,187,454],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[314,469,376,482],[504,684,582,706],[941,825,973,900],[941,825,973,900],[941,825,973,900],[941,825,973,900],[610,749,652,765],[130,659,168,672],[176,657,237,672],[238,657,312,672],[443,653,628,672],[443,653,628,672],[716,301,825,317],[1000,1000,1000,1000]]]					,   device=a__      )  # noqa: E231
							A    =       torch.tensor([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]					,   device=a__      )  # noqa: E231
							# these are sequence labels (i.e. at the token level)
							A    =       torch.tensor([[-100,10,10,10,9,1,-100,7,7,-100,7,7,4,2,5,2,8,8,-100,-100,5,0,3,2,-100],[-100,12,12,12,-100,12,10,-100,-100,-100,-100,10,12,9,-100,-100,-100,10,10,10,9,12,-100,10,-100]]					,   device=a__      )  # noqa: E231
							# fmt: on

							return input_ids, attention_mask, bbox, token_type_ids, labels






@require_torch
class   UpperCAmelCase__		(   unittest.TestCase  ):



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






									'''simple docstring'''

									A    =       LayoutLMModel.from_pretrained('microsoft/layoutlm-base-uncased'					).to(_lowerCamelCase					)

									A    =       prepare_layoutlm_batch_inputs()

									# forward pass
									A    =       model(input_ids=_lowerCamelCase   ,				bbox=_lowerCamelCase   ,				attention_mask=_lowerCamelCase   ,				token_type_ids=_lowerCamelCase					)

									# test the sequence output on [0, :3, :3]
									A    =       torch.tensor(
									    [[0.1785, -0.1947, -0.0425], [-0.3254, -0.2807, 0.2553], [-0.5391, -0.3322, 0.3364]]   ,				device=_lowerCamelCase   ,				)

									self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]   ,				_lowerCamelCase   ,				atol=1E-3					)					)

									# test the pooled output on [1, :3]
									A    =       torch.tensor([-0.6580, -0.0214, 0.8552]   ,				device=_lowerCamelCase					)

									self.assertTrue(torch.allclose(outputs.pooler_output[1, :3]   ,				_lowerCamelCase   ,				atol=1E-3					)					)



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






									'''simple docstring'''

									A    =       LayoutLMForSequenceClassification.from_pretrained('microsoft/layoutlm-base-uncased'   ,				num_labels=2					).to(
									    _lowerCamelCase					)

									A    =       prepare_layoutlm_batch_inputs()

									# forward pass
									A    =       model(
									    input_ids=_lowerCamelCase   ,				bbox=_lowerCamelCase   ,				attention_mask=_lowerCamelCase   ,				token_type_ids=_lowerCamelCase   ,				labels=torch.tensor([1, 1]   ,				device=_lowerCamelCase					)   ,				)

									# test whether we get a loss as a scalar
									A    =       outputs.loss
									A    =       torch.Size([]					)
									self.assertEqual(loss.shape   ,				_lowerCamelCase					)

									# test the shape of the logits
									A    =       outputs.logits
									A    =       torch.Size((2, 2)					)
									self.assertEqual(logits.shape   ,				_lowerCamelCase					)



		@slow
		def        A_		(			self	:     Any					)      ->    Any:






									'''simple docstring'''

									A    =       LayoutLMForTokenClassification.from_pretrained('microsoft/layoutlm-base-uncased'   ,				num_labels=13					).to(
									    _lowerCamelCase					)

									A    =       prepare_layoutlm_batch_inputs()

									# forward pass
									A    =       model(
									    input_ids=_lowerCamelCase   ,				bbox=_lowerCamelCase   ,				attention_mask=_lowerCamelCase   ,				token_type_ids=_lowerCamelCase   ,				labels=_lowerCamelCase					)

									# test the loss calculation to be around 2.65
									# expected_loss = torch.tensor(2.65, device=torch_device)

									# The loss is currently somewhat random and can vary between 0.1-0.3 atol.
									# self.assertTrue(torch.allclose(outputs.loss, expected_loss, atol=0.1))

									# test the shape of the logits
									A    =       outputs.logits
									A    =       torch.Size((2, 25, 13)					)
									self.assertEqual(logits.shape   ,				_lowerCamelCase					)



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






									'''simple docstring'''

									A    =       LayoutLMForQuestionAnswering.from_pretrained('microsoft/layoutlm-base-uncased'					).to(_lowerCamelCase					)

									A    =       prepare_layoutlm_batch_inputs()

									# forward pass
									A    =       model(input_ids=_lowerCamelCase   ,				bbox=_lowerCamelCase   ,				attention_mask=_lowerCamelCase   ,				token_type_ids=_lowerCamelCase					)

									# test the shape of the logits
									A    =       torch.Size((2, 25)					)
									self.assertEqual(outputs.start_logits.shape   ,				_lowerCamelCase					)
									self.assertEqual(outputs.end_logits.shape   ,				_lowerCamelCase					)





import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    EulerAncestralDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionModelEditingPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






@skip_mps
class     a_       (			a__				,    a__				,    a__				,    unittest.TestCase							):



       """simple docstring"""
       __SCREAMING_SNAKE_CASE       :					List[Any]						=  StableDiffusionModelEditingPipeline
       __SCREAMING_SNAKE_CASE       :					Optional[int]						=  TEXT_TO_IMAGE_PARAMS
       __SCREAMING_SNAKE_CASE       :					int						=  TEXT_TO_IMAGE_BATCH_PARAMS
       __SCREAMING_SNAKE_CASE       :					Any						=  TEXT_TO_IMAGE_IMAGE_PARAMS
       __SCREAMING_SNAKE_CASE       :					List[Any]						=  TEXT_TO_IMAGE_IMAGE_PARAMS






       def 	__lowerCAmelCase     (		self   )					->int:
           torch.manual_seed(0   )
           SCREAMING_SNAKE_CASE				:				Dict				      = UNetaDConditionModel(
               block_out_channels=(32, 64)				,       layers_per_block=2				,       sample_size=32				,       in_channels=4				,       out_channels=4				,       down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')				,       up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')				,       cross_attention_dim=32				,       )
           SCREAMING_SNAKE_CASE				:				Dict				      = DDIMScheduler()
           torch.manual_seed(0   )
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = 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				,       )
           torch.manual_seed(0   )
           SCREAMING_SNAKE_CASE				:				List[str]				      = 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				,       )
           SCREAMING_SNAKE_CASE				:				Dict				      = CLIPTextModel(_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Tuple				      = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''   )

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






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase				,       _lowerCamelCase=0   )					->Optional[int]:
           SCREAMING_SNAKE_CASE				:				Any				      = torch.manual_seed(_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = {
               '''prompt''': '''A field of roses''',
               '''generator''': generator,
               # Setting height and width to None to prevent OOMs on CPU.
               '''height''': None,
               '''width''': None,
               '''num_inference_steps''': 2,
               '''guidance_scale''': 6.0,
               '''output_type''': '''numpy''',
           }
           return inputs






       def 	__lowerCAmelCase     (		self   )					->Optional[int]:
           SCREAMING_SNAKE_CASE				:				Tuple				      = '''cpu'''  # ensure determinism for the device-dependent torch.Generator
           SCREAMING_SNAKE_CASE				:				Any				      = self.get_dummy_components()
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = StableDiffusionModelEditingPipeline(**_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				List[Any]				      = sd_pipe.to(_lowerCamelCase   )
           sd_pipe.set_progress_bar_config(disable=_lowerCamelCase   )

           SCREAMING_SNAKE_CASE				:				Tuple				      = self.get_dummy_inputs(_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Tuple				      = sd_pipe(**_lowerCamelCase   ).images
           SCREAMING_SNAKE_CASE				:				Any				      = image[0, -3:, -3:, -1]
           assert image.shape == (1, 64, 64, 3)

           SCREAMING_SNAKE_CASE				:				List[str]				      = np.array([0.4_7_5_5, 0.5_1_3_2, 0.4_9_7_6, 0.3_9_0_4, 0.3_5_5_4, 0.4_7_6_5, 0.5_1_3_9, 0.5_1_5_8, 0.4_8_8_9]   )

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






       def 	__lowerCAmelCase     (		self   )					->List[Any]:
           SCREAMING_SNAKE_CASE				:				Dict				      = '''cpu'''  # ensure determinism for the device-dependent torch.Generator
           SCREAMING_SNAKE_CASE				:				Tuple				      = self.get_dummy_components()
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = StableDiffusionModelEditingPipeline(**_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				str				      = sd_pipe.to(_lowerCamelCase   )
           sd_pipe.set_progress_bar_config(disable=_lowerCamelCase   )

           SCREAMING_SNAKE_CASE				:				Any				      = self.get_dummy_inputs(_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				List[str]				      = '''french fries'''
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = sd_pipe(**_lowerCamelCase				,       negative_prompt=_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Any				      = output.images
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = image[0, -3:, -3:, -1]

           assert image.shape == (1, 64, 64, 3)

           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = np.array([0.4_9_9_2, 0.5_1_0_1, 0.5_0_0_4, 0.3_9_4_9, 0.3_6_0_4, 0.4_7_3_5, 0.5_2_1_6, 0.5_2_0_4, 0.4_9_1_3]   )

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






       def 	__lowerCAmelCase     (		self   )					->Union[str, Any]:
           SCREAMING_SNAKE_CASE				:				List[str]				      = '''cpu'''  # ensure determinism for the device-dependent torch.Generator
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = self.get_dummy_components()
           SCREAMING_SNAKE_CASE				:				List[Any]				      = EulerAncestralDiscreteScheduler(
               beta_start=0.0_0_0_8_5				,       beta_end=0.0_1_2				,       beta_schedule='''scaled_linear'''   )
           SCREAMING_SNAKE_CASE				:				List[Any]				      = StableDiffusionModelEditingPipeline(**_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = sd_pipe.to(_lowerCamelCase   )
           sd_pipe.set_progress_bar_config(disable=_lowerCamelCase   )

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

           assert image.shape == (1, 64, 64, 3)

           SCREAMING_SNAKE_CASE				:				str				      = np.array([0.4_7_4_7, 0.5_3_7_2, 0.4_7_7_9, 0.4_9_8_2, 0.5_5_4_3, 0.4_8_1_6, 0.5_2_3_8, 0.4_9_0_4, 0.5_0_2_7]   )

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






       def 	__lowerCAmelCase     (		self   )					->Any:
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = '''cpu'''  # ensure determinism for the device-dependent torch.Generator
           SCREAMING_SNAKE_CASE				:				List[Any]				      = self.get_dummy_components()
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = PNDMScheduler()
           SCREAMING_SNAKE_CASE				:				Tuple				      = StableDiffusionModelEditingPipeline(**_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = sd_pipe.to(_lowerCamelCase   )
           sd_pipe.set_progress_bar_config(disable=_lowerCamelCase   )

           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = self.get_dummy_inputs(_lowerCamelCase   )
           # the pipeline does not expect pndm so test if it raises error.
           with self.assertRaises(_lowerCamelCase   ):
               SCREAMING_SNAKE_CASE				:				Dict				      = sd_pipe(**_lowerCamelCase   ).images






       def 	__lowerCAmelCase     (		self   )					->Dict:
           super().test_inference_batch_single_identical(expected_max_diff=5e-3   )






       def 	__lowerCAmelCase     (		self   )					->List[Any]:
           super().test_attention_slicing_forward_pass(expected_max_diff=5e-3   )






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



       """simple docstring"""






       def 	__lowerCAmelCase     (		self   )					->Dict:
           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()






       def 	__lowerCAmelCase     (		self				,       _lowerCamelCase=0   )					->Dict:
           SCREAMING_SNAKE_CASE				:				str				      = torch.manual_seed(_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				List[Any]				      = {
               '''prompt''': '''A field of roses''',
               '''generator''': generator,
               '''num_inference_steps''': 3,
               '''guidance_scale''': 7.5,
               '''output_type''': '''numpy''',
           }
           return inputs






       def 	__lowerCAmelCase     (		self   )					->List[str]:
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = '''CompVis/stable-diffusion-v1-4'''
           SCREAMING_SNAKE_CASE				:				List[str]				      = StableDiffusionModelEditingPipeline.from_pretrained(_lowerCamelCase				,       safety_checker=_lowerCamelCase   )
           pipe.to(_lowerCamelCase   )
           pipe.set_progress_bar_config(disable=_lowerCamelCase   )
           pipe.enable_attention_slicing()

           SCREAMING_SNAKE_CASE				:				Any				      = self.get_inputs()
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = pipe(**_lowerCamelCase   ).images
           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = image[0, -3:, -3:, -1].flatten()

           assert image.shape == (1, 512, 512, 3)

           SCREAMING_SNAKE_CASE				:				str				      = np.array(
               [0.6_7_4_9_4_9_6, 0.6_3_8_6_4_5_3, 0.5_1_4_4_3_2_6_7, 0.6_6_0_9_4_9_0_5, 0.6_1_9_2_1_2_1_5, 0.5_4_9_1_3_3_2, 0.5_7_4_4_4_1_7, 0.5_8_0_7_5_1_0_6, 0.5_1_7_4_6_5_8]   )

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

           # make sure image changes after editing
           pipe.edit_model('''A pack of roses'''				,       '''A pack of blue roses'''   )

           SCREAMING_SNAKE_CASE				:				Any				      = pipe(**_lowerCamelCase   ).images
           SCREAMING_SNAKE_CASE				:				List[str]				      = image[0, -3:, -3:, -1].flatten()

           assert image.shape == (1, 512, 512, 3)

           assert np.abs(expected_slice - image_slice   ).max() > 1e-1






       def 	__lowerCAmelCase     (		self   )					->str:
           torch.cuda.empty_cache()
           torch.cuda.reset_max_memory_allocated()
           torch.cuda.reset_peak_memory_stats()

           SCREAMING_SNAKE_CASE				:				Optional[int]				      = '''CompVis/stable-diffusion-v1-4'''
           SCREAMING_SNAKE_CASE				:				Any				      = DDIMScheduler.from_pretrained(_lowerCamelCase				,       subfolder='''scheduler'''   )
           SCREAMING_SNAKE_CASE				:				Optional[int]				      = StableDiffusionModelEditingPipeline.from_pretrained(
               _lowerCamelCase				,       scheduler=_lowerCamelCase				,       safety_checker=_lowerCamelCase   )
           SCREAMING_SNAKE_CASE				:				Dict				      = pipe.to(_lowerCamelCase   )
           pipe.set_progress_bar_config(disable=_lowerCamelCase   )
           pipe.enable_attention_slicing(1   )
           pipe.enable_sequential_cpu_offload()

           SCREAMING_SNAKE_CASE				:				List[Any]				      = self.get_inputs()
           SCREAMING_SNAKE_CASE				:				Union[str, Any]				      = pipe(**_lowerCamelCase   )

           SCREAMING_SNAKE_CASE				:				Optional[Any]				      = torch.cuda.max_memory_allocated()
           # make sure that less than 4.4 GB is allocated
           assert mem_bytes < 4.4 * 10**9
