


"""simple docstring"""



import inspect
import unittest

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

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 torch import nn

  from transformers import RegNetForImageClassification, RegNetModel
  from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor







class _lowerCAmelCase				:







   def __init__(	self						,	UpperCamelCase__						,	UpperCamelCase__=3						,	UpperCamelCase__=32						,	UpperCamelCase__=3						,	UpperCamelCase__=10						,	UpperCamelCase__=[10, 20, 30, 40]						,	UpperCamelCase__=[1, 1, 2, 1]						,	UpperCamelCase__=True						,	UpperCamelCase__=True						,	UpperCamelCase__="relu"						,	UpperCamelCase__=3						,	UpperCamelCase__=None						,	)	->		int:

       '''simple docstring'''




       snake_case    :      Any      					=    parent
       snake_case    :      int      					=    batch_size
       snake_case    :      List[str]      					=    image_size
       snake_case    :      Any      					=    num_channels
       snake_case    :      List[Any]      					=    embeddings_size
       snake_case    :      Dict      					=    hidden_sizes
       snake_case    :      List[str]      					=    depths
       snake_case    :      int      					=    is_training
       snake_case    :      Union[str, Any]      					=    use_labels
       snake_case    :      List[Any]      					=    hidden_act
       snake_case    :      Optional[int]      					=    num_labels
       snake_case    :      List[Any]      					=    scope
       snake_case    :      Optional[Any]      					=    len(UpperCamelCase__						)







   def  lowerCamelCase		(	self						)	->		Optional[int]:

       '''simple docstring'''




       snake_case    :      Any      					=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

       snake_case    :      Union[str, Any]      					=    None
       if self.use_labels:
           snake_case    :      Optional[Any]      					=    ids_tensor([self.batch_size]						,	self.num_labels						)

       snake_case    :      List[Any]      					=    self.get_config()

       return config, pixel_values, labels







   def  lowerCamelCase		(	self						)	->		Union[str, Any]:

       '''simple docstring'''




       return RegNetConfig(
           num_channels=self.num_channels						,	embeddings_size=self.embeddings_size						,	hidden_sizes=self.hidden_sizes						,	depths=self.depths						,	hidden_act=self.hidden_act						,	num_labels=self.num_labels						,	)







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						)	->		Union[str, Any]:

       '''simple docstring'''




       snake_case    :      List[str]      					=    RegNetModel(config=UpperCamelCase__						)
       model.to(UpperCamelCase__						)
       model.eval()
       snake_case    :      Optional[int]      					=    model(UpperCamelCase__						)
       # expected last hidden states: B, C, H // 32, W // 32
       self.parent.assertEqual(
           result.last_hidden_state.shape						,	(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)						,	)







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						)	->		Optional[int]:

       '''simple docstring'''




       snake_case    :      List[str]      					=    self.num_labels
       snake_case    :      List[Any]      					=    RegNetForImageClassification(UpperCamelCase__						)
       model.to(UpperCamelCase__						)
       model.eval()
       snake_case    :      Tuple      					=    model(UpperCamelCase__						,	labels=UpperCamelCase__						)
       self.parent.assertEqual(result.logits.shape						,	(self.batch_size, self.num_labels)						)







   def  lowerCamelCase		(	self						)	->		Optional[int]:

       '''simple docstring'''




       snake_case    :      Union[str, Any]      					=    self.prepare_config_and_inputs()
       snake_case					,snake_case					,snake_case    :      Tuple      					=    config_and_inputs
       snake_case    :      Union[str, Any]      					=    {"pixel_values": pixel_values}
       return config, inputs_dict







