


"""simple docstring"""
from abc import ABC, abstractmethod
from typing import List, Optional



class 			_UpperCAmelCase (							__snake_case				):






		'''simple docstring'''

		def __init__(self					):





			'''simple docstring'''

			self.test()



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						List[str]						=				0
			__snake_case	:						Tuple						=				False
			while not completed:
				if counter == 1:
					self.reset()
				__snake_case	:						Dict						=				self.advance()
				if not self.does_advance(a_					):
					raise Exception(
					    '''Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.'''					)

				__snake_case	,							__snake_case	,							__snake_case	:						Tuple						=				self.update(a_					)
				counter += 1

				if counter > 1_00_00:
					raise Exception('''update() does not fulfill the constraint.'''					)

			if self.remaining() != 0:
				raise Exception('''Custom Constraint is not defined correctly.'''					)



		@abstractmethod
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			raise NotImplementedError(
			    f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""					)



		@abstractmethod
		def 				SCREAMING_SNAKE_CASE  (self				,       a_					):





			'''simple docstring'''

			raise NotImplementedError(
			    f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""					)



		@abstractmethod
		def 				SCREAMING_SNAKE_CASE  (self				,       a_					):





			'''simple docstring'''

			raise NotImplementedError(
			    f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""					)



		@abstractmethod
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			raise NotImplementedError(
			    f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""					)



		@abstractmethod
		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			raise NotImplementedError(
			    f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""					)



		@abstractmethod
		def 				SCREAMING_SNAKE_CASE  (self				,       a_=False					):





			'''simple docstring'''

			raise NotImplementedError(
			    f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""					)



class 			_UpperCAmelCase (							__snake_case				):






		'''simple docstring'''

		def __init__(self				,       a_					):





			'''simple docstring'''

			super(a_				,       self					).__init__()

			if not isinstance(a_				,       a_					) or len(a_					) == 0:
				raise ValueError(f"""`token_ids` has to be a non-empty list, but is {token_ids}."""					)
			if any((not isinstance(a_				,       a_					) or token_id < 0) for token_id in token_ids					):
				raise ValueError(f"""Each list in `token_ids` has to be a list of positive integers, but is {token_ids}."""					)

			__snake_case	:						str						=				token_ids

			__snake_case	:						Optional[Any]						=				len(self.token_ids					)
			__snake_case	:						Dict						=				-1  # the index of the currently fulfilled step
			__snake_case	:						List[str]						=				False



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			if self.completed:
				return None
			return self.token_ids[self.fulfilled_idx + 1]



		def 				SCREAMING_SNAKE_CASE  (self				,       a_					):





			'''simple docstring'''

			if not isinstance(a_				,       a_					):
				raise ValueError(f"""`token_id` has to be an `int`, but is {token_id} of type {type(a_					)}"""					)

			if self.completed:
				return False

			return token_id == self.token_ids[self.fulfilled_idx + 1]



		def 				SCREAMING_SNAKE_CASE  (self				,       a_					):





			'''simple docstring'''

			if not isinstance(a_				,       a_					):
				raise ValueError(f"""`token_id` has to be an `int`, but is {token_id} of type {type(a_					)}"""					)

			__snake_case	:						Optional[Any]						=				False
			__snake_case	:						Tuple						=				False
			__snake_case	:						Optional[Any]						=				False

			if self.does_advance(a_					):
				self.fulfilled_idx += 1
				__snake_case	:						Optional[Any]						=				True
				if self.fulfilled_idx == (self.seqlen - 1):
					__snake_case	:						List[str]						=				True
				__snake_case	:						Tuple						=				completed
			else:
				# failed to make progress.
				__snake_case	:						Union[str, Any]						=				True
				self.reset()
			return stepped, completed, reset



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Optional[int]						=				False
			__snake_case	:						Optional[int]						=				0



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			return self.seqlen - (self.fulfilled_idx + 1)



		def 				SCREAMING_SNAKE_CASE  (self				,       a_=False					):





			'''simple docstring'''

			__snake_case	:						Union[str, Any]						=				PhrasalConstraint(self.token_ids					)

			if stateful:
				__snake_case	:						List[Any]						=				self.seqlen
				__snake_case	:						str						=				self.fulfilled_idx
				__snake_case	:						Union[str, Any]						=				self.completed

			return new_constraint



