



"""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  _UpperCAmelCase :

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

 def 		_snake_case      (  self	: str       ):
     snake_case_				:  List[Any]       =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

     snake_case_				:  List[Any]       =			None
     if self.use_labels:
         snake_case_				:  Optional[int]       =			ids_tensor([self.batch_size]						,  self.num_labels       )

     snake_case_				:  Tuple       =			self.get_config()
     return config, pixel_values, labels

 def 		_snake_case      (  self	: Union[str, 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=lowercase_						,  initializer_range=self.initializer_range						,  out_features=self.out_features						,  out_indices=self.out_indices						,  num_labels=self.num_labels						,  )

 def 		_snake_case      (  self	: Optional[int]						,  lowercase_	: Optional[Any]						,  lowercase_	: int						,  lowercase_	: Dict       ):
     snake_case_				:  Optional[Any]       =			ConvNextModel(config=lowercase_       )
     model.to(lowercase_       )
     model.eval()
     snake_case_				:  Optional[int]       =			model(lowercase_       )
     # 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 		_snake_case      (  self	: Union[str, Any]						,  lowercase_	: int						,  lowercase_	: Union[str, Any]						,  lowercase_	: Union[str, Any]       ):
     snake_case_				:  Any       =			ConvNextForImageClassification(lowercase_       )
     model.to(lowercase_       )
     model.eval()
     snake_case_				:  Optional[int]       =			model(lowercase_						,  labels=lowercase_       )
     self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.num_labels)       )

 def 		_snake_case      (  self	: str						,  lowercase_	: int						,  lowercase_	: List[str]						,  lowercase_	: Optional[int]       ):
     snake_case_				:  List[str]       =			ConvNextBackbone(config=lowercase_       )
     model.to(lowercase_       )
     model.eval()
     snake_case_				:  int       =			model(lowercase_       )

     # 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=lowercase_       )
     model.to(lowercase_       )
     model.eval()
     snake_case_				:  str       =			model(lowercase_       )

     # 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 		_snake_case      (  self	: Tuple       ):
     snake_case_				:  List[str]       =			self.prepare_config_and_inputs()
     snake_case_,			snake_case_,			snake_case_				:  List[Any]       =			config_and_inputs
     snake_case_				:  List[Any]       =			{'''pixel_values''': pixel_values}
     return config, inputs_dict





@require_torch
class  _UpperCAmelCase (    lowerCAmelCase__					,  lowerCAmelCase__					,  unittest.TestCase):
 _lowerCAmelCase     :    List[str]	      =	(
     (
         ConvNextModel,
         ConvNextForImageClassification,
         ConvNextBackbone,
     )
     if is_torch_available()
     else ()
 )
 _lowerCAmelCase     :    Dict	      =	(
     {"""feature-extraction""": ConvNextModel, """image-classification""": ConvNextForImageClassification}
     if is_torch_available()
     else {}
 )

 _lowerCAmelCase     :    Any	      =	True
 _lowerCAmelCase     :    Union[str, Any]	      =	False
 _lowerCAmelCase     :    Union[str, Any]	      =	False
 _lowerCAmelCase     :    Optional[Any]	      =	False
 _lowerCAmelCase     :    List[str]	      =	False

 def 		_snake_case      (  self	: Optional[int]       ):
     snake_case_				:  Union[str, Any]       =			ConvNextModelTester(self       )
     snake_case_				:  Optional[int]       =			ConfigTester(self						,  config_class=lowercase_						,  has_text_modality=lowercase_						,  hidden_size=37       )

 def 		_snake_case      (  self	: Optional[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 		_snake_case      (  self	: Dict       ):
     return

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

 @unittest.skip(reason='''ConvNext does not support input and output embeddings'''       )
 def 		_snake_case      (  self	: Dict       ):
     pass

 @unittest.skip(reason='''ConvNext does not use feedforward chunking'''       )
 def 		_snake_case      (  self	: str       ):
     pass

 def 		_snake_case      (  self	: Any       ):
     snake_case_,			snake_case_				:  Any       =			self.model_tester.prepare_config_and_inputs_for_common()

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

         snake_case_				:  List[Any]       =			['''pixel_values''']
         self.assertListEqual(arg_names[:1]						,  lowercase_       )

 def 		_snake_case      (  self	: Union[str, Any]       ):
     snake_case_				:  Union[str, Any]       =			self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowercase_       )

 def 		_snake_case      (  self	: Tuple       ):
     snake_case_				:  str       =			self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_backbone(*lowercase_       )

 def 		_snake_case      (  self	: str       ):
     def check_hidden_states_output(lowercase_	: Union[str, Any]						,  lowercase_	: Dict						,  lowercase_	: int       ):
         snake_case_				:  Tuple       =			model_class(lowercase_       )
         model.to(lowercase_       )
         model.eval()

         with torch.no_grad():
             snake_case_				:  Tuple       =			model(**self._prepare_for_class(lowercase_						,  lowercase_       )       )

         snake_case_				:  Dict       =			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

         snake_case_				:  List[Any]       =			self.model_tester.num_stages
         self.assertEqual(len(lowercase_       )						,  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_,			snake_case_				:  Tuple       =			self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
         snake_case_				:  Dict       =			True
         check_hidden_states_output(lowercase_						,  lowercase_						,  lowercase_       )

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

         check_hidden_states_output(lowercase_						,  lowercase_						,  lowercase_       )

 def 		_snake_case      (  self	: str       ):
     snake_case_				:  Optional[int]       =			self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*lowercase_       )






 @slow
 def 		_snake_case      (  self	: int       ):
     for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         snake_case_				:  Tuple       =			ConvNextModel.from_pretrained(lowercase_       )
         self.assertIsNotNone(lowercase_       )





def __lowercase    (							):
    snake_case_				:  Dict       =			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''					)
    return image




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

 @cached_property
 def 		_snake_case      (  self	: Any       ):
     return AutoImageProcessor.from_pretrained('''facebook/convnext-tiny-224'''       ) if is_vision_available() else None






 @slow
 def 		_snake_case      (  self	: List[Any]       ):
     snake_case_				:  Any       =			ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''       ).to(lowercase_       )

     snake_case_				:  Tuple       =			self.default_image_processor
     snake_case_				:  Optional[Any]       =			prepare_img()
     snake_case_				:  int       =			image_processor(images=lowercase_						,  return_tensors='''pt'''       ).to(lowercase_       )

     # forward pass
     with torch.no_grad():
         snake_case_				:  Optional[Any]       =			model(**lowercase_       )

     # verify the logits
     snake_case_				:  List[str]       =			torch.Size((1, 1000)       )
     self.assertEqual(outputs.logits.shape						,  lowercase_       )

     snake_case_				:  Optional[Any]       =			torch.tensor([-0.02_60, -0.47_39, 0.19_11]       ).to(lowercase_       )

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





@require_torch
class  _UpperCAmelCase (    unittest.TestCase					,  lowerCAmelCase__):
 _lowerCAmelCase     :    int	      =	(ConvNextBackbone,) if is_torch_available() else ()
 _lowerCAmelCase     :    Dict	      =	ConvNextConfig

 _lowerCAmelCase     :    int	      =	False

 def 		_snake_case      (  self	: Union[str, Any]       ):
     snake_case_				:  int       =			ConvNextModelTester(self       )










"""simple docstring"""

import unittest

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


if is_torch_available():
     import torch

     from transformers import AutoModelForImageClassification

if is_vision_available():
     from transformers import AutoImageProcessor




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

 @slow
 def 		_snake_case      (  self	: List[Any]       ):
     snake_case_				:  List[Any]       =			AutoImageProcessor.from_pretrained('''microsoft/dit-base-finetuned-rvlcdip'''       )
     snake_case_				:  List[Any]       =			AutoModelForImageClassification.from_pretrained('''microsoft/dit-base-finetuned-rvlcdip'''       )
     model.to(lowercase_       )

     from datasets import load_dataset

     snake_case_				:  str       =			load_dataset('''nielsr/rvlcdip-demo'''       )

     snake_case_				:  Tuple       =			dataset['''train'''][0]['''image'''].convert('''RGB'''       )

     snake_case_				:  Union[str, Any]       =			image_processor(lowercase_						,  return_tensors='''pt'''       ).to(lowercase_       )

     # forward pass
     with torch.no_grad():
         snake_case_				:  List[Any]       =			model(**lowercase_       )
         snake_case_				:  int       =			outputs.logits

     snake_case_				:  Any       =			torch.Size((1, 16)       )
     self.assertEqual(logits.shape						,  lowercase_       )

     snake_case_				:  Any       =			torch.tensor(
         [-0.41_58, -0.40_92, -0.43_47]						,  device=lowercase_						,  dtype=torch.float						,  )
     self.assertTrue(torch.allclose(logits[0, :3]						,  lowercase_						,  atol=1E-4       )       )





