





'''simple docstring'''







import enum
import inspect
from typing import Iterable, List, Optional, Tuple, Union


class        __a   (enum.Enum  ):
							__a       : Tuple          =							"timm"
							__a       : Tuple          =							"transformers"





def 							lowerCamelCase_   (	SCREAMING_SNAKE_CASE__   :      Optional[Iterable[str]],      SCREAMING_SNAKE_CASE__   :      Optional[Iterable[int]],      SCREAMING_SNAKE_CASE__   :      Optional[Iterable[str]] )			->						int:
						if stage_names is None:
												raise ValueError('''Stage_names must be set for transformers backbones''' )

						if out_features is not None:
												if not isinstance(SCREAMING_SNAKE_CASE__,      (list,) ):
																		raise ValueError(F"""out_features must be a list {type(SCREAMING_SNAKE_CASE__ )}""" )
												if any(feat not in stage_names for feat in out_features ):
																		raise ValueError(F"""out_features must be a subset of stage_names: {stage_names} got {out_features}""" )

						if out_indices is not None:
												if not isinstance(SCREAMING_SNAKE_CASE__,      (list, tuple) ):
																		raise ValueError(F"""out_indices must be a list or tuple, got {type(SCREAMING_SNAKE_CASE__ )}""" )
												if any(idx >= len(SCREAMING_SNAKE_CASE__ ) for idx in out_indices ):
																		raise ValueError('''out_indices must be valid indices for stage_names {stage_names}, got {out_indices}''' )

						if out_features is not None and out_indices is not None:
												if len(SCREAMING_SNAKE_CASE__ ) != len(SCREAMING_SNAKE_CASE__ ):
																		raise ValueError('''out_features and out_indices should have the same length if both are set''' )
												if out_features != [stage_names[idx] for idx in out_indices]:
																		raise ValueError('''out_features and out_indices should correspond to the same stages if both are set''' )





def 							lowerCamelCase_   (	SCREAMING_SNAKE_CASE__   :      Optional[List[str]],      SCREAMING_SNAKE_CASE__   :      Optional[Union[List[int], Tuple[int]]],      SCREAMING_SNAKE_CASE__   :      List[str],      )			->						Optional[Any]:
						if out_indices is None and out_features is None:
												UpperCAmelCase_      :   Union[str, Any]      =	[len(SCREAMING_SNAKE_CASE__ ) - 1]
												UpperCAmelCase_      :   str      =	[stage_names[-1]]
						elif out_indices is None and out_features is not None:
												UpperCAmelCase_      :   List[str]      =	[stage_names.index(SCREAMING_SNAKE_CASE__ ) for layer in out_features]
						elif out_features is None and out_indices is not None:
												UpperCAmelCase_      :   List[str]      =	[stage_names[idx] for idx in out_indices]
						return out_features, out_indices





def 							lowerCamelCase_   (	SCREAMING_SNAKE_CASE__   :      Optional[List[str]],      SCREAMING_SNAKE_CASE__   :      Optional[Union[List[int], Tuple[int]]],      SCREAMING_SNAKE_CASE__   :      List[str],      )			->						Tuple[List[str], List[int]]:
						verify_out_features_out_indices(out_features=SCREAMING_SNAKE_CASE__,      out_indices=SCREAMING_SNAKE_CASE__,      stage_names=SCREAMING_SNAKE_CASE__ )
						UpperCAmelCase_    ,							UpperCAmelCase_      :   Dict      =	_align_output_features_output_indices(
						    out_features=SCREAMING_SNAKE_CASE__,      out_indices=SCREAMING_SNAKE_CASE__,      stage_names=SCREAMING_SNAKE_CASE__ )
						# Verify that the aligned out_features and out_indices are valid
						verify_out_features_out_indices(out_features=SCREAMING_SNAKE_CASE__,      out_indices=SCREAMING_SNAKE_CASE__,      stage_names=SCREAMING_SNAKE_CASE__ )
						return output_features, output_indices


