


'''simple docstring'''




import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMParallelScheduler,
    DDPMParallelScheduler,
    StableDiffusionParadigmsPipeline,
    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   (  __lowercase	,				__lowercase	,				unittest.TestCase       ):
   _SCREAMING_SNAKE_CASE     :     int									=  StableDiffusionParadigmsPipeline
   _SCREAMING_SNAKE_CASE     :     str									=  TEXT_TO_IMAGE_PARAMS
   _SCREAMING_SNAKE_CASE     :     int									=  TEXT_TO_IMAGE_BATCH_PARAMS
   _SCREAMING_SNAKE_CASE     :     Optional[int]									=  TEXT_TO_IMAGE_IMAGE_PARAMS
   _SCREAMING_SNAKE_CASE     :     Dict									=  TEXT_TO_IMAGE_IMAGE_PARAMS
   def a     (	self					:			Union[str, Any]			)   ->       Optional[int]:
        torch.manual_seed(0			)
        __snake_case    			=	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					,      attention_head_dim=(2, 4)					,      use_linear_projection=SCREAMING_SNAKE_CASE_					,      )
        __snake_case    			=	DDIMParallelScheduler(
            beta_start=0.0_0_0_8_5					,      beta_end=0.0_1_2					,      beta_schedule='scaled_linear'					,      clip_sample=SCREAMING_SNAKE_CASE_					,      set_alpha_to_one=SCREAMING_SNAKE_CASE_					,      )
        torch.manual_seed(0			)
        __snake_case    			=	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			)
        __snake_case    			=	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=1000					,      hidden_act='gelu'					,      projection_dim=512					,      )
        __snake_case    			=	CLIPTextModel(SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'			)

        __snake_case    			=	{
            'unet': unet,
            'scheduler': scheduler,
            'vae': vae,
            'text_encoder': text_encoder,
            'tokenizer': tokenizer,
            'safety_checker': None,
            'feature_extractor': None,
        }
        return components
   def a     (	self					:			Dict					,      SCREAMING_SNAKE_CASE_					:			str					,      SCREAMING_SNAKE_CASE_					:			Tuple=0			)   ->       str:
        if str(SCREAMING_SNAKE_CASE_			).startswith('mps'			):
             __snake_case    			=	torch.manual_seed(SCREAMING_SNAKE_CASE_			)
        else:
             __snake_case    			=	torch.Generator(device=SCREAMING_SNAKE_CASE_			).manual_seed(SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	{
            'prompt': 'a photograph of an astronaut riding a horse',
            'generator': generator,
            'num_inference_steps': 10,
            'guidance_scale': 6.0,
            'output_type': 'numpy',
            'parallel': 3,
            'debug': True,
        }
        return inputs
   def a     (	self					:			Dict			)   ->       List[str]:
        __snake_case    			=	'cpu'  # ensure determinism for the device-dependent torch.Generator
        __snake_case    			=	self.get_dummy_components()
        __snake_case    			=	StableDiffusionParadigmsPipeline(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	sd_pipe.to(SCREAMING_SNAKE_CASE_			)
        sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_			)

        __snake_case    			=	self.get_dummy_inputs(SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	sd_pipe(**SCREAMING_SNAKE_CASE_			).images
        __snake_case    			=	image[0, -3:, -3:, -1]
        assert image.shape == (1, 64, 64, 3)

        __snake_case    			=	np.array([0.4_7_7_3, 0.5_4_1_7, 0.4_7_2_3, 0.4_9_2_5, 0.5_6_3_1, 0.4_7_5_2, 0.5_2_4_0, 0.4_9_3_5, 0.5_0_2_3]			)

        assert np.abs(image_slice.flatten() - expected_slice			).max() < 1e-2
   def a     (	self					:			List[str]			)   ->       int:
        __snake_case    			=	'cpu'  # ensure determinism for the device-dependent torch.Generator
        __snake_case    			=	self.get_dummy_components()
        torch.manual_seed(0			)
        __snake_case    			=	DDPMParallelScheduler()
        torch.manual_seed(0			)
        __snake_case    			=	StableDiffusionParadigmsPipeline(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	sd_pipe.to(SCREAMING_SNAKE_CASE_			)
        sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_			)

        __snake_case    			=	self.get_dummy_inputs(SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	sd_pipe(**SCREAMING_SNAKE_CASE_			).images
        __snake_case    			=	image[0, -3:, -3:, -1]
        assert image.shape == (1, 64, 64, 3)

        __snake_case    			=	np.array([0.3_5_7_3, 0.4_4_2_0, 0.4_9_6_0, 0.4_7_9_9, 0.3_7_9_6, 0.3_8_7_9, 0.4_8_1_9, 0.4_3_6_5, 0.4_4_6_8]			)

        assert np.abs(image_slice.flatten() - expected_slice			).max() < 1e-2
   def a     (	self					:			Any			)   ->       List[str]:
        super().test_inference_batch_consistent(batch_sizes=[1, 2]			)
   def a     (	self					:			Union[str, Any]			)   ->       int:
        super().test_inference_batch_single_identical(batch_size=2					,      expected_max_diff=3e-3			)





   def a     (	self					:			Union[str, Any]			)   ->       List[Any]:
        __snake_case    			=	'cpu'  # ensure determinism for the device-dependent torch.Generator
        __snake_case    			=	self.get_dummy_components()
        __snake_case    			=	StableDiffusionParadigmsPipeline(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	sd_pipe.to(SCREAMING_SNAKE_CASE_			)
        sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_			)

        __snake_case    			=	self.get_dummy_inputs(SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	'french fries'
        __snake_case    			=	sd_pipe(**SCREAMING_SNAKE_CASE_					,      negative_prompt=SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	output.images
        __snake_case    			=	image[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)

        __snake_case    			=	np.array([0.4_7_7_1, 0.5_4_2_0, 0.4_6_8_3, 0.4_9_1_8, 0.5_6_3_6, 0.4_7_2_5, 0.5_2_3_0, 0.4_9_2_3, 0.5_0_1_5]			)

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




@slow
@require_torch_gpu
class  _lowercase   (  unittest.TestCase       ):
   def a     (	self					:			List[Any]			)   ->       Union[str, Any]:
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()
   def a     (	self					:			int					,      SCREAMING_SNAKE_CASE_					:			List[str]=0			)   ->       Dict:
        __snake_case    			=	torch.Generator(device=SCREAMING_SNAKE_CASE_			).manual_seed(SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	{
            'prompt': 'a photograph of an astronaut riding a horse',
            'generator': generator,
            'num_inference_steps': 10,
            'guidance_scale': 7.5,
            'output_type': 'numpy',
            'parallel': 3,
            'debug': True,
        }
        return inputs





   def a     (	self					:			List[Any]			)   ->       Optional[int]:
        __snake_case    			=	'stabilityai/stable-diffusion-2-base'
        __snake_case    			=	DDIMParallelScheduler.from_pretrained(SCREAMING_SNAKE_CASE_					,      subfolder='scheduler'			)
        __snake_case    			=	StableDiffusionParadigmsPipeline.from_pretrained(SCREAMING_SNAKE_CASE_					,      scheduler=SCREAMING_SNAKE_CASE_					,      safety_checker=SCREAMING_SNAKE_CASE_			)
        pipe.to(SCREAMING_SNAKE_CASE_			)
        pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_			)
        pipe.enable_attention_slicing()

        __snake_case    			=	self.get_inputs()
        __snake_case    			=	pipe(**SCREAMING_SNAKE_CASE_			).images
        __snake_case    			=	image[0, -3:, -3:, -1].flatten()

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

        __snake_case    			=	np.array([0.9_6_2_2, 0.9_6_0_2, 0.9_7_4_8, 0.9_5_9_1, 0.9_6_3_0, 0.9_6_9_1, 0.9_6_6_1, 0.9_6_3_1, 0.9_7_4_1]			)

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








'''simple docstring'''




import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_a      :      List[str]       				=      logging.get_logger(__name__)

_a      :      Any       				=      {
    "facebook/sam-vit-huge": "https://huggingface.co/facebook/sam-vit-huge/resolve/main/config.json",
    "facebook/sam-vit-large": "https://huggingface.co/facebook/sam-vit-large/resolve/main/config.json",
    "facebook/sam-vit-base": "https://huggingface.co/facebook/sam-vit-base/resolve/main/config.json",
}




class  _lowercase   (  __lowercase       ):
   def __init__(	self					:			int					,      SCREAMING_SNAKE_CASE_					:			List[Any]=256					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]=1024					,      SCREAMING_SNAKE_CASE_					:			Any=16					,      SCREAMING_SNAKE_CASE_					:			int=16					,      SCREAMING_SNAKE_CASE_					:			List[Any]=4					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]="gelu"					,      SCREAMING_SNAKE_CASE_					:			Tuple=1e-6					,      **SCREAMING_SNAKE_CASE_					:			Optional[Any]					,      )   ->       Tuple:
        super().__init__(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	hidden_size
        __snake_case    			=	image_size
        __snake_case    			=	patch_size
        __snake_case    			=	image_size // patch_size
        __snake_case    			=	mask_input_channels
        __snake_case    			=	num_point_embeddings
        __snake_case    			=	hidden_act
        __snake_case    			=	layer_norm_eps




class  _lowercase   (  __lowercase       ):
   def __init__(	self					:			List[Any]					,      SCREAMING_SNAKE_CASE_					:			List[Any]=256					,      SCREAMING_SNAKE_CASE_					:			Dict="relu"					,      SCREAMING_SNAKE_CASE_					:			Any=2048					,      SCREAMING_SNAKE_CASE_					:			int=2					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]=8					,      SCREAMING_SNAKE_CASE_					:			int=2					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=3					,      SCREAMING_SNAKE_CASE_					:			str=3					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]=256					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=1e-6					,      **SCREAMING_SNAKE_CASE_					:			int					,      )   ->       str:
        super().__init__(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	hidden_size
        __snake_case    			=	hidden_act
        __snake_case    			=	mlp_dim
        __snake_case    			=	num_hidden_layers
        __snake_case    			=	num_attention_heads
        __snake_case    			=	attention_downsample_rate
        __snake_case    			=	num_multimask_outputs
        __snake_case    			=	iou_head_depth
        __snake_case    			=	iou_head_hidden_dim
        __snake_case    			=	layer_norm_eps




class  _lowercase   (  __lowercase       ):
   def __init__(	self					:			Union[str, Any]					,      SCREAMING_SNAKE_CASE_					:			int=768					,      SCREAMING_SNAKE_CASE_					:			int=256					,      SCREAMING_SNAKE_CASE_					:			str=12					,      SCREAMING_SNAKE_CASE_					:			Tuple=12					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]=3					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=1024					,      SCREAMING_SNAKE_CASE_					:			List[str]=16					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]="gelu"					,      SCREAMING_SNAKE_CASE_					:			Any=1e-06					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=0.0					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=1e-10					,      SCREAMING_SNAKE_CASE_					:			List[Any]=True					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=4.0					,      SCREAMING_SNAKE_CASE_					:			List[Any]=True					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=True					,      SCREAMING_SNAKE_CASE_					:			Union[str, Any]=14					,      SCREAMING_SNAKE_CASE_					:			str=[2, 5, 8, 11]					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=128					,      SCREAMING_SNAKE_CASE_					:			Tuple=None					,      **SCREAMING_SNAKE_CASE_					:			List[Any]					,      )   ->       Optional[Any]:
        super().__init__(**SCREAMING_SNAKE_CASE_			)

        __snake_case    			=	hidden_size
        __snake_case    			=	output_channels
        __snake_case    			=	num_hidden_layers
        __snake_case    			=	num_attention_heads
        __snake_case    			=	num_channels
        __snake_case    			=	image_size
        __snake_case    			=	patch_size
        __snake_case    			=	hidden_act
        __snake_case    			=	layer_norm_eps
        __snake_case    			=	attention_dropout
        __snake_case    			=	initializer_range
        __snake_case    			=	qkv_bias
        __snake_case    			=	mlp_ratio
        __snake_case    			=	use_abs_pos
        __snake_case    			=	use_rel_pos
        __snake_case    			=	window_size
        __snake_case    			=	global_attn_indexes
        __snake_case    			=	num_pos_feats
        __snake_case    			=	int(hidden_size * mlp_ratio			) if mlp_dim is None else mlp_dim




class  _lowercase   (  __lowercase       ):
   _SCREAMING_SNAKE_CASE     :     Union[str, Any]									=  "sam"
   _SCREAMING_SNAKE_CASE     :     Any									=  True
   def __init__(	self					:			Optional[Any]					,      SCREAMING_SNAKE_CASE_					:			Dict=None					,      SCREAMING_SNAKE_CASE_					:			List[Any]=None					,      SCREAMING_SNAKE_CASE_					:			List[str]=None					,      SCREAMING_SNAKE_CASE_					:			str=0.0_2					,      **SCREAMING_SNAKE_CASE_					:			str					,      )   ->       str:
        super().__init__(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	vision_config if vision_config is not None else {}
        __snake_case    			=	prompt_encoder_config if prompt_encoder_config is not None else {}
        __snake_case    			=	mask_decoder_config if mask_decoder_config is not None else {}

        if isinstance(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			):
             __snake_case    			=	vision_config.to_dict()
        if isinstance(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			):
             __snake_case    			=	prompt_encoder_config.to_dict()
        if isinstance(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			):
             __snake_case    			=	mask_decoder_config.to_dict()

        __snake_case    			=	SamVisionConfig(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	SamPromptEncoderConfig(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	SamMaskDecoderConfig(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	initializer_range





   def a     (	self					:			int			)   ->       str:
        __snake_case    			=	copy.deepcopy(self.__dict__			)
        __snake_case    			=	self.vision_config.to_dict()
        __snake_case    			=	self.prompt_encoder_config.to_dict()
        __snake_case    			=	self.mask_decoder_config.to_dict()
        __snake_case    			=	self.__class__.model_type
        return output




