





import inspect
import unittest

from transformers import ConvNextConfig
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_backbone_common import BackboneTesterMixin
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 ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
     from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor



class     _UpperCAmelCase   :

  """simple docstring"""


  def __init__(    self			:		List[str] ,  lowerCAmelCase_			:		List[Any] ,  lowerCAmelCase_			:		List[Any]=1_3 ,  lowerCAmelCase_			:		List[Any]=3_2 ,  lowerCAmelCase_			:		Optional[Any]=3 ,  lowerCAmelCase_			:		Optional[Any]=4 ,  lowerCAmelCase_			:		Tuple=[1_0, 2_0, 3_0, 4_0] ,  lowerCAmelCase_			:		Optional[int]=[2, 2, 3, 2] ,  lowerCAmelCase_			:		Union[str, Any]=True ,  lowerCAmelCase_			:		int=True ,  lowerCAmelCase_			:		Optional[Any]=3_7 ,  lowerCAmelCase_			:		Optional[int]="gelu" ,  lowerCAmelCase_			:		List[Any]=1_0 ,  lowerCAmelCase_			:		Union[str, Any]=0.02 ,  lowerCAmelCase_			:		List[Any]=["stage2", "stage3", "stage4"] ,  lowerCAmelCase_			:		Dict=[2, 3, 4] ,  lowerCAmelCase_			:		Dict=None ,  )							->						Optional[Any]:
     __lowerCAmelCase							     =     parent
     __lowerCAmelCase							     =     batch_size
     __lowerCAmelCase							     =     image_size
     __lowerCAmelCase							     =     num_channels
     __lowerCAmelCase							     =     num_stages
     __lowerCAmelCase							     =     hidden_sizes
     __lowerCAmelCase							     =     depths
     __lowerCAmelCase							     =     is_training
     __lowerCAmelCase							     =     use_labels
     __lowerCAmelCase							     =     intermediate_size
     __lowerCAmelCase							     =     hidden_act
     __lowerCAmelCase							     =     num_labels
     __lowerCAmelCase							     =     initializer_range
     __lowerCAmelCase							     =     out_features
     __lowerCAmelCase							     =     out_indices
     __lowerCAmelCase							     =     scope






  def     lowercase		(    self			:		Union[str, Any]					)							->						str:
     __lowerCAmelCase							     =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

     __lowerCAmelCase							     =     self.get_config()
     return config, pixel_values, labels






  def     lowercase		(    self			:		Any					)							->						Any:
     return ConvNextConfig(
         num_channels=self.num_channels ,  hidden_sizes=self.hidden_sizes ,  depths=self.depths ,  num_stages=self.num_stages ,  hidden_act=self.hidden_act ,  is_decoder=lowerCAmelCase_ ,  initializer_range=self.initializer_range ,  out_features=self.out_features ,  out_indices=self.out_indices ,  num_labels=self.num_labels ,  )






  def     lowercase		(    self			:		Optional[int] ,  lowerCAmelCase_			:		Any ,  lowerCAmelCase_			:		int ,  lowerCAmelCase_			:		Any					)							->						str:
     __lowerCAmelCase							     =     ConvNextModel(config=lowerCAmelCase_					)
     model.to(lowerCAmelCase_					)
     model.eval()
     __lowerCAmelCase							     =     model(lowerCAmelCase_					)
     # 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 // 3_2, self.image_size // 3_2) ,  )






  def     lowercase		(    self			:		int ,  lowerCAmelCase_			:		Any ,  lowerCAmelCase_			:		Union[str, Any] ,  lowerCAmelCase_			:		str					)							->						Optional[Any]:
     __lowerCAmelCase							     =     ConvNextForImageClassification(lowerCAmelCase_					)
     model.to(lowerCAmelCase_					)
     model.eval()
     __lowerCAmelCase							     =     model(lowerCAmelCase_ ,  labels=lowerCAmelCase_					)
     self.parent.assertEqual(result.logits.shape ,  (self.batch_size, self.num_labels)					)






  def     lowercase		(    self			:		Optional[Any] ,  lowerCAmelCase_			:		Union[str, Any] ,  lowerCAmelCase_			:		Union[str, Any] ,  lowerCAmelCase_			:		Optional[Any]					)							->						Dict:
     __lowerCAmelCase							     =     ConvNextBackbone(config=lowerCAmelCase_					)
     model.to(lowerCAmelCase_					)
     model.eval()
     __lowerCAmelCase							     =     model(lowerCAmelCase_					)

     # verify hidden states
     self.parent.assertEqual(len(result.feature_maps					) ,  len(config.out_features					)					)
     self.parent.assertListEqual(list(result.feature_maps[0].shape					) ,  [self.batch_size, self.hidden_sizes[1], 4, 4]					)

     # verify channels
     self.parent.assertEqual(len(model.channels					) ,  len(config.out_features					)					)
     self.parent.assertListEqual(model.channels ,  config.hidden_sizes[1:]					)

     # verify backbone works with out_features=None
     __lowerCAmelCase							     =     None
     __lowerCAmelCase							     =     ConvNextBackbone(config=lowerCAmelCase_					)
     model.to(lowerCAmelCase_					)
     model.eval()
     __lowerCAmelCase							     =     model(lowerCAmelCase_					)

     # verify feature maps
     self.parent.assertEqual(len(result.feature_maps					) ,  1					)
     self.parent.assertListEqual(list(result.feature_maps[0].shape					) ,  [self.batch_size, self.hidden_sizes[-1], 1, 1]					)

     # verify channels
     self.parent.assertEqual(len(model.channels					) ,  1					)
     self.parent.assertListEqual(model.channels ,  [config.hidden_sizes[-1]]					)






  def     lowercase		(    self			:		List[Any]					)							->						int:
     __lowerCAmelCase							     =     self.prepare_config_and_inputs()
     __lowerCAmelCase     ,     __lowerCAmelCase     ,     __lowerCAmelCase							     =     config_and_inputs
     __lowerCAmelCase							     =     {'pixel_values': pixel_values}
     return config, inputs_dict





