





'''simple docstring'''

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 lowerCamelCase						:







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






        """simple docstring"""





        _snake_case		:	Optional[int]					     =     parent
        _snake_case		:	Union[str, Any]					     =     batch_size
        _snake_case		:	Union[str, Any]					     =     image_size
        _snake_case		:	Optional[Any]					     =     num_channels
        _snake_case		:	Optional[Any]					     =     num_stages
        _snake_case		:	int					     =     hidden_sizes
        _snake_case		:	Tuple					     =     depths
        _snake_case		:	List[str]					     =     is_training
        _snake_case		:	Tuple					     =     use_labels
        _snake_case		:	Tuple					     =     intermediate_size
        _snake_case		:	List[Any]					     =     hidden_act
        _snake_case		:	str					     =     num_labels
        _snake_case		:	List[str]					     =     initializer_range
        _snake_case		:	List[str]					     =     out_features
        _snake_case		:	Optional[int]					     =     out_indices
        _snake_case		:	List[Any]					     =     scope







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






        """simple docstring"""





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

        _snake_case		:	Dict					     =     None
        if self.use_labels:
              _snake_case		:	List[str]					     =     ids_tensor([self.batch_size]     ,     self.num_labels		)

        _snake_case		:	List[str]					     =     self.get_config()
        return config, pixel_values, labels







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






        """simple docstring"""





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







  def 				UpperCAmelCase_				(		self     ,     lowercase__     ,     lowercase__     ,     lowercase__		)		->						List[Any]:






        """simple docstring"""





        _snake_case		:	Dict					     =     ConvNextModel(config=_UpperCamelCase		)
        model.to(_UpperCamelCase		)
        model.eval()
        _snake_case		:	str					     =     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 				UpperCAmelCase_				(		self     ,     lowercase__     ,     lowercase__     ,     lowercase__		)		->						int:






        """simple docstring"""





        _snake_case		:	Optional[Any]					     =     ConvNextForImageClassification(_UpperCamelCase		)
        model.to(_UpperCamelCase		)
        model.eval()
        _snake_case		:	str					     =     model(_UpperCamelCase     ,     labels=_UpperCamelCase		)
        self.parent.assertEqual(result.logits.shape     ,     (self.batch_size, self.num_labels)		)







  def 				UpperCAmelCase_				(		self     ,     lowercase__     ,     lowercase__     ,     lowercase__		)		->						Tuple:






        """simple docstring"""





        _snake_case		:	Optional[int]					     =     ConvNextBackbone(config=_UpperCamelCase		)
        model.to(_UpperCamelCase		)
        model.eval()
        _snake_case		:	Optional[Any]					     =     model(_UpperCamelCase		)

        # 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
        _snake_case		:	Optional[Any]					     =     None
        _snake_case		:	List[Any]					     =     ConvNextBackbone(config=_UpperCamelCase		)
        model.to(_UpperCamelCase		)
        model.eval()
        _snake_case		:	str					     =     model(_UpperCamelCase		)

        # 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 				UpperCAmelCase_				(		self		)		->						List[str]:






        """simple docstring"""





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





