"""simple docstring"""





import gc
import random
import unittest

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

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()




class  _snake_case		(    __snake_case   ,       __snake_case   ,       unittest.TestCase ):







				"""simple docstring"""






				a			=						StableDiffusionXLImgaImgPipeline
				a			=						TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"}
				a			=						PipelineTesterMixin.required_optional_params - {"latents"}
				a			=						TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
				a			=						IMAGE_TO_IMAGE_IMAGE_PARAMS
				a			=						IMAGE_TO_IMAGE_IMAGE_PARAMS





				def 		_lowerCAmelCase		(      self							:							Dict):



											"""simple docstring"""







											torch.manual_seed(0)
											_SCREAMING_SNAKE_CASE		:						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""")      ,    attention_head_dim=(2, 4)      ,    use_linear_projection=_A      ,    addition_embed_type="""text_time"""      ,    addition_time_embed_dim=8      ,    transformer_layers_per_block=(1, 2)      ,    projection_class_embeddings_input_dim=8_0      ,    cross_attention_dim=6_4      ,    )
											_SCREAMING_SNAKE_CASE		:						Dict			  =    EulerDiscreteScheduler(
											    beta_start=0.00_085      ,    beta_end=0.012      ,    steps_offset=1      ,    beta_schedule="""scaled_linear"""      ,    timestep_spacing="""leading"""      ,    )
											torch.manual_seed(0)
											_SCREAMING_SNAKE_CASE		:						Any			  =    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      ,    sample_size=1_2_8      ,    )
											torch.manual_seed(0)
											_SCREAMING_SNAKE_CASE		:						Any			  =    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      ,    hidden_act="""gelu"""      ,    projection_dim=3_2      ,    )
											_SCREAMING_SNAKE_CASE		:						Union[str, Any]			  =    CLIPTextModel(_A)
											_SCREAMING_SNAKE_CASE		:						Union[str, Any]			  =    CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""      ,    local_files_only=_A)

											_SCREAMING_SNAKE_CASE		:						int			  =    CLIPTextModelWithProjection(_A)
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""      ,    local_files_only=_A)

											_SCREAMING_SNAKE_CASE		:						int			  =    {
											    """unet""": unet,
											    """scheduler""": scheduler,
											    """vae""": vae,
											    """text_encoder""": text_encoder,
											    """tokenizer""": tokenizer,
											    """text_encoder_2""": text_encoder_a,
											    """tokenizer_2""": tokenizer_a,
											    # "safety_checker": None,
											    # "feature_extractor": None,
											}
											return components





				def 		_lowerCAmelCase		(      self							:							int      ,    _A							:							Optional[int]      ,    _A							:							List[str]=0):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:						int			  =    floats_tensor((1, 3, 3_2, 3_2)      ,    rng=random.Random(_A)).to(_A)
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    image / 2 + 0.5
											if str(_A).startswith("""mps"""):
																		_SCREAMING_SNAKE_CASE		:						Union[str, Any]			  =    torch.manual_seed(_A)
											else:
																		_SCREAMING_SNAKE_CASE		:						str			  =    torch.Generator(device=_A).manual_seed(_A)
											_SCREAMING_SNAKE_CASE		:						int			  =    {
											    """prompt""": """A painting of a squirrel eating a burger""",
											    """image""": image,
											    """generator""": generator,
											    """num_inference_steps""": 2,
											    """guidance_scale""": 5.0,
											    """output_type""": """numpy""",
											    """strength""": 0.75,
											}
											return inputs





				def 		_lowerCAmelCase		(      self							:							Any):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:						Optional[Any]			  =    """cpu"""  # ensure determinism for the device-dependent torch.Generator
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    self.get_dummy_components()
											_SCREAMING_SNAKE_CASE		:						Dict			  =    StableDiffusionXLImgaImgPipeline(**_A)
											_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    sd_pipe.to(_A)
											sd_pipe.set_progress_bar_config(disable=_A)

											_SCREAMING_SNAKE_CASE		:						Optional[Any]			  =    self.get_dummy_inputs(_A)
											_SCREAMING_SNAKE_CASE		:						Any			  =    sd_pipe(**_A).images
											_SCREAMING_SNAKE_CASE		:						int			  =    image[0, -3:, -3:, -1]

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

											_SCREAMING_SNAKE_CASE		:						str			  =    np.array([0.4_656, 0.4_840, 0.4_439, 0.6_698, 0.5_574, 0.4_524, 0.5_799, 0.5_943, 0.5_165])

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





				def 		_lowerCAmelCase		(      self							:							Any):



											"""simple docstring"""







											super().test_attention_slicing_forward_pass(expected_max_diff=3e-3)





				def 		_lowerCAmelCase		(      self							:							Any):



											"""simple docstring"""







											super().test_inference_batch_single_identical(expected_max_diff=3e-3)





				def 		_lowerCAmelCase		(      self							:							Tuple):



											"""simple docstring"""







											pass





				def 		_lowerCAmelCase		(      self							:							List[str]):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    self.get_dummy_components()
											_SCREAMING_SNAKE_CASE		:						List[str]			  =    StableDiffusionXLImgaImgPipeline(**_A)
											_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    sd_pipe.to(_A)
											_SCREAMING_SNAKE_CASE		:						str			  =    sd_pipe.to(_A)
											sd_pipe.set_progress_bar_config(disable=_A)

											# forward without prompt embeds
											_SCREAMING_SNAKE_CASE		:						Optional[Any]			  =    self.get_dummy_inputs(_A)
											_SCREAMING_SNAKE_CASE		:						List[str]			  =    3 * ["""this is a negative prompt"""]
											_SCREAMING_SNAKE_CASE		:						str			  =    negative_prompt
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    3 * [inputs["""prompt"""]]

											_SCREAMING_SNAKE_CASE		:						List[str]			  =    sd_pipe(**_A)
											_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    output.images[0, -3:, -3:, -1]

											# forward with prompt embeds
											_SCREAMING_SNAKE_CASE		:						Any			  =    self.get_dummy_inputs(_A)
											_SCREAMING_SNAKE_CASE		:						Optional[Any]			  =    3 * ["""this is a negative prompt"""]
											_SCREAMING_SNAKE_CASE		:						Tuple			  =    3 * [inputs.pop("""prompt""")]

											(
											    (
											    _SCREAMING_SNAKE_CASE
											)  ,				(
											    _SCREAMING_SNAKE_CASE
											)  ,				(
											    _SCREAMING_SNAKE_CASE
											)  ,				(
											    _SCREAMING_SNAKE_CASE
											)  ,				
											)		:						Dict			  =    sd_pipe.encode_prompt(_A      ,    negative_prompt=_A)

											_SCREAMING_SNAKE_CASE		:						Tuple			  =    sd_pipe(
											    **_A      ,    prompt_embeds=_A      ,    negative_prompt_embeds=_A      ,    pooled_prompt_embeds=_A      ,    negative_pooled_prompt_embeds=_A      ,    )
											_SCREAMING_SNAKE_CASE		:						Dict			  =    output.images[0, -3:, -3:, -1]

											# make sure that it's equal
											assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()).max() < 1e-4




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







				"""simple docstring"""






				def 		_lowerCAmelCase		(      self							:							str):



											"""simple docstring"""







											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()





				def 		_lowerCAmelCase		(      self							:							Optional[Any]      ,    _A							:							Optional[Any]      ,    _A							:							Union[str, Any]="cpu"      ,    _A							:							Dict=torch.floataa      ,    _A							:							Optional[int]=0):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:						Dict			  =    torch.Generator(device=_A).manual_seed(_A)
											_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    np.random.RandomState(_A).standard_normal((1, 4, 6_4, 6_4))
											_SCREAMING_SNAKE_CASE		:						Tuple			  =    torch.from_numpy(_A).to(device=_A      ,    dtype=_A)
											_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    {
											    """prompt""": """a photograph of an astronaut riding a horse""",
											    """latents""": latents,
											    """generator""": generator,
											    """num_inference_steps""": 3,
											    """guidance_scale""": 7.5,
											    """output_type""": """numpy""",
											}
											return inputs





				def 		_lowerCAmelCase		(      self							:							List[str]):



											"""simple docstring"""







											_SCREAMING_SNAKE_CASE		:						int			  =    DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base""")
											pipe.to(_A)
											pipe.set_progress_bar_config(disable=_A)

											_SCREAMING_SNAKE_CASE		:						str			  =    self.get_inputs(_A)
											_SCREAMING_SNAKE_CASE		:						Dict			  =    pipe(**_A).images
											_SCREAMING_SNAKE_CASE		:						Tuple			  =    image[0, -3:, -3:, -1].flatten()

											assert image.shape == (1, 5_1_2, 5_1_2, 3)
											_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    np.array([0.49_493, 0.47_896, 0.40_798, 0.54_214, 0.53_212, 0.48_202, 0.47_656, 0.46_329, 0.48_506])
											assert np.abs(image_slice - expected_slice).max() < 7e-3