class 			_UpperCAmelCase :






		'''simple docstring'''

		def __init__(self				,       a_				,       a_=True					):





			'''simple docstring'''

			__snake_case	:						List[str]						=				max([len(a_					) for one in nested_token_ids]					)

			__snake_case	:						str						=				{}
			for token_ids in nested_token_ids:
				__snake_case	:						Optional[Any]						=				root
				for tidx, token_id in enumerate(a_					):
					if token_id not in level:
						__snake_case	:						Optional[Any]						=				{}

					__snake_case	:						List[Any]						=				level[token_id]

			if no_subsets and self.has_subsets(a_				,       a_					):
				raise ValueError(
				    '''Each list in `nested_token_ids` can\'t be a complete subset of another list, but is'''
				    f""" {nested_token_ids}."""					)

			__snake_case	:						Any						=				root



		def 				SCREAMING_SNAKE_CASE  (self				,       a_					):





			'''simple docstring'''

			__snake_case	:						int						=				self.trie

			for current_token in current_seq:
				__snake_case	:						str						=				start[current_token]

			__snake_case	:						Tuple						=				list(start.keys()					)

			return next_tokens



		def 				SCREAMING_SNAKE_CASE  (self				,       a_					):





			'''simple docstring'''

			__snake_case	:						int						=				self.next_tokens(a_					)

			return len(a_					) == 0



		def 				SCREAMING_SNAKE_CASE  (self				,       a_					):





			'''simple docstring'''

			__snake_case	:						int						=				list(root.values()					)
			if len(a_					) == 0:
				return 1
			else:
				return sum([self.count_leaves(a_					) for nn in next_nodes]					)



		def 				SCREAMING_SNAKE_CASE  (self				,       a_				,       a_					):





			'''simple docstring'''

			__snake_case	:						Optional[int]						=				self.count_leaves(a_					)
			return len(a_					) != leaf_count



class 			_UpperCAmelCase (							__snake_case				):






		'''simple docstring'''

		def __init__(self				,       a_					):





			'''simple docstring'''

			super(a_				,       self					).__init__()

			if not isinstance(a_				,       a_					) or len(a_					) == 0:
				raise ValueError(f"""`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}."""					)
			if any(not isinstance(a_				,       a_					) for token_ids in nested_token_ids					):
				raise ValueError(f"""`nested_token_ids` has to be a list of lists, but is {nested_token_ids}."""					)
			if any(
			    any((not isinstance(a_				,       a_					) or token_id < 0) for token_id in token_ids					)
			    for token_ids in nested_token_ids					):
				raise ValueError(
				    f"""Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}."""					)

			__snake_case	:						Union[str, Any]						=				DisjunctiveTrie(a_					)
			__snake_case	:						int						=				nested_token_ids

			__snake_case	:						List[Any]						=				self.trie.max_height
			__snake_case	:						Optional[Any]						=				[]
			__snake_case	:						List[Any]						=				False



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Optional[Any]						=				self.trie.next_tokens(self.current_seq					)

			if len(a_					) == 0:
				return None
			else:
				return token_list



		def 				SCREAMING_SNAKE_CASE  (self				,       a_					):





			'''simple docstring'''

			if not isinstance(a_				,       a_					):
				raise ValueError(f"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(a_					)}"""					)

			__snake_case	:						List[Any]						=				self.trie.next_tokens(self.current_seq					)

			return token_id in next_tokens



		def 				SCREAMING_SNAKE_CASE  (self				,       a_					):





			'''simple docstring'''

			if not isinstance(a_				,       a_					):
				raise ValueError(f"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(a_					)}"""					)

			__snake_case	:						Any						=				False
			__snake_case	:						int						=				False
			__snake_case	:						Optional[Any]						=				False

			if self.does_advance(a_					):
				self.current_seq.append(a_					)
				__snake_case	:						List[Any]						=				True
			else:
				__snake_case	:						Optional[Any]						=				True
				self.reset()

			__snake_case	:						Union[str, Any]						=				self.trie.reached_leaf(self.current_seq					)
			__snake_case	:						List[Any]						=				completed

			return stepped, completed, reset



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Optional[int]						=				False
			__snake_case	:						List[str]						=				[]



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			if self.completed:
				# since this can be completed without reaching max height
				return 0
			else:
				return self.seqlen - len(self.current_seq					)



		def 				SCREAMING_SNAKE_CASE  (self				,       a_=False					):





			'''simple docstring'''

			__snake_case	:						Optional[int]						=				DisjunctiveConstraint(self.token_ids					)

			if stateful:
				__snake_case	:						List[str]						=				self.seqlen
				__snake_case	:						Optional[Any]						=				self.current_seq
				__snake_case	:						Optional[int]						=				self.completed

			return new_constraint



