




import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
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 ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
   from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import AutoImageProcessor





class        lowerCamelCase_							:


 '''simple docstring'''







 def __init__(							self  :		Union[str, Any]				,				_lowerCAmelCase  :		Dict				,				_lowerCAmelCase  :		Optional[int]=13				,				_lowerCAmelCase  :		Tuple=32				,				_lowerCAmelCase  :		Optional[Any]=3				,				_lowerCAmelCase  :		str=4				,				_lowerCAmelCase  :		List[Any]=[10, 20, 30, 40]				,				_lowerCAmelCase  :		Any=[2, 2, 3, 2]				,				_lowerCAmelCase  :		Dict=True				,				_lowerCAmelCase  :		Any=True				,				_lowerCAmelCase  :		Union[str, Any]=37				,				_lowerCAmelCase  :		Optional[int]="gelu"				,				_lowerCAmelCase  :		Optional[Any]=10				,				_lowerCAmelCase  :		List[Any]=0.02				,				_lowerCAmelCase  :		Any=["stage2", "stage3", "stage4"]				,				_lowerCAmelCase  :		Dict=[2, 3, 4]				,				_lowerCAmelCase  :		Tuple=None				,				):
       SCREAMING_SNAKE_CASE_							=			parent
       SCREAMING_SNAKE_CASE_							=			batch_size
       SCREAMING_SNAKE_CASE_							=			image_size
       SCREAMING_SNAKE_CASE_							=			num_channels
       SCREAMING_SNAKE_CASE_							=			num_stages
       SCREAMING_SNAKE_CASE_							=			hidden_sizes
       SCREAMING_SNAKE_CASE_							=			depths
       SCREAMING_SNAKE_CASE_							=			is_training
       SCREAMING_SNAKE_CASE_							=			use_labels
       SCREAMING_SNAKE_CASE_							=			intermediate_size
       SCREAMING_SNAKE_CASE_							=			hidden_act
       SCREAMING_SNAKE_CASE_							=			num_labels
       SCREAMING_SNAKE_CASE_							=			initializer_range
       SCREAMING_SNAKE_CASE_							=			out_features
       SCREAMING_SNAKE_CASE_							=			out_indices
       SCREAMING_SNAKE_CASE_							=			scope



 def       lowerCAmelCase_  (							self  :		Optional[int]						):
       SCREAMING_SNAKE_CASE_							=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

       SCREAMING_SNAKE_CASE_							=			self.get_config()

       return config, pixel_values, labels



 def       lowerCAmelCase_  (							self  :		str						):
       return ConvNextVaConfig(
           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       lowerCAmelCase_  (							self  :		List[Any]				,				_lowerCAmelCase  :		Optional[Any]				,				_lowerCAmelCase  :		Optional[Any]				,				_lowerCAmelCase  :		Optional[int]						):
       SCREAMING_SNAKE_CASE_							=			ConvNextVaModel(config=_lowerCAmelCase						)
       model.to(_lowerCAmelCase						)
       model.eval()
       SCREAMING_SNAKE_CASE_							=			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 // 32, self.image_size // 32)				,				)



 def       lowerCAmelCase_  (							self  :		int				,				_lowerCAmelCase  :		Tuple				,				_lowerCAmelCase  :		Tuple				,				_lowerCAmelCase  :		List[str]						):
       SCREAMING_SNAKE_CASE_							=			ConvNextVaForImageClassification(_lowerCAmelCase						)
       model.to(_lowerCAmelCase						)
       model.eval()
       SCREAMING_SNAKE_CASE_							=			model(_lowerCAmelCase				,				labels=_lowerCAmelCase						)
       self.parent.assertEqual(result.logits.shape				,				(self.batch_size, self.num_labels)						)



 def       lowerCAmelCase_  (							self  :		Optional[int]				,				_lowerCAmelCase  :		Tuple				,				_lowerCAmelCase  :		int				,				_lowerCAmelCase  :		List[Any]						):
       SCREAMING_SNAKE_CASE_							=			ConvNextVaBackbone(config=_lowerCAmelCase						)
       model.to(_lowerCAmelCase						)
       model.eval()
       SCREAMING_SNAKE_CASE_							=			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
       SCREAMING_SNAKE_CASE_							=			None
       SCREAMING_SNAKE_CASE_							=			ConvNextVaBackbone(config=_lowerCAmelCase						)
       model.to(_lowerCAmelCase						)
       model.eval()
       SCREAMING_SNAKE_CASE_							=			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       lowerCAmelCase_  (							self  :		Optional[int]						):
       SCREAMING_SNAKE_CASE_							=			self.prepare_config_and_inputs()
       SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_							=			config_and_inputs
       SCREAMING_SNAKE_CASE_							=			{'pixel_values': pixel_values}
       return config, inputs_dict




 def       lowerCAmelCase_  (							self  :		Dict						):
       SCREAMING_SNAKE_CASE_							=			self.prepare_config_and_inputs()
       SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_							=			config_and_inputs
       SCREAMING_SNAKE_CASE_							=			{'pixel_values': pixel_values, 'labels': labels}
       return config, inputs_dict





@require_torch
class        lowerCamelCase_							(      _SCREAMING_SNAKE_CASE       ,   _SCREAMING_SNAKE_CASE       ,   unittest.TestCase					):


 '''simple docstring'''







 lowercase_				    =    (
     (
         ConvNextVaModel,
         ConvNextVaForImageClassification,
         ConvNextVaBackbone,
     )
     if is_torch_available()
     else ()
 )
 lowercase_				    =    (
     {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification}
     if is_torch_available()
     else {}
 )

 lowercase_				    =    False
 lowercase_				    =    False
 lowercase_				    =    False
 lowercase_				    =    False
 lowercase_				    =    False



 def       lowerCAmelCase_  (							self  :		Optional[int]						):
       SCREAMING_SNAKE_CASE_							=			ConvNextVaModelTester(self						)
       SCREAMING_SNAKE_CASE_							=			ConfigTester(self				,				config_class=_lowerCAmelCase				,				has_text_modality=_lowerCAmelCase				,				hidden_size=37						)



 def       lowerCAmelCase_  (							self  :		Any						):
       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  :		Dict						):
       return



 @unittest.skip(reason='ConvNextV2 does not use inputs_embeds'						)
 def       lowerCAmelCase_  (							self  :		List[str]						):
       pass



 @unittest.skip(reason='ConvNextV2 does not support input and output embeddings'						)
 def       lowerCAmelCase_  (							self  :		List[str]						):
       pass



 @unittest.skip(reason='ConvNextV2 does not use feedforward chunking'						)
 def       lowerCAmelCase_  (							self  :		List[str]						):
       pass



 def       lowerCAmelCase_  (							self  :		Optional[int]						):
       if not self.model_tester.is_training:
             return

       for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_							=			self.model_tester.prepare_config_and_inputs_with_labels()
             SCREAMING_SNAKE_CASE_							=			True

             if model_class.__name__ in [
                 *get_values(_lowerCAmelCase						),
                 *get_values(_lowerCAmelCase						),
             ]:
                   continue

             SCREAMING_SNAKE_CASE_							=			model_class(_lowerCAmelCase						)
             model.to(_lowerCAmelCase						)
             model.train()
             SCREAMING_SNAKE_CASE_							=			self._prepare_for_class(_lowerCAmelCase				,				_lowerCAmelCase				,				return_labels=_lowerCAmelCase						)
             SCREAMING_SNAKE_CASE_							=			model(**_lowerCAmelCase						).loss
             loss.backward()



 def       lowerCAmelCase_  (							self  :		Dict						):
       if not self.model_tester.is_training:
             return

       for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_							=			self.model_tester.prepare_config_and_inputs_with_labels()
             SCREAMING_SNAKE_CASE_							=			False
             SCREAMING_SNAKE_CASE_							=			True

             if (
                 model_class.__name__
                 in [*get_values(_lowerCAmelCase						), *get_values(_lowerCAmelCase						)]
                 or not model_class.supports_gradient_checkpointing
             ):
                   continue

             SCREAMING_SNAKE_CASE_							=			model_class(_lowerCAmelCase						)
             model.to(_lowerCAmelCase						)
             model.gradient_checkpointing_enable()
             model.train()
             SCREAMING_SNAKE_CASE_							=			self._prepare_for_class(_lowerCAmelCase				,				_lowerCAmelCase				,				return_labels=_lowerCAmelCase						)
             SCREAMING_SNAKE_CASE_							=			model(**_lowerCAmelCase						).loss
             loss.backward()



 def       lowerCAmelCase_  (							self  :		Dict						):
       SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_							=			self.model_tester.prepare_config_and_inputs_for_common()

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

             SCREAMING_SNAKE_CASE_							=			['pixel_values']
             self.assertListEqual(arg_names[:1]				,				_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		List[str]						):
       SCREAMING_SNAKE_CASE_							=			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		Dict						):
       def check_hidden_states_output(_lowerCAmelCase  :		int				,				_lowerCAmelCase  :		Union[str, Any]				,				_lowerCAmelCase  :		List[Any]						):
             SCREAMING_SNAKE_CASE_							=			model_class(_lowerCAmelCase						)
             model.to(_lowerCAmelCase						)
             model.eval()

             with torch.no_grad():
                   SCREAMING_SNAKE_CASE_							=			model(**self._prepare_for_class(_lowerCAmelCase				,				_lowerCAmelCase						)						)

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

             SCREAMING_SNAKE_CASE_							=			self.model_tester.num_stages
             self.assertEqual(len(_lowerCAmelCase						)				,				expected_num_stages + 1						)

             # ConvNextV2'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]				,				)

       SCREAMING_SNAKE_CASE_						, SCREAMING_SNAKE_CASE_							=			self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE_							=			True
             check_hidden_states_output(_lowerCAmelCase				,				_lowerCAmelCase				,				_lowerCAmelCase						)

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

             check_hidden_states_output(_lowerCAmelCase				,				_lowerCAmelCase				,				_lowerCAmelCase						)



 def       lowerCAmelCase_  (							self  :		Tuple						):
       SCREAMING_SNAKE_CASE_							=			self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase						)




 @slow
 def       lowerCAmelCase_  (							self  :		List[Any]						):
       for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             SCREAMING_SNAKE_CASE_							=			ConvNextVaModel.from_pretrained(_lowerCAmelCase						)
             self.assertIsNotNone(_lowerCAmelCase						)