@require_torch
class _lowerCAmelCase				(      snake_case_    ,							snake_case_    ,							unittest.TestCase	):
   __UpperCAmelCase :       Optional[Any]							  =  (RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
   __UpperCAmelCase :       Union[str, Any]							  =  (
       {'''feature-extraction''': RegNetModel, '''image-classification''': RegNetForImageClassification}
       if is_torch_available()
       else {}
   )

   __UpperCAmelCase :       List[str]							  =  False
   __UpperCAmelCase :       Dict							  =  False
   __UpperCAmelCase :       Optional[Any]							  =  False
   __UpperCAmelCase :       Any							  =  False







   def  lowerCamelCase		(	self						)	->		List[str]:

       '''simple docstring'''




       snake_case    :      Optional[int]      					=    RegNetModelTester(self						)
       snake_case    :      List[str]      					=    ConfigTester(self						,	config_class=UpperCamelCase__						,	has_text_modality=UpperCamelCase__						)







   def  lowerCamelCase		(	self						)	->		Tuple:

       '''simple docstring'''




       self.create_and_test_config_common_properties()
       self.config_tester.create_and_test_config_to_json_string()
       self.config_tester.create_and_test_config_to_json_file()
       self.config_tester.create_and_test_config_from_and_save_pretrained()
       self.config_tester.create_and_test_config_with_num_labels()
       self.config_tester.check_config_can_be_init_without_params()
       self.config_tester.check_config_arguments_init()







   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       return







   @unittest.skip(reason="RegNet does not use inputs_embeds"						)
   def  lowerCamelCase		(	self						)	->		List[str]:

       '''simple docstring'''




       pass







   @unittest.skip(reason="RegNet does not support input and output embeddings"						)
   def  lowerCamelCase		(	self						)	->		List[str]:

       '''simple docstring'''




       pass







   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       snake_case					,snake_case    :      List[str]      					=    self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           snake_case    :      Optional[Any]      					=    model_class(UpperCamelCase__						)
           snake_case    :      List[Any]      					=    inspect.signature(model.forward						)
           # signature.parameters is an OrderedDict => so arg_names order is deterministic
           snake_case    :      Optional[int]      					=    [*signature.parameters.keys()]

           snake_case    :      Dict      					=    ["pixel_values"]
           self.assertListEqual(arg_names[:1]						,	UpperCamelCase__						)







   def  lowerCamelCase		(	self						)	->		Optional[Any]:

       '''simple docstring'''




       snake_case    :      List[str]      					=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCamelCase__						)







   def  lowerCamelCase		(	self						)	->		Optional[int]:

       '''simple docstring'''




       snake_case					,snake_case    :      List[Any]      					=    self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           snake_case    :      str      					=    model_class(config=UpperCamelCase__						)
           for name, module in model.named_modules():
               if isinstance(UpperCamelCase__						,	(nn.BatchNormad, nn.GroupNorm)						):
                   self.assertTrue(
                       torch.all(module.weight == 1						)						,	msg=F'Parameter {name} of model {model_class} seems not properly initialized'						,	)
                   self.assertTrue(
                       torch.all(module.bias == 0						)						,	msg=F'Parameter {name} of model {model_class} seems not properly initialized'						,	)







   def  lowerCamelCase		(	self						)	->		Optional[int]:

       '''simple docstring'''




       def check_hidden_states_output(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						):
           snake_case    :      List[str]      					=    model_class(UpperCamelCase__						)
           model.to(UpperCamelCase__						)
           model.eval()

           with torch.no_grad():
               snake_case    :      Tuple      					=    model(**self._prepare_for_class(UpperCamelCase__						,	UpperCamelCase__						)						)

           snake_case    :      List[str]      					=    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

           snake_case    :      Optional[int]      					=    self.model_tester.num_stages
           self.assertEqual(len(UpperCamelCase__						)						,	expected_num_stages + 1						)

           # RegNet's feature maps are of shape (batch_size, num_channels, height, width)
           self.assertListEqual(
               list(hidden_states[0].shape[-2:]						)						,	[self.model_tester.image_size // 2, self.model_tester.image_size // 2]						,	)

       snake_case					,snake_case    :      Optional[int]      					=    self.model_tester.prepare_config_and_inputs_for_common()
       snake_case    :      List[str]      					=    ["basic", "bottleneck"]
       for model_class in self.all_model_classes:
           for layer_type in layers_type:
               snake_case    :      Optional[Any]      					=    layer_type
               snake_case    :      List[Any]      					=    True
               check_hidden_states_output(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						)

               # check that output_hidden_states also work using config
               del inputs_dict["output_hidden_states"]
               snake_case    :      Optional[Any]      					=    True

               check_hidden_states_output(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						)







   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       snake_case    :      Any      					=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__						)







   @slow
   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           snake_case    :      str      					=    RegNetModel.from_pretrained(UpperCamelCase__						)
           self.assertIsNotNone(UpperCamelCase__						)







def   __lowerCAmelCase						(						)	->						List[Any]:


    """simple docstring"""





    snake_case    :      Optional[Any]      					=    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
    return image







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







   @cached_property
   def  lowerCamelCase		(	self						)	->		int:

       '''simple docstring'''




       return (
           AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)
           if is_vision_available()
           else None
       )







   @slow
   def  lowerCamelCase		(	self						)	->		List[Any]:

       '''simple docstring'''




       snake_case    :      int      					=    RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						).to(UpperCamelCase__						)

       snake_case    :      List[Any]      					=    self.default_image_processor
       snake_case    :      List[Any]      					=    prepare_img()
       snake_case    :      Optional[Any]      					=    image_processor(images=UpperCamelCase__						,	return_tensors="pt"						).to(UpperCamelCase__						)

       # forward pass
       with torch.no_grad():
           snake_case    :      Any      					=    model(**UpperCamelCase__						)

       # verify the logits
       snake_case    :      Optional[int]      					=    torch.Size((1, 1000)						)
       self.assertEqual(outputs.logits.shape						,	UpperCamelCase__						)

       snake_case    :      Any      					=    torch.tensor([-0.4180, -1.5051, -3.4836]						).to(UpperCamelCase__						)

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









