



import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionSAGPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, 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 PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()



class 				__snake_case						(     UpperCamelCase_						,UpperCamelCase_						,unittest.TestCase						):
							_a			      = StableDiffusionSAGPipeline
							_a			      = TEXT_TO_IMAGE_PARAMS
							_a			      = TEXT_TO_IMAGE_BATCH_PARAMS
							_a			      = TEXT_TO_IMAGE_IMAGE_PARAMS
							_a			      = TEXT_TO_IMAGE_IMAGE_PARAMS
							_a			      = False




							def    UpperCAmelCase__			(       self     :       str):
									torch.manual_seed(0)
									lowerCAmelCase_			:     Optional[Any]									= UNetaDConditionModel(
									    block_out_channels=(3_2, 6_4)				,				layers_per_block=2				,				sample_size=3_2				,				in_channels=4				,				out_channels=4				,				down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')				,				up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')				,				cross_attention_dim=3_2				,				)
									lowerCAmelCase_			:     Optional[int]									= DDIMScheduler(
									    beta_start=0.0_0085				,				beta_end=0.012				,				beta_schedule='''scaled_linear'''				,				clip_sample=A_				,				set_alpha_to_one=A_				,				)
									torch.manual_seed(0)
									lowerCAmelCase_			:     int									= AutoencoderKL(
									    block_out_channels=[3_2, 6_4]				,				in_channels=3				,				out_channels=3				,				down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']				,				up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']				,				latent_channels=4				,				)
									torch.manual_seed(0)
									lowerCAmelCase_			:     int									= CLIPTextConfig(
									    bos_token_id=0				,				eos_token_id=2				,				hidden_size=3_2				,				intermediate_size=3_7				,				layer_norm_eps=1e-05				,				num_attention_heads=4				,				num_hidden_layers=5				,				pad_token_id=1				,				vocab_size=1_0_0_0				,				)
									lowerCAmelCase_			:     List[Any]									= CLIPTextModel(A_)
									lowerCAmelCase_			:     int									= CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''')

									lowerCAmelCase_			:     Optional[Any]									= {
									    '''unet''': unet,
									    '''scheduler''': scheduler,
									    '''vae''': vae,
									    '''text_encoder''': text_encoder,
									    '''tokenizer''': tokenizer,
									    '''safety_checker''': None,
									    '''feature_extractor''': None,
									}
									return components




							def    UpperCAmelCase__			(       self     :       List[Any]				,				A_     :       List[str]				,				A_     :       Dict=0):
									if str(A_).startswith('''mps'''):
											lowerCAmelCase_			:     str									= torch.manual_seed(A_)
									else:
											lowerCAmelCase_			:     str									= torch.Generator(device=A_).manual_seed(A_)
									lowerCAmelCase_			:     Optional[int]									= {
									    '''prompt''': '''.''',
									    '''generator''': generator,
									    '''num_inference_steps''': 2,
									    '''guidance_scale''': 1.0,
									    '''sag_scale''': 1.0,
									    '''output_type''': '''numpy''',
									}
									return inputs







							def    UpperCAmelCase__			(       self     :       int):
									super().test_inference_batch_single_identical(expected_max_diff=3e-3)





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




							def    UpperCAmelCase__			(       self     :       Dict):
									# clean up the VRAM after each test
									super().tearDown()
									gc.collect()
									torch.cuda.empty_cache()




							def    UpperCAmelCase__			(       self     :       Union[str, Any]):
									lowerCAmelCase_			:     Optional[int]									= StableDiffusionSAGPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4''')
									lowerCAmelCase_			:     Optional[Any]									= sag_pipe.to(A_)
									sag_pipe.set_progress_bar_config(disable=A_)

									lowerCAmelCase_			:     Optional[Any]									= '''.'''
									lowerCAmelCase_			:     Union[str, Any]									= torch.manual_seed(0)
									lowerCAmelCase_			:     List[str]									= sag_pipe(
									    [prompt]				,				generator=A_				,				guidance_scale=7.5				,				sag_scale=1.0				,				num_inference_steps=2_0				,				output_type='''np''')

									lowerCAmelCase_			:     List[Any]									= output.images

									lowerCAmelCase_			:     str									= image[0, -3:, -3:, -1]

									assert image.shape == (1, 5_1_2, 5_1_2, 3)
									lowerCAmelCase_			:     Any									= np.array([0.1568, 0.1738, 0.1695, 0.1693, 0.1507, 0.1705, 0.1547, 0.1751, 0.1949])

									assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2




							def    UpperCAmelCase__			(       self     :       List[str]):
									lowerCAmelCase_			:     Optional[int]									= StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''')
									lowerCAmelCase_			:     Any									= sag_pipe.to(A_)
									sag_pipe.set_progress_bar_config(disable=A_)

									lowerCAmelCase_			:     Optional[Any]									= '''.'''
									lowerCAmelCase_			:     str									= torch.manual_seed(0)
									lowerCAmelCase_			:     Tuple									= sag_pipe(
									    [prompt]				,				generator=A_				,				guidance_scale=7.5				,				sag_scale=1.0				,				num_inference_steps=2_0				,				output_type='''np''')

									lowerCAmelCase_			:     Any									= output.images

									lowerCAmelCase_			:     Optional[int]									= image[0, -3:, -3:, -1]

									assert image.shape == (1, 5_1_2, 5_1_2, 3)
									lowerCAmelCase_			:     int									= np.array([0.3459, 0.2876, 0.2537, 0.3002, 0.2671, 0.2160, 0.3026, 0.2262, 0.2371])

									assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2







							def    UpperCAmelCase__			(       self     :       List[Any]):
									lowerCAmelCase_			:     Optional[Any]									= StableDiffusionSAGPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''')
									lowerCAmelCase_			:     int									= sag_pipe.to(A_)
									sag_pipe.set_progress_bar_config(disable=A_)

									lowerCAmelCase_			:     List[str]									= '''.'''
									lowerCAmelCase_			:     str									= torch.manual_seed(0)
									lowerCAmelCase_			:     Dict									= sag_pipe(
									    [prompt]				,				width=7_6_8				,				height=5_1_2				,				generator=A_				,				guidance_scale=7.5				,				sag_scale=1.0				,				num_inference_steps=2_0				,				output_type='''np'''				,				)

									lowerCAmelCase_			:     Union[str, Any]									= output.images

									assert image.shape == (1, 5_1_2, 7_6_8, 3)






