




'''simple docstring'''



from abc import ABC, abstractmethod
from typing import List, Optional






class 							_a				(			SCREAMING_SNAKE_CASE ):





       '''simple docstring'''






       def __init__(      self  ):







             '''simple docstring'''







             self.test()







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						0
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						False
             while not completed:
                   if counter == 1:
                         self.reset()
                   SCREAMING_SNAKE_CASE   :      str    					=						self.advance()
                   if not self.does_advance(A  ):
                         raise Exception(
                             'Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.'  )

                   SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						self.update(A  )
                   counter += 1

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

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







       @abstractmethod
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







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







       @abstractmethod
       def        UpperCamelCase_							(      self,							A  ):







             '''simple docstring'''







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







       @abstractmethod
       def        UpperCamelCase_							(      self,							A  ):







             '''simple docstring'''







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







       @abstractmethod
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







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







       @abstractmethod
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







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







       @abstractmethod
       def        UpperCamelCase_							(      self,							A=False  ):







             '''simple docstring'''







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






class 							_a				(			SCREAMING_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}."  )

             SCREAMING_SNAKE_CASE   :      Tuple    					=						token_ids

             SCREAMING_SNAKE_CASE   :      Tuple    					=						len(self.token_ids  )
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						-1  # the index of the currently fulfilled step
             SCREAMING_SNAKE_CASE   :      Any    					=						False







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







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







       def        UpperCamelCase_							(      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        UpperCamelCase_							(      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  )}"  )

             SCREAMING_SNAKE_CASE   :      Dict    					=						False
             SCREAMING_SNAKE_CASE   :      str    					=						False
             SCREAMING_SNAKE_CASE   :      int    					=						False

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







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						False
             SCREAMING_SNAKE_CASE   :      Dict    					=						0







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







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







       def        UpperCamelCase_							(      self,							A=False  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      str    					=						PhrasalConstraint(self.token_ids  )

             if stateful:
                   SCREAMING_SNAKE_CASE   :      str    					=						self.seqlen
                   SCREAMING_SNAKE_CASE   :      List[Any]    					=						self.fulfilled_idx
                   SCREAMING_SNAKE_CASE   :      List[Any]    					=						self.completed

             return new_constraint






class 							_a				:





       '''simple docstring'''






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







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Any    					=						max([len(A  ) for one in nested_token_ids]  )

             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						{}
             for token_ids in nested_token_ids:
                   SCREAMING_SNAKE_CASE   :      Dict    					=						root
                   for tidx, token_id in enumerate(A  ):
                         if token_id not in level:
                               SCREAMING_SNAKE_CASE   :      Dict    					=						{}

                         SCREAMING_SNAKE_CASE   :      Optional[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}."  )

             SCREAMING_SNAKE_CASE   :      Any    					=						root







       def        UpperCamelCase_							(      self,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[Any]    					=						self.trie

             for current_token in current_seq:
                   SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						start[current_token]

             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						list(start.keys()  )

             return next_tokens







       def        UpperCamelCase_							(      self,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[str]    					=						self.next_tokens(A  )

             return len(A  ) == 0







       def        UpperCamelCase_							(      self,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[Any]    					=						list(root.values()  )
             if len(A  ) == 0:
                   return 1
             else:
                   return sum([self.count_leaves(A  ) for nn in next_nodes]  )







       def        UpperCamelCase_							(      self,							A,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      str    					=						self.count_leaves(A  )
             return len(A  ) != leaf_count






class 							_a				(			SCREAMING_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}."  )

             SCREAMING_SNAKE_CASE   :      Dict    					=						DisjunctiveTrie(A  )
             SCREAMING_SNAKE_CASE   :      int    					=						nested_token_ids

             SCREAMING_SNAKE_CASE   :      int    					=						self.trie.max_height
             SCREAMING_SNAKE_CASE   :      str    					=						[]
             SCREAMING_SNAKE_CASE   :      List[str]    					=						False







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      str    					=						self.trie.next_tokens(self.current_seq  )

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







       def        UpperCamelCase_							(      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  )}"  )

             SCREAMING_SNAKE_CASE   :      List[str]    					=						self.trie.next_tokens(self.current_seq  )

             return token_id in next_tokens







       def        UpperCamelCase_							(      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  )}"  )

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

             if self.does_advance(A  ):
                   self.current_seq.append(A  )
                   SCREAMING_SNAKE_CASE   :      Tuple    					=						True
             else:
                   SCREAMING_SNAKE_CASE   :      Dict    					=						True
                   self.reset()

             SCREAMING_SNAKE_CASE   :      int    					=						self.trie.reached_leaf(self.current_seq  )
             SCREAMING_SNAKE_CASE   :      List[str]    					=						completed

             return stepped, completed, reset







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







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







       def        UpperCamelCase_							(      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        UpperCamelCase_							(      self,							A=False  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      str    					=						DisjunctiveConstraint(self.token_ids  )

             if stateful:
                   SCREAMING_SNAKE_CASE   :      Tuple    					=						self.seqlen
                   SCREAMING_SNAKE_CASE   :      Dict    					=						self.current_seq
                   SCREAMING_SNAKE_CASE   :      str    					=						self.completed

             return new_constraint






class 							_a				:





       '''simple docstring'''






       def __init__(      self,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      str    					=						constraints

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

             self.init_state()







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[Any]    					=						[]
             SCREAMING_SNAKE_CASE   :      Any    					=						None
             SCREAMING_SNAKE_CASE   :      str    					=						[constraint.copy(stateful=A  ) for constraint in self.constraints]







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[Any]    					=						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        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      str    					=						[]
             if self.inprogress_constraint is None:
                   for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
                         SCREAMING_SNAKE_CASE   :      List[str]    					=						constraint.advance()
                         if isinstance(A,							A  ):
                               token_list.append(A  )
                         elif isinstance(A,							A  ):
                               token_list.extend(A  )
             else:
                   SCREAMING_SNAKE_CASE   :      List[Any]    					=						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        UpperCamelCase_							(      self,							A  ):







             '''simple docstring'''







             self.init_state()

             if token_ids is not None:
                   for token in token_ids:
                         # completes or steps **one** constraint
                         SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						self.add(A  )

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







       def        UpperCamelCase_							(      self,							A  ):







             '''simple docstring'''







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

             SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      List[Any]    					=						False, False

             if self.completed:
                   SCREAMING_SNAKE_CASE   :      Tuple    					=						True
                   SCREAMING_SNAKE_CASE   :      Dict    					=						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

                   SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      Optional[int]    					=						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  )  )
                         SCREAMING_SNAKE_CASE   :      Dict    					=						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  )
                         SCREAMING_SNAKE_CASE   :      Any    					=						None

                         if len(self.pending_constraints  ) == 0:
                               # we're done!
                               SCREAMING_SNAKE_CASE   :      Optional[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  ):
                               SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      Dict    					=						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  )
                                     SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						None

                               if not complete and stepped:
                                     SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						pending_constraint

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

                                     SCREAMING_SNAKE_CASE   :      Any    					=						(
                                         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.

                                           SCREAMING_SNAKE_CASE   :      Dict    					=						True

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

             return complete, stepped







       def        UpperCamelCase_							(      self,							A=True  ):







             '''simple docstring'''







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

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

             return new_state







import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionAttendAndExcitePipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_numpy, skip_mps, slow
from diffusers.utils.testing_utils import 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 PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


a_      :      Optional[int]    =     False
@skip_mps
class    __UpperCamelCase			(       _lowercase	,	_lowercase	,	_lowercase	,	unittest.TestCase				):

 """simple docstring"""



 _lowercase   :    List[Any]      						=					StableDiffusionAttendAndExcitePipeline
 _lowercase   :    str      						=					False
 _lowercase   :    List[str]      						=					TEXT_TO_IMAGE_PARAMS
 _lowercase   :    Optional[int]      						=					TEXT_TO_IMAGE_BATCH_PARAMS.union({'''token_indices'''}				)
 _lowercase   :    Union[str, Any]      						=					TEXT_TO_IMAGE_IMAGE_PARAMS
 _lowercase   :    List[Any]      						=					TEXT_TO_IMAGE_IMAGE_PARAMS

 @classmethod
 def 						_UpperCAmelCase       (	cls      ) ->			Dict:
  super().setUpClass()
  torch.use_deterministic_algorithms(SCREAMING_SNAKE_CASE      )

 @classmethod
 def 						_UpperCAmelCase       (	cls      ) ->			Tuple:
  super().tearDownClass()
  torch.use_deterministic_algorithms(SCREAMING_SNAKE_CASE      )

 def 						_UpperCAmelCase       (	self      ) ->			List[Any]:
  torch.manual_seed(0      )
  a__												= UNetaDConditionModel(
      block_out_channels=(3_2, 6_4)		,				layers_per_block=1		,				sample_size=3_2		,				in_channels=4		,				out_channels=4		,				down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')		,				up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')		,				cross_attention_dim=3_2		,				attention_head_dim=(2, 4)		,				use_linear_projection=SCREAMING_SNAKE_CASE		,				)
  a__												= DDIMScheduler(
      beta_start=0.0_00_85		,				beta_end=0.0_12		,				beta_schedule='''scaled_linear'''		,				clip_sample=SCREAMING_SNAKE_CASE		,				set_alpha_to_one=SCREAMING_SNAKE_CASE		,				)
  torch.manual_seed(0      )
  a__												= 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      )
  a__												= CLIPTextConfig(
      bos_token_id=0		,				eos_token_id=2		,				hidden_size=3_2		,				intermediate_size=3_7		,				layer_norm_eps=1e-0_5		,				num_attention_heads=4		,				num_hidden_layers=5		,				pad_token_id=1		,				vocab_size=1_0_0_0		,				hidden_act='''gelu'''		,				projection_dim=5_1_2		,				)
  a__												= CLIPTextModel(SCREAMING_SNAKE_CASE      )
  a__												= CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''      )

  a__												= {
      '''unet''': unet,
      '''scheduler''': scheduler,
      '''vae''': vae,
      '''text_encoder''': text_encoder,
      '''tokenizer''': tokenizer,
      '''safety_checker''': None,
      '''feature_extractor''': None,
  }

  return components

 def 						_UpperCAmelCase       (	self		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE=0      ) ->			Dict:
  if str(SCREAMING_SNAKE_CASE      ).startswith('''mps'''      ):
   a__												= torch.manual_seed(SCREAMING_SNAKE_CASE      )
  else:
   a__												= torch.Generator(device=SCREAMING_SNAKE_CASE      ).manual_seed(SCREAMING_SNAKE_CASE      )
  a__												= a__												= {
      '''prompt''': '''a cat and a frog''',
      '''token_indices''': [2, 5],
      '''generator''': generator,
      '''num_inference_steps''': 1,
      '''guidance_scale''': 6.0,
      '''output_type''': '''numpy''',
      '''max_iter_to_alter''': 2,
      '''thresholds''': {0: 0.7},
  }
  return inputs

 def 						_UpperCAmelCase       (	self      ) ->			str:
  a__												= '''cpu'''

  a__												= self.get_dummy_components()
  a__												= self.pipeline_class(**SCREAMING_SNAKE_CASE      )
  pipe.to(SCREAMING_SNAKE_CASE      )
  pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE      )

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

  self.assertEqual(image.shape		,				(1, 6_4, 6_4, 3)      )
  a__												= np.array(
      [0.63_90_53_64, 0.62_89_73_07, 0.48_59_90_17, 0.5_13_36_24, 0.5_55_00_48, 0.45_76_95_16, 0.50_32_69_73, 0.5_02_31_39, 0.45_38_44_96]      )
  a__												= np.abs(image_slice.flatten() - expected_slice      ).max()
  self.assertLessEqual(SCREAMING_SNAKE_CASE		,				1e-3      )

 def 						_UpperCAmelCase       (	self      ) ->			str:
  super().test_cpu_offload_forward_pass(expected_max_diff=5e-4      )

 def 						_UpperCAmelCase       (	self      ) ->			List[Any]:
  # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
  self._test_inference_batch_consistent(batch_sizes=[1, 2]      )

 def 						_UpperCAmelCase       (	self      ) ->			List[Any]:
  self._test_inference_batch_single_identical(batch_size=2		,				expected_max_diff=7e-4      )

 def 						_UpperCAmelCase       (	self      ) ->			int:
  super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3      )

 def 						_UpperCAmelCase       (	self      ) ->			Optional[Any]:
  super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5e-4      )

 def 						_UpperCAmelCase       (	self      ) ->			Dict:
  super().test_save_load_local(expected_max_difference=5e-4      )



 def 						_UpperCAmelCase       (	self      ) ->			str:
  super().test_save_load_optional_components(expected_max_difference=4e-4      )





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

 """simple docstring"""



 @classmethod
 def 						_UpperCAmelCase       (	cls      ) ->			Optional[int]:
  super().setUpClass()
  torch.use_deterministic_algorithms(SCREAMING_SNAKE_CASE      )

 @classmethod
 def 						_UpperCAmelCase       (	cls      ) ->			str:
  super().tearDownClass()
  torch.use_deterministic_algorithms(SCREAMING_SNAKE_CASE      )

 def 						_UpperCAmelCase       (	self      ) ->			List[str]:
  super().tearDown()
  gc.collect()
  torch.cuda.empty_cache()



 def 						_UpperCAmelCase       (	self      ) ->			str:
  a__												= torch.manual_seed(5_1      )

  a__												= StableDiffusionAttendAndExcitePipeline.from_pretrained(
      '''CompVis/stable-diffusion-v1-4'''		,				safety_checker=SCREAMING_SNAKE_CASE		,				torch_dtype=torch.floataa      )
  pipe.to('''cuda'''      )

  a__												= '''a painting of an elephant with glasses'''
  a__												= [5, 7]

  a__												= pipe(
      prompt=SCREAMING_SNAKE_CASE		,				token_indices=SCREAMING_SNAKE_CASE		,				guidance_scale=7.5		,				generator=SCREAMING_SNAKE_CASE		,				num_inference_steps=5		,				max_iter_to_alter=5		,				output_type='''numpy'''		,				).images[0]

  a__												= load_numpy(
      '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy'''      )
  assert np.abs((expected_image - image).max()      ) < 5e-1





