


"""simple docstring"""


import itertools
import random
import unittest

import numpy as np

from transformers import BatchFeature, SpeechTaFeatureExtractor
from transformers.testing_utils import require_torch
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
    import torch


__lowerCamelCase      :List[Any]	    =		random.Random()




def   snake_case		(     UpperCamelCase__       :						Optional[Any]			,				UpperCamelCase__       :						Optional[Any]=1.0			,				UpperCamelCase__       :						int=None			,				UpperCamelCase__       :						Tuple=None    )   ->      Any:
      if rng is None:
            lowerCamelCase					:					Tuple        =	global_rng

      lowerCamelCase					:					Union[str, Any]        =	[]
      for batch_idx in range(shape[0]    ):
            values.append([]    )
            for _ in range(shape[1]    ):
                  values[-1].append(rng.random() * scale    )

      return values


@require_torch
class 			A__	(						unittest.TestCase):


     """simple docstring"""

     def __init__(	self:						Optional[int]     ,		__a:						str     ,		__a:						Union[str, Any]=7     ,		__a:						int=400     ,		__a:						Union[str, Any]=2_000     ,		__a:						int=1     ,		__a:						Union[str, Any]=0.0     ,		__a:						Union[str, Any]=16_000     ,		__a:						Optional[int]=True     ,		__a:						Optional[int]=80     ,		__a:						Union[str, Any]=16     ,		__a:						Union[str, Any]=64     ,		__a:						Any="hann_window"     ,		__a:						Any=80     ,		__a:						Union[str, Any]=7_600     ,		__a:						Dict=1e-1_0     ,		__a:						List[str]=True     ,		)->    Dict:
           lowerCamelCase					:					Union[str, Any]        =	parent
           lowerCamelCase					:					int        =	batch_size
           lowerCamelCase					:					List[Any]        =	min_seq_length
           lowerCamelCase					:					Dict        =	max_seq_length
           lowerCamelCase					:					Any        =	(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
           lowerCamelCase					:					List[str]        =	feature_size
           lowerCamelCase					:					Dict        =	padding_value
           lowerCamelCase					:					Dict        =	sampling_rate
           lowerCamelCase					:					Any        =	do_normalize
           lowerCamelCase					:					List[Any]        =	num_mel_bins
           lowerCamelCase					:					Optional[int]        =	hop_length
           lowerCamelCase					:					str        =	win_length
           lowerCamelCase					:					str        =	win_function
           lowerCamelCase					:					str        =	fmin
           lowerCamelCase					:					Optional[Any]        =	fmax
           lowerCamelCase					:					str        =	mel_floor
           lowerCamelCase					:					Any        =	return_attention_mask

     def 		a__						(	self:						str	)->    Any:
           return {
               "feature_size": self.feature_size,
               "padding_value": self.padding_value,
               "sampling_rate": self.sampling_rate,
               "do_normalize": self.do_normalize,
               "num_mel_bins": self.num_mel_bins,
               "hop_length": self.hop_length,
               "win_length": self.win_length,
               "win_function": self.win_function,
               "fmin": self.fmin,
               "fmax": self.fmax,
               "mel_floor": self.mel_floor,
               "return_attention_mask": self.return_attention_mask,
           }

     def 		a__						(	self:						int     ,		__a:						Optional[Any]=False     ,		__a:						Tuple=False	)->    Dict:
           def _flatten(__a:						Any	):
                 return list(itertools.chain(*__a	)	)

           if equal_length:
                 lowerCamelCase					:					Optional[int]        =	floats_list((self.batch_size, self.max_seq_length)	)
           else:
                 # make sure that inputs increase in size
                 lowerCamelCase					:					int        =	[
                     _flatten(floats_list((x, self.feature_size)	)	)
                     for x in range(self.min_seq_length     ,		self.max_seq_length     ,		self.seq_length_diff	)
                 ]

           if numpify:
                 lowerCamelCase					:					Dict        =	[np.asarray(__a	) for x in speech_inputs]

           return speech_inputs







     def 		a__						(	self:						Dict     ,		__a:						Tuple=False     ,		__a:						int=False	)->    Union[str, Any]:
           if equal_length:
                 lowerCamelCase					:					Any        =	[floats_list((self.max_seq_length, self.num_mel_bins)	) for _ in range(self.batch_size	)]
           else:
                 # make sure that inputs increase in size
                 lowerCamelCase					:					Dict        =	[
                     floats_list((x, self.num_mel_bins)	)
                     for x in range(self.min_seq_length     ,		self.max_seq_length     ,		self.seq_length_diff	)
                 ]

           if numpify:
                 lowerCamelCase					:					int        =	[np.asarray(__a	) for x in speech_inputs]

           return speech_inputs


@require_torch
class 			A__	(						__lowercase ,     unittest.TestCase):


     """simple docstring"""
     snake_case__	:					Optional[int]													=SpeechTaFeatureExtractor

     def 		a__						(	self:						Dict	)->    Union[str, Any]:
           lowerCamelCase					:					Union[str, Any]        =	SpeechTaFeatureExtractionTester(self	)

     def 		a__						(	self:						Tuple     ,		__a:						Dict	)->    Optional[Any]:
           self.assertTrue(np.all(np.mean(__a     ,		axis=0	) < 1e-3	)	)
           self.assertTrue(np.all(np.abs(np.var(__a     ,		axis=0	) - 1	) < 1e-3	)	)

     def 		a__						(	self:						Optional[Any]	)->    Tuple:
           # Tests that all call wrap to encode_plus and batch_encode_plus
           lowerCamelCase					:					Optional[Any]        =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()	)
           # create three inputs of length 800, 1000, and 1200
           lowerCamelCase					:					Dict        =	[floats_list((1, x)	)[0] for x in range(800     ,		1_400     ,		200	)]
           lowerCamelCase					:					Any        =	[np.asarray(__a	) for speech_input in speech_inputs]

           # Test not batched input
           lowerCamelCase					:					Any        =	feat_extract(speech_inputs[0]     ,		return_tensors="""np"""	).input_values
           lowerCamelCase					:					int        =	feat_extract(np_speech_inputs[0]     ,		return_tensors="""np"""	).input_values
           self.assertTrue(np.allclose(__a     ,		__a     ,		atol=1e-3	)	)

           # Test batched
           lowerCamelCase					:					Dict        =	feat_extract(__a     ,		return_tensors="""np"""	).input_values
           lowerCamelCase					:					Any        =	feat_extract(__a     ,		return_tensors="""np"""	).input_values
           for enc_seq_a, enc_seq_a in zip(__a     ,		__a	):
                 self.assertTrue(np.allclose(__a     ,		__a     ,		atol=1e-3	)	)

     def 		a__						(	self:						Optional[int]	)->    Any:
           lowerCamelCase					:					Dict        =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()	)
           lowerCamelCase					:					int        =	[floats_list((1, x)	)[0] for x in range(800     ,		1_400     ,		200	)]

           lowerCamelCase					:					List[str]        =	["""longest""", """max_length""", """do_not_pad"""]
           lowerCamelCase					:					List[str]        =	[None, 1_600, None]
           for max_length, padding in zip(__a     ,		__a	):
                 lowerCamelCase					:					Optional[int]        =	feat_extract(__a     ,		padding=__a     ,		max_length=__a     ,		return_tensors="""np"""	)
                 lowerCamelCase					:					str        =	processed.input_values

                 self._check_zero_mean_unit_variance(input_values[0][:800]	)
                 self.assertTrue(input_values[0][800:].sum() < 1e-6	)
                 self._check_zero_mean_unit_variance(input_values[1][:1_000]	)
                 self.assertTrue(input_values[0][1_000:].sum() < 1e-6	)
                 self._check_zero_mean_unit_variance(input_values[2][:1_200]	)

     def 		a__						(	self:						Any	)->    Tuple:
           lowerCamelCase					:					Any        =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()	)
           lowerCamelCase					:					List[Any]        =	range(800     ,		1_400     ,		200	)
           lowerCamelCase					:					int        =	[floats_list((1, x)	)[0] for x in lengths]

           lowerCamelCase					:					Optional[Any]        =	["""longest""", """max_length""", """do_not_pad"""]
           lowerCamelCase					:					List[Any]        =	[None, 1_600, None]

           for max_length, padding in zip(__a     ,		__a	):
                 lowerCamelCase					:					List[str]        =	feat_extract(__a     ,		max_length=__a     ,		padding=__a	)
                 lowerCamelCase					:					List[str]        =	processed.input_values

                 self._check_zero_mean_unit_variance(input_values[0][:800]	)
                 self._check_zero_mean_unit_variance(input_values[1][:1_000]	)
                 self._check_zero_mean_unit_variance(input_values[2][:1_200]	)

     def 		a__						(	self:						str	)->    str:
           lowerCamelCase					:					Union[str, Any]        =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()	)
           lowerCamelCase					:					Tuple        =	[floats_list((1, x)	)[0] for x in range(800     ,		1_400     ,		200	)]
           lowerCamelCase					:					List[Any]        =	feat_extract(
               __a     ,		truncation=__a     ,		max_length=1_000     ,		padding="""max_length"""     ,		return_tensors="""np"""	)
           lowerCamelCase					:					Union[str, Any]        =	processed.input_values

           self._check_zero_mean_unit_variance(input_values[0, :800]	)
           self._check_zero_mean_unit_variance(input_values[1]	)
           self._check_zero_mean_unit_variance(input_values[2]	)

     def 		a__						(	self:						Optional[int]	)->    Optional[Any]:
           lowerCamelCase					:					List[Any]        =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()	)
           lowerCamelCase					:					Any        =	[floats_list((1, x)	)[0] for x in range(800     ,		1_400     ,		200	)]
           lowerCamelCase					:					Any        =	feat_extract(
               __a     ,		truncation=__a     ,		max_length=1_000     ,		padding="""longest"""     ,		return_tensors="""np"""	)
           lowerCamelCase					:					List[str]        =	processed.input_values

           self._check_zero_mean_unit_variance(input_values[0, :800]	)
           self._check_zero_mean_unit_variance(input_values[1, :1_000]	)
           self._check_zero_mean_unit_variance(input_values[2]	)

           # make sure that if max_length < longest -> then pad to max_length
           self.assertTrue(input_values.shape == (3, 1_000)	)

           lowerCamelCase					:					int        =	[floats_list((1, x)	)[0] for x in range(800     ,		1_400     ,		200	)]
           lowerCamelCase					:					Optional[int]        =	feat_extract(
               __a     ,		truncation=__a     ,		max_length=2_000     ,		padding="""longest"""     ,		return_tensors="""np"""	)
           lowerCamelCase					:					Union[str, Any]        =	processed.input_values

           self._check_zero_mean_unit_variance(input_values[0, :800]	)
           self._check_zero_mean_unit_variance(input_values[1, :1_000]	)
           self._check_zero_mean_unit_variance(input_values[2]	)

           # make sure that if max_length > longest -> then pad to longest
           self.assertTrue(input_values.shape == (3, 1_200)	)

     def 		a__						(	self:						List[Any]	)->    Tuple:
           lowerCamelCase					:					Union[str, Any]        =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()	)
           lowerCamelCase					:					Tuple        =	np.random.rand(100	).astype(np.floataa	)
           lowerCamelCase					:					str        =	np_speech_inputs.tolist()

           for inputs in [py_speech_inputs, np_speech_inputs]:
                 lowerCamelCase					:					Optional[Any]        =	feature_extractor.pad([{"""input_values""": inputs}]     ,		return_tensors="""np"""	)
                 self.assertTrue(np_processed.input_values.dtype == np.floataa	)
                 lowerCamelCase					:					Union[str, Any]        =	feature_extractor.pad([{"""input_values""": inputs}]     ,		return_tensors="""pt"""	)
                 self.assertTrue(pt_processed.input_values.dtype == torch.floataa	)

     def 		a__						(	self:						int	)->    List[str]:
           # Tests that all call wrap to encode_plus and batch_encode_plus
           lowerCamelCase					:					Any        =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()	)
           # create three inputs of length 800, 1000, and 1200
           lowerCamelCase					:					Any        =	[floats_list((1, x)	)[0] for x in range(800     ,		1_400     ,		200	)]
           lowerCamelCase					:					Union[str, Any]        =	[np.asarray(__a	) for speech_input in speech_inputs]

           # Test feature size
           lowerCamelCase					:					Dict        =	feature_extractor(audio_target=__a     ,		padding=__a     ,		return_tensors="""np"""	).input_values
           self.assertTrue(input_values.ndim == 3	)
           self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins	)

           # Test not batched input
           lowerCamelCase					:					Optional[Any]        =	feature_extractor(speech_inputs[0]     ,		return_tensors="""np"""	).input_values
           lowerCamelCase					:					Union[str, Any]        =	feature_extractor(np_speech_inputs[0]     ,		return_tensors="""np"""	).input_values
           self.assertTrue(np.allclose(__a     ,		__a     ,		atol=1e-3	)	)

           # Test batched
           lowerCamelCase					:					List[str]        =	feature_extractor(__a     ,		return_tensors="""np"""	).input_values
           lowerCamelCase					:					Any        =	feature_extractor(__a     ,		return_tensors="""np"""	).input_values
           for enc_seq_a, enc_seq_a in zip(__a     ,		__a	):
                 self.assertTrue(np.allclose(__a     ,		__a     ,		atol=1e-3	)	)

           # Test 2-D numpy arrays are batched.
           lowerCamelCase					:					Any        =	[floats_list((1, x)	)[0] for x in (800, 800, 800)]
           lowerCamelCase					:					Optional[int]        =	np.asarray(__a	)
           lowerCamelCase					:					Optional[Any]        =	feature_extractor(__a     ,		return_tensors="""np"""	).input_values
           lowerCamelCase					:					Any        =	feature_extractor(__a     ,		return_tensors="""np"""	).input_values
           for enc_seq_a, enc_seq_a in zip(__a     ,		__a	):
                 self.assertTrue(np.allclose(__a     ,		__a     ,		atol=1e-3	)	)

     def 		a__						(	self:						str	)->    Union[str, Any]:
           lowerCamelCase					:					Any        =	self.feat_extract_tester.prepare_inputs_for_target()
           lowerCamelCase					:					str        =	self.feature_extraction_class(**self.feat_extract_dict	)
           lowerCamelCase					:					str        =	feat_extract.model_input_names[0]

           lowerCamelCase					:					Any        =	BatchFeature({input_name: speech_inputs}	)

           self.assertTrue(all(len(__a	) == len(__a	) for x, y in zip(__a     ,		processed_features[input_name]	)	)	)

           lowerCamelCase					:					Tuple        =	self.feat_extract_tester.prepare_inputs_for_target(equal_length=__a	)
           lowerCamelCase					:					Tuple        =	BatchFeature({input_name: speech_inputs}     ,		tensor_type="""np"""	)

           lowerCamelCase					:					Optional[int]        =	processed_features[input_name]

           if len(batch_features_input.shape	) < 3:
                 lowerCamelCase					:					int        =	batch_features_input[:, :, None]

           self.assertTrue(
               batch_features_input.shape
               == (self.feat_extract_tester.batch_size, len(speech_inputs[0]	), self.feat_extract_tester.num_mel_bins)	)

     @require_torch
     def 		a__						(	self:						Any	)->    Union[str, Any]:
           lowerCamelCase					:					Optional[int]        =	self.feat_extract_tester.prepare_inputs_for_target(equal_length=__a	)
           lowerCamelCase					:					List[Any]        =	self.feature_extraction_class(**self.feat_extract_dict	)
           lowerCamelCase					:					Tuple        =	feat_extract.model_input_names[0]

           lowerCamelCase					:					Optional[Any]        =	BatchFeature({input_name: speech_inputs}     ,		tensor_type="""pt"""	)

           lowerCamelCase					:					int        =	processed_features[input_name]

           if len(batch_features_input.shape	) < 3:
                 lowerCamelCase					:					Tuple        =	batch_features_input[:, :, None]

           self.assertTrue(
               batch_features_input.shape
               == (self.feat_extract_tester.batch_size, len(speech_inputs[0]	), self.feat_extract_tester.num_mel_bins)	)

     @require_torch
     def 		a__						(	self:						Optional[Any]	)->    List[Any]:
           lowerCamelCase					:					List[str]        =	self.feature_extraction_class(**self.feat_extract_dict	)
           lowerCamelCase					:					str        =	self.feat_extract_tester.prepare_inputs_for_target()
           lowerCamelCase					:					Union[str, Any]        =	feat_extract.model_input_names[0]

           lowerCamelCase					:					Optional[Any]        =	BatchFeature({input_name: speech_inputs}	)

           lowerCamelCase					:					List[Any]        =	feat_extract.num_mel_bins  # hack!

           lowerCamelCase					:					Optional[Any]        =	feat_extract.pad(__a     ,		padding="""longest"""     ,		return_tensors="""np"""	)[input_name]
           lowerCamelCase					:					str        =	feat_extract.pad(__a     ,		padding="""longest"""     ,		return_tensors="""pt"""	)[input_name]

           self.assertTrue(abs(input_np.astype(np.floataa	).sum() - input_pt.numpy().astype(np.floataa	).sum()	) < 1e-2	)

     def 		a__						(	self:						str	)->    int:
           lowerCamelCase					:					List[Any]        =	self.feat_extract_dict
           lowerCamelCase					:					List[str]        =	True
           lowerCamelCase					:					Dict        =	self.feature_extraction_class(**__a	)
           lowerCamelCase					:					Union[str, Any]        =	self.feat_extract_tester.prepare_inputs_for_target()
           lowerCamelCase					:					Tuple        =	[len(__a	) for x in speech_inputs]
           lowerCamelCase					:					Tuple        =	feat_extract.model_input_names[0]

           lowerCamelCase					:					Tuple        =	BatchFeature({input_name: speech_inputs}	)

           lowerCamelCase					:					Optional[int]        =	feat_extract.num_mel_bins  # hack!

           lowerCamelCase					:					List[Any]        =	feat_extract.pad(__a     ,		padding="""longest"""     ,		return_tensors="""np"""	)
           self.assertIn("""attention_mask"""     ,		__a	)
           self.assertListEqual(list(processed.attention_mask.shape	)     ,		list(processed[input_name].shape[:2]	)	)
           self.assertListEqual(processed.attention_mask.sum(-1	).tolist()     ,		__a	)

     def 		a__						(	self:						int	)->    str:
           lowerCamelCase					:					List[Any]        =	self.feat_extract_dict
           lowerCamelCase					:					Dict        =	True
           lowerCamelCase					:					List[str]        =	self.feature_extraction_class(**__a	)
           lowerCamelCase					:					Any        =	self.feat_extract_tester.prepare_inputs_for_target()
           lowerCamelCase					:					List[Any]        =	[len(__a	) for x in speech_inputs]
           lowerCamelCase					:					int        =	feat_extract.model_input_names[0]

           lowerCamelCase					:					Optional[Any]        =	BatchFeature({input_name: speech_inputs}	)
           lowerCamelCase					:					Tuple        =	min(__a	)

           lowerCamelCase					:					List[str]        =	feat_extract.num_mel_bins  # hack!

           lowerCamelCase					:					Any        =	feat_extract.pad(
               __a     ,		padding="""max_length"""     ,		max_length=__a     ,		truncation=__a     ,		return_tensors="""np"""	)
           self.assertIn("""attention_mask"""     ,		__a	)
           self.assertListEqual(
               list(processed_pad.attention_mask.shape	)     ,		[processed_pad[input_name].shape[0], max_length]	)
           self.assertListEqual(
               processed_pad.attention_mask[:, :max_length].sum(-1	).tolist()     ,		[max_length for x in speech_inputs]	)

     def 		a__						(	self:						int     ,		__a:						str	)->    List[Any]:
           from datasets import load_dataset

           lowerCamelCase					:					Dict        =	load_dataset("""hf-internal-testing/librispeech_asr_dummy"""     ,		"""clean"""     ,		split="""validation"""	)
           # automatic decoding with librispeech
           lowerCamelCase					:					Optional[int]        =	ds.sort("""id"""	).select(range(__a	)	)[:num_samples]["""audio"""]

           return [x["array"] for x in speech_samples]

     def 		a__						(	self:						int	)->    Dict:
           # fmt: off
           lowerCamelCase					:					str        =	torch.tensor(
               [2.3_8_0_4e-0_3, 2.0_7_5_2e-0_3, 1.9_8_3_6e-0_3, 2.1_0_5_7e-0_3, 1.6_1_7_4e-0_3,
                3.0_5_1_8e-0_4, 9.1_5_5_3e-0_5, 3.3_5_6_9e-0_4, 9.7_6_5_6e-0_4, 1.8_3_1_1e-0_3,
                2.0_1_4_2e-0_3, 2.1_0_5_7e-0_3, 1.7_3_9_5e-0_3, 4.5_7_7_6e-0_4, -3.9_6_7_3e-0_4,
                4.5_7_7_6e-0_4, 1.0_0_7_1e-0_3, 9.1_5_5_3e-0_5, 4.8_8_2_8e-0_4, 1.1_5_9_7e-0_3,
                7.3_2_4_2e-0_4, 9.4_6_0_4e-0_4, 1.8_0_0_5e-0_3, 1.8_3_1_1e-0_3, 8.8_5_0_1e-0_4,
                4.2_7_2_5e-0_4, 4.8_8_2_8e-0_4, 7.3_2_4_2e-0_4, 1.0_9_8_6e-0_3, 2.1_0_5_7e-0_3]	)
           # fmt: on

           lowerCamelCase					:					Tuple        =	self._load_datasamples(1	)
           lowerCamelCase					:					Optional[int]        =	SpeechTaFeatureExtractor()
           lowerCamelCase					:					int        =	feature_extractor(__a     ,		return_tensors="""pt"""	).input_values
           self.assertEquals(input_values.shape     ,		(1, 93_680)	)
           self.assertTrue(torch.allclose(input_values[0, :30]     ,		__a     ,		atol=1e-6	)	)







     def 		a__						(	self:						List[str]	)->    List[str]:
           # fmt: off
           lowerCamelCase					:					List[Any]        =	torch.tensor(
               [-2.68_70, -3.01_04, -3.13_56, -3.53_52, -3.00_44, -3.03_53, -3.47_19, -3.67_77,
                -3.15_20, -2.94_35, -2.65_53, -2.87_95, -2.99_44, -2.59_21, -3.02_79, -3.03_86,
                -3.08_64, -3.12_91, -3.23_53, -2.74_44, -2.68_31, -2.72_87, -3.17_61, -3.15_71,
                -3.27_26, -3.05_82, -3.10_07, -3.45_33, -3.46_95, -3.09_98]	)
           # fmt: on

           lowerCamelCase					:					List[str]        =	self._load_datasamples(1	)
           lowerCamelCase					:					str        =	SpeechTaFeatureExtractor()
           lowerCamelCase					:					Dict        =	feature_extractor(audio_target=__a     ,		return_tensors="""pt"""	).input_values
           self.assertEquals(input_values.shape     ,		(1, 366, 80)	)
           self.assertTrue(torch.allclose(input_values[0, 0, :30]     ,		__a     ,		atol=1e-4	)	)








