




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													=			False




@skip_mps
class       _A				(		__lowercase       ,     __lowercase       ,     __lowercase       ,     unittest.TestCase     ):
		__a					    =       StableDiffusionAttendAndExcitePipeline
		__a					    =       False
		__a					    =       TEXT_TO_IMAGE_PARAMS
		__a					    =       TEXT_TO_IMAGE_BATCH_PARAMS.union({"""token_indices"""}     )
		__a					    =       TEXT_TO_IMAGE_IMAGE_PARAMS
		__a					    =       TEXT_TO_IMAGE_IMAGE_PARAMS






		@classmethod
		def 				UpperCAmelCase (    cls			):
								super().setUpClass()
								torch.use_deterministic_algorithms(_SCREAMING_SNAKE_CASE			)






		@classmethod
		def 				UpperCAmelCase (    cls			):
								super().tearDownClass()
								torch.use_deterministic_algorithms(_SCREAMING_SNAKE_CASE			)






		def 				UpperCAmelCase (    self			):
								torch.manual_seed(0			)
								_UpperCAmelCase      =			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=_SCREAMING_SNAKE_CASE						,		)
								_UpperCAmelCase      =			DDIMScheduler(
								    beta_start=0.0_0085						,		beta_end=0.012						,		beta_schedule="""scaled_linear"""						,		clip_sample=_SCREAMING_SNAKE_CASE						,		set_alpha_to_one=_SCREAMING_SNAKE_CASE						,		)
								torch.manual_seed(0			)
								_UpperCAmelCase      =			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			)
								_UpperCAmelCase      =			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=512						,		)
								_UpperCAmelCase      =			CLIPTextModel(_SCREAMING_SNAKE_CASE			)
								_UpperCAmelCase      =			CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""			)

								_UpperCAmelCase      =			{
								    """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			):
								if str(_SCREAMING_SNAKE_CASE			).startswith("""mps"""			):
														_UpperCAmelCase      =			torch.manual_seed(_SCREAMING_SNAKE_CASE			)
								else:
														_UpperCAmelCase      =			torch.Generator(device=_SCREAMING_SNAKE_CASE			).manual_seed(_SCREAMING_SNAKE_CASE			)
								_UpperCAmelCase      =			_UpperCAmelCase      =			{
								    """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			):
								_UpperCAmelCase      =			"""cpu"""

								_UpperCAmelCase      =			self.get_dummy_components()
								_UpperCAmelCase      =			self.pipeline_class(**_SCREAMING_SNAKE_CASE			)
								pipe.to(_SCREAMING_SNAKE_CASE			)
								pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE			)

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

								self.assertEqual(image.shape						,		(1, 64, 64, 3)			)
								_UpperCAmelCase      =			np.array(
								    [0.6390_5364, 0.6289_7307, 0.4859_9017, 0.513_3624, 0.555_0048, 0.4576_9516, 0.5032_6973, 0.502_3139, 0.4538_4496]			)
								_UpperCAmelCase      =			np.abs(image_slice.flatten() - expected_slice			).max()
								self.assertLessEqual(_SCREAMING_SNAKE_CASE						,		1e-3			)






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






		def 				UpperCAmelCase (    self			):
								# 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			):
								self._test_inference_batch_single_identical(batch_size=2						,		expected_max_diff=7e-4			)






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






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






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






		def 				UpperCAmelCase (    self			):
								super().test_save_load_optional_components(expected_max_difference=4e-4			)




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






		@classmethod
		def 				UpperCAmelCase (    cls			):
								super().setUpClass()
								torch.use_deterministic_algorithms(_SCREAMING_SNAKE_CASE			)






		@classmethod
		def 				UpperCAmelCase (    cls			):
								super().tearDownClass()
								torch.use_deterministic_algorithms(_SCREAMING_SNAKE_CASE			)






		def 				UpperCAmelCase (    self			):
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase      =			torch.manual_seed(51			)

								_UpperCAmelCase      =			StableDiffusionAttendAndExcitePipeline.from_pretrained(
								    """CompVis/stable-diffusion-v1-4"""						,		safety_checker=_SCREAMING_SNAKE_CASE						,		torch_dtype=torch.floataa			)
								pipe.to("""cuda"""			)

								_UpperCAmelCase      =			"""a painting of an elephant with glasses"""
								_UpperCAmelCase      =			[5, 7]

								_UpperCAmelCase      =			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]

								_UpperCAmelCase      =			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





