
"""simple docstring"""


import inspect
import unittest

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

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch

		from transformers import MobileNetVaForImageClassification, MobileNetVaModel
		from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import MobileNetVaImageProcessor







class 					lowerCAmelCase_					(   _lowercase     ):



						'''simple docstring'''


						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[Any]   )  -> List[Any]:
							A     = self.config_class(**self.inputs_dict   )
							self.parent.assertTrue(hasattr(A_	,'tf_padding'   )   )
							self.parent.assertTrue(hasattr(A_	,'depth_multiplier'   )   )







class 					lowerCAmelCase_					:



						'''simple docstring'''


						def __init__(			self  :   List[Any]	,A_  :   Optional[int]	,A_  :   Optional[int]=13	,A_  :   Tuple=3	,A_  :   Any=32	,A_  :   Optional[Any]=0.25	,A_  :   Union[str, Any]=8	,A_  :   List[str]=True	,A_  :   List[Any]=1024	,A_  :   str=32	,A_  :   Tuple="relu6"	,A_  :   Optional[int]=0.1	,A_  :   int=0.02	,A_  :   int=True	,A_  :   Any=True	,A_  :   Optional[int]=10	,A_  :   List[Any]=None	,)  -> List[Any]:
							A     = parent
							A     = batch_size
							A     = num_channels
							A     = image_size
							A     = depth_multiplier
							A     = min_depth
							A     = tf_padding
							A     = int(last_hidden_size * depth_multiplier   )
							A     = output_stride
							A     = hidden_act
							A     = classifier_dropout_prob
							A     = use_labels
							A     = is_training
							A     = num_labels
							A     = initializer_range
							A     = scope


						def     _SCREAMING_SNAKE_CASE   (			self  :   Dict   )  -> Any:
							A     = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

							A     = None
							A     = None
							if self.use_labels:
								A     = ids_tensor([self.batch_size]	,self.num_labels   )
								A     = ids_tensor([self.batch_size, self.image_size, self.image_size]	,self.num_labels   )

							A     = self.get_config()

							return config, pixel_values, labels, pixel_labels


						def     _SCREAMING_SNAKE_CASE   (			self  :   Any   )  -> List[Any]:
							return MobileNetVaConfig(
							    num_channels=self.num_channels	,image_size=self.image_size	,depth_multiplier=self.depth_multiplier	,min_depth=self.min_depth	,tf_padding=self.tf_padding	,hidden_act=self.hidden_act	,classifier_dropout_prob=self.classifier_dropout_prob	,initializer_range=self.initializer_range	,)


						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[Any]	,A_  :   int	,A_  :   List[Any]	,A_  :   Optional[Any]	,A_  :   Tuple   )  -> List[Any]:
							A     = MobileNetVaModel(config=A_   )
							model.to(A_   )
							model.eval()
							A     = model(A_   )
							self.parent.assertEqual(
							    result.last_hidden_state.shape	,(
							        self.batch_size,
							        self.last_hidden_size,
							        self.image_size // self.output_stride,
							        self.image_size // self.output_stride,
							    )	,)


						def     _SCREAMING_SNAKE_CASE   (			self  :   Any	,A_  :   int	,A_  :   Dict	,A_  :   Optional[Any]	,A_  :   Union[str, Any]   )  -> Tuple:
							A     = self.num_labels
							A     = MobileNetVaForImageClassification(A_   )
							model.to(A_   )
							model.eval()
							A     = model(A_	,labels=A_   )
							self.parent.assertEqual(result.logits.shape	,(self.batch_size, self.num_labels)   )




						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[Any]   )  -> Optional[Any]:
							A     = self.prepare_config_and_inputs()
							A ,   A ,   A ,   A     = config_and_inputs
							A     = {'pixel_values': pixel_values}
							return config, inputs_dict







