






'''simple docstring'''




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       __lowercase					(__lowerCamelCase   ,				__lowerCamelCase   ,				unittest.TestCase    ):
	_lowerCamelCase              =  StableDiffusionSAGPipeline
	_lowerCamelCase              =  TEXT_TO_IMAGE_PARAMS
	_lowerCamelCase              =  TEXT_TO_IMAGE_BATCH_PARAMS
	_lowerCamelCase              =  TEXT_TO_IMAGE_IMAGE_PARAMS
	_lowerCamelCase              =  TEXT_TO_IMAGE_IMAGE_PARAMS
	_lowerCamelCase              =  False

	def      __UpperCamelCase							(      self   :						List[Any]):
			torch.manual_seed(0)
			UpperCamelCase__				:					str					=					UNetaDConditionModel(
			    block_out_channels=(32, 64)  ,					layers_per_block=2  ,					sample_size=32  ,					in_channels=4  ,					out_channels=4  ,					down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')  ,					up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')  ,					cross_attention_dim=32  ,					)
			UpperCamelCase__				:					Dict					=					DDIMScheduler(
			    beta_start=0.0_00_85  ,					beta_end=0.0_12  ,					beta_schedule='scaled_linear'  ,					clip_sample=UpperCAmelCase_  ,					set_alpha_to_one=UpperCAmelCase_  ,					)
			torch.manual_seed(0)
			UpperCamelCase__				:					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  ,					)
			torch.manual_seed(0)
			UpperCamelCase__				:					Tuple					=					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=1_000  ,					)
			UpperCamelCase__				:					List[Any]					=					CLIPTextModel(UpperCAmelCase_)
			UpperCamelCase__				:					Any					=					CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip')

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

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





	def      __UpperCamelCase							(      self   :						Optional[Any]):
			super().test_inference_batch_single_identical(expected_max_diff=3e-3)







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

	def      __UpperCamelCase							(      self   :						Union[str, Any]):
			# clean up the VRAM after each test
			super().tearDown()
			gc.collect()
			torch.cuda.empty_cache()

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

			UpperCamelCase__				:					Dict					=					'.'
			UpperCamelCase__				:					Any					=					torch.manual_seed(0)
			UpperCamelCase__				:					Dict					=					sag_pipe(
			    [prompt]  ,					generator=UpperCAmelCase_  ,					guidance_scale=7.5  ,					sag_scale=1.0  ,					num_inference_steps=20  ,					output_type='np')

			UpperCamelCase__				:					List[str]					=					output.images

			UpperCamelCase__				:					List[Any]					=					image[0, -3:, -3:, -1]

			assert image.shape == (1, 512, 512, 3)
			UpperCamelCase__				:					Optional[Any]					=					np.array([0.15_68, 0.17_38, 0.16_95, 0.16_93, 0.15_07, 0.17_05, 0.15_47, 0.17_51, 0.19_49])

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

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

			UpperCamelCase__				:					Any					=					'.'
			UpperCamelCase__				:					List[Any]					=					torch.manual_seed(0)
			UpperCamelCase__				:					List[str]					=					sag_pipe(
			    [prompt]  ,					generator=UpperCAmelCase_  ,					guidance_scale=7.5  ,					sag_scale=1.0  ,					num_inference_steps=20  ,					output_type='np')

			UpperCamelCase__				:					Dict					=					output.images

			UpperCamelCase__				:					List[Any]					=					image[0, -3:, -3:, -1]

			assert image.shape == (1, 512, 512, 3)
			UpperCamelCase__				:					List[Any]					=					np.array([0.34_59, 0.28_76, 0.25_37, 0.30_02, 0.26_71, 0.21_60, 0.30_26, 0.22_62, 0.23_71])

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





	def      __UpperCamelCase							(      self   :						str):
			UpperCamelCase__				:					Dict					=					StableDiffusionSAGPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base')
			UpperCamelCase__				:					List[str]					=					sag_pipe.to(UpperCAmelCase_)
			sag_pipe.set_progress_bar_config(disable=UpperCAmelCase_)

			UpperCamelCase__				:					List[str]					=					'.'
			UpperCamelCase__				:					List[str]					=					torch.manual_seed(0)
			UpperCamelCase__				:					List[Any]					=					sag_pipe(
			    [prompt]  ,					width=768  ,					height=512  ,					generator=UpperCAmelCase_  ,					guidance_scale=7.5  ,					sag_scale=1.0  ,					num_inference_steps=20  ,					output_type='np'  ,					)

			UpperCamelCase__				:					List[Any]					=					output.images

			assert image.shape == (1, 512, 768, 3)