class 			_UpperCAmelCase :






		'''simple docstring'''

		def __init__(self				,       a_					):





			'''simple docstring'''

			__snake_case	:						int						=				constraints

			# max # of steps required to fulfill a given constraint
			__snake_case	:						List[str]						=				max([c.seqlen for c in constraints]					)
			__snake_case	:						List[str]						=				len(a_					)
			__snake_case	:						Optional[Any]						=				False

			self.init_state()



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Dict						=				[]
			__snake_case	:						List[str]						=				None
			__snake_case	:						Dict						=				[constraint.copy(stateful=a_					) for constraint in self.constraints]



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Optional[int]						=				0
			if self.inprogress_constraint:
				# extra points for having a constraint mid-fulfilled
				add += self.max_seqlen - self.inprogress_constraint.remaining()

			return (len(self.complete_constraints					) * self.max_seqlen) + add



		def 				SCREAMING_SNAKE_CASE  (self					):





			'''simple docstring'''

			__snake_case	:						Optional[int]						=				[]
			if self.inprogress_constraint is None:
				for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
					__snake_case	:						List[Any]						=				constraint.advance()
					if isinstance(a_				,       a_					):
						token_list.append(a_					)
					elif isinstance(a_				,       a_					):
						token_list.extend(a_					)
			else:
				__snake_case	:						Dict						=				self.inprogress_constraint.advance()
				if isinstance(a_				,       a_					):
					token_list.append(a_					)
				elif isinstance(a_				,       a_					):
					token_list.extend(a_					)

			if len(a_					) == 0:
				return None
			else:
				return token_list



		def 				SCREAMING_SNAKE_CASE  (self				,       a_					):





			'''simple docstring'''

			self.init_state()

			if token_ids is not None:
				for token in token_ids:
					# completes or steps **one** constraint
					__snake_case	,							__snake_case	:						List[str]						=				self.add(a_					)

					# the entire list of constraints are fulfilled
					if self.completed:
						break



		def 				SCREAMING_SNAKE_CASE  (self				,       a_					):





			'''simple docstring'''

			if not isinstance(a_				,       a_					):
				raise ValueError(f"""`token_id` should be an `int`, but is `{token_id}`."""					)

			__snake_case	,							__snake_case	:						Dict						=				False, False

			if self.completed:
				__snake_case	:						Dict						=				True
				__snake_case	:						Optional[Any]						=				False
				return complete, stepped

			if self.inprogress_constraint is not None:
				# In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
				# job, simply update the state

				__snake_case	,							__snake_case	,							__snake_case	:						Tuple						=				self.inprogress_constraint.update(a_					)
				if reset:
					# 1. If the next token breaks the progress, then we must restart.
					#     e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".

					#     But that doesn't mean we self.init_state(), since we only reset the state for this particular
					#     constraint, not the full list of constraints.

					self.pending_constraints.append(self.inprogress_constraint.copy(stateful=a_					)					)
					__snake_case	:						str						=				None

				if complete:
					# 2. If the next token completes the constraint, move it to completed list, set
					#     inprogress to None. If there are no pending constraints either, then this full list of constraints
					#     is complete.

					self.complete_constraints.append(self.inprogress_constraint					)
					__snake_case	:						List[str]						=				None

					if len(self.pending_constraints					) == 0:
						# we're done!
						__snake_case	:						int						=				True

			else:
				# Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
				# of constraints?

				for cidx, pending_constraint in enumerate(self.pending_constraints					):
					if pending_constraint.does_advance(a_					):
						__snake_case	,							__snake_case	,							__snake_case	:						Any						=				pending_constraint.update(a_					)

						if not stepped:
							raise Exception(
							    '''`constraint.update(token_id)` is not yielding incremental progress, '''
							    '''even though `constraint.does_advance(token_id)` is true.'''					)

						if complete:
							self.complete_constraints.append(a_					)
							__snake_case	:						List[Any]						=				None

						if not complete and stepped:
							__snake_case	:						Tuple						=				pending_constraint

						if complete or stepped:
							# If we made any progress at all, then it's at least not a "pending constraint".

							__snake_case	:						str						=				(
							    self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
							)

							if len(self.pending_constraints					) == 0 and self.inprogress_constraint is None:
								# If there's no longer any pending after this and no inprogress either, then we must be
								# complete.

								__snake_case	:						Optional[Any]						=				True

							break  # prevent accidentally stepping through multiple constraints with just one token.

			return complete, stepped



		def 				SCREAMING_SNAKE_CASE  (self				,       a_=True					):





			'''simple docstring'''

			__snake_case	:						List[Any]						=				ConstraintListState(self.constraints					)  # we actually never though self.constraints objects
			# throughout this process. So it's at initialization state.

			if stateful:
				__snake_case	:						List[str]						=				[
				    constraint.copy(stateful=a_					) for constraint in self.complete_constraints
				]
				if self.inprogress_constraint is not None:
					__snake_case	:						int						=				self.inprogress_constraint.copy(stateful=a_					)
				__snake_case	:						Optional[Any]						=				[constraint.copy() for constraint in self.pending_constraints]

			return new_state