"""simple docstring"""


from collections import OrderedDict
from typing import List, Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


UpperCAmelCase__     						=  logging.get_logger(__name__)

UpperCAmelCase__     						=  {
    """google/efficientnet-b7""": """https://huggingface.co/google/efficientnet-b7/resolve/main/config.json""",
}


class 				a (						lowerCAmelCase_      ):
    _snake_case   :     Any   							=							'efficientnet'


    def __init__(    self		:     Any      , __lowerCAmelCase		:     int = 3      , __lowerCAmelCase		:     int = 600      , __lowerCAmelCase		:     float = 2.0      , __lowerCAmelCase		:     float = 3.1      , __lowerCAmelCase		:     int = 8      , __lowerCAmelCase		:     List[int] = [3, 3, 5, 3, 5, 5, 3]      , __lowerCAmelCase		:     List[int] = [32, 16, 24, 40, 80, 112, 192]      , __lowerCAmelCase		:     List[int] = [16, 24, 40, 80, 112, 192, 320]      , __lowerCAmelCase		:     List[int] = []      , __lowerCAmelCase		:     List[int] = [1, 2, 2, 2, 1, 2, 1]      , __lowerCAmelCase		:     List[int] = [1, 2, 2, 3, 3, 4, 1]      , __lowerCAmelCase		:     List[int] = [1, 6, 6, 6, 6, 6, 6]      , __lowerCAmelCase		:     float = 0.25      , __lowerCAmelCase		:     str = "swish"      , __lowerCAmelCase		:     int = 2560      , __lowerCAmelCase		:     str = "mean"      , __lowerCAmelCase		:     float = 0.02      , __lowerCAmelCase		:     float = 0.001      , __lowerCAmelCase		:     float = 0.99      , __lowerCAmelCase		:     float = 0.5      , __lowerCAmelCase		:     float = 0.2      , **__lowerCAmelCase		:     List[Any]      , ):
      super().__init__(**__lowerCAmelCase    )

      _UpperCAmelCase         =					num_channels
      _UpperCAmelCase         =					image_size
      _UpperCAmelCase         =					width_coefficient
      _UpperCAmelCase         =					depth_coefficient
      _UpperCAmelCase         =					depth_divisor
      _UpperCAmelCase         =					kernel_sizes
      _UpperCAmelCase         =					in_channels
      _UpperCAmelCase         =					out_channels
      _UpperCAmelCase         =					depthwise_padding
      _UpperCAmelCase         =					strides
      _UpperCAmelCase         =					num_block_repeats
      _UpperCAmelCase         =					expand_ratios
      _UpperCAmelCase         =					squeeze_expansion_ratio
      _UpperCAmelCase         =					hidden_act
      _UpperCAmelCase         =					hidden_dim
      _UpperCAmelCase         =					pooling_type
      _UpperCAmelCase         =					initializer_range
      _UpperCAmelCase         =					batch_norm_eps
      _UpperCAmelCase         =					batch_norm_momentum
      _UpperCAmelCase         =					dropout_rate
      _UpperCAmelCase         =					drop_connect_rate
      _UpperCAmelCase         =					sum(__lowerCAmelCase    ) * 4



class 				a (						lowerCAmelCase_      ):
    _snake_case   :     Dict   							=							version.parse('1.11'      )


    @property
    def    lowerCAmelCase_     (    self		:     Any    ):
      return OrderedDict(
          [
              ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
          ]    )


    @property
    def    lowerCAmelCase_     (    self		:     int    ):
      return 1e-5