@require_torch
class lowerCamelCase						(__lowerCAmelCase						,      __lowerCAmelCase						,      unittest.TestCase					):
  _lowercase  :	Tuple       					=				(
      (
          ConvNextModel,
          ConvNextForImageClassification,
          ConvNextBackbone,
      )
      if is_torch_available()
      else ()
  )
  _lowercase  :	Optional[int]       					=				(
      {"""feature-extraction""": ConvNextModel, """image-classification""": ConvNextForImageClassification}
      if is_torch_available()
      else {}
  )

  _lowercase  :	str       					=				True
  _lowercase  :	Any       					=				False
  _lowercase  :	List[str]       					=				False
  _lowercase  :	Union[str, Any]       					=				False
  _lowercase  :	List[Any]       					=				False







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






        """simple docstring"""





        _snake_case		:	List[Any]					     =     ConvNextModelTester(self		)
        _snake_case		:	List[str]					     =     ConfigTester(self     ,     config_class=_UpperCamelCase     ,     has_text_modality=_UpperCamelCase     ,     hidden_size=37		)







  def 				UpperCAmelCase_				(		self		)		->						str:






        """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 				UpperCAmelCase_				(		self		)		->						List[Any]:






        """simple docstring"""





        return







  @unittest.skip(reason='''ConvNext does not use inputs_embeds'''		)
  def 				UpperCAmelCase_				(		self		)		->						List[Any]:






        """simple docstring"""





        pass







  @unittest.skip(reason='''ConvNext does not support input and output embeddings'''		)
  def 				UpperCAmelCase_				(		self		)		->						int:






        """simple docstring"""





        pass







  @unittest.skip(reason='''ConvNext does not use feedforward chunking'''		)
  def 				UpperCAmelCase_				(		self		)		->						Tuple:






        """simple docstring"""





        pass







  def 				UpperCAmelCase_				(		self		)		->						Tuple:






        """simple docstring"""





        _snake_case		:	Optional[Any]					     =     self.model_tester.prepare_config_and_inputs_for_common()

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

              _snake_case		:	Any					     =     ["""pixel_values"""]
              self.assertListEqual(arg_names[:1]     ,     _UpperCamelCase		)







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






        """simple docstring"""





        _snake_case		:	Dict					     =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*_UpperCamelCase		)







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






        """simple docstring"""





        _snake_case		:	str					     =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_backbone(*_UpperCamelCase		)







  def 				UpperCAmelCase_				(		self		)		->						Tuple:






        """simple docstring"""





        def check_hidden_states_output(lowercase__     ,     lowercase__     ,     lowercase__		):
              _snake_case		:	Union[str, Any]					     =     model_class(_UpperCamelCase		)
              model.to(_UpperCamelCase		)
              model.eval()

              with torch.no_grad():
                    _snake_case		:	Dict					     =     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[Any]					     =     self.model_tester.num_stages
              self.assertEqual(len(_UpperCamelCase		)     ,     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]     ,     )

        _snake_case		:	Optional[int]					     =     self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              _snake_case		:	Union[str, 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		:	Any					     =     True

              check_hidden_states_output(_UpperCamelCase     ,     _UpperCamelCase     ,     _UpperCamelCase		)







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






        """simple docstring"""





        _snake_case		:	Any					     =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*_UpperCamelCase		)







  @slow
  def 				UpperCAmelCase_				(		self		)		->						List[str]:






        """simple docstring"""





        for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _snake_case		:	int					     =     ConvNextModel.from_pretrained(_UpperCamelCase		)
              self.assertIsNotNone(_UpperCamelCase		)




def    _a				(							):





      """simple docstring"""



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





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







  @cached_property
  def 				UpperCAmelCase_				(		self		)		->						Any:






        """simple docstring"""





        return AutoImageProcessor.from_pretrained('''facebook/convnext-tiny-224'''		) if is_vision_available() else None







  @slow
  def 				UpperCAmelCase_				(		self		)		->						Dict:






        """simple docstring"""





        _snake_case		:	List[str]					     =     ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''		).to(_UpperCamelCase		)

        _snake_case		:	Optional[Any]					     =     self.default_image_processor
        _snake_case		:	str					     =     prepare_img()
        _snake_case		:	Optional[Any]					     =     image_processor(images=_UpperCamelCase     ,     return_tensors='''pt'''		).to(_UpperCamelCase		)

        # forward pass
        with torch.no_grad():
              _snake_case		:	List[Any]					     =     model(**_UpperCamelCase		)

        # verify the logits
        _snake_case		:	str					     =     torch.Size((1, 1_000)		)
        self.assertEqual(outputs.logits.shape     ,     _UpperCamelCase		)

        _snake_case		:	Any					     =     torch.tensor([-0.0_260, -0.4_739, 0.1_911]		).to(_UpperCamelCase		)

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





@require_torch
class lowerCamelCase						(unittest.TestCase						,      __lowerCAmelCase					):
  _lowercase  :	str       					=				(ConvNextBackbone,) if is_torch_available() else ()
  _lowercase  :	Union[str, Any]       					=				ConvNextConfig

  _lowercase  :	Optional[int]       					=				False







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






        """simple docstring"""





        _snake_case		:	Tuple					     =     ConvNextModelTester(self		)









'''simple docstring'''

from typing import List, Optional, Union

import numpy as np
import PIL.Image

from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import rescale, resize, to_channel_dimension_format
from ...image_utils import (
    ChannelDimension,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


UpperCAmelCase					:		Dict		=							logging.get_logger(__name__)





class lowerCamelCase						(a__					):
  _lowercase  :	int       					=				["""pixel_values"""]







  def __init__(		self     ,     lowercase__ = True     ,     lowercase__ = 32     ,     lowercase__=PILImageResampling.BILINEAR     ,     lowercase__ = True     ,     **lowercase__     ,     )		->						None:






        """simple docstring"""





        _snake_case		:	Any					     =     do_resize
        _snake_case		:	List[str]					     =     do_rescale
        _snake_case		:	Any					     =     size_divisor
        _snake_case		:	Optional[Any]					     =     resample
        super().__init__(**lowercase__		)







  def 				UpperCAmelCase_				(		self     ,     lowercase__     ,     lowercase__     ,     lowercase__     ,     lowercase__ = None     ,     **lowercase__		)		->						np.ndarray:






        """simple docstring"""





        _snake_case     ,							_snake_case		:	Dict					     =     get_image_size(lowercase__		)
        # Rounds the height and width down to the closest multiple of size_divisor
        _snake_case		:	Optional[int]					     =     height // size_divisor * size_divisor
        _snake_case		:	Dict					     =     width // size_divisor * size_divisor
        _snake_case		:	str					     =     resize(lowercase__     ,     (new_h, new_w)     ,     resample=lowercase__     ,     data_format=lowercase__     ,     **lowercase__		)
        return image







  def 				UpperCAmelCase_				(		self     ,     lowercase__     ,     lowercase__     ,     lowercase__ = None     ,     **lowercase__		)		->						np.ndarray:






        """simple docstring"""





        return rescale(image=lowercase__     ,     scale=lowercase__     ,     data_format=lowercase__     ,     **lowercase__		)







  def 				UpperCAmelCase_				(		self     ,     lowercase__     ,     lowercase__ = None     ,     lowercase__ = None     ,     lowercase__=None     ,     lowercase__ = None     ,     lowercase__ = None     ,     lowercase__ = ChannelDimension.FIRST     ,     **lowercase__     ,     )		->						BatchFeature:






        """simple docstring"""





        _snake_case		:	Any					     =     do_resize if do_resize is not None else self.do_resize
        _snake_case		:	List[Any]					     =     do_rescale if do_rescale is not None else self.do_rescale
        _snake_case		:	List[str]					     =     size_divisor if size_divisor is not None else self.size_divisor
        _snake_case		:	int					     =     resample if resample is not None else self.resample

        if do_resize and size_divisor is None:
              raise ValueError('''size_divisor is required for resizing'''		)

        _snake_case		:	Tuple					     =     make_list_of_images(lowercase__		)

        if not valid_images(lowercase__		):
              raise ValueError('''Invalid image(s)'''		)

        # All transformations expect numpy arrays.
        _snake_case		:	Tuple					     =     [to_numpy_array(lowercase__		) for img in images]

        if do_resize:
              _snake_case		:	Optional[int]					     =     [self.resize(lowercase__     ,     size_divisor=lowercase__     ,     resample=lowercase__		) for image in images]

        if do_rescale:
              _snake_case		:	Union[str, Any]					     =     [self.rescale(lowercase__     ,     scale=1 / 255		) for image in images]

        _snake_case		:	Union[str, Any]					     =     [to_channel_dimension_format(lowercase__     ,     lowercase__		) for image in images]

        _snake_case		:	List[str]					     =     {'''pixel_values''': images}
        return BatchFeature(data=lowercase__     ,     tensor_type=lowercase__		)