@require_torch
class 					lowerCAmelCase_					(   _lowercase		,       _lowercase		,       unittest.TestCase     ):



						'''simple docstring'''


						_lowerCamelCase:     List[str]   =     (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
						_lowerCamelCase:     Any   =     (
						    {'''feature-extraction''': MobileNetVaModel, '''image-classification''': MobileNetVaForImageClassification}
						    if is_torch_available()
						    else {}
						)

						_lowerCamelCase:     List[str]   =     False
						_lowerCamelCase:     Optional[Any]   =     False
						_lowerCamelCase:     List[Any]   =     False
						_lowerCamelCase:     Union[str, Any]   =     False


						def     _SCREAMING_SNAKE_CASE   (			self  :   Any   )  -> str:
							A     = MobileNetVaModelTester(self   )
							A     = MobileNetVaConfigTester(self	,config_class=A_	,has_text_modality=A_   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[int]   )  -> Tuple:
							self.config_tester.run_common_tests()


						@unittest.skip(reason='MobileNetV1 does not use inputs_embeds'   )
						def     _SCREAMING_SNAKE_CASE   (			self  :   Tuple   )  -> Union[str, Any]:
							pass


						@unittest.skip(reason='MobileNetV1 does not support input and output embeddings'   )
						def     _SCREAMING_SNAKE_CASE   (			self  :   int   )  -> Union[str, Any]:
							pass


						@unittest.skip(reason='MobileNetV1 does not output attentions'   )
						def     _SCREAMING_SNAKE_CASE   (			self  :   Tuple   )  -> List[str]:
							pass


						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[int]   )  -> List[Any]:
							A ,   A     = self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
								A     = model_class(A_   )
								A     = inspect.signature(model.forward   )
								# signature.parameters is an OrderedDict => so arg_names order is deterministic
								A     = [*signature.parameters.keys()]

								A     = ['pixel_values']
								self.assertListEqual(arg_names[:1]	,A_   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   str   )  -> Tuple:
							A     = self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*A_   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   Any   )  -> List[Any]:
							def check_hidden_states_output(A_  :   int	,A_  :   Dict	,A_  :   str   ):
								A     = model_class(A_   )
								model.to(A_   )
								model.eval()

								with torch.no_grad():
									A     = model(**self._prepare_for_class(A_	,A_   )   )

								A     = outputs.hidden_states

								A     = 26
								self.assertEqual(len(A_   )	,A_   )

							A ,   A     = self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
								A     = True
								check_hidden_states_output(A_	,A_	,A_   )

								# check that output_hidden_states also work using config
								del inputs_dict["output_hidden_states"]
								A     = True

								check_hidden_states_output(A_	,A_	,A_   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[int]   )  -> List[str]:
							A     = self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*A_   )




						@slow
						def     _SCREAMING_SNAKE_CASE   (			self  :   str   )  -> int:
							for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								A     = MobileNetVaModel.from_pretrained(A_   )
								self.assertIsNotNone(A_   )






def    _snake_case					(		):
	A     = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
	return image







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



						'''simple docstring'''


						@cached_property
						def     _SCREAMING_SNAKE_CASE   (			self  :   Tuple   )  -> Dict:
							return (
							    MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v1_1.0_224'   ) if is_vision_available() else None
							)




						@slow
						def     _SCREAMING_SNAKE_CASE   (			self  :   List[Any]   )  -> str:
							A     = MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v1_1.0_224'   ).to(A_   )

							A     = self.default_image_processor
							A     = prepare_img()
							A     = image_processor(images=A_	,return_tensors='pt'   ).to(A_   )

							# forward pass
							with torch.no_grad():
								A     = model(**A_   )

							# verify the logits
							A     = torch.Size((1, 1001)   )
							self.assertEqual(outputs.logits.shape	,A_   )

							A     = torch.tensor([-4.17_39, -1.12_33, 3.12_05]   ).to(A_   )

							self.assertTrue(torch.allclose(outputs.logits[0, :3]	,A_	,atol=1e-4   )   )

