
import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()






class      _UpperCAmelCase				(					unittest.TestCase):
    def 					lowerCamelCase__	(    self     ):
      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()
    @property
    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						int						=   1
      _snake_case     :						List[str]						=   3
      _snake_case     :						str						=   (32, 32)

      _snake_case     :						Optional[int]						=   floats_tensor((batch_size, num_channels) + sizes						,    rng=random.Random(0     )     ).to(__a     )
      return image
    @property
    def 					lowerCamelCase__	(    self     ):
      torch.manual_seed(0     )
      _snake_case     :						Tuple						=   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						,    )
      return model
    @property
    def 					lowerCamelCase__	(    self     ):
      torch.manual_seed(0     )
      _snake_case     :						List[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						,    )
      return model
    @property
    def 					lowerCamelCase__	(    self     ):
      torch.manual_seed(0     )
      _snake_case     :						int						=   RobertaSeriesConfig(
          hidden_size=32						,    project_dim=32						,    intermediate_size=37						,    layer_norm_eps=1E-05						,    num_attention_heads=4						,    num_hidden_layers=5						,    pad_token_id=1						,    vocab_size=50_06						,    )
      return RobertaSeriesModelWithTransformation(__a     )
    @property
    def 					lowerCamelCase__	(    self     ):
      def extract(*snake_case_						,    **snake_case_     ):






        class      _UpperCAmelCase				:
            def __init__(    self     ):
              _snake_case     :						Union[str, Any]						=   torch.ones([0]     )


            def 					lowerCamelCase__	(    self						,    snake_case_     ):
              self.pixel_values.to(__a     )
              return self


        return Out()

      return extract
    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						List[str]						=   "cpu"  # ensure determinism for the device-dependent torch.Generator
      _snake_case     :						str						=   self.dummy_cond_unet
      _snake_case     :						Optional[Any]						=   PNDMScheduler(skip_prk_steps=__a     )
      _snake_case     :						str						=   self.dummy_vae
      _snake_case     :						Dict						=   self.dummy_text_encoder
      _snake_case     :						Any						=   XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta"     )
      _snake_case     :						Union[str, Any]						=   77

      _snake_case     :						Dict						=   self.dummy_image.to(__a     )
      _snake_case     :						List[str]						=   init_image / 2 + 0.5

      # make sure here that pndm scheduler skips prk
      _snake_case     :						Optional[int]						=   AltDiffusionImgaImgPipeline(
          unet=__a						,    scheduler=__a						,    vae=__a						,    text_encoder=__a						,    tokenizer=__a						,    safety_checker=__a						,    feature_extractor=self.dummy_extractor						,    )
      _snake_case     :						List[str]						=   VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor						,    do_normalize=__a     )
      _snake_case     :						List[str]						=   alt_pipe.to(__a     )
      alt_pipe.set_progress_bar_config(disable=__a     )

      _snake_case     :						str						=   "A painting of a squirrel eating a burger"
      _snake_case     :						int						=   torch.Generator(device=__a     ).manual_seed(0     )
      _snake_case     :						Tuple						=   alt_pipe(
          [prompt]						,    generator=__a						,    guidance_scale=6.0						,    num_inference_steps=2						,    output_type="np"						,    image=__a						,    )

      _snake_case     :						int						=   output.images

      _snake_case     :						Any						=   torch.Generator(device=__a     ).manual_seed(0     )
      _snake_case     :						Any						=   alt_pipe(
          [prompt]						,    generator=__a						,    guidance_scale=6.0						,    num_inference_steps=2						,    output_type="np"						,    image=__a						,    return_dict=__a						,    )[0]

      _snake_case     :						int						=   image[0, -3:, -3:, -1]
      _snake_case     :						Tuple						=   image_from_tuple[0, -3:, -3:, -1]

      assert image.shape == (1, 32, 32, 3)
      _snake_case     :						int						=   np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499]     )

      assert np.abs(image_slice.flatten() - expected_slice     ).max() < 5E-3
      assert np.abs(image_from_tuple_slice.flatten() - expected_slice     ).max() < 5E-3
    @unittest.skipIf(torch_device != "cuda"						,    "This test requires a GPU"     )
    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						Optional[Any]						=   self.dummy_cond_unet
      _snake_case     :						Union[str, Any]						=   PNDMScheduler(skip_prk_steps=__a     )
      _snake_case     :						str						=   self.dummy_vae
      _snake_case     :						Tuple						=   self.dummy_text_encoder
      _snake_case     :						str						=   XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta"     )
      _snake_case     :						Union[str, Any]						=   77

      _snake_case     :						Any						=   self.dummy_image.to(__a     )

      # put models in fp16
      _snake_case     :						Optional[int]						=   unet.half()
      _snake_case     :						str						=   vae.half()
      _snake_case     :						str						=   bert.half()

      # make sure here that pndm scheduler skips prk
      _snake_case     :						Optional[Any]						=   AltDiffusionImgaImgPipeline(
          unet=__a						,    scheduler=__a						,    vae=__a						,    text_encoder=__a						,    tokenizer=__a						,    safety_checker=__a						,    feature_extractor=self.dummy_extractor						,    )
      _snake_case     :						Any						=   VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor						,    do_normalize=__a     )
      _snake_case     :						List[Any]						=   alt_pipe.to(__a     )
      alt_pipe.set_progress_bar_config(disable=__a     )

      _snake_case     :						Dict						=   "A painting of a squirrel eating a burger"
      _snake_case     :						Optional[int]						=   torch.manual_seed(0     )
      _snake_case     :						List[str]						=   alt_pipe(
          [prompt]						,    generator=__a						,    num_inference_steps=2						,    output_type="np"						,    image=__a						,    ).images

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


    @unittest.skipIf(torch_device != "cuda"						,    "This test requires a GPU"     )
    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						List[str]						=   load_image(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
          "/img2img/sketch-mountains-input.jpg"     )
      # resize to resolution that is divisible by 8 but not 16 or 32
      _snake_case     :						List[Any]						=   init_image.resize((7_60, 5_04)     )

      _snake_case     :						Optional[Any]						=   "BAAI/AltDiffusion"
      _snake_case     :						Optional[int]						=   AltDiffusionImgaImgPipeline.from_pretrained(
          __a						,    safety_checker=__a						,    )
      pipe.to(__a     )
      pipe.set_progress_bar_config(disable=__a     )
      pipe.enable_attention_slicing()

      _snake_case     :						Optional[Any]						=   "A fantasy landscape, trending on artstation"

      _snake_case     :						Any						=   torch.manual_seed(0     )
      _snake_case     :						Dict						=   pipe(
          prompt=__a						,    image=__a						,    strength=0.75						,    guidance_scale=7.5						,    generator=__a						,    output_type="np"						,    )
      _snake_case     :						int						=   output.images[0]

      _snake_case     :						int						=   image[2_55:2_58, 3_83:3_86, -1]

      assert image.shape == (5_04, 7_60, 3)
      _snake_case     :						List[Any]						=   np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000]     )

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