"""simple docstring"""





import functools
import operator

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


lowerCAmelCase_     =	logging.get_logger(__name__)

lowerCAmelCase_     =	{
    '''asapp/sew-tiny-100k''': '''https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json''',
    # See all SEW models at https://huggingface.co/models?filter=sew
}




class  _snake_case		(    __snake_case ):







				"""simple docstring"""






				a			=						"sew"





				def __init__(      self							:							List[Any]      ,    _A							:							Tuple=3_2      ,    _A							:							str=7_6_8      ,    _A							:							Dict=1_2      ,    _A							:							Tuple=1_2      ,    _A							:							Optional[Any]=3_0_7_2      ,    _A							:							List[str]=2      ,    _A							:							Dict="gelu"      ,    _A							:							Union[str, Any]=0.1      ,    _A							:							Optional[int]=0.1      ,    _A							:							Optional[int]=0.1      ,    _A							:							Optional[int]=0.0      ,    _A							:							str=0.1      ,    _A							:							Tuple=0.1      ,    _A							:							Optional[int]=0.02      ,    _A							:							Dict=1e-5      ,    _A							:							str="group"      ,    _A							:							Tuple="gelu"      ,    _A							:							Union[str, Any]=(6_4, 1_2_8, 1_2_8, 1_2_8, 1_2_8, 2_5_6, 2_5_6, 2_5_6, 2_5_6, 5_1_2, 5_1_2, 5_1_2, 5_1_2)      ,    _A							:							Optional[Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)      ,    _A							:							Any=(1_0, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)      ,    _A							:							Tuple=False      ,    _A							:							Tuple=1_2_8      ,    _A							:							int=1_6      ,    _A							:							Union[str, Any]=True      ,    _A							:							Optional[Any]=0.05      ,    _A							:							List[Any]=1_0      ,    _A							:							Union[str, Any]=2      ,    _A							:							Tuple=0.0      ,    _A							:							Union[str, Any]=1_0      ,    _A							:							Optional[int]=0      ,    _A							:							Union[str, Any]="mean"      ,    _A							:							Optional[int]=False      ,    _A							:							List[Any]=False      ,    _A							:							int=2_5_6      ,    _A							:							str=0      ,    _A							:							Optional[int]=1      ,    _A							:							List[Any]=2      ,    **_A							:							Dict      ,    ):



											"""simple docstring"""







											super().__init__(**_A      ,    pad_token_id=_A      ,    bos_token_id=_A      ,    eos_token_id=_A)
											_SCREAMING_SNAKE_CASE		:						str			  =    hidden_size
											_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    feat_extract_norm
											_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    feat_extract_activation
											_SCREAMING_SNAKE_CASE		:						Dict			  =    list(_A)
											_SCREAMING_SNAKE_CASE		:						int			  =    list(_A)
											_SCREAMING_SNAKE_CASE		:						int			  =    list(_A)
											_SCREAMING_SNAKE_CASE		:						str			  =    conv_bias
											_SCREAMING_SNAKE_CASE		:						Tuple			  =    num_conv_pos_embeddings
											_SCREAMING_SNAKE_CASE		:						List[str]			  =    num_conv_pos_embedding_groups
											_SCREAMING_SNAKE_CASE		:						Tuple			  =    len(self.conv_dim)
											_SCREAMING_SNAKE_CASE		:						Tuple			  =    num_hidden_layers
											_SCREAMING_SNAKE_CASE		:						List[str]			  =    intermediate_size
											_SCREAMING_SNAKE_CASE		:						str			  =    squeeze_factor
											_SCREAMING_SNAKE_CASE		:						Dict			  =    hidden_act
											_SCREAMING_SNAKE_CASE		:						str			  =    num_attention_heads
											_SCREAMING_SNAKE_CASE		:						Dict			  =    hidden_dropout
											_SCREAMING_SNAKE_CASE		:						Tuple			  =    attention_dropout
											_SCREAMING_SNAKE_CASE		:						int			  =    activation_dropout
											_SCREAMING_SNAKE_CASE		:						Any			  =    feat_proj_dropout
											_SCREAMING_SNAKE_CASE		:						str			  =    final_dropout
											_SCREAMING_SNAKE_CASE		:						Union[str, Any]			  =    layerdrop
											_SCREAMING_SNAKE_CASE		:						Any			  =    layer_norm_eps
											_SCREAMING_SNAKE_CASE		:						int			  =    initializer_range
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    vocab_size

											if (
											    (len(self.conv_stride) != self.num_feat_extract_layers)
											    or (len(self.conv_kernel) != self.num_feat_extract_layers)
											    or (len(self.conv_dim) != self.num_feat_extract_layers)
											):
																		raise ValueError(
																		    """Configuration for convolutional layers is incorrect."""
																		    """It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"""
																		    f"""but is `len(config.conv_dim) = {len(self.conv_dim)}`, `len(config.conv_stride)"""
																		    f"""= {len(self.conv_stride)}`, `len(config.conv_kernel) = {len(self.conv_kernel)}`.""")

											# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    apply_spec_augment
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    mask_time_prob
											_SCREAMING_SNAKE_CASE		:						List[str]			  =    mask_time_length
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    mask_time_min_masks
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    mask_feature_prob
											_SCREAMING_SNAKE_CASE		:						int			  =    mask_feature_length
											_SCREAMING_SNAKE_CASE		:						List[Any]			  =    mask_feature_min_masks

											# ctc loss
											_SCREAMING_SNAKE_CASE		:						int			  =    ctc_loss_reduction
											_SCREAMING_SNAKE_CASE		:						Optional[int]			  =    ctc_zero_infinity

											# sequence classification
											_SCREAMING_SNAKE_CASE		:						Dict			  =    use_weighted_layer_sum
											_SCREAMING_SNAKE_CASE		:						List[str]			  =    classifier_proj_size





				@property
				def 		_lowerCAmelCase		(      self							:							Any):



											"""simple docstring"""







											return functools.reduce(operator.mul      ,    self.conv_stride      ,    1)