"""simple docstring"""


import random
import unittest

import numpy as np

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionImgaImgPipeline,
    PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
		import onnxruntime as ort







class 					lowerCAmelCase_					(   _lowercase		,       unittest.TestCase     ):



						'''simple docstring'''


						_lowerCamelCase:     Dict   =     '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'''


						def     _SCREAMING_SNAKE_CASE   (			self  :   Any	,A_  :   List[str]=0   )  -> str:
							A     = floats_tensor((1, 3, 128, 128)	,rng=random.Random(A_   )   )
							A     = np.random.RandomState(A_   )
							A     = {
							    'prompt': 'A painting of a squirrel eating a burger',
							    'image': image,
							    'generator': generator,
							    'num_inference_steps': 3,
							    'strength': 0.75,
							    'guidance_scale': 7.5,
							    'output_type': 'numpy',
							}
							return inputs


						def     _SCREAMING_SNAKE_CASE   (			self  :   Dict   )  -> Tuple:
							A     = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint	,provider='CPUExecutionProvider'   )
							pipe.set_progress_bar_config(disable=A_   )

							A     = self.get_dummy_inputs()
							A     = pipe(**A_   ).images
							A     = image[0, -3:, -3:, -1].flatten()

							assert image.shape == (1, 128, 128, 3)
							A     = np.array([0.6_96_43, 0.5_84_84, 0.5_03_14, 0.5_87_60, 0.5_53_68, 0.5_96_43, 0.5_15_29, 0.4_12_17, 0.4_90_87]   )
							assert np.abs(image_slice - expected_slice   ).max() < 1e-1


						def     _SCREAMING_SNAKE_CASE   (			self  :   List[Any]   )  -> Any:
							A     = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint	,provider='CPUExecutionProvider'   )
							A     = PNDMScheduler.from_config(pipe.scheduler.config	,skip_prk_steps=A_   )
							pipe.set_progress_bar_config(disable=A_   )

							A     = self.get_dummy_inputs()
							A     = pipe(**A_   ).images
							A     = image[0, -3:, -3:, -1]

							assert image.shape == (1, 128, 128, 3)
							A     = np.array([0.6_17_37, 0.5_46_42, 0.5_31_83, 0.5_44_65, 0.5_27_42, 0.6_05_25, 0.4_99_69, 0.4_06_55, 0.4_81_54]   )

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


						def     _SCREAMING_SNAKE_CASE   (			self  :   Union[str, Any]   )  -> int:
							A     = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint	,provider='CPUExecutionProvider'   )
							A     = LMSDiscreteScheduler.from_config(pipe.scheduler.config   )
							pipe.set_progress_bar_config(disable=A_   )

							# warmup pass to apply optimizations
							A     = pipe(**self.get_dummy_inputs()   )

							A     = self.get_dummy_inputs()
							A     = pipe(**A_   ).images
							A     = image[0, -3:, -3:, -1]

							assert image.shape == (1, 128, 128, 3)
							A     = np.array([0.5_27_61, 0.5_99_77, 0.4_90_33, 0.4_96_19, 0.5_42_82, 0.5_03_11, 0.4_76_00, 0.4_09_18, 0.4_52_03]   )

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


						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[int]   )  -> Tuple:
							A     = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint	,provider='CPUExecutionProvider'   )
							A     = EulerDiscreteScheduler.from_config(pipe.scheduler.config   )
							pipe.set_progress_bar_config(disable=A_   )

							A     = self.get_dummy_inputs()
							A     = pipe(**A_   ).images
							A     = image[0, -3:, -3:, -1]

							assert image.shape == (1, 128, 128, 3)
							A     = np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04]   )

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


						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[Any]   )  -> str:
							A     = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint	,provider='CPUExecutionProvider'   )
							A     = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config   )
							pipe.set_progress_bar_config(disable=A_   )

							A     = self.get_dummy_inputs()
							A     = pipe(**A_   ).images
							A     = image[0, -3:, -3:, -1]

							assert image.shape == (1, 128, 128, 3)
							A     = np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04]   )

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




						def     _SCREAMING_SNAKE_CASE   (			self  :   int   )  -> Tuple:
							A     = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint	,provider='CPUExecutionProvider'   )
							A     = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config   )
							pipe.set_progress_bar_config(disable=A_   )

							A     = self.get_dummy_inputs()
							A     = pipe(**A_   ).images
							A     = image[0, -3:, -3:, -1]

							assert image.shape == (1, 128, 128, 3)
							A     = np.array([0.6_53_31, 0.5_82_77, 0.4_82_04, 0.5_60_59, 0.5_36_65, 0.5_62_35, 0.5_09_69, 0.4_00_09, 0.4_65_52]   )

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







