




"""simple docstring"""




from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import numpy as np
import PIL
from PIL import Image

from ...utils import BaseOutput, is_torch_available, is_transformers_available
@dataclass
class 							lowerCamelCase						(       _UpperCAmelCase ):
   lowercase				:     List[Any]            = {
       'sld_warmup_steps': 1_5,
       'sld_guidance_scale': 2_0,
       'sld_threshold': 0.0,
       'sld_momentum_scale': 0.0,
       'sld_mom_beta': 0.0,
   }
   lowercase				:     Union[str, Any]            = {
       'sld_warmup_steps': 1_0,
       'sld_guidance_scale': 1_0_0_0,
       'sld_threshold': 0.01,
       'sld_momentum_scale': 0.3,
       'sld_mom_beta': 0.4,
   }
   lowercase				:     Any            = {
       'sld_warmup_steps': 7,
       'sld_guidance_scale': 2_0_0_0,
       'sld_threshold': 0.025,
       'sld_momentum_scale': 0.5,
       'sld_mom_beta': 0.7,
   }
   lowercase				:     str            = {
       'sld_warmup_steps': 0,
       'sld_guidance_scale': 5_0_0_0,
       'sld_threshold': 1.0,
       'sld_momentum_scale': 0.5,
       'sld_mom_beta': 0.7,
   }







@dataclass
class 							lowerCamelCase						(       _UpperCAmelCase ):
   lowercase				:     List[str]            = 4_2
   lowercase				:     List[Any]            = 4_2
   lowercase				:     int            = 4_2
   lowercase				:     Optional[Any]            = 4_2


if is_transformers_available() and is_torch_available():
  from .pipeline_stable_diffusion_safe import StableDiffusionPipelineSafe
  from .safety_checker import SafeStableDiffusionSafetyChecker












import tempfile
import unittest

import numpy as np
import torch

from diffusers import DiffusionPipeline
from diffusers.models.attention_processor import Attention, AttnAddedKVProcessor





class   SCREAMING_SNAKE_CASE (       unittest.TestCase    ):





							"""simple docstring"""

							def 					__A       (     self:      Optional[Any]						,   __A:      bool = False      )			-> Union[str, Any]:
												_A									=       10

												if only_cross_attention:
																	_A									=       12
												else:
																	# when only cross attention is not set, the cross attention dim must be the same as the query dim
																	_A									=       query_dim

												return {
												    "query_dim": query_dim,
												    "cross_attention_dim": cross_attention_dim,
												    "heads": 2,
												    "dim_head": 4,
												    "added_kv_proj_dim": 6,
												    "norm_num_groups": 1,
												    "only_cross_attention": only_cross_attention,
												    "processor": AttnAddedKVProcessor(),
												}

							def 					__A       (     self:      List[Any]						,   __A:      str						,   __A:      Union[str, Any]      )			-> Union[str, Any]:
												_A									=       2

												_A									=       torch.rand(__A						,   __A						,   3						,   2      )
												_A									=       torch.rand(__A						,   4						,   __A      )
												_A									=       None

												return {
												    "hidden_states": hidden_states,
												    "encoder_hidden_states": encoder_hidden_states,
												    "attention_mask": attention_mask,
												}



							def 					__A       (     self:      Optional[int]      )			-> Any:
												# self and cross attention

												torch.manual_seed(0      )

												_A									=       self.get_constructor_arguments(only_cross_attention=__A      )
												_A									=       Attention(**__A      )

												self.assertTrue(attn.to_k is not None      )
												self.assertTrue(attn.to_v is not None      )

												_A									=       self.get_forward_arguments(
												    query_dim=constructor_args['''query_dim''']						,   added_kv_proj_dim=constructor_args['''added_kv_proj_dim''']      )

												_A									=       attn(**__A      )

												# only self attention

												torch.manual_seed(0      )

												_A									=       self.get_constructor_arguments(only_cross_attention=__A      )
												_A									=       Attention(**__A      )

												self.assertTrue(attn.to_k is None      )
												self.assertTrue(attn.to_v is None      )

												_A									=       self.get_forward_arguments(
												    query_dim=constructor_args['''query_dim''']						,   added_kv_proj_dim=constructor_args['''added_kv_proj_dim''']      )

												_A									=       attn(**__A      )

												self.assertTrue((only_cross_attn_out != self_and_cross_attn_out).all()      )





class   SCREAMING_SNAKE_CASE (       unittest.TestCase    ):





							"""simple docstring"""

							def 					__A       (     self:      Any      )			-> Dict:
												_A									=       DiffusionPipeline.from_pretrained('''hf-internal-testing/tiny-stable-diffusion-pipe'''						,   safety_checker=__A      )

												_A									=       pipe(
												    '''foo'''						,   num_inference_steps=2						,   generator=torch.Generator('''cpu'''      ).manual_seed(0      )						,   output_type='''np'''						,   ).images

												# the initial conversion succeeds
												_A									=       DiffusionPipeline.from_pretrained(
												    '''hf-internal-testing/tiny-stable-diffusion-pipe'''						,   device_map='''sequential'''						,   safety_checker=__A      )

												_A									=       pipe(
												    '''foo'''						,   num_inference_steps=2						,   generator=torch.Generator('''cpu'''      ).manual_seed(0      )						,   output_type='''np'''						,   ).images

												with tempfile.TemporaryDirectory() as tmpdir:
																	# save the converted model
																	pipe.save_pretrained(__A      )

																	# can also load the converted weights
																	_A									=       DiffusionPipeline.from_pretrained(__A						,   device_map='''sequential'''						,   safety_checker=__A      )

												_A									=       pipe(
												    '''foo'''						,   num_inference_steps=2						,   generator=torch.Generator('''cpu'''      ).manual_seed(0      )						,   output_type='''np'''						,   ).images

												self.assertTrue(np.allclose(__A						,   __A						,   atol=1e-5      )      )
												self.assertTrue(np.allclose(__A						,   __A						,   atol=1e-5      )      )



