





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      lowerCamelCase(						unittest.TestCase	):
     '''simple docstring'''


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




     @property
     def        lowerCAmelCase__		(    self							):
         _A     =							1
         _A     =							3
         _A     =							(32, 32)

         _A     =							floats_tensor((batch_size, num_channels) + sizes				,     rng=random.Random(0							)							).to(_a							)
         return image




     @property
     def        lowerCAmelCase__		(    self							):
         torch.manual_seed(0							)
         _A     =							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							)
         _A     =							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							)
         _A     =							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=5006				,     )
         return RobertaSeriesModelWithTransformation(_a							)




     @property
     def        lowerCAmelCase__		(    self							):
         def extract(*snake_case_				,     **snake_case_							):







             class      lowerCamelCase:
                  '''simple docstring'''


                  def __init__(    self							):
                      _A     =							torch.ones([0]							)




                  def        lowerCAmelCase__		(    self				,     snake_case_							):
                      self.pixel_values.to(_a							)
                      return self




             return Out()

         return extract




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

         _A     =							self.dummy_image.to(_a							)
         _A     =							init_image / 2 + 0.5

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

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

         _A     =							output.images

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

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

         assert image.shape == (1, 32, 32, 3)
         _A     =							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							):
         _A     =							self.dummy_cond_unet
         _A     =							PNDMScheduler(skip_prk_steps=_a							)
         _A     =							self.dummy_vae
         _A     =							self.dummy_text_encoder
         _A     =							XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'							)
         _A     =							77

         _A     =							self.dummy_image.to(_a							)

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

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

         _A     =							'''A painting of a squirrel eating a burger'''
         _A     =							torch.manual_seed(0							)
         _A     =							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							):
         _A     =							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
         _A     =							init_image.resize((760, 504)							)

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

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

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

         _A     =							image[255:258, 383:386, -1]

         assert image.shape == (504, 760, 3)
         _A     =							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      lowerCamelCase(						unittest.TestCase	):
     '''simple docstring'''


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




     def        lowerCAmelCase__		(    self							):
         _A     =							load_image(
             'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
             '/img2img/sketch-mountains-input.jpg'							)
         _A     =							init_image.resize((768, 512)							)
         _A     =							load_numpy(
             'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy'							)

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

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

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

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








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


a__												=						logging.get_logger(__name__)

a__												=						{
    '''google/mobilenet_v1_1.0_224''': '''https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json''',
    '''google/mobilenet_v1_0.75_192''': '''https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json''',
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
}

class 							UpperCAmelCase_						(     __lowercase  ):
							"""simple docstring"""







							UpperCAmelCase__			:		int             =       "mobilenet_v1"


							def __init__(     self			,				_a=3			,				_a=2_2_4			,				_a=1.0			,				_a=8			,				_a="relu6"			,				_a=True			,				_a=0.999			,				_a=0.02			,				_a=0.001			,				**_a			,				)       ->       List[Any]:
												super().__init__(**_a			)

												if depth_multiplier <= 0:
																	raise ValueError('''depth_multiplier must be greater than zero.'''			)

												_a      :       Tuple   =						num_channels
												_a      :       str   =						image_size
												_a      :       Tuple   =						depth_multiplier
												_a      :       Any   =						min_depth
												_a      :       int   =						hidden_act
												_a      :       Optional[Any]   =						tf_padding
												_a      :       str   =						classifier_dropout_prob
												_a      :       Optional[int]   =						initializer_range
												_a      :       Any   =						layer_norm_eps



class 							UpperCAmelCase_						(     __lowercase  ):
							"""simple docstring"""







							UpperCAmelCase__			:		str             =       version.parse("1.11"  )


							@property
							def 							__lowercase							(     self			)       ->       Mapping[str, Mapping[int, str]]:
												return OrderedDict([('''pixel_values''', {0: '''batch'''})]			)


							@property
							def 							__lowercase							(     self			)       ->       Mapping[str, Mapping[int, str]]:
												if self.task == "image-classification":
																	return OrderedDict([('''logits''', {0: '''batch'''})]			)
												else:
																	return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})]			)




							@property
							def 							__lowercase							(     self			)       ->       float:
												return 1e-4