@nightly
@require_onnxruntime
@require_torch_gpu
class 					lowerCAmelCase_					(   unittest.TestCase     ):



						'''simple docstring'''


						@property
						def     _SCREAMING_SNAKE_CASE   (			self  :   int   )  -> Union[str, Any]:
							return (
							    "CUDAExecutionProvider",
							    {
							        "gpu_mem_limit": "15000000000",  # 15GB
							        "arena_extend_strategy": "kSameAsRequested",
							    },
							)


						@property
						def     _SCREAMING_SNAKE_CASE   (			self  :   str   )  -> List[Any]:
							A     = ort.SessionOptions()
							A     = False
							return options


						def     _SCREAMING_SNAKE_CASE   (			self  :   Tuple   )  -> str:
							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)   )
							# using the PNDM scheduler by default
							A     = OnnxStableDiffusionImgaImgPipeline.from_pretrained(
							    'CompVis/stable-diffusion-v1-4'	,revision='onnx'	,safety_checker=A_	,feature_extractor=A_	,provider=self.gpu_provider	,sess_options=self.gpu_options	,)
							pipe.set_progress_bar_config(disable=A_   )

							A     = 'A fantasy landscape, trending on artstation'

							A     = np.random.RandomState(0   )
							A     = pipe(
							    prompt=A_	,image=A_	,strength=0.75	,guidance_scale=7.5	,num_inference_steps=10	,generator=A_	,output_type='np'	,)
							A     = output.images
							A     = images[0, 255:258, 383:386, -1]

							assert images.shape == (1, 512, 768, 3)
							A     = np.array([0.49_09, 0.50_59, 0.53_72, 0.46_23, 0.48_76, 0.50_49, 0.48_20, 0.49_56, 0.50_19]   )
							# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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




						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[int]   )  -> Optional[Any]:
							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     = LMSDiscreteScheduler.from_pretrained(
							    'runwayml/stable-diffusion-v1-5'	,subfolder='scheduler'	,revision='onnx'   )
							A     = OnnxStableDiffusionImgaImgPipeline.from_pretrained(
							    'runwayml/stable-diffusion-v1-5'	,revision='onnx'	,scheduler=A_	,safety_checker=A_	,feature_extractor=A_	,provider=self.gpu_provider	,sess_options=self.gpu_options	,)
							pipe.set_progress_bar_config(disable=A_   )

							A     = 'A fantasy landscape, trending on artstation'

							A     = np.random.RandomState(0   )
							A     = pipe(
							    prompt=A_	,image=A_	,strength=0.75	,guidance_scale=7.5	,num_inference_steps=20	,generator=A_	,output_type='np'	,)
							A     = output.images
							A     = images[0, 255:258, 383:386, -1]

							assert images.shape == (1, 512, 768, 3)
							A     = np.array([0.80_43, 0.9_26, 0.95_81, 0.81_19, 0.89_54, 0.9_13, 0.72_09, 0.74_63, 0.74_31]   )
							# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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