@require_torch
class     _UpperCAmelCase   (   _UpperCamelCase		,   _UpperCamelCase		,   unittest.TestCase   ):

  """simple docstring"""


  a_      =			(
      (
          ConvNextModel,
          ConvNextForImageClassification,
          ConvNextBackbone,
      )
      if is_torch_available()
      else ()
  )
  a_      =			(
      {"""feature-extraction""": ConvNextModel, """image-classification""": ConvNextForImageClassification}
      if is_torch_available()
      else {}
  )

  a_      =			True
  a_      =			False
  a_      =			False
  a_      =			False
  a_      =			False






  def     lowercase		(    self			:		Optional[int]					)							->						List[Any]:
     __lowerCAmelCase							     =     ConvNextModelTester(self					)
     __lowerCAmelCase							     =     ConfigTester(self ,  config_class=lowerCAmelCase_ ,  has_text_modality=lowerCAmelCase_ ,  hidden_size=3_7					)






  def     lowercase		(    self			:		Tuple					)							->						List[str]:
     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     lowercase		(    self			:		Tuple					)							->						Optional[int]:
     return






  @unittest.skip(reason='ConvNext does not use inputs_embeds'					)
  def     lowercase		(    self			:		Optional[Any]					)							->						Dict:
     pass






  @unittest.skip(reason='ConvNext does not support input and output embeddings'					)
  def     lowercase		(    self			:		Optional[Any]					)							->						List[Any]:
     pass






  @unittest.skip(reason='ConvNext does not use feedforward chunking'					)
  def     lowercase		(    self			:		List[Any]					)							->						Any:
     pass






  def     lowercase		(    self			:		Optional[Any]					)							->						Union[str, Any]:
     __lowerCAmelCase     ,     __lowerCAmelCase							     =     self.model_tester.prepare_config_and_inputs_for_common()

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

        __lowerCAmelCase							     =     ['pixel_values']
        self.assertListEqual(arg_names[:1] ,  lowerCAmelCase_					)






  def     lowercase		(    self			:		Union[str, Any]					)							->						Optional[Any]:
     __lowerCAmelCase							     =     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowerCAmelCase_					)






  def     lowercase		(    self			:		List[Any]					)							->						List[Any]:
     __lowerCAmelCase							     =     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_backbone(*lowerCAmelCase_					)






  def     lowercase		(    self			:		Dict					)							->						Union[str, Any]:
     def check_hidden_states_output(lowerCAmelCase_			:		int ,  lowerCAmelCase_			:		Tuple ,  lowerCAmelCase_			:		str					):
        __lowerCAmelCase							     =     model_class(lowerCAmelCase_					)
        model.to(lowerCAmelCase_					)
        model.eval()

        with torch.no_grad():
           __lowerCAmelCase							     =     model(**self._prepare_for_class(lowerCAmelCase_ ,  lowerCAmelCase_					)					)

        __lowerCAmelCase							     =     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        __lowerCAmelCase							     =     self.model_tester.num_stages
        self.assertEqual(len(lowerCAmelCase_					) ,  expected_num_stages + 1					)

        # ConvNext'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 // 4, self.model_tester.image_size // 4] ,  )

     __lowerCAmelCase     ,     __lowerCAmelCase							     =     self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        __lowerCAmelCase							     =     True
        check_hidden_states_output(lowerCAmelCase_ ,  lowerCAmelCase_ ,  lowerCAmelCase_					)

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

        check_hidden_states_output(lowerCAmelCase_ ,  lowerCAmelCase_ ,  lowerCAmelCase_					)






  def     lowercase		(    self			:		Optional[int]					)							->						List[Any]:
     __lowerCAmelCase							     =     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_					)






  @slow
  def     lowercase		(    self			:		List[str]					)							->						Any:
     for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        __lowerCAmelCase							     =     ConvNextModel.from_pretrained(lowerCAmelCase_					)
        self.assertIsNotNone(lowerCAmelCase_					)





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



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

  """simple docstring"""


  @cached_property
  def     lowercase		(    self			:		Union[str, Any]					)							->						List[Any]:
     return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224'					) if is_vision_available() else None






  @slow
  def     lowercase		(    self			:		Any					)							->						int:
     __lowerCAmelCase							     =     ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'					).to(lowerCAmelCase_					)

     __lowerCAmelCase							     =     self.default_image_processor
     __lowerCAmelCase							     =     prepare_img()
     __lowerCAmelCase							     =     image_processor(images=lowerCAmelCase_ ,  return_tensors='pt'					).to(lowerCAmelCase_					)

     # forward pass
     with torch.no_grad():
        __lowerCAmelCase							     =     model(**lowerCAmelCase_					)

     # verify the logits
     __lowerCAmelCase							     =     torch.Size((1, 1_0_0_0)					)
     self.assertEqual(outputs.logits.shape ,  lowerCAmelCase_					)

     __lowerCAmelCase							     =     torch.tensor([-0.02_60, -0.47_39, 0.19_11]					).to(lowerCAmelCase_					)

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





