




from dataclasses import dataclass
from typing import Dict, Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .attention_processor import AttentionProcessor, AttnProcessor
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder







@dataclass
class 						lowercase							(   UpperCamelCase__		):
     _a							 =						42







class 						lowercase							(   UpperCamelCase__,UpperCamelCase__		):
     _a							 =						True

     @register_to_config
     def __init__(  self		,     _a = 3		,     _a = 3		,     _a = ("DownEncoderBlock2D",)		,     _a = ("UpDecoderBlock2D",)		,     _a = (64,)		,     _a = 1		,     _a = "silu"		,     _a = 4		,     _a = 32		,     _a = 32		,     _a = 0.18215		,     )						->							Any:
           super().__init__()

           # pass init params to Encoder
           _A							:     Tuple			=						Encoder(
               in_channels=_a		,     out_channels=_a		,     down_block_types=_a		,     block_out_channels=_a		,     layers_per_block=_a		,     act_fn=_a		,     norm_num_groups=_a		,     double_z=_a		,     )

           # pass init params to Decoder
           _A							:     Union[str, Any]			=						Decoder(
               in_channels=_a		,     out_channels=_a		,     up_block_types=_a		,     block_out_channels=_a		,     layers_per_block=_a		,     norm_num_groups=_a		,     act_fn=_a		,     )

           _A							:     Any			=						nn.Convad(2 * latent_channels		,     2 * latent_channels		,     1				)
           _A							:     List[str]			=						nn.Convad(_a		,     _a		,     1				)

           _A							:     List[Any]			=						False
           _A							:     Any			=						False

           # only relevant if vae tiling is enabled
           _A							:     Any			=						self.config.sample_size
           _A							:     Union[str, Any]			=						(
               self.config.sample_size[0]
               if isinstance(self.config.sample_size		,     (list, tuple)				)
               else self.config.sample_size
           )
           _A							:     List[str]			=						int(sample_size / (2 ** (len(self.config.block_out_channels				) - 1))				)
           _A							:     int			=						0.25

     def 					a__	(  self		,     _a		,     _a=False				)						->							str:
           if isinstance(_a		,     (Encoder, Decoder)				):
                 _A							:     Dict			=						value

     def 					a__	(  self		,     _a = True				)						->							int:
           _A							:     int			=						use_tiling

     def 					a__	(  self				)						->							Dict:
           self.enable_tiling(_a				)

     def 					a__	(  self				)						->							Optional[int]:
           _A							:     Tuple			=						True

     def 					a__	(  self				)						->							List[str]:
           _A							:     List[Any]			=						False

     @property
     # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
     def 					a__	(  self				)						->							Dict[str, AttentionProcessor]:
           _A							:     Dict			=						{}

           def fn_recursive_add_processors(_a		,     _a		,     _a				):
                 if hasattr(_a		,     """set_processor"""				):
                       _A							:     Optional[int]			=						module.processor

                 for sub_name, child in module.named_children():
                       fn_recursive_add_processors(F'''{name}.{sub_name}'''		,     _a		,     _a				)

                 return processors

           for name, module in self.named_children():
                 fn_recursive_add_processors(_a		,     _a		,     _a				)

           return processors

     def 					a__	(  self		,     _a				)						->							str:
           _A							:     int			=						len(self.attn_processors.keys()				)

           if isinstance(_a		,     _a				) and len(_a				) != count:
                 raise ValueError(
                     F'''A dict of processors was passed, but the number of processors {len(_a				)} does not match the'''
                     F''' number of attention layers: {count}. Please make sure to pass {count} processor classes.'''				)

           def fn_recursive_attn_processor(_a		,     _a		,     _a				):
                 if hasattr(_a		,     """set_processor"""				):
                       if not isinstance(_a		,     _a				):
                             module.set_processor(_a				)
                       else:
                             module.set_processor(processor.pop(F'''{name}.processor'''				)				)

                 for sub_name, child in module.named_children():
                       fn_recursive_attn_processor(F'''{name}.{sub_name}'''		,     _a		,     _a				)

           for name, module in self.named_children():
                 fn_recursive_attn_processor(_a		,     _a		,     _a				)

     def 					a__	(  self				)						->							Dict:
           self.set_attn_processor(AttnProcessor()				)

     @apply_forward_hook
     def 					a__	(  self		,     _a		,     _a = True				)						->							AutoencoderKLOutput:
           if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size):
                 return self.tiled_encode(_a		,     return_dict=_a				)

           if self.use_slicing and x.shape[0] > 1:
                 _A							:     List[Any]			=						[self.encoder(_a				) for x_slice in x.split(1				)]
                 _A							:     Dict			=						torch.cat(_a				)
           else:
                 _A							:     Any			=						self.encoder(_a				)

           _A							:     Tuple			=						self.quant_conv(_a				)
           _A							:     Any			=						DiagonalGaussianDistribution(_a				)

           if not return_dict:
                 return (posterior,)

           return AutoencoderKLOutput(latent_dist=_a				)

     def 					a__	(  self		,     _a		,     _a = True				)						->							Union[DecoderOutput, torch.FloatTensor]:
           if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size):
                 return self.tiled_decode(_a		,     return_dict=_a				)

           _A							:     Union[str, Any]			=						self.post_quant_conv(_a				)
           _A							:     int			=						self.decoder(_a				)

           if not return_dict:
                 return (dec,)

           return DecoderOutput(sample=_a				)

     @apply_forward_hook
     def 					a__	(  self		,     _a		,     _a = True				)						->							Union[DecoderOutput, torch.FloatTensor]:
           if self.use_slicing and z.shape[0] > 1:
                 _A							:     Dict			=						[self._decode(_a				).sample for z_slice in z.split(1				)]
                 _A							:     str			=						torch.cat(_a				)
           else:
                 _A							:     Optional[int]			=						self._decode(_a				).sample

           if not return_dict:
                 return (decoded,)

           return DecoderOutput(sample=_a				)

     def 					a__	(  self		,     _a		,     _a		,     _a				)						->							Any:
           _A							:     int			=						min(a.shape[2]		,     b.shape[2]		,     _a				)
           for y in range(_a				):
                 _A							:     List[Any]			=						a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent)
           return b

     def 					a__	(  self		,     _a		,     _a		,     _a				)						->							Tuple:
           _A							:     Union[str, Any]			=						min(a.shape[3]		,     b.shape[3]		,     _a				)
           for x in range(_a				):
                 _A							:     int			=						a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent)
           return b

     def 					a__	(  self		,     _a		,     _a = True				)						->							AutoencoderKLOutput:
           _A							:     Tuple			=						int(self.tile_sample_min_size * (1 - self.tile_overlap_factor)				)
           _A							:     List[Any]			=						int(self.tile_latent_min_size * self.tile_overlap_factor				)
           _A							:     Union[str, Any]			=						self.tile_latent_min_size - blend_extent

           # Split the image into 512x512 tiles and encode them separately.
           _A							:     str			=						[]
           for i in range(0		,     x.shape[2]		,     _a				):
                 _A							:     Dict			=						[]
                 for j in range(0		,     x.shape[3]		,     _a				):
                       _A							:     Optional[int]			=						x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size]
                       _A							:     Any			=						self.encoder(_a				)
                       _A							:     List[str]			=						self.quant_conv(_a				)
                       row.append(_a				)
                 rows.append(_a				)
           _A							:     List[str]			=						[]
           for i, row in enumerate(_a				):
                 _A							:     Any			=						[]
                 for j, tile in enumerate(_a				):
                       # blend the above tile and the left tile
                       # to the current tile and add the current tile to the result row
                       if i > 0:
                             _A							:     str			=						self.blend_v(rows[i - 1][j]		,     _a		,     _a				)
                       if j > 0:
                             _A							:     Tuple			=						self.blend_h(row[j - 1]		,     _a		,     _a				)
                       result_row.append(tile[:, :, :row_limit, :row_limit]				)
                 result_rows.append(torch.cat(_a		,     dim=3				)				)

           _A							:     Tuple			=						torch.cat(_a		,     dim=2				)
           _A							:     Union[str, Any]			=						DiagonalGaussianDistribution(_a				)

           if not return_dict:
                 return (posterior,)

           return AutoencoderKLOutput(latent_dist=_a				)

     def 					a__	(  self		,     _a		,     _a = True				)						->							Union[DecoderOutput, torch.FloatTensor]:
           _A							:     List[str]			=						int(self.tile_latent_min_size * (1 - self.tile_overlap_factor)				)
           _A							:     List[str]			=						int(self.tile_sample_min_size * self.tile_overlap_factor				)
           _A							:     Dict			=						self.tile_sample_min_size - blend_extent

           # Split z into overlapping 64x64 tiles and decode them separately.
           # The tiles have an overlap to avoid seams between tiles.
           _A							:     Optional[Any]			=						[]
           for i in range(0		,     z.shape[2]		,     _a				):
                 _A							:     List[str]			=						[]
                 for j in range(0		,     z.shape[3]		,     _a				):
                       _A							:     Any			=						z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size]
                       _A							:     List[str]			=						self.post_quant_conv(_a				)
                       _A							:     List[Any]			=						self.decoder(_a				)
                       row.append(_a				)
                 rows.append(_a				)
           _A							:     Dict			=						[]
           for i, row in enumerate(_a				):
                 _A							:     str			=						[]
                 for j, tile in enumerate(_a				):
                       # blend the above tile and the left tile
                       # to the current tile and add the current tile to the result row
                       if i > 0:
                             _A							:     Optional[Any]			=						self.blend_v(rows[i - 1][j]		,     _a		,     _a				)
                       if j > 0:
                             _A							:     Tuple			=						self.blend_h(row[j - 1]		,     _a		,     _a				)
                       result_row.append(tile[:, :, :row_limit, :row_limit]				)
                 result_rows.append(torch.cat(_a		,     dim=3				)				)

           _A							:     Optional[Any]			=						torch.cat(_a		,     dim=2				)
           if not return_dict:
                 return (dec,)

           return DecoderOutput(sample=_a				)



     def 					a__	(  self		,     _a		,     _a = False		,     _a = True		,     _a = None		,     )						->							Union[DecoderOutput, torch.FloatTensor]:
           _A							:     Tuple			=						sample
           _A							:     Union[str, Any]			=						self.encode(_a				).latent_dist
           if sample_posterior:
                 _A							:     str			=						posterior.sample(generator=_a				)
           else:
                 _A							:     Any			=						posterior.mode()
           _A							:     str			=						self.decode(_a				).sample

           if not return_dict:
                 return (dec,)

           return DecoderOutput(sample=_a				)





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