"""simple docstring"""





import gc
import random
import unittest

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

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

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






class 					_lowerCAmelCase   (     a  ,   a  ,   unittest.TestCase       ):
       """simple docstring"""




       __magic_name__     :Tuple		  =					StableDiffusionXLImgaImgPipeline
       __magic_name__     :List[Any]		  =					TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""}
       __magic_name__     :Optional[Any]		  =					PipelineTesterMixin.required_optional_params - {"""latents"""}
       __magic_name__     :Optional[Any]		  =					TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
       __magic_name__     :str		  =					IMAGE_TO_IMAGE_IMAGE_PARAMS
       __magic_name__     :Any		  =					IMAGE_TO_IMAGE_IMAGE_PARAMS






       def      snake_case						(    self      ):



         '''simple docstring'''

         torch.manual_seed(0      )
         lowerCAmelCase__			:Optional[Any]											=							UNetaDConditionModel(
             block_out_channels=(3_2, 6_4)    , layers_per_block=2    , sample_size=3_2    , 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=8_0    , cross_attention_dim=6_4    , )
         lowerCAmelCase__			:str											=							EulerDiscreteScheduler(
             beta_start=0.0_00_85    , beta_end=0.0_12    , steps_offset=1    , beta_schedule='scaled_linear'    , timestep_spacing='leading'    , )
         torch.manual_seed(0      )
         lowerCAmelCase__			:str											=							AutoencoderKL(
             block_out_channels=[3_2, 6_4]    , in_channels=3    , out_channels=3    , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']    , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']    , latent_channels=4    , sample_size=1_2_8    , )
         torch.manual_seed(0      )
         lowerCAmelCase__			:str											=							CLIPTextConfig(
             bos_token_id=0    , eos_token_id=2    , hidden_size=3_2    , intermediate_size=3_7    , layer_norm_eps=1E-05    , num_attention_heads=4    , num_hidden_layers=5    , pad_token_id=1    , vocab_size=1_0_0_0    , hidden_act='gelu'    , projection_dim=3_2    , )
         lowerCAmelCase__			:int											=							CLIPTextModel(__UpperCAmelCase      )
         lowerCAmelCase__			:Tuple											=							CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'    , local_files_only=__UpperCAmelCase      )

         lowerCAmelCase__			:Any											=							CLIPTextModelWithProjection(__UpperCAmelCase      )
         lowerCAmelCase__			:Optional[Any]											=							CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'    , local_files_only=__UpperCAmelCase      )

         lowerCAmelCase__			: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      snake_case						(    self    , __UpperCAmelCase    , __UpperCAmelCase=0      ):



         '''simple docstring'''

         lowerCAmelCase__			:Dict											=							floats_tensor((1, 3, 3_2, 3_2)    , rng=random.Random(__UpperCAmelCase      )      ).to(__UpperCAmelCase      )
         lowerCAmelCase__			:Optional[int]											=							image / 2 + 0.5
         if str(__UpperCAmelCase      ).startswith('mps'      ):
           lowerCAmelCase__			:Optional[int]											=							torch.manual_seed(__UpperCAmelCase      )
         else:
           lowerCAmelCase__			:Optional[Any]											=							torch.Generator(device=__UpperCAmelCase      ).manual_seed(__UpperCAmelCase      )
         lowerCAmelCase__			:Dict											=							{
             'prompt': 'A painting of a squirrel eating a burger',
             'image': image,
             'generator': generator,
             'num_inference_steps': 2,
             'guidance_scale': 5.0,
             'output_type': 'numpy',
             'strength': 0.75,
         }
         return inputs






       def      snake_case						(    self      ):



         '''simple docstring'''

         lowerCAmelCase__			:List[Any]											=							'cpu'  # ensure determinism for the device-dependent torch.Generator
         lowerCAmelCase__			:int											=							self.get_dummy_components()
         lowerCAmelCase__			:List[str]											=							StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase      )
         lowerCAmelCase__			:str											=							sd_pipe.to(__UpperCAmelCase      )
         sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase      )

         lowerCAmelCase__			:str											=							self.get_dummy_inputs(__UpperCAmelCase      )
         lowerCAmelCase__			:int											=							sd_pipe(**__UpperCAmelCase      ).images
         lowerCAmelCase__			:int											=							image[0, -3:, -3:, -1]

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

         lowerCAmelCase__			:List[str]											=							np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65]      )

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






       def      snake_case						(    self      ):



         '''simple docstring'''

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






       def      snake_case						(    self      ):



         '''simple docstring'''

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






       def      snake_case						(    self      ):



         '''simple docstring'''

         pass






       def      snake_case						(    self      ):



         '''simple docstring'''

         lowerCAmelCase__			:Tuple											=							self.get_dummy_components()
         lowerCAmelCase__			:str											=							StableDiffusionXLImgaImgPipeline(**__UpperCAmelCase      )
         lowerCAmelCase__			:str											=							sd_pipe.to(__UpperCAmelCase      )
         lowerCAmelCase__			:List[str]											=							sd_pipe.to(__UpperCAmelCase      )
         sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase      )

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

         lowerCAmelCase__			:Optional[Any]											=							sd_pipe(**__UpperCAmelCase      )
         lowerCAmelCase__			:List[Any]											=							output.images[0, -3:, -3:, -1]

         # forward with prompt embeds
         lowerCAmelCase__			:Optional[Any]											=							self.get_dummy_inputs(__UpperCAmelCase      )
         lowerCAmelCase__			:Tuple											=							3 * ['this is a negative prompt']
         lowerCAmelCase__			:str											=							3 * [inputs.pop('prompt'      )]

         (
             (
             lowerCAmelCase__
         )							,				(
             lowerCAmelCase__
         )							,				(
             lowerCAmelCase__
         )							,				(
             lowerCAmelCase__
         )							,				
         )			:List[str]											=							sd_pipe.encode_prompt(__UpperCAmelCase    , negative_prompt=__UpperCAmelCase      )

         lowerCAmelCase__			:str											=							sd_pipe(
             **__UpperCAmelCase    , prompt_embeds=__UpperCAmelCase    , negative_prompt_embeds=__UpperCAmelCase    , pooled_prompt_embeds=__UpperCAmelCase    , negative_pooled_prompt_embeds=__UpperCAmelCase    , )
         lowerCAmelCase__			: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