class        __a   :
							__a       : Optional[BackboneType]          =							None

							def      UpperCAmelCase__						(				self				:  Dict							,  __magic_name__				:  List[Any] )       ->							None:







													"""simple docstring"""
													if getattr(self							,  '''_backbone'''							,  __magic_name__ ) is None:
																			raise ValueError('''self._backbone must be set before calling _init_timm_backbone''' )

													# These will diagree with the defaults for the transformers models e.g. for resnet50
													# the transformer model has out_features = ['stem', 'stage1', 'stage2', 'stage3', 'stage4']
													# the timm model has out_features = ['act', 'layer1', 'layer2', 'layer3', 'layer4']
													UpperCAmelCase_      :   int      =	[stage['''module'''] for stage in self._backbone.feature_info.info]
													UpperCAmelCase_      :   Tuple      =	[stage['''num_chs'''] for stage in self._backbone.feature_info.info]
													UpperCAmelCase_      :   List[Any]      =	self._backbone.feature_info.out_indices
													UpperCAmelCase_      :   Any      =	self._backbone.feature_info.module_name()

													# We verify the out indices and out features are valid
													verify_out_features_out_indices(
													    out_features=__magic_name__							,  out_indices=__magic_name__							,  stage_names=self.stage_names )
													UpperCAmelCase_    ,							UpperCAmelCase_      :   Optional[Any]      =	out_features, out_indices

							def      UpperCAmelCase__						(				self				:  str							,  __magic_name__				:  Dict )       ->							None:







													"""simple docstring"""
													UpperCAmelCase_      :   str      =	getattr(__magic_name__							,  '''stage_names''' )
													UpperCAmelCase_      :   Tuple      =	getattr(__magic_name__							,  '''out_features'''							,  __magic_name__ )
													UpperCAmelCase_      :   Union[str, Any]      =	getattr(__magic_name__							,  '''out_indices'''							,  __magic_name__ )

													UpperCAmelCase_      :   List[str]      =	stage_names
													UpperCAmelCase_    ,							UpperCAmelCase_      :   str      =	get_aligned_output_features_output_indices(
													    out_features=__magic_name__							,  out_indices=__magic_name__							,  stage_names=__magic_name__ )
													# Number of channels for each stage. This is set in the transformer backbone model init
													UpperCAmelCase_      :   List[str]      =	None

							def      UpperCAmelCase__						(				self				:  Any							,  __magic_name__				:  Tuple )       ->							None:







													"""simple docstring"""
													UpperCAmelCase_      :   int      =	config

													UpperCAmelCase_      :   str      =	getattr(__magic_name__							,  '''use_timm_backbone'''							,  __magic_name__ )
													UpperCAmelCase_      :   str      =	BackboneType.TIMM if self.use_timm_backbone else BackboneType.TRANSFORMERS

													if self.backbone_type == BackboneType.TIMM:
																			self._init_timm_backbone(__magic_name__ )
													elif self.backbone_type == BackboneType.TRANSFORMERS:
																			self._init_transformers_backbone(__magic_name__ )
													else:
																			raise ValueError(F"""backbone_type {self.backbone_type} not supported.""" )

							@property
							def      UpperCAmelCase__						(				self				:  List[Any] )       ->							Optional[Any]:







													"""simple docstring"""
													return self._out_features

							@out_features.setter
							def      UpperCAmelCase__						(				self				:  int							,  __magic_name__				:  List[str] )       ->							List[str]:







													"""simple docstring"""
													UpperCAmelCase_    ,							UpperCAmelCase_      :   Union[str, Any]      =	get_aligned_output_features_output_indices(
													    out_features=__magic_name__							,  out_indices=__magic_name__							,  stage_names=self.stage_names )

							@property
							def      UpperCAmelCase__						(				self				:  int )       ->							List[Any]:







													"""simple docstring"""
													return self._out_indices

							@out_indices.setter
							def      UpperCAmelCase__						(				self				:  Union[str, Any]							,  __magic_name__				:  Union[Tuple[int], List[int]] )       ->							Union[str, Any]:







													"""simple docstring"""
													UpperCAmelCase_    ,							UpperCAmelCase_      :   int      =	get_aligned_output_features_output_indices(
													    out_features=__magic_name__							,  out_indices=__magic_name__							,  stage_names=self.stage_names )

							@property
							def      UpperCAmelCase__						(				self				:  int )       ->							Optional[int]:







													"""simple docstring"""
													# the current backbones will output the number of channels for each stage
													# even if that stage is not in the out_features list.
													return {stage: self.num_features[i] for i, stage in enumerate(self.stage_names )}

							@property
							def      UpperCAmelCase__						(				self				:  Tuple )       ->							Optional[Any]:







													"""simple docstring"""
													return [self.out_feature_channels[name] for name in self.out_features]

							def      UpperCAmelCase__						(				self				:  Any							,  *__magic_name__				:  Optional[int]							,  **__magic_name__				:  Dict )       ->							int:







													"""simple docstring"""
													UpperCAmelCase_      :   Tuple      =	dict(inspect.signature(self.forward ).parameters )
													UpperCAmelCase_      :   Optional[Any]      =	{k: v for k, v in kwargs.items() if k in signature}
													return self(*__magic_name__							,  **__magic_name__ )

							def      UpperCAmelCase__						(				self				:  Union[str, Any]							,  __magic_name__				:  List[str]							,  __magic_name__				:  Optional[bool] = None							,  __magic_name__				:  Optional[bool] = None							,  __magic_name__				:  Optional[bool] = None							,  )       ->							List[Any]:







													"""simple docstring"""
													raise NotImplementedError('''This method should be implemented by the derived class.''' )



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







													"""simple docstring"""
													UpperCAmelCase_      :   List[Any]      =	super().to_dict()
													UpperCAmelCase_      :   List[Any]      =	output.pop('''_out_features''' )
													UpperCAmelCase_      :   Tuple      =	output.pop('''_out_indices''' )
													return output