"""simple docstring"""



import random
import unittest

import numpy as np
import torch

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionUpscalePipeline,
    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				(      snake_case_    ,							unittest.TestCase	):
   # TODO: is there an appropriate internal test set?
   __UpperCAmelCase :       Optional[Any]							  =  '''ssube/stable-diffusion-x4-upscaler-onnx'''







   def  lowerCamelCase		(	self						,	UpperCamelCase__=0						)	->		Tuple:

       '''simple docstring'''




       snake_case    :      Union[str, Any]      					=    floats_tensor((1, 3, 128, 128)						,	rng=random.Random(UpperCamelCase__						)						)
       snake_case    :      Any      					=    torch.manual_seed(UpperCamelCase__						)
       snake_case    :      List[str]      					=    {
           "prompt": "A painting of a squirrel eating a burger",
           "image": image,
           "generator": generator,
           "num_inference_steps": 3,
           "guidance_scale": 7.5,
           "output_type": "numpy",
       }
       return inputs







   def  lowerCamelCase		(	self						)	->		Tuple:

       '''simple docstring'''




       snake_case    :      Optional[Any]      					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"						)
       pipe.set_progress_bar_config(disable=UpperCamelCase__						)

       snake_case    :      Tuple      					=    self.get_dummy_inputs()
       snake_case    :      int      					=    pipe(**UpperCamelCase__						).images
       snake_case    :      Tuple      					=    image[0, -3:, -3:, -1].flatten()

       # started as 128, should now be 512
       assert image.shape == (1, 512, 512, 3)
       snake_case    :      Optional[int]      					=    np.array(
           [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223]						)
       assert np.abs(image_slice - expected_slice						).max() < 1e-1







   def  lowerCamelCase		(	self						)	->		Union[str, Any]:

       '''simple docstring'''




       snake_case    :      Tuple      					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"						)
       snake_case    :      Optional[Any]      					=    PNDMScheduler.from_config(pipe.scheduler.config						,	skip_prk_steps=UpperCamelCase__						)
       pipe.set_progress_bar_config(disable=UpperCamelCase__						)

       snake_case    :      Tuple      					=    self.get_dummy_inputs()
       snake_case    :      Optional[Any]      					=    pipe(**UpperCamelCase__						).images
       snake_case    :      List[str]      					=    image[0, -3:, -3:, -1]

       assert image.shape == (1, 512, 512, 3)
       snake_case    :      Dict      					=    np.array(
           [0.6898892, 0.59240556, 0.52499527, 0.58866215, 0.52258235, 0.52572715, 0.62414473, 0.6174387, 0.6214964]						)
       assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-1







   def  lowerCamelCase		(	self						)	->		Any:

       '''simple docstring'''




       snake_case    :      Optional[int]      					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"						)
       snake_case    :      Optional[Any]      					=    DPMSolverMultistepScheduler.from_config(pipe.scheduler.config						)
       pipe.set_progress_bar_config(disable=UpperCamelCase__						)

       snake_case    :      Any      					=    self.get_dummy_inputs()
       snake_case    :      List[Any]      					=    pipe(**UpperCamelCase__						).images
       snake_case    :      List[str]      					=    image[0, -3:, -3:, -1]

       assert image.shape == (1, 512, 512, 3)
       snake_case    :      Optional[Any]      					=    np.array(
           [0.7659278, 0.76437664, 0.75579107, 0.7691116, 0.77666986, 0.7727672, 0.7758664, 0.7812226, 0.76942515]						)

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







   def  lowerCamelCase		(	self						)	->		Any:

       '''simple docstring'''




       snake_case    :      Union[str, Any]      					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"						)
       snake_case    :      Any      					=    EulerDiscreteScheduler.from_config(pipe.scheduler.config						)
       pipe.set_progress_bar_config(disable=UpperCamelCase__						)

       snake_case    :      Dict      					=    self.get_dummy_inputs()
       snake_case    :      Union[str, Any]      					=    pipe(**UpperCamelCase__						).images
       snake_case    :      str      					=    image[0, -3:, -3:, -1]

       assert image.shape == (1, 512, 512, 3)
       snake_case    :      Union[str, Any]      					=    np.array(
           [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223]						)
       assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-1







   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       snake_case    :      Optional[Any]      					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"						)
       snake_case    :      Optional[Any]      					=    EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config						)
       pipe.set_progress_bar_config(disable=UpperCamelCase__						)

       snake_case    :      Any      					=    self.get_dummy_inputs()
       snake_case    :      int      					=    pipe(**UpperCamelCase__						).images
       snake_case    :      List[Any]      					=    image[0, -3:, -3:, -1]

       assert image.shape == (1, 512, 512, 3)
       snake_case    :      Union[str, Any]      					=    np.array(
           [0.77424496, 0.773601, 0.7645288, 0.7769598, 0.7772739, 0.7738688, 0.78187233, 0.77879584, 0.767043]						)

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







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







   @property
   def  lowerCamelCase		(	self						)	->		Tuple:

       '''simple docstring'''




       return (
           "CUDAExecutionProvider",
           {
               "gpu_mem_limit": "15000000000",  # 15GB
               "arena_extend_strategy": "kSameAsRequested",
           },
       )







   @property
   def  lowerCamelCase		(	self						)	->		List[Any]:

       '''simple docstring'''




       snake_case    :      List[Any]      					=    ort.SessionOptions()
       snake_case    :      str      					=    False
       return options







   def  lowerCamelCase		(	self						)	->		List[Any]:

       '''simple docstring'''




       snake_case    :      str      					=    load_image(
           "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
           "/img2img/sketch-mountains-input.jpg"						)
       snake_case    :      Tuple      					=    init_image.resize((128, 128)						)
       # using the PNDM scheduler by default
       snake_case    :      Tuple      					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(
           "ssube/stable-diffusion-x4-upscaler-onnx"						,	provider=self.gpu_provider						,	sess_options=self.gpu_options						,	)
       pipe.set_progress_bar_config(disable=UpperCamelCase__						)

       snake_case    :      List[Any]      					=    "A fantasy landscape, trending on artstation"

       snake_case    :      Union[str, Any]      					=    torch.manual_seed(0						)
       snake_case    :      int      					=    pipe(
           prompt=UpperCamelCase__						,	image=UpperCamelCase__						,	guidance_scale=7.5						,	num_inference_steps=10						,	generator=UpperCamelCase__						,	output_type="np"						,	)
       snake_case    :      str      					=    output.images
       snake_case    :      Tuple      					=    images[0, 255:258, 383:386, -1]

       assert images.shape == (1, 512, 512, 3)
       snake_case    :      int      					=    np.array([0.4883, 0.4947, 0.4980, 0.4975, 0.4982, 0.4980, 0.5000, 0.5006, 0.4972]						)
       # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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







   def  lowerCamelCase		(	self						)	->		Optional[Any]:

       '''simple docstring'''




       snake_case    :      Tuple      					=    load_image(
           "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
           "/img2img/sketch-mountains-input.jpg"						)
       snake_case    :      Optional[Any]      					=    init_image.resize((128, 128)						)
       snake_case    :      Union[str, Any]      					=    LMSDiscreteScheduler.from_pretrained(
           "ssube/stable-diffusion-x4-upscaler-onnx"						,	subfolder="scheduler"						)
       snake_case    :      List[Any]      					=    OnnxStableDiffusionUpscalePipeline.from_pretrained(
           "ssube/stable-diffusion-x4-upscaler-onnx"						,	scheduler=UpperCamelCase__						,	provider=self.gpu_provider						,	sess_options=self.gpu_options						,	)
       pipe.set_progress_bar_config(disable=UpperCamelCase__						)

       snake_case    :      Union[str, Any]      					=    "A fantasy landscape, trending on artstation"

       snake_case    :      Tuple      					=    torch.manual_seed(0						)
       snake_case    :      str      					=    pipe(
           prompt=UpperCamelCase__						,	image=UpperCamelCase__						,	guidance_scale=7.5						,	num_inference_steps=20						,	generator=UpperCamelCase__						,	output_type="np"						,	)
       snake_case    :      List[Any]      					=    output.images
       snake_case    :      List[Any]      					=    images[0, 255:258, 383:386, -1]

       assert images.shape == (1, 512, 512, 3)
       snake_case    :      int      					=    np.array(
           [0.50173753, 0.50223356, 0.502039, 0.50233036, 0.5023725, 0.5022601, 0.5018758, 0.50234085, 0.50241566]						)
       # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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





