



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       _lowercase   :
				'''simple docstring'''







				def __init__( self     , snake_case__     , snake_case__=13     , snake_case__=32     , snake_case__=3     , snake_case__=4     , snake_case__=[10, 20, 30, 40]     , snake_case__=[2, 2, 3, 2]     , snake_case__=True     , snake_case__=True     , snake_case__=37     , snake_case__="gelu"     , snake_case__=10     , snake_case__=0.02     , snake_case__=["stage2", "stage3", "stage4"]     , snake_case__=[2, 3, 4]     , snake_case__=None     , ):

									'''simple docstring'''


									UpperCamelCase_		  =   parent
									UpperCamelCase_		  =   batch_size
									UpperCamelCase_		  =   image_size
									UpperCamelCase_		  =   num_channels
									UpperCamelCase_		  =   num_stages
									UpperCamelCase_		  =   hidden_sizes
									UpperCamelCase_		  =   depths
									UpperCamelCase_		  =   is_training
									UpperCamelCase_		  =   use_labels
									UpperCamelCase_		  =   intermediate_size
									UpperCamelCase_		  =   hidden_act
									UpperCamelCase_		  =   num_labels
									UpperCamelCase_		  =   initializer_range
									UpperCamelCase_		  =   out_features
									UpperCamelCase_		  =   out_indices
									UpperCamelCase_		  =   scope

				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									UpperCamelCase_		  =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

									UpperCamelCase_		  =   self.get_config()

									return config, pixel_values, labels

				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									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=snake_case__     , initializer_range=self.initializer_range     , out_features=self.out_features     , out_indices=self.out_indices     , num_labels=self.num_labels     , )

				def       _lowerCamelCase					( self     , snake_case__     , snake_case__     , snake_case__    ):

									'''simple docstring'''


									UpperCamelCase_		  =   ConvNextVaModel(config=snake_case__    )
									model.to(snake_case__    )
									model.eval()
									UpperCamelCase_		  =   model(snake_case__    )
									# 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     , snake_case__     , snake_case__     , snake_case__    ):

									'''simple docstring'''


									UpperCamelCase_		  =   ConvNextVaForImageClassification(snake_case__    )
									model.to(snake_case__    )
									model.eval()
									UpperCamelCase_		  =   model(snake_case__     , labels=snake_case__    )
									self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.num_labels)    )

				def       _lowerCamelCase					( self     , snake_case__     , snake_case__     , snake_case__    ):

									'''simple docstring'''


									UpperCamelCase_		  =   ConvNextVaBackbone(config=snake_case__    )
									model.to(snake_case__    )
									model.eval()
									UpperCamelCase_		  =   model(snake_case__    )

									# 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
									UpperCamelCase_		  =   None
									UpperCamelCase_		  =   ConvNextVaBackbone(config=snake_case__    )
									model.to(snake_case__    )
									model.eval()
									UpperCamelCase_		  =   model(snake_case__    )

									# 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    ):

									'''simple docstring'''


									UpperCamelCase_		  =   self.prepare_config_and_inputs()
									UpperCamelCase_  ,    UpperCamelCase_  ,    UpperCamelCase_		  =   config_and_inputs
									UpperCamelCase_		  =   {"pixel_values": pixel_values}
									return config, inputs_dict

				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									UpperCamelCase_		  =   self.prepare_config_and_inputs()
									UpperCamelCase_  ,    UpperCamelCase_  ,    UpperCamelCase_		  =   config_and_inputs
									UpperCamelCase_		  =   {"pixel_values": pixel_values, "labels": labels}
									return config, inputs_dict