class        __a   :

							@property
							def      UpperCAmelCase__						(				self				:  Optional[Any] )       ->							str:







													"""simple docstring"""
													return self._out_features

							@out_features.setter
							def      UpperCAmelCase__						(				self				:  int							,  __magic_name__				:  List[str] )       ->							Union[str, Any]:







													"""simple docstring"""
													UpperCAmelCase_    ,							UpperCAmelCase_      :   List[Any]      =	get_aligned_output_features_output_indices(
													    out_features=__magic_name__							,  out_indices=__magic_name__							,  stage_names=self.stage_names )

							@property
							def      UpperCAmelCase__						(				self				:  Optional[Any] )       ->							int:







													"""simple docstring"""
													return self._out_indices

							@out_indices.setter
							def      UpperCAmelCase__						(				self				:  List[Any]							,  __magic_name__				:  Union[Tuple[int], List[int]] )       ->							str:







													"""simple docstring"""
													UpperCAmelCase_    ,							UpperCAmelCase_      :   str      =	get_aligned_output_features_output_indices(
													    out_features=__magic_name__							,  out_indices=__magic_name__							,  stage_names=self.stage_names )



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







													"""simple docstring"""
													UpperCAmelCase_      :   str      =	super().to_dict()
													UpperCAmelCase_      :   Union[str, Any]      =	output.pop('''_out_features''' )
													UpperCAmelCase_      :   Any      =	output.pop('''_out_indices''' )
													return output










'''simple docstring'''



import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

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


enable_full_determinism()






