
'''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      a_     (_UpperCAmelCase							,	_UpperCAmelCase							,	unittest.TestCase			):
       __lowerCAmelCase			: List[str]			=					StableDiffusionXLImgaImgPipeline
       __lowerCAmelCase			: Tuple			=					TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""}
       __lowerCAmelCase			: List[str]			=					PipelineTesterMixin.required_optional_params - {"""latents"""}
       __lowerCAmelCase			: Optional[Any]			=					TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
       __lowerCAmelCase			: Any			=					IMAGE_TO_IMAGE_IMAGE_PARAMS
       __lowerCAmelCase			: str			=					IMAGE_TO_IMAGE_IMAGE_PARAMS




       def 							__UpperCamelCase				(   self     ):
         torch.manual_seed(0     )
         _lowerCAmelCase				:     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      ,      )
         _lowerCAmelCase				:     Optional[Any]       =    EulerDiscreteScheduler(
             beta_start=0.0_0085      ,      beta_end=0.012      ,      steps_offset=1      ,      beta_schedule="""scaled_linear"""      ,      timestep_spacing="""leading"""      ,      )
         torch.manual_seed(0     )
         _lowerCAmelCase				:     str       =    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     )
         _lowerCAmelCase				:     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      ,      )
         _lowerCAmelCase				:     Any       =    CLIPTextModel(A_     )
         _lowerCAmelCase				:     Dict       =    CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""      ,      local_files_only=A_     )

         _lowerCAmelCase				:     int       =    CLIPTextModelWithProjection(A_     )
         _lowerCAmelCase				:     Optional[int]       =    CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""      ,      local_files_only=A_     )

         _lowerCAmelCase				:     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 							__UpperCamelCase				(   self      ,      snake_case_      ,      snake_case_=0     ):
         _lowerCAmelCase				:     int       =    floats_tensor((1, 3, 3_2, 3_2)      ,      rng=random.Random(A_     )     ).to(A_     )
         _lowerCAmelCase				:     int       =    image / 2 + 0.5
         if str(A_     ).startswith("""mps"""     ):
           _lowerCAmelCase				:     Union[str, Any]       =    torch.manual_seed(A_     )
         else:
           _lowerCAmelCase				:     int       =    torch.Generator(device=A_     ).manual_seed(A_     )
         _lowerCAmelCase				:     Dict       =    {
             '''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 							__UpperCamelCase				(   self     ):
         _lowerCAmelCase				:     Dict       =    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
         _lowerCAmelCase				:     Optional[int]       =    self.get_dummy_components()
         _lowerCAmelCase				:     Dict       =    StableDiffusionXLImgaImgPipeline(**A_     )
         _lowerCAmelCase				:     Optional[int]       =    sd_pipe.to(A_     )
         sd_pipe.set_progress_bar_config(disable=A_     )

         _lowerCAmelCase				:     Union[str, Any]       =    self.get_dummy_inputs(A_     )
         _lowerCAmelCase				:     Any       =    sd_pipe(**A_     ).images
         _lowerCAmelCase				:     Tuple       =    image[0, -3:, -3:, -1]

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

         _lowerCAmelCase				:     Dict       =    np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165]     )

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




       def 							__UpperCamelCase				(   self     ):
         super().test_attention_slicing_forward_pass(expected_max_diff=3E-3     )




       def 							__UpperCamelCase				(   self     ):
         super().test_inference_batch_single_identical(expected_max_diff=3E-3     )




       def 							__UpperCamelCase				(   self     ):
         pass







       def 							__UpperCamelCase				(   self     ):
         _lowerCAmelCase				:     int       =    self.get_dummy_components()
         _lowerCAmelCase				:     str       =    StableDiffusionXLImgaImgPipeline(**A_     )
         _lowerCAmelCase				:     List[str]       =    sd_pipe.to(A_     )
         _lowerCAmelCase				:     int       =    sd_pipe.to(A_     )
         sd_pipe.set_progress_bar_config(disable=A_     )

         # forward without prompt embeds
         _lowerCAmelCase				:     Optional[Any]       =    self.get_dummy_inputs(A_     )
         _lowerCAmelCase				:     List[str]       =    3 * ['''this is a negative prompt''']
         _lowerCAmelCase				:     List[Any]       =    negative_prompt
         _lowerCAmelCase				:     Dict       =    3 * [inputs['''prompt''']]

         _lowerCAmelCase				:     Any       =    sd_pipe(**A_     )
         _lowerCAmelCase				:     List[str]       =    output.images[0, -3:, -3:, -1]

         # forward with prompt embeds
         _lowerCAmelCase				:     Optional[Any]       =    self.get_dummy_inputs(A_     )
         _lowerCAmelCase				:     Tuple       =    3 * ['''this is a negative prompt''']
         _lowerCAmelCase				:     List[str]       =    3 * [inputs.pop("""prompt"""     )]

         (
             _lowerCAmelCase							
         )				:     Tuple       =    sd_pipe.encode_prompt(A_      ,      negative_prompt=A_     )

         _lowerCAmelCase				:     Dict       =    sd_pipe(
             **A_      ,      prompt_embeds=A_      ,      negative_prompt_embeds=A_      ,      pooled_prompt_embeds=A_      ,      negative_pooled_prompt_embeds=A_      ,      )
         _lowerCAmelCase				:     Optional[int]       =    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      a_     (unittest.TestCase			):




       def 							__UpperCamelCase				(   self     ):
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()




       def 							__UpperCamelCase				(   self      ,      snake_case_      ,      snake_case_="cpu"      ,      snake_case_=torch.floataa      ,      snake_case_=0     ):
         _lowerCAmelCase				:     str       =    torch.Generator(device=A_     ).manual_seed(A_     )
         _lowerCAmelCase				:     Dict       =    np.random.RandomState(A_     ).standard_normal((1, 4, 6_4, 6_4)     )
         _lowerCAmelCase				:     str       =    torch.from_numpy(A_     ).to(device=A_      ,      dtype=A_     )
         _lowerCAmelCase				:     Union[str, Any]       =    {
             '''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 							__UpperCamelCase				(   self     ):
         _lowerCAmelCase				:     str       =    DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base"""     )
         pipe.to(A_     )
         pipe.set_progress_bar_config(disable=A_     )

         _lowerCAmelCase				:     int       =    self.get_inputs(A_     )
         _lowerCAmelCase				:     Tuple       =    pipe(**A_     ).images
         _lowerCAmelCase				:     Dict       =    image[0, -3:, -3:, -1].flatten()

         assert image.shape == (1, 5_1_2, 5_1_2, 3)
         _lowerCAmelCase				:     Dict       =    np.array([0.4_9493, 0.4_7896, 0.4_0798, 0.5_4214, 0.5_3212, 0.4_8202, 0.4_7656, 0.4_6329, 0.4_8506]     )
         assert np.abs(image_slice - expected_slice     ).max() < 7E-3





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
from ..auto import CONFIG_MAPPING


_UpperCamelCase 			=		logging.get_logger(__name__)

_UpperCamelCase 			=		{
    "microsoft/table-transformer-detection": (
        "https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json"
    ),
}







class   __lowercase      (_UpperCAmelCase ):
 _UpperCamelCase			  =  """table-transformer"""
 _UpperCamelCase			  =  ["""past_key_values"""]
 _UpperCamelCase			  =  {
     """hidden_size""": """d_model""",
     """num_attention_heads""": """encoder_attention_heads""",
 }
 def __init__(							self      ,							A_=True      ,							A_=None      ,							A_=3      ,							A_=100      ,							A_=6      ,							A_=2048      ,							A_=8      ,							A_=6      ,							A_=2048      ,							A_=8      ,							A_=0.0      ,							A_=0.0      ,							A_=True      ,							A_="relu"      ,							A_=256      ,							A_=0.1      ,							A_=0.0      ,							A_=0.0      ,							A_=0.02      ,							A_=1.0      ,							A_=False      ,							A_="sine"      ,							A_="resnet50"      ,							A_=True      ,							A_=False      ,							A_=1      ,							A_=5      ,							A_=2      ,							A_=1      ,							A_=1      ,							A_=5      ,							A_=2      ,							A_=0.1      ,							**A_      ,							)					->Any:



       '''simple docstring'''





       if backbone_config is not None and use_timm_backbone:
             raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.'''					)

       if not use_timm_backbone:
             if backbone_config is None:
                   logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.'''					)
                   __lowerCAmelCase					:						Optional[Any]					=					CONFIG_MAPPING['''resnet'''](out_features=['''stage4''']					)
             elif isinstance(A_      ,							A_					):
                   __lowerCAmelCase					:						int					=					backbone_config.get('''model_type'''					)
                   __lowerCAmelCase					:						List[str]					=					CONFIG_MAPPING[backbone_model_type]
                   __lowerCAmelCase					:						Any					=					config_class.from_dict(A_					)
             # set timm attributes to None
             __lowerCAmelCase,							__lowerCAmelCase,							__lowerCAmelCase					:						List[str]					=					None, None, None

       __lowerCAmelCase					:						Tuple					=					use_timm_backbone
       __lowerCAmelCase					:						Optional[Any]					=					backbone_config
       __lowerCAmelCase					:						List[str]					=					num_channels
       __lowerCAmelCase					:						Tuple					=					num_queries
       __lowerCAmelCase					:						int					=					d_model
       __lowerCAmelCase					:						List[Any]					=					encoder_ffn_dim
       __lowerCAmelCase					:						Optional[int]					=					encoder_layers
       __lowerCAmelCase					:						List[str]					=					encoder_attention_heads
       __lowerCAmelCase					:						str					=					decoder_ffn_dim
       __lowerCAmelCase					:						Union[str, Any]					=					decoder_layers
       __lowerCAmelCase					:						Any					=					decoder_attention_heads
       __lowerCAmelCase					:						Optional[int]					=					dropout
       __lowerCAmelCase					:						Any					=					attention_dropout
       __lowerCAmelCase					:						Tuple					=					activation_dropout
       __lowerCAmelCase					:						Optional[Any]					=					activation_function
       __lowerCAmelCase					:						List[str]					=					init_std
       __lowerCAmelCase					:						Tuple					=					init_xavier_std
       __lowerCAmelCase					:						Any					=					encoder_layerdrop
       __lowerCAmelCase					:						List[Any]					=					decoder_layerdrop
       __lowerCAmelCase					:						Optional[Any]					=					encoder_layers
       __lowerCAmelCase					:						Optional[Any]					=					auxiliary_loss
       __lowerCAmelCase					:						Optional[Any]					=					position_embedding_type
       __lowerCAmelCase					:						Tuple					=					backbone
       __lowerCAmelCase					:						Any					=					use_pretrained_backbone
       __lowerCAmelCase					:						int					=					dilation
       # Hungarian matcher
       __lowerCAmelCase					:						Dict					=					class_cost
       __lowerCAmelCase					:						List[str]					=					bbox_cost
       __lowerCAmelCase					:						int					=					giou_cost
       # Loss coefficients
       __lowerCAmelCase					:						Optional[Any]					=					mask_loss_coefficient
       __lowerCAmelCase					:						Tuple					=					dice_loss_coefficient
       __lowerCAmelCase					:						int					=					bbox_loss_coefficient
       __lowerCAmelCase					:						List[Any]					=					giou_loss_coefficient
       __lowerCAmelCase					:						int					=					eos_coefficient
       super().__init__(is_encoder_decoder=A_      ,							**A_					)
 @property
 def 	UpperCamelCase__  (							self					)					->int:



       '''simple docstring'''





       return self.encoder_attention_heads





 @property
 def 	UpperCamelCase__  (							self					)					->int:



       '''simple docstring'''





       return self.d_model







class   __lowercase      (_UpperCAmelCase ):
 _UpperCamelCase			  =  version.parse("""1.11""" )
 @property
 def 	UpperCamelCase__  (							self					)					->Mapping[str, Mapping[int, str]]:



       '''simple docstring'''





       return OrderedDict(
           [
               ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
               ('''pixel_mask''', {0: '''batch'''}),
           ]					)
 @property
 def 	UpperCamelCase__  (							self					)					->float:



       '''simple docstring'''





       return 1e-5





 @property
 def 	UpperCamelCase__  (							self					)					->int:



       '''simple docstring'''





       return 12