def 					UpperCAmelCase_							(      )					-> Tuple:
      SCREAMING_SNAKE_CASE_							=			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
      return image





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


 '''simple docstring'''







 @cached_property
 def       lowerCAmelCase_  (							self  :		Optional[Any]						):
       return AutoImageProcessor.from_pretrained('facebook/convnextv2-tiny-1k-224'						) if is_vision_available() else None




 @slow
 def       lowerCAmelCase_  (							self  :		Dict						):
       SCREAMING_SNAKE_CASE_							=			ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224'						).to(_lowerCAmelCase						)

       SCREAMING_SNAKE_CASE_							=			self.default_image_processor
       SCREAMING_SNAKE_CASE_							=			prepare_img()
       SCREAMING_SNAKE_CASE_							=			preprocessor(images=_lowerCAmelCase				,				return_tensors='pt'						).to(_lowerCAmelCase						)

       # forward pass
       with torch.no_grad():
             SCREAMING_SNAKE_CASE_							=			model(**_lowerCAmelCase						)

       # verify the logits
       SCREAMING_SNAKE_CASE_							=			torch.Size((1, 1_000)						)
       self.assertEqual(outputs.logits.shape				,				_lowerCAmelCase						)

       SCREAMING_SNAKE_CASE_							=			torch.tensor([0.9996, 0.1966, -0.4386]						).to(_lowerCAmelCase						)
       self.assertTrue(torch.allclose(outputs.logits[0, :3]				,				_lowerCAmelCase				,				atol=1E-4						)						)





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        lowerCamelCase_							(      unittest.TestCase					):


 '''simple docstring'''







 @property
 def       lowerCAmelCase_  (							self  :		Optional[Any]						):
       return (
           "CUDAExecutionProvider",
           {
               "gpu_mem_limit": "15000000000",  # 15GB
               "arena_extend_strategy": "kSameAsRequested",
           },
       )



 @property
 def       lowerCAmelCase_  (							self  :		str						):
       SCREAMING_SNAKE_CASE_							=			ort.SessionOptions()
       SCREAMING_SNAKE_CASE_							=			False
       return options




 def       lowerCAmelCase_  (							self  :		Tuple						):
       SCREAMING_SNAKE_CASE_							=			load_image(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
           '/in_paint/overture-creations-5sI6fQgYIuo.png'						)
       SCREAMING_SNAKE_CASE_							=			load_image(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
           '/in_paint/overture-creations-5sI6fQgYIuo_mask.png'						)
       SCREAMING_SNAKE_CASE_							=			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
       SCREAMING_SNAKE_CASE_							=			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						)

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

       SCREAMING_SNAKE_CASE_							=			np.random.RandomState(0						)
       SCREAMING_SNAKE_CASE_							=			pipe(
           prompt=_lowerCAmelCase				,				image=_lowerCAmelCase				,				mask_image=_lowerCAmelCase				,				strength=0.75				,				guidance_scale=7.5				,				num_inference_steps=15				,				generator=_lowerCAmelCase				,				output_type='np'				,				)

       SCREAMING_SNAKE_CASE_							=			output.images[0]

       assert image.shape == (512, 512, 3)
       assert np.abs(expected_image - image						).max() < 1E-2