@require_torch
class     _UpperCAmelCase   (   unittest.TestCase		,   _UpperCamelCase   ):

  """simple docstring"""


  a_      =			(ConvNextBackbone,) if is_torch_available() else ()
  a_      =			ConvNextConfig

  a_      =			False






  def     lowercase		(    self			:		Tuple					)							->						Dict:
     __lowerCAmelCase							     =     ConvNextModelTester(self					)








import unittest

import numpy as np

from diffusers import OnnxStableDiffusionInpaintPipelineLegacy
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    load_numpy,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)


if is_onnx_available():
     import onnxruntime as ort



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

  """simple docstring"""


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






  @property
  def     lowercase		(    self			:		List[Any]					)							->						int:
     __lowerCAmelCase							     =     ort.SessionOptions()
     __lowerCAmelCase							     =     False
     return options






  def     lowercase		(    self			:		Tuple					)							->						List[Any]:
     __lowerCAmelCase							     =     load_image(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
         '/in_paint/overture-creations-5sI6fQgYIuo.png'					)
     __lowerCAmelCase							     =     load_image(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
         '/in_paint/overture-creations-5sI6fQgYIuo_mask.png'					)
     __lowerCAmelCase							     =     load_numpy(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
         '/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy'					)

     # using the PNDM scheduler by default
     __lowerCAmelCase							     =     OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained(
         'CompVis/stable-diffusion-v1-4' ,  revision='onnx' ,  safety_checker=lowerCAmelCase_ ,  feature_extractor=lowerCAmelCase_ ,  provider=self.gpu_provider ,  sess_options=self.gpu_options ,  )
     pipe.set_progress_bar_config(disable=lowerCAmelCase_					)

     __lowerCAmelCase							     =     'A red cat sitting on a park bench'

     __lowerCAmelCase							     =     np.random.RandomState(0					)
     __lowerCAmelCase							     =     pipe(
         prompt=lowerCAmelCase_ ,  image=lowerCAmelCase_ ,  mask_image=lowerCAmelCase_ ,  strength=0.75 ,  guidance_scale=7.5 ,  num_inference_steps=1_5 ,  generator=lowerCAmelCase_ ,  output_type='np' ,  )

     __lowerCAmelCase							     =     output.images[0]

     assert image.shape == (5_1_2, 5_1_2, 3)
     assert np.abs(expected_image - image					).max() < 1e-2

