




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     SCREAMING_SNAKE_CASE__		(unittest.TestCase			):
     def        A__      (						self	:		str						):



       """simple docstring"""
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()
     @property
     def        A__      (						self	:		Tuple						):



       """simple docstring"""
       lowerCAmelCase__										=      1
       lowerCAmelCase__										=      3
       lowerCAmelCase__										=      (32, 32)

       lowerCAmelCase__										=      floats_tensor((batch_size, num_channels) + sizes       ,						rng=random.Random(0						)						).to(__lowerCamelCase						)
       return image
     @property
     def        A__      (						self	:		Dict						):



       """simple docstring"""
       torch.manual_seed(0						)
       lowerCAmelCase__										=      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        A__      (						self	:		int						):



       """simple docstring"""
       torch.manual_seed(0						)
       lowerCAmelCase__										=      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        A__      (						self	:		Union[str, Any]						):



       """simple docstring"""
       torch.manual_seed(0						)
       lowerCAmelCase__										=      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(__lowerCamelCase						)
     @property
     def        A__      (						self	:		List[Any]						):



       """simple docstring"""
       def extract(*__lowerCamelCase	:		Dict       ,						**__lowerCamelCase	:		str						):





         class     SCREAMING_SNAKE_CASE__		:
              def __init__(						self	:		Tuple						):



                """simple docstring"""
                lowerCAmelCase__										=      torch.ones([0]						)



              def        A__      (						self	:		Tuple       ,						__lowerCamelCase	:		str						):



                """simple docstring"""
                self.pixel_values.to(__lowerCamelCase						)
                return self



         return Out()

       return extract
     def        A__      (						self	:		List[Any]						):



       """simple docstring"""
       lowerCAmelCase__										=      '''cpu'''  # ensure determinism for the device-dependent torch.Generator
       lowerCAmelCase__										=      self.dummy_cond_unet
       lowerCAmelCase__										=      PNDMScheduler(skip_prk_steps=__lowerCamelCase						)
       lowerCAmelCase__										=      self.dummy_vae
       lowerCAmelCase__										=      self.dummy_text_encoder
       lowerCAmelCase__										=      XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta'''						)
       lowerCAmelCase__										=      77

       lowerCAmelCase__										=      self.dummy_image.to(__lowerCamelCase						)
       lowerCAmelCase__										=      init_image / 2 + 0.5

       # make sure here that pndm scheduler skips prk
       lowerCAmelCase__										=      AltDiffusionImgaImgPipeline(
           unet=__lowerCamelCase       ,						scheduler=__lowerCamelCase       ,						vae=__lowerCamelCase       ,						text_encoder=__lowerCamelCase       ,						tokenizer=__lowerCamelCase       ,						safety_checker=__lowerCamelCase       ,						feature_extractor=self.dummy_extractor       ,						)
       lowerCAmelCase__										=      VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor       ,						do_normalize=__lowerCamelCase						)
       lowerCAmelCase__										=      alt_pipe.to(__lowerCamelCase						)
       alt_pipe.set_progress_bar_config(disable=__lowerCamelCase						)

       lowerCAmelCase__										=      '''A painting of a squirrel eating a burger'''
       lowerCAmelCase__										=      torch.Generator(device=__lowerCamelCase						).manual_seed(0						)
       lowerCAmelCase__										=      alt_pipe(
           [prompt]       ,						generator=__lowerCamelCase       ,						guidance_scale=6.0       ,						num_inference_steps=2       ,						output_type='''np'''       ,						image=__lowerCamelCase       ,						)

       lowerCAmelCase__										=      output.images

       lowerCAmelCase__										=      torch.Generator(device=__lowerCamelCase						).manual_seed(0						)
       lowerCAmelCase__										=      alt_pipe(
           [prompt]       ,						generator=__lowerCamelCase       ,						guidance_scale=6.0       ,						num_inference_steps=2       ,						output_type='''np'''       ,						image=__lowerCamelCase       ,						return_dict=__lowerCamelCase       ,						)[0]

       lowerCAmelCase__										=      image[0, -3:, -3:, -1]
       lowerCAmelCase__										=      image_from_tuple[0, -3:, -3:, -1]

       assert image.shape == (1, 32, 32, 3)
       lowerCAmelCase__										=      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        A__      (						self	:		int						):



       """simple docstring"""
       lowerCAmelCase__										=      self.dummy_cond_unet
       lowerCAmelCase__										=      PNDMScheduler(skip_prk_steps=__lowerCamelCase						)
       lowerCAmelCase__										=      self.dummy_vae
       lowerCAmelCase__										=      self.dummy_text_encoder
       lowerCAmelCase__										=      XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta'''						)
       lowerCAmelCase__										=      77

       lowerCAmelCase__										=      self.dummy_image.to(__lowerCamelCase						)

       # put models in fp16
       lowerCAmelCase__										=      unet.half()
       lowerCAmelCase__										=      vae.half()
       lowerCAmelCase__										=      bert.half()

       # make sure here that pndm scheduler skips prk
       lowerCAmelCase__										=      AltDiffusionImgaImgPipeline(
           unet=__lowerCamelCase       ,						scheduler=__lowerCamelCase       ,						vae=__lowerCamelCase       ,						text_encoder=__lowerCamelCase       ,						tokenizer=__lowerCamelCase       ,						safety_checker=__lowerCamelCase       ,						feature_extractor=self.dummy_extractor       ,						)
       lowerCAmelCase__										=      VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor       ,						do_normalize=__lowerCamelCase						)
       lowerCAmelCase__										=      alt_pipe.to(__lowerCamelCase						)
       alt_pipe.set_progress_bar_config(disable=__lowerCamelCase						)

       lowerCAmelCase__										=      '''A painting of a squirrel eating a burger'''
       lowerCAmelCase__										=      torch.manual_seed(0						)
       lowerCAmelCase__										=      alt_pipe(
           [prompt]       ,						generator=__lowerCamelCase       ,						num_inference_steps=2       ,						output_type='''np'''       ,						image=__lowerCamelCase       ,						).images

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



     @unittest.skipIf(torch_device != '''cuda'''       ,						'''This test requires a GPU'''						)
     def        A__      (						self	:		List[str]						):



       """simple docstring"""
       lowerCAmelCase__										=      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
       lowerCAmelCase__										=      init_image.resize((7_60, 5_04)						)

       lowerCAmelCase__										=      '''BAAI/AltDiffusion'''
       lowerCAmelCase__										=      AltDiffusionImgaImgPipeline.from_pretrained(
           __lowerCamelCase       ,						safety_checker=__lowerCamelCase       ,						)
       pipe.to(__lowerCamelCase						)
       pipe.set_progress_bar_config(disable=__lowerCamelCase						)
       pipe.enable_attention_slicing()

       lowerCAmelCase__										=      '''A fantasy landscape, trending on artstation'''

       lowerCAmelCase__										=      torch.manual_seed(0						)
       lowerCAmelCase__										=      pipe(
           prompt=__lowerCamelCase       ,						image=__lowerCamelCase       ,						strength=0.75       ,						guidance_scale=7.5       ,						generator=__lowerCamelCase       ,						output_type='''np'''       ,						)
       lowerCAmelCase__										=      output.images[0]

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

       assert image.shape == (5_04, 7_60, 3)
       lowerCAmelCase__										=      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     SCREAMING_SNAKE_CASE__		(unittest.TestCase			):
     def        A__      (						self	:		Tuple						):



       """simple docstring"""
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()



     def        A__      (						self	:		Optional[Any]						):



       """simple docstring"""
       lowerCAmelCase__										=      load_image(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/img2img/sketch-mountains-input.jpg'''						)
       lowerCAmelCase__										=      init_image.resize((7_68, 5_12)						)
       lowerCAmelCase__										=      load_numpy(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy'''						)

       lowerCAmelCase__										=      '''BAAI/AltDiffusion'''
       lowerCAmelCase__										=      AltDiffusionImgaImgPipeline.from_pretrained(
           __lowerCamelCase       ,						safety_checker=__lowerCamelCase       ,						)
       pipe.to(__lowerCamelCase						)
       pipe.set_progress_bar_config(disable=__lowerCamelCase						)
       pipe.enable_attention_slicing()

       lowerCAmelCase__										=      '''A fantasy landscape, trending on artstation'''

       lowerCAmelCase__										=      torch.manual_seed(0						)
       lowerCAmelCase__										=      pipe(
           prompt=__lowerCamelCase       ,						image=__lowerCamelCase       ,						strength=0.75       ,						guidance_scale=7.5       ,						generator=__lowerCamelCase       ,						output_type='''np'''       ,						)
       lowerCAmelCase__										=      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







from __future__ import annotations
def 		a_							( __lowerCAmelCase				):
  if not nums:
    return 0
  lowerCAmelCase__										=      nums[0]
  lowerCAmelCase__										=      0
  for num in nums[1:]:
    lowerCAmelCase__				,      lowerCAmelCase__										=      (
        max_excluding + num,
        max(__lowerCAmelCase   , __lowerCAmelCase				),
    )
  return max(__lowerCAmelCase   , __lowerCAmelCase				)


if __name__ == "__main__":
      import doctest

      doctest.testmod()