@slow
@require_torch_gpu
class 					_lowerCAmelCase   (     unittest.TestCase       ):
       """simple docstring"""




       def      snake_case						(    self      ):



         '''simple docstring'''

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






       def      snake_case						(    self    , __UpperCAmelCase    , __UpperCAmelCase="cpu"    , __UpperCAmelCase=torch.floataa    , __UpperCAmelCase=0      ):



         '''simple docstring'''

         lowerCAmelCase__			:Any											=							torch.Generator(device=__UpperCAmelCase      ).manual_seed(__UpperCAmelCase      )
         lowerCAmelCase__			:Dict											=							np.random.RandomState(__UpperCAmelCase      ).standard_normal((1, 4, 6_4, 6_4)      )
         lowerCAmelCase__			:Optional[int]											=							torch.from_numpy(__UpperCAmelCase      ).to(device=__UpperCAmelCase    , dtype=__UpperCAmelCase      )
         lowerCAmelCase__			: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      snake_case						(    self      ):



         '''simple docstring'''

         lowerCAmelCase__			:List[Any]											=							DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base'      )
         pipe.to(__UpperCAmelCase      )
         pipe.set_progress_bar_config(disable=__UpperCAmelCase      )

         lowerCAmelCase__			:Tuple											=							self.get_inputs(__UpperCAmelCase      )
         lowerCAmelCase__			:int											=							pipe(**__UpperCAmelCase      ).images
         lowerCAmelCase__			:Union[str, Any]											=							image[0, -3:, -3:, -1].flatten()

         assert image.shape == (1, 5_1_2, 5_1_2, 3)
         lowerCAmelCase__			:List[str]											=							np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06]      )
         assert np.abs(image_slice - expected_slice      ).max() < 7E-3