import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bert import BertTokenizer


a													=			logging.get_logger(__name__)

a													=			{"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}

a													=			{
    "vocab_file": {
        "bert-base-uncased": "https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt",
        "bert-large-uncased": "https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt",
        "bert-base-cased": "https://huggingface.co/bert-base-cased/resolve/main/vocab.txt",
        "bert-large-cased": "https://huggingface.co/bert-large-cased/resolve/main/vocab.txt",
        "bert-base-multilingual-uncased": (
            "https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt"
        ),
        "bert-base-multilingual-cased": "https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt",
        "bert-base-chinese": "https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt",
        "bert-base-german-cased": "https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt",
        "bert-large-uncased-whole-word-masking": (
            "https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt"
        ),
        "bert-large-cased-whole-word-masking": (
            "https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt"
        ),
        "bert-large-uncased-whole-word-masking-finetuned-squad": (
            "https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt"
        ),
        "bert-large-cased-whole-word-masking-finetuned-squad": (
            "https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt"
        ),
        "bert-base-cased-finetuned-mrpc": (
            "https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt"
        ),
        "bert-base-german-dbmdz-cased": "https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt",
        "bert-base-german-dbmdz-uncased": (
            "https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt"
        ),
        "TurkuNLP/bert-base-finnish-cased-v1": (
            "https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt"
        ),
        "TurkuNLP/bert-base-finnish-uncased-v1": (
            "https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt"
        ),
        "wietsedv/bert-base-dutch-cased": (
            "https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt"
        ),
    },
    "tokenizer_file": {
        "bert-base-uncased": "https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json",
        "bert-large-uncased": "https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json",
        "bert-base-cased": "https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json",
        "bert-large-cased": "https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json",
        "bert-base-multilingual-uncased": (
            "https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json"
        ),
        "bert-base-multilingual-cased": (
            "https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json"
        ),
        "bert-base-chinese": "https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json",
        "bert-base-german-cased": "https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json",
        "bert-large-uncased-whole-word-masking": (
            "https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json"
        ),
        "bert-large-cased-whole-word-masking": (
            "https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json"
        ),
        "bert-large-uncased-whole-word-masking-finetuned-squad": (
            "https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json"
        ),
        "bert-large-cased-whole-word-masking-finetuned-squad": (
            "https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json"
        ),
        "bert-base-cased-finetuned-mrpc": (
            "https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json"
        ),
        "bert-base-german-dbmdz-cased": (
            "https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json"
        ),
        "bert-base-german-dbmdz-uncased": (
            "https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json"
        ),
        "TurkuNLP/bert-base-finnish-cased-v1": (
            "https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json"
        ),
        "TurkuNLP/bert-base-finnish-uncased-v1": (
            "https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json"
        ),
        "wietsedv/bert-base-dutch-cased": (
            "https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json"
        ),
    },
}

a													=			{
    "bert-base-uncased": 512,
    "bert-large-uncased": 512,
    "bert-base-cased": 512,
    "bert-large-cased": 512,
    "bert-base-multilingual-uncased": 512,
    "bert-base-multilingual-cased": 512,
    "bert-base-chinese": 512,
    "bert-base-german-cased": 512,
    "bert-large-uncased-whole-word-masking": 512,
    "bert-large-cased-whole-word-masking": 512,
    "bert-large-uncased-whole-word-masking-finetuned-squad": 512,
    "bert-large-cased-whole-word-masking-finetuned-squad": 512,
    "bert-base-cased-finetuned-mrpc": 512,
    "bert-base-german-dbmdz-cased": 512,
    "bert-base-german-dbmdz-uncased": 512,
    "TurkuNLP/bert-base-finnish-cased-v1": 512,
    "TurkuNLP/bert-base-finnish-uncased-v1": 512,
    "wietsedv/bert-base-dutch-cased": 512,
}

a													=			{
    "bert-base-uncased": {"do_lower_case": True},
    "bert-large-uncased": {"do_lower_case": True},
    "bert-base-cased": {"do_lower_case": False},
    "bert-large-cased": {"do_lower_case": False},
    "bert-base-multilingual-uncased": {"do_lower_case": True},
    "bert-base-multilingual-cased": {"do_lower_case": False},
    "bert-base-chinese": {"do_lower_case": False},
    "bert-base-german-cased": {"do_lower_case": False},
    "bert-large-uncased-whole-word-masking": {"do_lower_case": True},
    "bert-large-cased-whole-word-masking": {"do_lower_case": False},
    "bert-large-uncased-whole-word-masking-finetuned-squad": {"do_lower_case": True},
    "bert-large-cased-whole-word-masking-finetuned-squad": {"do_lower_case": False},
    "bert-base-cased-finetuned-mrpc": {"do_lower_case": False},
    "bert-base-german-dbmdz-cased": {"do_lower_case": False},
    "bert-base-german-dbmdz-uncased": {"do_lower_case": True},
    "TurkuNLP/bert-base-finnish-cased-v1": {"do_lower_case": False},
    "TurkuNLP/bert-base-finnish-uncased-v1": {"do_lower_case": True},
    "wietsedv/bert-base-dutch-cased": {"do_lower_case": False},
}




class       _A				(		__lowercase     ):
		__a					    =       VOCAB_FILES_NAMES
		__a					    =       PRETRAINED_VOCAB_FILES_MAP
		__a					    =       PRETRAINED_INIT_CONFIGURATION
		__a					    =       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
		__a					    =       BertTokenizer






		def __init__(    self						,		_SCREAMING_SNAKE_CASE=None						,		_SCREAMING_SNAKE_CASE=None						,		_SCREAMING_SNAKE_CASE=True						,		_SCREAMING_SNAKE_CASE="[UNK]"						,		_SCREAMING_SNAKE_CASE="[SEP]"						,		_SCREAMING_SNAKE_CASE="[PAD]"						,		_SCREAMING_SNAKE_CASE="[CLS]"						,		_SCREAMING_SNAKE_CASE="[MASK]"						,		_SCREAMING_SNAKE_CASE=True						,		_SCREAMING_SNAKE_CASE=None						,		**_SCREAMING_SNAKE_CASE						,		):
								super().__init__(
								    _SCREAMING_SNAKE_CASE						,		tokenizer_file=_SCREAMING_SNAKE_CASE						,		do_lower_case=_SCREAMING_SNAKE_CASE						,		unk_token=_SCREAMING_SNAKE_CASE						,		sep_token=_SCREAMING_SNAKE_CASE						,		pad_token=_SCREAMING_SNAKE_CASE						,		cls_token=_SCREAMING_SNAKE_CASE						,		mask_token=_SCREAMING_SNAKE_CASE						,		tokenize_chinese_chars=_SCREAMING_SNAKE_CASE						,		strip_accents=_SCREAMING_SNAKE_CASE						,		**_SCREAMING_SNAKE_CASE						,		)

								_UpperCAmelCase      =			json.loads(self.backend_tokenizer.normalizer.__getstate__()			)
								if (
								    normalizer_state.get("""lowercase"""						,		_SCREAMING_SNAKE_CASE			) != do_lower_case
								    or normalizer_state.get("""strip_accents"""						,		_SCREAMING_SNAKE_CASE			) != strip_accents
								    or normalizer_state.get("""handle_chinese_chars"""						,		_SCREAMING_SNAKE_CASE			) != tokenize_chinese_chars
								):
														_UpperCAmelCase      =			getattr(_SCREAMING_SNAKE_CASE						,		normalizer_state.pop("""type"""			)			)
														_UpperCAmelCase      =			do_lower_case
														_UpperCAmelCase      =			strip_accents
														_UpperCAmelCase      =			tokenize_chinese_chars
														_UpperCAmelCase      =			normalizer_class(**_SCREAMING_SNAKE_CASE			)

								_UpperCAmelCase      =			do_lower_case






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE=None			):
								_UpperCAmelCase      =			[self.cls_token_id] + token_ids_a + [self.sep_token_id]

								if token_ids_a:
														output += token_ids_a + [self.sep_token_id]

								return output






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE = None			):
								_UpperCAmelCase      =			[self.sep_token_id]
								_UpperCAmelCase      =			[self.cls_token_id]
								if token_ids_a is None:
														return len(cls + token_ids_a + sep			) * [0]
								return len(cls + token_ids_a + sep			) * [0] + len(token_ids_a + sep			) * [1]






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE = None			):
								_UpperCAmelCase      =			self._tokenizer.model.save(_SCREAMING_SNAKE_CASE						,		name=_SCREAMING_SNAKE_CASE			)
								return tuple(_SCREAMING_SNAKE_CASE			)