@require_torch
class       _lowercase   (a_      ,   a_      ,   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    ):

									'''simple docstring'''


									UpperCamelCase_		  =   ConvNextVaModelTester(self    )
									UpperCamelCase_		  =   ConfigTester(self     , config_class=snake_case__     , has_text_modality=snake_case__     , hidden_size=37    )

				def       _lowerCamelCase					( self    ):

									'''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    ):

									'''simple docstring'''


									return

				@unittest.skip(reason="ConvNextV2 does not use inputs_embeds"    )
				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									pass

				@unittest.skip(reason="ConvNextV2 does not support input and output embeddings"    )
				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									pass

				@unittest.skip(reason="ConvNextV2 does not use feedforward chunking"    )
				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									pass

				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									if not self.model_tester.is_training:
														return

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

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

														UpperCamelCase_		  =   model_class(snake_case__    )
														model.to(snake_case__    )
														model.train()
														UpperCamelCase_		  =   self._prepare_for_class(snake_case__     , snake_case__     , return_labels=snake_case__    )
														UpperCamelCase_		  =   model(**snake_case__    ).loss
														loss.backward()

				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									if not self.model_tester.is_training:
														return

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

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

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

				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									UpperCamelCase_  ,    UpperCamelCase_		  =   self.model_tester.prepare_config_and_inputs_for_common()

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

														UpperCamelCase_		  =   ["pixel_values"]
														self.assertListEqual(arg_names[:1]     , snake_case__    )

				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									UpperCamelCase_		  =   self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*snake_case__    )

				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									def check_hidden_states_output(snake_case__     , snake_case__     , snake_case__    ):
														UpperCamelCase_		  =   model_class(snake_case__    )
														model.to(snake_case__    )
														model.eval()

														with torch.no_grad():
																			UpperCamelCase_		  =   model(**self._prepare_for_class(snake_case__     , snake_case__    )    )

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

														UpperCamelCase_		  =   self.model_tester.num_stages
														self.assertEqual(len(snake_case__    )     , 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]     , )

									UpperCamelCase_  ,    UpperCamelCase_		  =   self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
														UpperCamelCase_		  =   True
														check_hidden_states_output(snake_case__     , snake_case__     , snake_case__    )

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

														check_hidden_states_output(snake_case__     , snake_case__     , snake_case__    )

				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									UpperCamelCase_		  =   self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*snake_case__    )

				@slow
				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														UpperCamelCase_		  =   ConvNextVaModel.from_pretrained(snake_case__    )
														self.assertIsNotNone(snake_case__    )




def    _lowerCAmelCase    ():
					UpperCamelCase_		  =   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
					return image






@require_torch
@require_vision
class       _lowercase   (unittest.TestCase      ):
				'''simple docstring'''







				@cached_property
				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									return AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224"    ) if is_vision_available() else None

				@slow
				def       _lowerCamelCase					( self    ):

									'''simple docstring'''


									UpperCamelCase_		  =   ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224"    ).to(snake_case__    )

									UpperCamelCase_		  =   self.default_image_processor
									UpperCamelCase_		  =   prepare_img()
									UpperCamelCase_		  =   preprocessor(images=snake_case__     , return_tensors="pt"    ).to(snake_case__    )

									# forward pass
									with torch.no_grad():
														UpperCamelCase_		  =   model(**snake_case__    )

									# verify the logits
									UpperCamelCase_		  =   torch.Size((1, 1000)    )
									self.assertEqual(outputs.logits.shape     , snake_case__    )

									UpperCamelCase_		  =   torch.tensor([0.9_996, 0.1_966, -0.4_386]    ).to(snake_case__    )
									self.assertTrue(torch.allclose(outputs.logits[0, :3]     , snake_case__     , atol=1e-4    )    )





from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


UpperCAmelCase   :							Dict							 =logging.get_logger(__name__)


class       _lowercase   (a_      ):
				'''simple docstring'''







				lowercase__   						=						["""pixel_values"""]

				def __init__( self     , snake_case__ = True     , snake_case__ = None     , snake_case__ = PILImageResampling.BILINEAR     , snake_case__ = True     , snake_case__ = None     , snake_case__ = True     , snake_case__ = 1 / 255     , snake_case__ = True     , snake_case__ = None     , snake_case__ = None     , **snake_case__     , ):

									'''simple docstring'''


									super().__init__(**snake_case__    )
									UpperCamelCase_		  =   size if size is not None else {"shortest_edge": 256}
									UpperCamelCase_		  =   get_size_dict(snake_case__     , default_to_square=snake_case__    )
									UpperCamelCase_		  =   crop_size if crop_size is not None else {"height": 224, "width": 224}
									UpperCamelCase_		  =   get_size_dict(snake_case__    )
									UpperCamelCase_		  =   do_resize
									UpperCamelCase_		  =   size
									UpperCamelCase_		  =   resample
									UpperCamelCase_		  =   do_center_crop
									UpperCamelCase_		  =   crop_size
									UpperCamelCase_		  =   do_rescale
									UpperCamelCase_		  =   rescale_factor
									UpperCamelCase_		  =   do_normalize
									UpperCamelCase_		  =   image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
									UpperCamelCase_		  =   image_std if image_std is not None else IMAGENET_STANDARD_STD

				def       _lowerCamelCase					( self     , snake_case__     , snake_case__     , snake_case__ = PILImageResampling.BICUBIC     , snake_case__ = None     , **snake_case__     , ):

									'''simple docstring'''


									UpperCamelCase_		  =   get_size_dict(snake_case__     , default_to_square=snake_case__    )
									if "shortest_edge" not in size:
														raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"""    )
									UpperCamelCase_		  =   get_resize_output_image_size(snake_case__     , size=size["shortest_edge"]     , default_to_square=snake_case__    )
									return resize(snake_case__     , size=snake_case__     , resample=snake_case__     , data_format=snake_case__     , **snake_case__    )

				def       _lowerCamelCase					( self     , snake_case__     , snake_case__     , snake_case__ = None     , **snake_case__     , ):

									'''simple docstring'''


									UpperCamelCase_		  =   get_size_dict(snake_case__    )
									return center_crop(snake_case__     , size=(size["height"], size["width"])     , data_format=snake_case__     , **snake_case__    )

				def       _lowerCamelCase					( self     , snake_case__     , snake_case__     , snake_case__ = None     , **snake_case__    ):

									'''simple docstring'''


									return rescale(snake_case__     , scale=snake_case__     , data_format=snake_case__     , **snake_case__    )

				def       _lowerCamelCase					( self     , snake_case__     , snake_case__     , snake_case__     , snake_case__ = None     , **snake_case__     , ):

									'''simple docstring'''


									return normalize(snake_case__     , mean=snake_case__     , std=snake_case__     , data_format=snake_case__     , **snake_case__    )

				def       _lowerCamelCase					( self     , snake_case__     , snake_case__ = None     , snake_case__ = None     , snake_case__ = None     , snake_case__ = None     , snake_case__ = None     , snake_case__ = None     , snake_case__ = None     , snake_case__ = None     , snake_case__ = None     , snake_case__ = None     , snake_case__ = None     , snake_case__ = ChannelDimension.FIRST     , **snake_case__     , ):

									'''simple docstring'''


									UpperCamelCase_		  =   do_resize if do_resize is not None else self.do_resize
									UpperCamelCase_		  =   size if size is not None else self.size
									UpperCamelCase_		  =   get_size_dict(snake_case__     , default_to_square=snake_case__    )
									UpperCamelCase_		  =   resample if resample is not None else self.resample
									UpperCamelCase_		  =   do_center_crop if do_center_crop is not None else self.do_center_crop
									UpperCamelCase_		  =   crop_size if crop_size is not None else self.crop_size
									UpperCamelCase_		  =   get_size_dict(snake_case__    )
									UpperCamelCase_		  =   do_rescale if do_rescale is not None else self.do_rescale
									UpperCamelCase_		  =   rescale_factor if rescale_factor is not None else self.rescale_factor
									UpperCamelCase_		  =   do_normalize if do_normalize is not None else self.do_normalize
									UpperCamelCase_		  =   image_mean if image_mean is not None else self.image_mean
									UpperCamelCase_		  =   image_std if image_std is not None else self.image_std

									UpperCamelCase_		  =   make_list_of_images(snake_case__    )

									if not valid_images(snake_case__    ):
														raise ValueError(
														    "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
														    "torch.Tensor, tf.Tensor or jax.ndarray."    )

									if do_resize and size is None:
														raise ValueError("Size must be specified if do_resize is True."    )

									if do_center_crop and crop_size is None:
														raise ValueError("Crop size must be specified if do_center_crop is True."    )

									if do_rescale and rescale_factor is None:
														raise ValueError("Rescale factor must be specified if do_rescale is True."    )

									if do_normalize and (image_mean is None or image_std is None):
														raise ValueError("Image mean and std must be specified if do_normalize is True."    )

									# All transformations expect numpy arrays.
									UpperCamelCase_		  =   [to_numpy_array(snake_case__    ) for image in images]

									if do_resize:
														UpperCamelCase_		  =   [self.resize(image=snake_case__     , size=snake_case__     , resample=snake_case__    ) for image in images]

									if do_center_crop:
														UpperCamelCase_		  =   [self.center_crop(image=snake_case__     , size=snake_case__    ) for image in images]

									if do_rescale:
														UpperCamelCase_		  =   [self.rescale(image=snake_case__     , scale=snake_case__    ) for image in images]

									if do_normalize:
														UpperCamelCase_		  =   [self.normalize(image=snake_case__     , mean=snake_case__     , std=snake_case__    ) for image in images]

									UpperCamelCase_		  =   [to_channel_dimension_format(snake_case__     , snake_case__    ) for image in images]

									UpperCamelCase_		  =   {"pixel_values": images}
									return BatchFeature(data=snake_case__     , tensor_type=snake_case__    )