'''simple docstring'''




import warnings
from collections import OrderedDict
from typing import Mapping

from packaging import version

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


lowerCAmelCase__          =						logging.get_logger(__name__)

lowerCAmelCase__          =						{
    'nvidia/segformer-b0-finetuned-ade-512-512': (
        'https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json'
    ),
    # See all SegFormer models at https://huggingface.co/models?filter=segformer
}







class       __lowercase					(__lowerCamelCase    ):
	_lowerCamelCase              =  '''segformer'''

	def __init__(      self   :						Tuple  ,					UpperCAmelCase_   :						Optional[Any]=3  ,					UpperCAmelCase_   :						Optional[int]=4  ,					UpperCAmelCase_   :						Tuple=[2, 2, 2, 2]  ,					UpperCAmelCase_   :						List[str]=[8, 4, 2, 1]  ,					UpperCAmelCase_   :						Union[str, Any]=[32, 64, 160, 256]  ,					UpperCAmelCase_   :						Any=[7, 3, 3, 3]  ,					UpperCAmelCase_   :						Any=[4, 2, 2, 2]  ,					UpperCAmelCase_   :						Union[str, Any]=[1, 2, 5, 8]  ,					UpperCAmelCase_   :						Tuple=[4, 4, 4, 4]  ,					UpperCAmelCase_   :						str="gelu"  ,					UpperCAmelCase_   :						List[Any]=0.0  ,					UpperCAmelCase_   :						int=0.0  ,					UpperCAmelCase_   :						int=0.1  ,					UpperCAmelCase_   :						List[str]=0.02  ,					UpperCAmelCase_   :						Dict=0.1  ,					UpperCAmelCase_   :						Dict=1e-6  ,					UpperCAmelCase_   :						int=256  ,					UpperCAmelCase_   :						Optional[int]=255  ,					**UpperCAmelCase_   :						Tuple  ,					):
			super().__init__(**UpperCAmelCase_)

			if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False:
					warnings.warn(
					    'Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be'
					    ' removed, as the behaviour will default to that of reshape_last_stage = True.'  ,					UpperCAmelCase_  ,					)

			UpperCamelCase__				:					List[Any]					=					num_channels
			UpperCamelCase__				:					Any					=					num_encoder_blocks
			UpperCamelCase__				:					Dict					=					depths
			UpperCamelCase__				:					int					=					sr_ratios
			UpperCamelCase__				:					str					=					hidden_sizes
			UpperCamelCase__				:					List[str]					=					patch_sizes
			UpperCamelCase__				:					Optional[int]					=					strides
			UpperCamelCase__				:					Dict					=					mlp_ratios
			UpperCamelCase__				:					List[str]					=					num_attention_heads
			UpperCamelCase__				:					int					=					hidden_act
			UpperCamelCase__				:					Any					=					hidden_dropout_prob
			UpperCamelCase__				:					str					=					attention_probs_dropout_prob
			UpperCamelCase__				:					List[str]					=					classifier_dropout_prob
			UpperCamelCase__				:					List[Any]					=					initializer_range
			UpperCamelCase__				:					Union[str, Any]					=					drop_path_rate
			UpperCamelCase__				:					int					=					layer_norm_eps
			UpperCamelCase__				:					Dict					=					decoder_hidden_size
			UpperCamelCase__				:					List[Any]					=					kwargs.get('reshape_last_stage'  ,					UpperCAmelCase_)
			UpperCamelCase__				:					List[str]					=					semantic_loss_ignore_index







class       __lowercase					(__lowerCamelCase    ):
	_lowerCamelCase              =  version.parse('''1.11'''    )

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

	@property
	def      __UpperCamelCase							(      self   :						Optional[Any]):
			return 1e-4





	@property
	def      __UpperCamelCase							(      self   :						Any):
			return 12




