"""simple docstring"""





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 	_UpperCAmelCase (     self							) ->      Tuple:
             # clean up the VRAM after each test
             super().tearDown()
             gc.collect()
             torch.cuda.empty_cache()


      @property
      def 	_UpperCAmelCase (     self							) ->      Union[str, Any]:
             lowercase__    :	Optional[int]     					=			1
             lowercase__    :	List[str]     					=			3
             lowercase__    :	List[Any]     					=			(3_2, 3_2)

             lowercase__    :	int     					=			floats_tensor((batch_size, num_channels) + sizes	,    rng=random.Random(0							)							).to(a							)
             return image


      @property
      def 	_UpperCAmelCase (     self							) ->      List[Any]:
             torch.manual_seed(0							)
             lowercase__    :	List[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')	,    cross_attention_dim=3_2	,    )
             return model


      @property
      def 	_UpperCAmelCase (     self							) ->      List[Any]:
             torch.manual_seed(0							)
             lowercase__    :	Dict     					=			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	,    )
             return model


      @property
      def 	_UpperCAmelCase (     self							) ->      Tuple:
             torch.manual_seed(0							)
             lowercase__    :	Dict     					=			RobertaSeriesConfig(
                 hidden_size=3_2	,    project_dim=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=5_0_0_6	,    )
             return RobertaSeriesModelWithTransformation(a							)


      @property
      def 	_UpperCAmelCase (     self							) ->      Any:
             def extract(*a	,    **a							):


                    class   UpperCAmelCase_			:


                          def __init__(     self							) ->      Optional[Any]:
                                 lowercase__    :	Optional[Any]     					=			torch.ones([0]							)


                          def 	_UpperCAmelCase (     self	,    a							) ->      str:
                                 self.pixel_values.to(a							)
                                 return self





                    return Out()

             return extract


      def 	_UpperCAmelCase (     self							) ->      Optional[int]:
             lowercase__    :	int     					=			'cpu'  # ensure determinism for the device-dependent torch.Generator
             lowercase__    :	str     					=			self.dummy_cond_unet
             lowercase__    :	Any     					=			PNDMScheduler(skip_prk_steps=a							)
             lowercase__    :	str     					=			self.dummy_vae
             lowercase__    :	Union[str, Any]     					=			self.dummy_text_encoder
             lowercase__    :	Optional[int]     					=			XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'							)
             lowercase__    :	Any     					=			7_7

             lowercase__    :	List[Any]     					=			self.dummy_image.to(a							)
             lowercase__    :	Dict     					=			init_image / 2 + 0.5

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

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

             lowercase__    :	int     					=			output.images

             lowercase__    :	List[Any]     					=			torch.Generator(device=a							).manual_seed(0							)
             lowercase__    :	Dict     					=			alt_pipe(
                 [prompt]	,    generator=a	,    guidance_scale=6.0	,    num_inference_steps=2	,    output_type='np'	,    image=a	,    return_dict=a	,    )[0]

             lowercase__    :	Dict     					=			image[0, -3:, -3:, -1]
             lowercase__    :	List[Any]     					=			image_from_tuple[0, -3:, -3:, -1]

             assert image.shape == (1, 3_2, 3_2, 3)
             lowercase__    :	List[str]     					=			np.array([0.4_427, 0.3_731, 0.4_249, 0.4_941, 0.4_546, 0.4_148, 0.4_193, 0.4_666, 0.4_499]							)

             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 	_UpperCAmelCase (     self							) ->      List[str]:
             lowercase__    :	Optional[int]     					=			self.dummy_cond_unet
             lowercase__    :	Optional[Any]     					=			PNDMScheduler(skip_prk_steps=a							)
             lowercase__    :	Dict     					=			self.dummy_vae
             lowercase__    :	List[Any]     					=			self.dummy_text_encoder
             lowercase__    :	Optional[int]     					=			XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'							)
             lowercase__    :	int     					=			7_7

             lowercase__    :	str     					=			self.dummy_image.to(a							)

             # put models in fp16
             lowercase__    :	int     					=			unet.half()
             lowercase__    :	List[str]     					=			vae.half()
             lowercase__    :	Dict     					=			bert.half()

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

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

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


      @unittest.skipIf(torch_device != 'cuda'	,    'This test requires a GPU'							)
      def 	_UpperCAmelCase (     self							) ->      Optional[Any]:
             lowercase__    :	Dict     					=			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
             lowercase__    :	Optional[Any]     					=			init_image.resize((7_6_0, 5_0_4)							)

             lowercase__    :	Tuple     					=			'BAAI/AltDiffusion'
             lowercase__    :	Tuple     					=			AltDiffusionImgaImgPipeline.from_pretrained(
                 a	,    safety_checker=a	,    )
             pipe.to(a							)
             pipe.set_progress_bar_config(disable=a							)
             pipe.enable_attention_slicing()

             lowercase__    :	str     					=			'A fantasy landscape, trending on artstation'

             lowercase__    :	Dict     					=			torch.manual_seed(0							)
             lowercase__    :	List[str]     					=			pipe(
                 prompt=a	,    image=a	,    strength=0.75	,    guidance_scale=7.5	,    generator=a	,    output_type='np'	,    )
             lowercase__    :	Optional[Any]     					=			output.images[0]

             lowercase__    :	Optional[Any]     					=			image[2_5_5:2_5_8, 3_8_3:3_8_6, -1]

             assert image.shape == (5_0_4, 7_6_0, 3)
             lowercase__    :	int     					=			np.array([0.9_358, 0.9_397, 0.9_599, 0.9_901, 1.0_000, 1.0_000, 0.9_882, 1.0_000, 1.0_000]							)

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





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


      def 	_UpperCAmelCase (     self							) ->      str:
             # clean up the VRAM after each test
             super().tearDown()
             gc.collect()
             torch.cuda.empty_cache()


      def 	_UpperCAmelCase (     self							) ->      Optional[Any]:
             lowercase__    :	Tuple     					=			load_image(
                 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
                 '/img2img/sketch-mountains-input.jpg'							)
             lowercase__    :	Tuple     					=			init_image.resize((7_6_8, 5_1_2)							)
             lowercase__    :	int     					=			load_numpy(
                 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy'							)

             lowercase__    :	Union[str, Any]     					=			'BAAI/AltDiffusion'
             lowercase__    :	Union[str, Any]     					=			AltDiffusionImgaImgPipeline.from_pretrained(
                 a	,    safety_checker=a	,    )
             pipe.to(a							)
             pipe.set_progress_bar_config(disable=a							)
             pipe.enable_attention_slicing()

             lowercase__    :	Optional[Any]     					=			'A fantasy landscape, trending on artstation'

             lowercase__    :	Union[str, Any]     					=			torch.manual_seed(0							)
             lowercase__    :	Union[str, Any]     					=			pipe(
                 prompt=a	,    image=a	,    strength=0.75	,    guidance_scale=7.5	,    generator=a	,    output_type='np'	,    )
             lowercase__    :	Union[str, Any]     					=			output.images[0]

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


"""simple docstring"""





import unittest

from transformers import is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device


if is_torch_available():
       import torch

       from transformers import AutoModelForImageClassification

if is_vision_available():
       from transformers import AutoImageProcessor


@require_torch
@require_vision
class   UpperCAmelCase_			(					unittest.TestCase):


      @slow
      def 	_UpperCAmelCase (     self							) ->      str:
             lowercase__    :	Optional[Any]     					=			AutoImageProcessor.from_pretrained('microsoft/dit-base-finetuned-rvlcdip'							)
             lowercase__    :	Union[str, Any]     					=			AutoModelForImageClassification.from_pretrained('microsoft/dit-base-finetuned-rvlcdip'							)
             model.to(a							)

             from datasets import load_dataset

             lowercase__    :	str     					=			load_dataset('nielsr/rvlcdip-demo'							)

             lowercase__    :	Tuple     					=			dataset['train'][0]['image'].convert('RGB'							)

             lowercase__    :	int     					=			image_processor(a	,    return_tensors='pt'							).to(a							)

             # forward pass
             with torch.no_grad():
                    lowercase__    :	List[str]     					=			model(**a							)
                    lowercase__    :	List[Any]     					=			outputs.logits

             lowercase__    :	Union[str, Any]     					=			torch.Size((1, 1_6)							)
             self.assertEqual(logits.shape	,    a							)

             lowercase__    :	Tuple     					=			torch.tensor(
                 [-0.4_158, -0.4_092, -0.4_347]	,    device=a	,    dtype=torch.float	,    )
             self.assertTrue(torch.allclose(logits[0, :3]	,    a	,    atol=1e-4							)							)

