



'''simple docstring'''






import json
import os
import pickle
import shutil
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
from datasets import Dataset

from transformers import is_faiss_available
from transformers.models.bart.configuration_bart import BartConfig
from transformers.models.bart.tokenization_bart import BartTokenizer
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
from transformers.models.dpr.configuration_dpr import DPRConfig
from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer
from transformers.models.rag.configuration_rag import RagConfig
from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch


if is_faiss_available():
     import faiss

@require_faiss
class 							a__(      lowerCamelCase__			):







    def     lowercase_ (   self				:						Tuple			):
      a		:      List[str]       =  tempfile.mkdtemp()
      a		:      List[Any]       =  8

      # DPR tok
      a		:      Dict       =  [
          '[UNK]',
          '[CLS]',
          '[SEP]',
          '[PAD]',
          '[MASK]',
          'want',
          '##want',
          '##ed',
          'wa',
          'un',
          'runn',
          '##ing',
          ',',
          'low',
          'lowest',
      ]
      a		:      Tuple       =  os.path.join(self.tmpdirname		,    'dpr_tokenizer'			)
      os.makedirs(__snake_case		,    exist_ok=__snake_case			)
      a		:      str       =  os.path.join(__snake_case		,    DPR_VOCAB_FILES_NAMES['vocab_file']			)
      with open(self.vocab_file		,    'w'		,    encoding='utf-8'			) as vocab_writer:
        vocab_writer.write(''.join([x + '\n' for x in vocab_tokens]			)			)

      # BART tok
      a		:      List[Any]       =  [
          'l',
          'o',
          'w',
          'e',
          'r',
          's',
          't',
          'i',
          'd',
          'n',
          '\u0120',
          '\u0120l',
          '\u0120n',
          '\u0120lo',
          '\u0120low',
          'er',
          '\u0120lowest',
          '\u0120newer',
          '\u0120wider',
          '<unk>',
      ]
      a		:      Dict       =  dict(zip(__snake_case		,    range(len(__snake_case			)			)			)			)
      a		:      Any       =  ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', '']
      a		:      Any       =  {'unk_token': '<unk>'}

      a		:      Dict       =  os.path.join(self.tmpdirname		,    'bart_tokenizer'			)
      os.makedirs(__snake_case		,    exist_ok=__snake_case			)
      a		:      Dict       =  os.path.join(__snake_case		,    BART_VOCAB_FILES_NAMES['vocab_file']			)
      a		:      Tuple       =  os.path.join(__snake_case		,    BART_VOCAB_FILES_NAMES['merges_file']			)
      with open(self.vocab_file		,    'w'		,    encoding='utf-8'			) as fp:
        fp.write(json.dumps(__snake_case			) + '\n'			)
      with open(self.merges_file		,    'w'		,    encoding='utf-8'			) as fp:
        fp.write('\n'.join(__snake_case			)			)







    def     lowercase_ (   self				:						str			):
      return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname		,    'dpr_tokenizer'			)			)







    def     lowercase_ (   self				:						List[str]			):
      return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname		,    'dpr_tokenizer'			)			)







    def     lowercase_ (   self				:						List[Any]			):
      return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname		,    'bart_tokenizer'			)			)







    def     lowercase_ (   self				:						str			):
      shutil.rmtree(self.tmpdirname			)







    def     lowercase_ (   self				:						List[Any]			):
      a		:      Optional[Any]       =  Dataset.from_dict(
          {
              'id': ['0', '1'],
              'text': ['foo', 'bar'],
              'title': ['Foo', 'Bar'],
              'embeddings': [np.ones(self.retrieval_vector_size			), 2 * np.ones(self.retrieval_vector_size			)],
          }			)
      dataset.add_faiss_index('embeddings'		,    string_factory='Flat'		,    metric_type=faiss.METRIC_INNER_PRODUCT			)
      return dataset







    def     lowercase_ (   self				:						Dict			):
      a		:      Dict       =  self.get_dummy_dataset()
      a		:      List[Any]       =  RagConfig(
          retrieval_vector_size=self.retrieval_vector_size		,    question_encoder=DPRConfig().to_dict()		,    generator=BartConfig().to_dict()		,    )
      with patch('transformers.models.rag.retrieval_rag.load_dataset'			) as mock_load_dataset:
        a		:      int       =  dataset
        a		:      Dict       =  RagRetriever(
            __snake_case		,    question_encoder_tokenizer=self.get_dpr_tokenizer()		,    generator_tokenizer=self.get_bart_tokenizer()		,    )
      return retriever







    def     lowercase_ (   self				:						List[Any]		,    __snake_case				:						bool			):
      a		:      Optional[Any]       =  self.get_dummy_dataset()
      a		:      Any       =  RagConfig(
          retrieval_vector_size=self.retrieval_vector_size		,    question_encoder=DPRConfig().to_dict()		,    generator=BartConfig().to_dict()		,    index_name='custom'		,    )
      if from_disk:
        a		:      str       =  os.path.join(self.tmpdirname		,    'dataset'			)
        a		:      Any       =  os.path.join(self.tmpdirname		,    'index.faiss'			)
        dataset.get_index('embeddings'			).save(os.path.join(self.tmpdirname		,    'index.faiss'			)			)
        dataset.drop_index('embeddings'			)
        dataset.save_to_disk(os.path.join(self.tmpdirname		,    'dataset'			)			)
        del dataset
        a		:      Optional[Any]       =  RagRetriever(
            __snake_case		,    question_encoder_tokenizer=self.get_dpr_tokenizer()		,    generator_tokenizer=self.get_bart_tokenizer()		,    )
      else:
        a		:      Optional[Any]       =  RagRetriever(
            __snake_case		,    question_encoder_tokenizer=self.get_dpr_tokenizer()		,    generator_tokenizer=self.get_bart_tokenizer()		,    index=CustomHFIndex(config.retrieval_vector_size		,    __snake_case			)		,    )
      return retriever







    def     lowercase_ (   self				:						List[Any]			):
      a		:      List[str]       =  Dataset.from_dict(
          {
              'id': ['0', '1'],
              'text': ['foo', 'bar'],
              'title': ['Foo', 'Bar'],
              'embeddings': [np.ones(self.retrieval_vector_size + 1			), 2 * np.ones(self.retrieval_vector_size + 1			)],
          }			)
      dataset.add_faiss_index('embeddings'		,    string_factory='Flat'		,    metric_type=faiss.METRIC_INNER_PRODUCT			)

      a		:      Optional[Any]       =  os.path.join(self.tmpdirname		,    'hf_bert_base.hnswSQ8_correct_phi_128.c_index'			)
      dataset.save_faiss_index('embeddings'		,    index_file_name + '.index.dpr'			)
      pickle.dump(dataset['id']		,    open(index_file_name + '.index_meta.dpr'		,    'wb'			)			)

      a		:      Any       =  os.path.join(self.tmpdirname		,    'psgs_w100.tsv.pkl'			)
      a		:      List[Any]       =  {sample['id']: [sample['text'], sample['title']] for sample in dataset}
      pickle.dump(__snake_case		,    open(__snake_case		,    'wb'			)			)

      a		:      Tuple       =  RagConfig(
          retrieval_vector_size=self.retrieval_vector_size		,    question_encoder=DPRConfig().to_dict()		,    generator=BartConfig().to_dict()		,    index_name='legacy'		,    index_path=self.tmpdirname		,    )
      a		:      str       =  RagRetriever(
          __snake_case		,    question_encoder_tokenizer=self.get_dpr_tokenizer()		,    generator_tokenizer=self.get_bart_tokenizer()			)
      return retriever







    def     lowercase_ (   self				:						str			):
      a		:      Dict       =  1
      a		:      Tuple       =  self.get_dummy_canonical_hf_index_retriever()
      a		:      int       =  np.array(
          [np.ones(self.retrieval_vector_size			), -np.ones(self.retrieval_vector_size			)]		,    dtype=np.floataa			)
      a     ,			a     ,			a		:      int       =  retriever.retrieve(__snake_case		,    n_docs=__snake_case			)
      self.assertEqual(retrieved_doc_embeds.shape		,    (2, n_docs, self.retrieval_vector_size)			)
      self.assertEqual(len(__snake_case			)		,    2			)
      self.assertEqual(sorted(doc_dicts[0]			)		,    ['embeddings', 'id', 'text', 'title']			)
      self.assertEqual(len(doc_dicts[0]['id']			)		,    __snake_case			)
      self.assertEqual(doc_dicts[0]['id'][0]		,    '1'			)  # max inner product is reached with second doc
      self.assertEqual(doc_dicts[1]['id'][0]		,    '0'			)  # max inner product is reached with first doc
      self.assertListEqual(doc_ids.tolist()		,    [[1], [0]]			)







    def     lowercase_ (   self				:						str			):
      a		:      List[str]       =  self.get_dummy_canonical_hf_index_retriever()
      with tempfile.TemporaryDirectory() as tmp_dirname:
        with patch('transformers.models.rag.retrieval_rag.load_dataset'			) as mock_load_dataset:
          a		:      Optional[int]       =  self.get_dummy_dataset()
          retriever.save_pretrained(__snake_case			)
          a		:      Any       =  RagRetriever.from_pretrained(__snake_case			)
          self.assertIsInstance(__snake_case		,    __snake_case			)
          a		:      str       =  np.array(
              [np.ones(self.retrieval_vector_size			), -np.ones(self.retrieval_vector_size			)]		,    dtype=np.floataa			)
          a		:      int       =  retriever.retrieve(__snake_case		,    n_docs=1			)
          self.assertTrue(out is not None			)







    def     lowercase_ (   self				:						int			):
      a		:      Tuple       =  1
      a		:      Tuple       =  self.get_dummy_custom_hf_index_retriever(from_disk=__snake_case			)
      a		:      List[Any]       =  np.array(
          [np.ones(self.retrieval_vector_size			), -np.ones(self.retrieval_vector_size			)]		,    dtype=np.floataa			)
      a     ,			a     ,			a		:      Union[str, Any]       =  retriever.retrieve(__snake_case		,    n_docs=__snake_case			)
      self.assertEqual(retrieved_doc_embeds.shape		,    (2, n_docs, self.retrieval_vector_size)			)
      self.assertEqual(len(__snake_case			)		,    2			)
      self.assertEqual(sorted(doc_dicts[0]			)		,    ['embeddings', 'id', 'text', 'title']			)
      self.assertEqual(len(doc_dicts[0]['id']			)		,    __snake_case			)
      self.assertEqual(doc_dicts[0]['id'][0]		,    '1'			)  # max inner product is reached with second doc
      self.assertEqual(doc_dicts[1]['id'][0]		,    '0'			)  # max inner product is reached with first doc
      self.assertListEqual(doc_ids.tolist()		,    [[1], [0]]			)







    def     lowercase_ (   self				:						str			):
      a		:      Optional[Any]       =  self.get_dummy_custom_hf_index_retriever(from_disk=__snake_case			)
      with tempfile.TemporaryDirectory() as tmp_dirname:
        retriever.save_pretrained(__snake_case			)
        a		:      Any       =  RagRetriever.from_pretrained(__snake_case			)
        self.assertIsInstance(__snake_case		,    __snake_case			)
        a		:      List[str]       =  np.array(
            [np.ones(self.retrieval_vector_size			), -np.ones(self.retrieval_vector_size			)]		,    dtype=np.floataa			)
        a		:      Union[str, Any]       =  retriever.retrieve(__snake_case		,    n_docs=1			)
        self.assertTrue(out is not None			)







    def     lowercase_ (   self				:						Dict			):
      a		:      Optional[Any]       =  1
      a		:      Optional[Any]       =  self.get_dummy_custom_hf_index_retriever(from_disk=__snake_case			)
      a		:      Optional[Any]       =  np.array(
          [np.ones(self.retrieval_vector_size			), -np.ones(self.retrieval_vector_size			)]		,    dtype=np.floataa			)
      a     ,			a     ,			a		:      Tuple       =  retriever.retrieve(__snake_case		,    n_docs=__snake_case			)
      self.assertEqual(retrieved_doc_embeds.shape		,    (2, n_docs, self.retrieval_vector_size)			)
      self.assertEqual(len(__snake_case			)		,    2			)
      self.assertEqual(sorted(doc_dicts[0]			)		,    ['embeddings', 'id', 'text', 'title']			)
      self.assertEqual(len(doc_dicts[0]['id']			)		,    __snake_case			)
      self.assertEqual(doc_dicts[0]['id'][0]		,    '1'			)  # max inner product is reached with second doc
      self.assertEqual(doc_dicts[1]['id'][0]		,    '0'			)  # max inner product is reached with first doc
      self.assertListEqual(doc_ids.tolist()		,    [[1], [0]]			)







    def     lowercase_ (   self				:						List[Any]			):
      a		:      List[Any]       =  self.get_dummy_custom_hf_index_retriever(from_disk=__snake_case			)
      with tempfile.TemporaryDirectory() as tmp_dirname:
        retriever.save_pretrained(__snake_case			)
        a		:      Tuple       =  RagRetriever.from_pretrained(__snake_case			)
        self.assertIsInstance(__snake_case		,    __snake_case			)
        a		:      Optional[int]       =  np.array(
            [np.ones(self.retrieval_vector_size			), -np.ones(self.retrieval_vector_size			)]		,    dtype=np.floataa			)
        a		:      Dict       =  retriever.retrieve(__snake_case		,    n_docs=1			)
        self.assertTrue(out is not None			)







    def     lowercase_ (   self				:						Optional[int]			):
      a		:      Dict       =  1
      a		:      Any       =  self.get_dummy_legacy_index_retriever()
      a		:      List[Any]       =  np.array(
          [np.ones(self.retrieval_vector_size			), -np.ones(self.retrieval_vector_size			)]		,    dtype=np.floataa			)
      a     ,			a     ,			a		:      List[Any]       =  retriever.retrieve(__snake_case		,    n_docs=__snake_case			)
      self.assertEqual(retrieved_doc_embeds.shape		,    (2, n_docs, self.retrieval_vector_size)			)
      self.assertEqual(len(__snake_case			)		,    2			)
      self.assertEqual(sorted(doc_dicts[0]			)		,    ['text', 'title']			)
      self.assertEqual(len(doc_dicts[0]['text']			)		,    __snake_case			)
      self.assertEqual(doc_dicts[0]['text'][0]		,    'bar'			)  # max inner product is reached with second doc
      self.assertEqual(doc_dicts[1]['text'][0]		,    'foo'			)  # max inner product is reached with first doc
      self.assertListEqual(doc_ids.tolist()		,    [[1], [0]]			)







    def     lowercase_ (   self				:						Optional[Any]			):
      a		:      int       =  self.get_dummy_legacy_index_retriever()
      with tempfile.TemporaryDirectory() as tmp_dirname:
        retriever.save_pretrained(__snake_case			)
        a		:      Optional[int]       =  RagRetriever.from_pretrained(__snake_case			)
        self.assertIsInstance(__snake_case		,    __snake_case			)
        a		:      Tuple       =  np.array(
            [np.ones(self.retrieval_vector_size			), -np.ones(self.retrieval_vector_size			)]		,    dtype=np.floataa			)
        a		:      List[str]       =  retriever.retrieve(__snake_case		,    n_docs=1			)
        self.assertTrue(out is not None			)







    @require_torch
    @require_tokenizers
    @require_sentencepiece
    def     lowercase_ (   self				:						int			):
      import torch

      a		:      str       =  1
      a		:      Tuple       =  self.get_dummy_canonical_hf_index_retriever()
      a		:      Any       =  [[5, 7], [10, 11]]
      a		:      Optional[Any]       =  np.array(
          [np.ones(self.retrieval_vector_size			), -np.ones(self.retrieval_vector_size			)]		,    dtype=np.floataa			)
      a		:      Tuple       =  retriever(__snake_case		,    __snake_case		,    prefix=retriever.config.generator.prefix		,    n_docs=__snake_case			)
      a     ,			a     ,			a		:      Any       =  (
          out['context_input_ids'],
          out['context_attention_mask'],
          out['retrieved_doc_embeds'],
      )
      self.assertEqual(retrieved_doc_embeds.shape		,    (2, n_docs, self.retrieval_vector_size)			)
      self.assertIsInstance(__snake_case		,    __snake_case			)
      self.assertIsInstance(__snake_case		,    __snake_case			)
      self.assertIsInstance(__snake_case		,    np.ndarray			)

      a		:      List[Any]       =  retriever(
          __snake_case		,    __snake_case		,    prefix=retriever.config.generator.prefix		,    n_docs=__snake_case		,    return_tensors='pt'		,    )
      a     ,			a     ,			a     ,			a		:      Optional[int]       =  (  # noqa: F841
          out['context_input_ids'],
          out['context_attention_mask'],
          out['retrieved_doc_embeds'],
          out['doc_ids'],
      )
      self.assertEqual(retrieved_doc_embeds.shape		,    (2, n_docs, self.retrieval_vector_size)			)
      self.assertIsInstance(__snake_case		,    torch.Tensor			)
      self.assertIsInstance(__snake_case		,    torch.Tensor			)
      self.assertIsInstance(__snake_case		,    torch.Tensor			)







    @require_torch
    @require_tokenizers
    @require_sentencepiece
    def     lowercase_ (   self				:						Optional[int]			):
      a		:      Dict       =  self.get_dpr_ctx_encoder_tokenizer()
      a		:      List[str]       =  1
      a		:      Tuple       =  self.get_dummy_custom_hf_index_retriever(from_disk=__snake_case			)
      retriever.set_ctx_encoder_tokenizer(__snake_case			)

      a		:      Dict       =  [[5, 7], [10, 11]]
      a		:      Optional[int]       =  np.array(
          [np.ones(self.retrieval_vector_size			), -np.ones(self.retrieval_vector_size			)]		,    dtype=np.floataa			)
      a		:      Any       =  retriever(__snake_case		,    __snake_case		,    prefix=retriever.config.generator.prefix		,    n_docs=__snake_case			)

      self.assertEqual(
          len(__snake_case			)		,    6			)  # check whether the retriever output consist of 6 attributes including tokenized docs
      self.assertEqual(
          all(k in out for k in ('tokenized_doc_ids', 'tokenized_doc_attention_mask')			)		,    __snake_case			)  # check for doc token related keys in dictionary.