@slow
@require_torch_gpu
class      _UpperCAmelCase				(					unittest.TestCase):
    def 					lowerCamelCase__	(    self     ):
      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()


    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						Dict						=   load_image(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
          "/img2img/sketch-mountains-input.jpg"     )
      _snake_case     :						Optional[int]						=   init_image.resize((7_68, 5_12)     )
      _snake_case     :						str						=   load_numpy(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"     )

      _snake_case     :						str						=   "BAAI/AltDiffusion"
      _snake_case     :						Optional[int]						=   AltDiffusionImgaImgPipeline.from_pretrained(
          __a						,    safety_checker=__a						,    )
      pipe.to(__a     )
      pipe.set_progress_bar_config(disable=__a     )
      pipe.enable_attention_slicing()

      _snake_case     :						int						=   "A fantasy landscape, trending on artstation"

      _snake_case     :						Dict						=   torch.manual_seed(0     )
      _snake_case     :						List[Any]						=   pipe(
          prompt=__a						,    image=__a						,    strength=0.75						,    guidance_scale=7.5						,    generator=__a						,    output_type="np"						,    )
      _snake_case     :						Dict						=   output.images[0]

      assert image.shape == (5_12, 7_68, 3)
      # img2img is flaky across GPUs even in fp32, so using MAE here
      assert np.abs(expected_image - image     ).max() < 1E-2



"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


_a      :			Optional[int]					=							logging.get_logger(__name__)

_a      :			List[str]					=							{
    """facebook/convnextv2-tiny-1k-224""": """https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json""",
}






class      _UpperCAmelCase				(					_snake_case		,					_snake_case):
    __lowercase							: List[Any]  =					"""convnextv2"""
    def __init__(    self						,    snake_case_=3						,    snake_case_=4						,    snake_case_=4						,    snake_case_=None						,    snake_case_=None						,    snake_case_="gelu"						,    snake_case_=0.02						,    snake_case_=1E-12						,    snake_case_=0.0						,    snake_case_=2_24						,    snake_case_=None						,    snake_case_=None						,    **snake_case_						,    ):
      super().__init__(**snake_case_     )

      _snake_case     :						Tuple						=   num_channels
      _snake_case     :						Optional[int]						=   patch_size
      _snake_case     :						Tuple						=   num_stages
      _snake_case     :						int						=   [96, 1_92, 3_84, 7_68] if hidden_sizes is None else hidden_sizes
      _snake_case     :						str						=   [3, 3, 9, 3] if depths is None else depths
      _snake_case     :						int						=   hidden_act
      _snake_case     :						Tuple						=   initializer_range
      _snake_case     :						Union[str, Any]						=   layer_norm_eps
      _snake_case     :						Optional[int]						=   drop_path_rate
      _snake_case     :						Union[str, Any]						=   image_size
      _snake_case     :						List[Any]						=   ["stem"] + [F'stage{idx}' for idx in range(1						,    len(self.depths     ) + 1     )]
      _snake_case			,					_snake_case     :						Dict						=   get_aligned_output_features_output_indices(
          out_features=snake_case_						,    out_indices=snake_case_						,    stage_names=self.stage_names     )