snake_case							:       int     			=      False







@skip_mps
class        snake_case_   (lowerCamelCase_	,						lowerCamelCase_	,						lowerCamelCase_	,						unittest.TestCase      ):
					UpperCAmelCase__					:    Union[str, Any]          =			StableDiffusionAttendAndExcitePipeline
					UpperCAmelCase__					:    List[str]          =			False
					UpperCAmelCase__					:    int          =			TEXT_TO_IMAGE_PARAMS
					UpperCAmelCase__					:    List[Any]          =			TEXT_TO_IMAGE_BATCH_PARAMS.union({'''token_indices'''}      )
					UpperCAmelCase__					:    List[str]          =			TEXT_TO_IMAGE_IMAGE_PARAMS
					UpperCAmelCase__					:    str          =			TEXT_TO_IMAGE_IMAGE_PARAMS
					@classmethod
					def  lowerCamelCase__(      cls   :int      )					->    int:
												super().setUpClass()
												torch.use_deterministic_algorithms(__snake_case      )
					@classmethod
					def  lowerCamelCase__(      cls   :Optional[Any]      )					->    int:
												super().tearDownClass()
												torch.use_deterministic_algorithms(__snake_case      )
					def  lowerCamelCase__(      self   :Dict      )					->    Optional[Any]:
												torch.manual_seed(0      )
												a__             =     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__             =     DDIMScheduler(
												    beta_start=0.0_00_85			,beta_end=0.0_12			,beta_schedule='scaled_linear'			,clip_sample=__snake_case			,set_alpha_to_one=__snake_case			,)
												torch.manual_seed(0      )
												a__             =     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__             =     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=10_00			,hidden_act='gelu'			,projection_dim=5_12			,)
												a__             =     CLIPTextModel(__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  lowerCamelCase__(      self   :Any			,__snake_case   :Union[str, Any]			,__snake_case   :Tuple=0      )					->    Any:
												if str(__snake_case      ).startswith('mps'      ):
																			a__             =     torch.manual_seed(__snake_case      )
												else:
																			a__             =     torch.Generator(device=__snake_case      ).manual_seed(__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  lowerCamelCase__(      self   :Optional[int]      )					->    Any:
												a__             =     'cpu'

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

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

												self.assertEqual(image.shape			,(1, 64, 64, 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(__snake_case			,1E-3      )
					def  lowerCamelCase__(      self   :Optional[Any]      )					->    List[str]:
												super().test_cpu_offload_forward_pass(expected_max_diff=5E-4      )
					def  lowerCamelCase__(      self   :Dict      )					->    List[str]:
												# NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
												self._test_inference_batch_consistent(batch_sizes=[1, 2]      )
					def  lowerCamelCase__(      self   :List[str]      )					->    Optional[int]:
												self._test_inference_batch_single_identical(batch_size=2			,expected_max_diff=7E-4      )
					def  lowerCamelCase__(      self   :Dict      )					->    Dict:
												super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3      )
					def  lowerCamelCase__(      self   :Dict      )					->    Union[str, Any]:
												super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5E-4      )
					def  lowerCamelCase__(      self   :Optional[Any]      )					->    Dict:
												super().test_save_load_local(expected_max_difference=5E-4      )



					def  lowerCamelCase__(      self   :List[Any]      )					->    List[Any]:
												super().test_save_load_optional_components(expected_max_difference=4E-4      )







@require_torch_gpu
@slow
class        snake_case_   (unittest.TestCase      ):
					@classmethod
					def  lowerCamelCase__(      cls   :Optional[Any]      )					->    Tuple:
												super().setUpClass()
												torch.use_deterministic_algorithms(__snake_case      )
					@classmethod
					def  lowerCamelCase__(      cls   :Optional[int]      )					->    Tuple:
												super().tearDownClass()
												torch.use_deterministic_algorithms(__snake_case      )
					def  lowerCamelCase__(      self   :Tuple      )					->    Union[str, Any]:
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()



					def  lowerCamelCase__(      self   :Optional[Any]      )					->    Tuple:
												a__             =     torch.manual_seed(51      )

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

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

												a__             =     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__             =     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