'''simple docstring'''






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


lowerCAmelCase:      Any		 =		False

@skip_mps
class 							a__(      lowerCamelCase__	,				lowerCamelCase__	,				lowerCamelCase__	,				unittest.TestCase			):
    lowercase__				=					StableDiffusionAttendAndExcitePipeline
    lowercase__				=					False
    lowercase__				=					TEXT_TO_IMAGE_PARAMS
    lowercase__				=					TEXT_TO_IMAGE_BATCH_PARAMS.union({"""token_indices"""}			)
    lowercase__				=					TEXT_TO_IMAGE_IMAGE_PARAMS
    lowercase__				=					TEXT_TO_IMAGE_IMAGE_PARAMS







    @classmethod
    def     lowercase_ (   cls				:						Union[str, Any]			):
      super().setUpClass()
      torch.use_deterministic_algorithms(__snake_case			)







    @classmethod
    def     lowercase_ (   cls				:						Optional[Any]			):
      super().tearDownClass()
      torch.use_deterministic_algorithms(__snake_case			)







    def     lowercase_ (   self				:						List[Any]			):
      torch.manual_seed(0			)
      a		:      List[Any]       =  UNetaDConditionModel(
          block_out_channels=(32, 64)		,    layers_per_block=1		,    sample_size=32		,    in_channels=4		,    out_channels=4		,    down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')		,    up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')		,    cross_attention_dim=32		,    attention_head_dim=(2, 4)		,    use_linear_projection=__snake_case		,    )
      a		:      Optional[int]       =  DDIMScheduler(
          beta_start=0.00085		,    beta_end=0.012		,    beta_schedule='scaled_linear'		,    clip_sample=__snake_case		,    set_alpha_to_one=__snake_case		,    )
      torch.manual_seed(0			)
      a		:      str       =  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=1_28		,    )
      torch.manual_seed(0			)
      a		:      str       =  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=10_00		,    hidden_act='gelu'		,    projection_dim=5_12		,    )
      a		:      Any       =  CLIPTextModel(__snake_case			)
      a		:      Tuple       =  CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'			)

      a		:      List[str]       =  {
          'unet': unet,
          'scheduler': scheduler,
          'vae': vae,
          'text_encoder': text_encoder,
          'tokenizer': tokenizer,
          'safety_checker': None,
          'feature_extractor': None,
      }

      return components







    def     lowercase_ (   self				:						str		,    __snake_case				:						Tuple		,    __snake_case				:						Optional[int]=0			):
      if str(__snake_case			).startswith('mps'			):
        a		:      Any       =  torch.manual_seed(__snake_case			)
      else:
        a		:      Any       =  torch.Generator(device=__snake_case			).manual_seed(__snake_case			)
      a		:      int       =  {
          '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     lowercase_ (   self				:						List[Any]			):
      a		:      Union[str, Any]       =  'cpu'

      a		:      Any       =  self.get_dummy_components()
      a		:      List[str]       =  self.pipeline_class(**__snake_case			)
      pipe.to(__snake_case			)
      pipe.set_progress_bar_config(disable=__snake_case			)

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

      self.assertEqual(image.shape		,    (1, 64, 64, 3)			)
      a		:      str       =  np.array(
          [0.63905364, 0.62897307, 0.48599017, 0.5133624, 0.5550048, 0.45769516, 0.50326973, 0.5023139, 0.45384496]			)
      a		:      int       =  np.abs(image_slice.flatten() - expected_slice			).max()
      self.assertLessEqual(__snake_case		,    1e-3			)







    def     lowercase_ (   self				:						Dict			):
      super().test_cpu_offload_forward_pass(expected_max_diff=5e-4			)







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







    def     lowercase_ (   self				:						Union[str, Any]			):
      self._test_inference_batch_single_identical(batch_size=2		,    expected_max_diff=7e-4			)







    def     lowercase_ (   self				:						Tuple			):
      super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3			)







    def     lowercase_ (   self				:						str			):
      super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5e-4			)







    def     lowercase_ (   self				:						Any			):
      super().test_save_load_local(expected_max_difference=5e-4			)







    def     lowercase_ (   self				:						List[Any]			):
      super().test_save_load_optional_components(expected_max_difference=4e-4			)

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







    @classmethod
    def     lowercase_ (   cls				:						Union[str, Any]			):
      super().setUpClass()
      torch.use_deterministic_algorithms(__snake_case			)







    @classmethod
    def     lowercase_ (   cls				:						Union[str, Any]			):
      super().tearDownClass()
      torch.use_deterministic_algorithms(__snake_case			)







    def     lowercase_ (   self				:						Union[str, Any]			):
      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()







    def     lowercase_ (   self				:						Optional[Any]			):
      a		:      List[Any]       =  torch.manual_seed(51			)

      a		:      Dict       =  StableDiffusionAttendAndExcitePipeline.from_pretrained(
          'CompVis/stable-diffusion-v1-4'		,    safety_checker=__snake_case		,    torch_dtype=torch.floataa			)
      pipe.to('cuda'			)

      a		:      Optional[Any]       =  'a painting of an elephant with glasses'
      a		:      Any       =  [5, 7]

      a		:      Tuple       =  pipe(
          prompt=__snake_case		,    token_indices=__snake_case		,    guidance_scale=7.5		,    generator=__snake_case		,    num_inference_steps=5		,    max_iter_to_alter=5		,    output_type='numpy'		,    ).images[0]

      a		:      str       =  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