"""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__	(						__lowercase ,     __lowercase ,     __lowercase ,     unittest.TestCase):


     """simple docstring"""
     snake_case__	:					Optional[Any]													=StableDiffusionAttendAndExcitePipeline
     snake_case__	:					Any													=False
     snake_case__	:					Dict													=TEXT_TO_IMAGE_PARAMS
     snake_case__	:					Any													=TEXT_TO_IMAGE_BATCH_PARAMS.union({'''token_indices'''})
     snake_case__	:					Dict													=TEXT_TO_IMAGE_IMAGE_PARAMS
     snake_case__	:					str													=TEXT_TO_IMAGE_IMAGE_PARAMS

     @classmethod
     def 		a__						(	cls:						Dict	)->    Tuple:
           super().setUpClass()
           torch.use_deterministic_algorithms(__a	)

     @classmethod
     def 		a__						(	cls:						Union[str, Any]	)->    Any:
           super().tearDownClass()
           torch.use_deterministic_algorithms(__a	)

     def 		a__						(	self:						Tuple	)->    Union[str, Any]:
           torch.manual_seed(0	)
           lowerCamelCase					:					str        =	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=__a     ,		)
           lowerCamelCase					:					Union[str, Any]        =	DDIMScheduler(
               beta_start=0.0_00_85     ,		beta_end=0.0_12     ,		beta_schedule="""scaled_linear"""     ,		clip_sample=__a     ,		set_alpha_to_one=__a     ,		)
           torch.manual_seed(0	)
           lowerCamelCase					:					Union[str, Any]        =	AutoencoderKL(
               block_out_channels=[32, 64]     ,		in_channels=3     ,		out_channels=3     ,		down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]     ,		up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]     ,		latent_channels=4     ,		sample_size=128     ,		)
           torch.manual_seed(0	)
           lowerCamelCase					:					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=1_000     ,		hidden_act="""gelu"""     ,		projection_dim=512     ,		)
           lowerCamelCase					:					Optional[int]        =	CLIPTextModel(__a	)
           lowerCamelCase					:					str        =	CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""	)

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

           return components

     def 		a__						(	self:						Tuple     ,		__a:						int     ,		__a:						Union[str, Any]=0	)->    Optional[Any]:
           if str(__a	).startswith("""mps"""	):
                 lowerCamelCase					:					Tuple        =	torch.manual_seed(__a	)
           else:
                 lowerCamelCase					:					str        =	torch.Generator(device=__a	).manual_seed(__a	)
           lowerCamelCase					:					Dict        =	{
               """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 		a__						(	self:						Dict	)->    str:
           lowerCamelCase					:					Tuple        =	"""cpu"""

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

           lowerCamelCase					:					Any        =	self.get_dummy_inputs(__a	)
           lowerCamelCase					:					Union[str, Any]        =	pipe(**__a	).images
           lowerCamelCase					:					Tuple        =	image[0, -3:, -3:, -1]

           self.assertEqual(image.shape     ,		(1, 64, 64, 3)	)
           lowerCamelCase					:					Optional[Any]        =	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]	)
           lowerCamelCase					:					Optional[Any]        =	np.abs(image_slice.flatten() - expected_slice	).max()
           self.assertLessEqual(__a     ,		1e-3	)

     def 		a__						(	self:						int	)->    Optional[Any]:
           super().test_cpu_offload_forward_pass(expected_max_diff=5e-4	)

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

     def 		a__						(	self:						Tuple	)->    int:
           self._test_inference_batch_single_identical(batch_size=2     ,		expected_max_diff=7e-4	)

     def 		a__						(	self:						Dict	)->    List[Any]:
           super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3	)

     def 		a__						(	self:						Optional[int]	)->    Dict:
           super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5e-4	)

     def 		a__						(	self:						Any	)->    Tuple:
           super().test_save_load_local(expected_max_difference=5e-4	)







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


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


     """simple docstring"""

     @classmethod
     def 		a__						(	cls:						Any	)->    Tuple:
           super().setUpClass()
           torch.use_deterministic_algorithms(__a	)

     @classmethod
     def 		a__						(	cls:						Dict	)->    Optional[int]:
           super().tearDownClass()
           torch.use_deterministic_algorithms(__a	)

     def 		a__						(	self:						int	)->    Optional[int]:
           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()







     def 		a__						(	self:						int	)->    Optional[Any]:
           lowerCamelCase					:					List[Any]        =	torch.manual_seed(51	)

           lowerCamelCase					:					List[str]        =	StableDiffusionAttendAndExcitePipeline.from_pretrained(
               """CompVis/stable-diffusion-v1-4"""     ,		safety_checker=__a     ,		torch_dtype=torch.floataa	)
           pipe.to("""cuda"""	)

           lowerCamelCase					:					Dict        =	"""a painting of an elephant with glasses"""
           lowerCamelCase					:					Any        =	[5, 7]

           lowerCamelCase					:					Tuple        =	pipe(
               prompt=__a     ,		token_indices=__a     ,		guidance_scale=7.5     ,		generator=__a     ,		num_inference_steps=5     ,		max_iter_to_alter=5     ,		output_type="""numpy"""     ,		).images[0]

           lowerCamelCase					:					Union[str, Any]        =	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




