




import inspect
import unittest

from transformers import SegformerConfig, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

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


if is_torch_available():
						import torch

						from transformers import (
						    MODEL_MAPPING,
						    SegformerForImageClassification,
						    SegformerForSemanticSegmentation,
						    SegformerModel,
						)
						from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image

						from transformers import SegformerImageProcessor







class 				lowerCAmelCase_       (					lowerCamelCase_							):






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : str					  =      self.config_class(**self.inputs_dict )
							self.parent.assertTrue(hasattr(snake_case__      ,'hidden_sizes' ) )
							self.parent.assertTrue(hasattr(snake_case__      ,'num_attention_heads' ) )
							self.parent.assertTrue(hasattr(snake_case__      ,'num_encoder_blocks' ) )







class 				lowerCAmelCase_       :






				def __init__(			self      ,snake_case__      ,snake_case__=13      ,snake_case__=64      ,snake_case__=3      ,snake_case__=4      ,snake_case__=[2, 2, 2, 2]      ,snake_case__=[8, 4, 2, 1]      ,snake_case__=[16, 32, 64, 128]      ,snake_case__=[1, 4, 8, 16]      ,snake_case__=[1, 2, 4, 8]      ,snake_case__=True      ,snake_case__=True      ,snake_case__="gelu"      ,snake_case__=0.1      ,snake_case__=0.1      ,snake_case__=0.02      ,snake_case__=3      ,snake_case__=None      ,):
							SCREAMING_SNAKE_CASE_   : Dict					  =      parent
							SCREAMING_SNAKE_CASE_   : Tuple					  =      batch_size
							SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      image_size
							SCREAMING_SNAKE_CASE_   : List[Any]					  =      num_channels
							SCREAMING_SNAKE_CASE_   : str					  =      num_encoder_blocks
							SCREAMING_SNAKE_CASE_   : List[str]					  =      sr_ratios
							SCREAMING_SNAKE_CASE_   : int					  =      depths
							SCREAMING_SNAKE_CASE_   : int					  =      hidden_sizes
							SCREAMING_SNAKE_CASE_   : str					  =      downsampling_rates
							SCREAMING_SNAKE_CASE_   : Tuple					  =      num_attention_heads
							SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      is_training
							SCREAMING_SNAKE_CASE_   : List[str]					  =      use_labels
							SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      hidden_act
							SCREAMING_SNAKE_CASE_   : List[Any]					  =      hidden_dropout_prob
							SCREAMING_SNAKE_CASE_   : Dict					  =      attention_probs_dropout_prob
							SCREAMING_SNAKE_CASE_   : int					  =      initializer_range
							SCREAMING_SNAKE_CASE_   : List[str]					  =      num_labels
							SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      scope






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : Tuple					  =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

							SCREAMING_SNAKE_CASE_   : Dict					  =      None
							if self.use_labels:
										SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      ids_tensor([self.batch_size, self.image_size, self.image_size]      ,self.num_labels )

							SCREAMING_SNAKE_CASE_   : Tuple					  =      self.get_config()
							return config, pixel_values, labels






				def 		snake_case	(			self ):
							return SegformerConfig(
							    image_size=self.image_size      ,num_channels=self.num_channels      ,num_encoder_blocks=self.num_encoder_blocks      ,depths=self.depths      ,hidden_sizes=self.hidden_sizes      ,num_attention_heads=self.num_attention_heads      ,hidden_act=self.hidden_act      ,hidden_dropout_prob=self.hidden_dropout_prob      ,attention_probs_dropout_prob=self.attention_probs_dropout_prob      ,initializer_range=self.initializer_range      ,)






				def 		snake_case	(			self      ,snake_case__      ,snake_case__      ,snake_case__ ):
							SCREAMING_SNAKE_CASE_   : int					  =      SegformerModel(config=snake_case__ )
							model.to(snake_case__ )
							model.eval()
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      model(snake_case__ )
							SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      self.image_size // (self.downsampling_rates[-1] * 2)
							self.parent.assertEqual(
							    result.last_hidden_state.shape      ,(self.batch_size, self.hidden_sizes[-1], expected_height, expected_width) )






				def 		snake_case	(			self      ,snake_case__      ,snake_case__      ,snake_case__ ):
							SCREAMING_SNAKE_CASE_   : List[Any]					  =      self.num_labels
							SCREAMING_SNAKE_CASE_   : List[str]					  =      SegformerForSemanticSegmentation(snake_case__ )
							model.to(snake_case__ )
							model.eval()
							SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      model(snake_case__ )
							self.parent.assertEqual(
							    result.logits.shape      ,(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) )
							SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      model(snake_case__      ,labels=snake_case__ )
							self.parent.assertEqual(
							    result.logits.shape      ,(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) )
							self.parent.assertGreater(result.loss      ,0.0 )






				def 		snake_case	(			self      ,snake_case__      ,snake_case__      ,snake_case__ ):
							SCREAMING_SNAKE_CASE_   : List[Any]					  =      1
							SCREAMING_SNAKE_CASE_   : List[str]					  =      SegformerForSemanticSegmentation(config=snake_case__ )
							model.to(snake_case__ )
							model.eval()
							SCREAMING_SNAKE_CASE_   : Any					  =      torch.randint(0      ,1      ,(self.batch_size, self.image_size, self.image_size) ).to(snake_case__ )
							SCREAMING_SNAKE_CASE_   : int					  =      model(snake_case__      ,labels=snake_case__ )
							self.parent.assertGreater(result.loss      ,0.0 )






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : Any					  =      self.prepare_config_and_inputs()
							SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_   : Dict					  =      config_and_inputs
							SCREAMING_SNAKE_CASE_   : Dict					  =      {'pixel_values': pixel_values}
							return config, inputs_dict