class 			_SCREAMING_SNAKE_CASE				(lowercase__,	lowercase__,	unittest.TestCase      ):
			A__								=  StableDiffusionXLPipeline
			A__								=  TEXT_TO_IMAGE_PARAMS
			A__								=  TEXT_TO_IMAGE_BATCH_PARAMS
			A__								=  TEXT_TO_IMAGE_IMAGE_PARAMS
			A__								=  TEXT_TO_IMAGE_IMAGE_PARAMS



			def 				lowerCAmelCase (     self		:						List[str]			)      ->      Tuple:
							"""simple docstring"""





							torch.manual_seed(0			)
							snake_case__      :   Any      =    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''')    ,			attention_head_dim=(2, 4)    ,			use_linear_projection=__UpperCamelCase    ,			addition_embed_type='''text_time'''    ,			addition_time_embed_dim=8    ,			transformer_layers_per_block=(1, 2)    ,			projection_class_embeddings_input_dim=80    ,			cross_attention_dim=64    ,			)
							snake_case__      :   Tuple      =    EulerDiscreteScheduler(
							    beta_start=0.00085    ,			beta_end=0.012    ,			steps_offset=1    ,			beta_schedule='''scaled_linear'''    ,			timestep_spacing='''leading'''    ,			)
							torch.manual_seed(0			)
							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    ,			sample_size=128    ,			)
							torch.manual_seed(0			)
							snake_case__      :   List[Any]      =    CLIPTextConfig(
							    bos_token_id=0    ,			eos_token_id=2    ,			hidden_size=32    ,			intermediate_size=37    ,			layer_norm_eps=1e-05    ,			num_attention_heads=4    ,			num_hidden_layers=5    ,			pad_token_id=1    ,			vocab_size=1000    ,			hidden_act='''gelu'''    ,			projection_dim=32    ,			)
							snake_case__      :   List[str]      =    CLIPTextModel(__UpperCamelCase			)
							snake_case__      :   Dict      =    CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''    ,			local_files_only=__UpperCamelCase			)

							snake_case__      :   Optional[int]      =    CLIPTextModelWithProjection(__UpperCamelCase			)
							snake_case__      :   Optional[int]      =    CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''    ,			local_files_only=__UpperCamelCase			)

							snake_case__      :   List[str]      =    {
							    '''unet''': unet,
							    '''scheduler''': scheduler,
							    '''vae''': vae,
							    '''text_encoder''': text_encoder,
							    '''tokenizer''': tokenizer,
							    '''text_encoder_2''': text_encoder_a,
							    '''tokenizer_2''': tokenizer_a,
							    # "safety_checker": None,
							    # "feature_extractor": None,
							}
							return components



			def 				lowerCAmelCase (     self		:						Union[str, Any]    ,			__UpperCamelCase		:						int    ,			__UpperCamelCase		:						Union[str, Any]=0			)      ->      Optional[Any]:
							"""simple docstring"""





							if str(__UpperCamelCase			).startswith('''mps'''			):
											snake_case__      :   List[Any]      =    torch.manual_seed(__UpperCamelCase			)
							else:
											snake_case__      :   List[Any]      =    torch.Generator(device=__UpperCamelCase			).manual_seed(__UpperCamelCase			)
							snake_case__      :   Dict      =    {
							    '''prompt''': '''A painting of a squirrel eating a burger''',
							    '''generator''': generator,
							    '''num_inference_steps''': 2,
							    '''guidance_scale''': 5.0,
							    '''output_type''': '''numpy''',
							}
							return inputs



			def 				lowerCAmelCase (     self		:						List[Any]			)      ->      Tuple:
							"""simple docstring"""





							snake_case__      :   Any      =    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
							snake_case__      :   Union[str, Any]      =    self.get_dummy_components()
							snake_case__      :   List[Any]      =    StableDiffusionXLPipeline(**__UpperCamelCase			)
							snake_case__      :   Optional[int]      =    sd_pipe.to(__UpperCamelCase			)
							sd_pipe.set_progress_bar_config(disable=__UpperCamelCase			)

							snake_case__      :   Dict      =    self.get_dummy_inputs(__UpperCamelCase			)
							snake_case__      :   Union[str, Any]      =    sd_pipe(**__UpperCamelCase			).images
							snake_case__      :   List[Any]      =    image[0, -3:, -3:, -1]

							assert image.shape == (1, 64, 64, 3)
							snake_case__      :   Union[str, Any]      =    np.array([0.5873, 0.6128, 0.4797, 0.5122, 0.5674, 0.4639, 0.5227, 0.5149, 0.4747]			)

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



			def 				lowerCAmelCase (     self		:						Optional[Any]			)      ->      Optional[int]:
							"""simple docstring"""





							snake_case__      :   List[str]      =    self.get_dummy_components()
							snake_case__      :   Optional[Any]      =    StableDiffusionXLPipeline(**__UpperCamelCase			)
							snake_case__      :   str      =    sd_pipe.to(__UpperCamelCase			)
							snake_case__      :   Tuple      =    sd_pipe.to(__UpperCamelCase			)
							sd_pipe.set_progress_bar_config(disable=__UpperCamelCase			)

							# forward without prompt embeds
							snake_case__      :   str      =    self.get_dummy_inputs(__UpperCamelCase			)
							snake_case__      :   Any      =    3 * ['''this is a negative prompt''']
							snake_case__      :   Optional[int]      =    negative_prompt
							snake_case__      :   Tuple      =    3 * [inputs['''prompt''']]

							snake_case__      :   Tuple      =    sd_pipe(**__UpperCamelCase			)
							snake_case__      :   str      =    output.images[0, -3:, -3:, -1]

							# forward with prompt embeds
							snake_case__      :   Tuple      =    self.get_dummy_inputs(__UpperCamelCase			)
							snake_case__      :   List[Any]      =    3 * ['''this is a negative prompt''']
							snake_case__      :   List[Any]      =    3 * [inputs.pop('''prompt'''			)]

							(
							    (
							    snake_case__
							)  ,      (
							    snake_case__
							)  ,      (
							    snake_case__
							)  ,      (
							    snake_case__
							)  ,      
							)      :   List[Any]      =    sd_pipe.encode_prompt(__UpperCamelCase    ,			negative_prompt=__UpperCamelCase			)

							snake_case__      :   Dict      =    sd_pipe(
							    **__UpperCamelCase    ,			prompt_embeds=__UpperCamelCase    ,			negative_prompt_embeds=__UpperCamelCase    ,			pooled_prompt_embeds=__UpperCamelCase    ,			negative_pooled_prompt_embeds=__UpperCamelCase    ,			)
							snake_case__      :   Optional[Any]      =    output.images[0, -3:, -3:, -1]

							# make sure that it's equal
							assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()			).max() < 1e-4



			def 				lowerCAmelCase (     self		:						Dict			)      ->      Dict:
							"""simple docstring"""





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







			def 				lowerCAmelCase (     self		:						int			)      ->      Dict:
							"""simple docstring"""





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






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



			def 				lowerCAmelCase (     self		:						Union[str, Any]			)      ->      Union[str, Any]:
							"""simple docstring"""





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



			def 				lowerCAmelCase (     self		:						Tuple    ,			__UpperCamelCase		:						Optional[int]    ,			__UpperCamelCase		:						List[str]="cpu"    ,			__UpperCamelCase		:						Tuple=torch.floataa    ,			__UpperCamelCase		:						List[str]=0			)      ->      Dict:
							"""simple docstring"""





							snake_case__      :   Dict      =    torch.Generator(device=__UpperCamelCase			).manual_seed(__UpperCamelCase			)
							snake_case__      :   int      =    np.random.RandomState(__UpperCamelCase			).standard_normal((1, 4, 64, 64)			)
							snake_case__      :   List[Any]      =    torch.from_numpy(__UpperCamelCase			).to(device=__UpperCamelCase    ,			dtype=__UpperCamelCase			)
							snake_case__      :   int      =    {
							    '''prompt''': '''a photograph of an astronaut riding a horse''',
							    '''latents''': latents,
							    '''generator''': generator,
							    '''num_inference_steps''': 3,
							    '''guidance_scale''': 7.5,
							    '''output_type''': '''numpy''',
							}
							return inputs







			def 				lowerCAmelCase (     self		:						int			)      ->      Dict:
							"""simple docstring"""





							snake_case__      :   Dict      =    DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base'''			)
							pipe.to(__UpperCamelCase			)
							pipe.set_progress_bar_config(disable=__UpperCamelCase			)

							snake_case__      :   Optional[Any]      =    self.get_inputs(__UpperCamelCase			)
							snake_case__      :   Any      =    pipe(**__UpperCamelCase			).images
							snake_case__      :   Optional[int]      =    image[0, -3:, -3:, -1].flatten()

							assert image.shape == (1, 512, 512, 3)
							snake_case__      :   Tuple      =    np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506]			)
							assert np.abs(image_slice - expected_slice			).max() < 7e-3