@require_torch
class 				lowerCAmelCase_       (					lowerCamelCase_						,     lowerCamelCase_						,     unittest.TestCase							):
				__a     :       Any						=     (
				    (
				        SegformerModel,
				        SegformerForSemanticSegmentation,
				        SegformerForImageClassification,
				    )
				    if is_torch_available()
				    else ()
				)
				__a     :       Union[str, Any]						=     (
				    {
				        "feature-extraction": SegformerModel,
				        "image-classification": SegformerForImageClassification,
				        "image-segmentation": SegformerForSemanticSegmentation,
				    }
				    if is_torch_available()
				    else {}
				)

				__a     :       Tuple						=     True
				__a     :       List[Any]						=     False
				__a     :       Any						=     False
				__a     :       Tuple						=     False






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : Dict					  =      SegformerModelTester(self )
							SCREAMING_SNAKE_CASE_   : List[str]					  =      SegformerConfigTester(self      ,config_class=snake_case__ )






				def 		snake_case	(			self ):
							self.config_tester.run_common_tests()






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : List[Any]					  =      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*snake_case__ )






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_binary_image_segmentation(*snake_case__ )






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : List[Any]					  =      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_segmentation(*snake_case__ )






				@unittest.skip('SegFormer does not use inputs_embeds' )
				def 		snake_case	(			self ):
							pass






				@unittest.skip('SegFormer does not have get_input_embeddings method and get_output_embeddings methods' )
				def 		snake_case	(			self ):
							pass






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
										SCREAMING_SNAKE_CASE_   : Dict					  =      model_class(snake_case__ )
										SCREAMING_SNAKE_CASE_   : Optional[int]					  =      inspect.signature(model.forward )
										# signature.parameters is an OrderedDict => so arg_names order is deterministic
										SCREAMING_SNAKE_CASE_   : List[Any]					  =      [*signature.parameters.keys()]

										SCREAMING_SNAKE_CASE_   : str					  =      ['pixel_values']
										self.assertListEqual(arg_names[:1]      ,snake_case__ )






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_   : List[Any]					  =      self.model_tester.prepare_config_and_inputs_for_common()
							SCREAMING_SNAKE_CASE_   : Dict					  =      True

							for model_class in self.all_model_classes:
										SCREAMING_SNAKE_CASE_   : Any					  =      True
										SCREAMING_SNAKE_CASE_   : Any					  =      False
										SCREAMING_SNAKE_CASE_   : Any					  =      True
										SCREAMING_SNAKE_CASE_   : Optional[int]					  =      model_class(snake_case__ )
										model.to(snake_case__ )
										model.eval()
										with torch.no_grad():
													SCREAMING_SNAKE_CASE_   : Any					  =      model(**self._prepare_for_class(snake_case__      ,snake_case__ ) )
										SCREAMING_SNAKE_CASE_   : Dict					  =      outputs.attentions

										SCREAMING_SNAKE_CASE_   : Dict					  =      sum(self.model_tester.depths )
										self.assertEqual(len(snake_case__ )      ,snake_case__ )

										# check that output_attentions also work using config
										del inputs_dict["output_attentions"]
										SCREAMING_SNAKE_CASE_   : int					  =      True
										SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      model_class(snake_case__ )
										model.to(snake_case__ )
										model.eval()
										with torch.no_grad():
													SCREAMING_SNAKE_CASE_   : Optional[int]					  =      model(**self._prepare_for_class(snake_case__      ,snake_case__ ) )
										SCREAMING_SNAKE_CASE_   : str					  =      outputs.attentions

										self.assertEqual(len(snake_case__ )      ,snake_case__ )

										# verify the first attentions (first block, first layer)
										SCREAMING_SNAKE_CASE_   : List[str]					  =      (self.model_tester.image_size // 4) ** 2
										SCREAMING_SNAKE_CASE_   : Tuple					  =      (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
										self.assertListEqual(
										    list(attentions[0].shape[-3:] )      ,[self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]      ,)

										# verify the last attentions (last block, last layer)
										SCREAMING_SNAKE_CASE_   : Any					  =      (self.model_tester.image_size // 32) ** 2
										SCREAMING_SNAKE_CASE_   : Tuple					  =      (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2
										self.assertListEqual(
										    list(attentions[-1].shape[-3:] )      ,[self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len]      ,)
										SCREAMING_SNAKE_CASE_   : List[Any]					  =      len(snake_case__ )

										# Check attention is always last and order is fine
										SCREAMING_SNAKE_CASE_   : int					  =      True
										SCREAMING_SNAKE_CASE_   : str					  =      True
										SCREAMING_SNAKE_CASE_   : str					  =      model_class(snake_case__ )
										model.to(snake_case__ )
										model.eval()
										with torch.no_grad():
													SCREAMING_SNAKE_CASE_   : str					  =      model(**self._prepare_for_class(snake_case__      ,snake_case__ ) )

										self.assertEqual(out_len + 1      ,len(snake_case__ ) )

										SCREAMING_SNAKE_CASE_   : List[str]					  =      outputs.attentions

										self.assertEqual(len(snake_case__ )      ,snake_case__ )
										# verify the first attentions (first block, first layer)
										SCREAMING_SNAKE_CASE_   : Any					  =      (self.model_tester.image_size // 4) ** 2
										SCREAMING_SNAKE_CASE_   : Any					  =      (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
										self.assertListEqual(
										    list(self_attentions[0].shape[-3:] )      ,[self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]      ,)






				def 		snake_case	(			self ):
							def check_hidden_states_output(snake_case__      ,snake_case__      ,snake_case__ ):
										SCREAMING_SNAKE_CASE_   : int					  =      model_class(snake_case__ )
										model.to(snake_case__ )
										model.eval()

										with torch.no_grad():
													SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      model(**self._prepare_for_class(snake_case__      ,snake_case__ ) )

										SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      outputs.hidden_states

										SCREAMING_SNAKE_CASE_   : List[str]					  =      self.model_tester.num_encoder_blocks
										self.assertEqual(len(snake_case__ )      ,snake_case__ )

										# verify the first hidden states (first block)
										self.assertListEqual(
										    list(hidden_states[0].shape[-3:] )      ,[
										        self.model_tester.hidden_sizes[0],
										        self.model_tester.image_size // 4,
										        self.model_tester.image_size // 4,
										    ]      ,)

							SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_   : Any					  =      self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
										SCREAMING_SNAKE_CASE_   : Tuple					  =      True
										check_hidden_states_output(snake_case__      ,snake_case__      ,snake_case__ )

										# check that output_hidden_states also work using config
										del inputs_dict["output_hidden_states"]
										SCREAMING_SNAKE_CASE_   : Any					  =      True

										check_hidden_states_output(snake_case__      ,snake_case__      ,snake_case__ )






				def 		snake_case	(			self ):
							if not self.model_tester.is_training:
										return

							SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_   : Tuple					  =      self.model_tester.prepare_config_and_inputs_for_common()
							SCREAMING_SNAKE_CASE_   : Tuple					  =      True

							for model_class in self.all_model_classes:
										if model_class in get_values(snake_case__ ):
													continue

										SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      model_class(snake_case__ )
										model.to(snake_case__ )
										model.train()
										SCREAMING_SNAKE_CASE_   : Any					  =      self._prepare_for_class(snake_case__      ,snake_case__      ,return_labels=snake_case__ )
										SCREAMING_SNAKE_CASE_   : Optional[int]					  =      model(**snake_case__ ).loss
										loss.backward()






				@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' )
				def 		snake_case	(			self ):
							pass






				@slow
				def 		snake_case	(			self ):
							for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										SCREAMING_SNAKE_CASE_   : Any					  =      SegformerModel.from_pretrained(snake_case__ )
										self.assertIsNotNone(snake_case__ )





def        __UpperCAmelCase						(							)       ->  int:







			"""simple docstring"""





			SCREAMING_SNAKE_CASE_   : Any					  =      Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
			return image







@require_torch
class 				lowerCAmelCase_       (					unittest.TestCase							):






				@slow
				def 		snake_case	(			self ):
							# only resize + normalize
							SCREAMING_SNAKE_CASE_   : List[str]					  =      SegformerImageProcessor(
							    image_scale=(512, 512)      ,keep_ratio=snake_case__      ,align=snake_case__      ,do_random_crop=snake_case__ )
							SCREAMING_SNAKE_CASE_   : List[Any]					  =      SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512' ).to(
							    snake_case__ )

							SCREAMING_SNAKE_CASE_   : Dict					  =      prepare_img()
							SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      image_processor(images=snake_case__      ,return_tensors='pt' )
							SCREAMING_SNAKE_CASE_   : Any					  =      encoded_inputs.pixel_values.to(snake_case__ )

							with torch.no_grad():
										SCREAMING_SNAKE_CASE_   : Optional[int]					  =      model(snake_case__ )

							SCREAMING_SNAKE_CASE_   : List[str]					  =      torch.Size((1, model.config.num_labels, 128, 128) )
							self.assertEqual(outputs.logits.shape      ,snake_case__ )

							SCREAMING_SNAKE_CASE_   : List[Any]					  =      torch.tensor(
							    [
							        [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]],
							        [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]],
							        [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]],
							    ] ).to(snake_case__ )
							self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]      ,snake_case__      ,atol=1E-4 ) )






				@slow
				def 		snake_case	(			self ):
							# only resize + normalize
							SCREAMING_SNAKE_CASE_   : Dict					  =      SegformerImageProcessor(
							    image_scale=(512, 512)      ,keep_ratio=snake_case__      ,align=snake_case__      ,do_random_crop=snake_case__ )
							SCREAMING_SNAKE_CASE_   : Dict					  =      SegformerForSemanticSegmentation.from_pretrained(
							    'nvidia/segformer-b1-finetuned-cityscapes-1024-1024' ).to(snake_case__ )

							SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      prepare_img()
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      image_processor(images=snake_case__      ,return_tensors='pt' )
							SCREAMING_SNAKE_CASE_   : int					  =      encoded_inputs.pixel_values.to(snake_case__ )

							with torch.no_grad():
										SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      model(snake_case__ )

							SCREAMING_SNAKE_CASE_   : List[str]					  =      torch.Size((1, model.config.num_labels, 128, 128) )
							self.assertEqual(outputs.logits.shape      ,snake_case__ )

							SCREAMING_SNAKE_CASE_   : List[Any]					  =      torch.tensor(
							    [
							        [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]],
							        [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]],
							        [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]],
							    ] ).to(snake_case__ )
							self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]      ,snake_case__      ,atol=1E-1 ) )






				@slow
				def 		snake_case	(			self ):
							# only resize + normalize
							SCREAMING_SNAKE_CASE_   : List[str]					  =      SegformerImageProcessor(
							    image_scale=(512, 512)      ,keep_ratio=snake_case__      ,align=snake_case__      ,do_random_crop=snake_case__ )
							SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512' ).to(
							    snake_case__ )

							SCREAMING_SNAKE_CASE_   : List[Any]					  =      prepare_img()
							SCREAMING_SNAKE_CASE_   : Any					  =      image_processor(images=snake_case__      ,return_tensors='pt' )
							SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      encoded_inputs.pixel_values.to(snake_case__ )

							with torch.no_grad():
										SCREAMING_SNAKE_CASE_   : List[Any]					  =      model(snake_case__ )

							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      outputs.logits.detach().cpu()

							SCREAMING_SNAKE_CASE_   : List[str]					  =      image_processor.post_process_semantic_segmentation(outputs=snake_case__      ,target_sizes=[(500, 300)] )
							SCREAMING_SNAKE_CASE_   : int					  =      torch.Size((500, 300) )
							self.assertEqual(segmentation[0].shape      ,snake_case__ )

							SCREAMING_SNAKE_CASE_   : int					  =      image_processor.post_process_semantic_segmentation(outputs=snake_case__ )
							SCREAMING_SNAKE_CASE_   : Dict					  =      torch.Size((128, 128) )
							self.assertEqual(segmentation[0].shape      ,snake_case__ )









import gc
import random
import unittest

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

import diffusers
from diffusers import (
    AutoencoderKL,
    EulerDiscreteScheduler,
    StableDiffusionLatentUpscalePipeline,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.schedulers import KarrasDiffusionSchedulers
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()





def 						__A						(      __lowerCamelCase       ) ->			Optional[int]:
	a									=				[tensor.shape for tensor in tensor_list]
	return all(shape == shapes[0] for shape in shapes[1:]       )

class 						__lowerCAmelCase      (      __magic_name__ ,			__magic_name__ ,			__magic_name__ ,			unittest.TestCase					):
							UpperCamelCase__   	=    StableDiffusionLatentUpscalePipeline
							UpperCamelCase__   	=    TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
							    '''height''',
							    '''width''',
							    '''cross_attention_kwargs''',
							    '''negative_prompt_embeds''',
							    '''prompt_embeds''',
							}
							UpperCamelCase__   	=    PipelineTesterMixin.required_optional_params - {'''num_images_per_prompt'''}
							UpperCamelCase__   	=    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
							UpperCamelCase__   	=    frozenset(
							    []					)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
							UpperCamelCase__   	=    frozenset([]					)

							UpperCamelCase__   	=    True
							@property
							def  lowerCamelCase__				(		self		:List[str]							):







								'''simple docstring'''







								a									=				1
								a									=				4
								a									=				(16, 16)

								a									=				floats_tensor((batch_size, num_channels) + sizes						, rng=random.Random(0							)							).to(__magic_name__							)
								return image
							def  lowerCamelCase__				(		self		:Any							):







								'''simple docstring'''







								torch.manual_seed(0							)
								a									=				UNetaDConditionModel(
								    act_fn="""gelu"""						, attention_head_dim=8						, norm_num_groups=__magic_name__						, block_out_channels=[32, 32, 64, 64]						, time_cond_proj_dim=160						, conv_in_kernel=1						, conv_out_kernel=1						, cross_attention_dim=32						, down_block_types=(
								        """KDownBlock2D""",
								        """KCrossAttnDownBlock2D""",
								        """KCrossAttnDownBlock2D""",
								        """KCrossAttnDownBlock2D""",
								    )						, in_channels=8						, mid_block_type=__magic_name__						, only_cross_attention=__magic_name__						, out_channels=5						, resnet_time_scale_shift="""scale_shift"""						, time_embedding_type="""fourier"""						, timestep_post_act="""gelu"""						, up_block_types=("""KCrossAttnUpBlock2D""", """KCrossAttnUpBlock2D""", """KCrossAttnUpBlock2D""", """KUpBlock2D""")						, )
								a									=				AutoencoderKL(
								    block_out_channels=[32, 32, 64, 64]						, in_channels=3						, out_channels=3						, down_block_types=[
								        """DownEncoderBlock2D""",
								        """DownEncoderBlock2D""",
								        """DownEncoderBlock2D""",
								        """DownEncoderBlock2D""",
								    ]						, up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D""", """UpDecoderBlock2D""", """UpDecoderBlock2D"""]						, latent_channels=4						, )
								a									=				EulerDiscreteScheduler(prediction_type="""sample"""							)
								a									=				CLIPTextConfig(
								    bos_token_id=0						, eos_token_id=2						, hidden_size=32						, intermediate_size=37						, layer_norm_eps=1E-0_5						, num_attention_heads=4						, num_hidden_layers=5						, pad_token_id=1						, vocab_size=1000						, hidden_act="""quick_gelu"""						, projection_dim=512						, )
								a									=				CLIPTextModel(__magic_name__							)
								a									=				CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""							)

								a									=				{
								    """unet""": model.eval(),
								    """vae""": vae.eval(),
								    """scheduler""": scheduler,
								    """text_encoder""": text_encoder,
								    """tokenizer""": tokenizer,
								}

								return components
							def  lowerCamelCase__				(		self		:Optional[int]						, __magic_name__		:Tuple						, __magic_name__		:Optional[int]=0							):







								'''simple docstring'''







								if str(__magic_name__							).startswith("""mps"""							):
									a									=				torch.manual_seed(__magic_name__							)
								else:
									a									=				torch.Generator(device=__magic_name__							).manual_seed(__magic_name__							)
								a									=				{
								    """prompt""": """A painting of a squirrel eating a burger""",
								    """image""": self.dummy_image.cpu(),
								    """generator""": generator,
								    """num_inference_steps""": 2,
								    """output_type""": """numpy""",
								}
								return inputs
							def  lowerCamelCase__				(		self		:Optional[int]							):







								'''simple docstring'''







								a									=				"""cpu"""

								a									=				self.get_dummy_components()
								a									=				self.pipeline_class(**__magic_name__							)
								pipe.to(__magic_name__							)
								pipe.set_progress_bar_config(disable=__magic_name__							)

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

								self.assertEqual(image.shape						, (1, 256, 256, 3)							)
								a									=				np.array(
								    [0.47222412, 0.41921633, 0.44717434, 0.46874192, 0.42588258, 0.46150726, 0.4677534, 0.45583832, 0.48579055]							)
								a									=				np.abs(image_slice.flatten() - expected_slice							).max()
								self.assertLessEqual(__magic_name__						, 1E-3							)
							def  lowerCamelCase__				(		self		:Any							):







								'''simple docstring'''







								super().test_attention_slicing_forward_pass(expected_max_diff=7E-3							)
							def  lowerCamelCase__				(		self		:Optional[int]							):







								'''simple docstring'''







								super().test_cpu_offload_forward_pass(expected_max_diff=3E-3							)
							def  lowerCamelCase__				(		self		:Dict							):







								'''simple docstring'''







								super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3							)
							def  lowerCamelCase__				(		self		:List[Any]							):







								'''simple docstring'''







								super().test_inference_batch_single_identical(expected_max_diff=7E-3							)
							def  lowerCamelCase__				(		self		:Optional[int]							):







								'''simple docstring'''







								super().test_pt_np_pil_outputs_equivalent(expected_max_diff=3E-3							)
							def  lowerCamelCase__				(		self		:str							):







								'''simple docstring'''







								super().test_save_load_local(expected_max_difference=3E-3							)
							def  lowerCamelCase__				(		self		:Tuple							):







								'''simple docstring'''







								super().test_save_load_optional_components(expected_max_difference=3E-3							)





							def  lowerCamelCase__				(		self		:List[str]							):







								'''simple docstring'''







								a									=				[
								    """DDIMScheduler""",
								    """DDPMScheduler""",
								    """PNDMScheduler""",
								    """HeunDiscreteScheduler""",
								    """EulerAncestralDiscreteScheduler""",
								    """KDPM2DiscreteScheduler""",
								    """KDPM2AncestralDiscreteScheduler""",
								    """DPMSolverSDEScheduler""",
								]
								a									=				self.get_dummy_components()
								a									=				self.pipeline_class(**__magic_name__							)

								# make sure that PNDM does not need warm-up
								pipe.scheduler.register_to_config(skip_prk_steps=__magic_name__							)

								pipe.to(__magic_name__							)
								pipe.set_progress_bar_config(disable=__magic_name__							)
								a									=				self.get_dummy_inputs(__magic_name__							)
								a									=				2

								a									=				[]
								for scheduler_enum in KarrasDiffusionSchedulers:
									if scheduler_enum.name in skip_schedulers:
										# no sigma schedulers are not supported
										# no schedulers
										continue

									a									=				getattr(__magic_name__						, scheduler_enum.name							)
									a									=				scheduler_cls.from_config(pipe.scheduler.config							)
									a									=				pipe(**__magic_name__							)[0]
									outputs.append(__magic_name__							)

								assert check_same_shape(__magic_name__							)







@require_torch_gpu
@slow
class 						__lowerCAmelCase      (      unittest.TestCase					):
							def  lowerCamelCase__				(		self		:List[str]							):







								'''simple docstring'''







								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()
							def  lowerCamelCase__				(		self		:List[Any]							):







								'''simple docstring'''







								a									=				torch.manual_seed(33							)

								a									=				StableDiffusionPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4"""						, torch_dtype=torch.floataa							)
								pipe.to("""cuda"""							)

								a									=				StableDiffusionLatentUpscalePipeline.from_pretrained(
								    """stabilityai/sd-x2-latent-upscaler"""						, torch_dtype=torch.floataa							)
								upscaler.to("""cuda"""							)

								a									=				"""a photo of an astronaut high resolution, unreal engine, ultra realistic"""

								a									=				pipe(__magic_name__						, generator=__magic_name__						, output_type="""latent"""							).images

								a									=				upscaler(
								    prompt=__magic_name__						, image=__magic_name__						, num_inference_steps=20						, guidance_scale=0						, generator=__magic_name__						, output_type="""np"""						, ).images[0]

								a									=				load_numpy(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/astronaut_1024.npy"""							)
								assert np.abs((expected_image - image).mean()							) < 5E-2





							def  lowerCamelCase__				(		self		:Optional[Any]							):







								'''simple docstring'''







								a									=				torch.manual_seed(33							)

								a									=				StableDiffusionLatentUpscalePipeline.from_pretrained(
								    """stabilityai/sd-x2-latent-upscaler"""						, torch_dtype=torch.floataa							)
								upscaler.to("""cuda"""							)

								a									=				"""the temple of fire by Ross Tran and Gerardo Dottori, oil on canvas"""

								a									=				load_image(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_512.png"""							)

								a									=				upscaler(
								    prompt=__magic_name__						, image=__magic_name__						, num_inference_steps=20						, guidance_scale=0						, generator=__magic_name__						, output_type="""np"""						, ).images[0]

								a									=				load_numpy(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_1024.npy"""							)
								assert np.abs((expected_image - image).max()							) < 5E-2

