






from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import tensorflow as tf

  from transformers import TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
  from PIL import Image

  from transformers import ConvNextImageProcessor
class 							__magic_name__      :






 '''simple docstring'''




 def __init__(		self							,					_A							,					_A=13							,					_A=32							,					_A=3							,					_A=4							,					_A=[10, 20, 30, 40]							,					_A=[2, 2, 3, 2]							,					_A=True							,					_A=True							,					_A=37							,					_A="gelu"							,					_A=10							,					_A=0.02							,					_A=3							,					_A=None							,					)	->						Dict:

     """simple docstring"""



     _UpperCAmelCase			: Optional[Any]     					=			parent
     _UpperCAmelCase			: Any     					=			batch_size
     _UpperCAmelCase			: Optional[Any]     					=			image_size
     _UpperCAmelCase			: Optional[int]     					=			num_channels
     _UpperCAmelCase			: Optional[int]     					=			num_stages
     _UpperCAmelCase			: List[Any]     					=			hidden_sizes
     _UpperCAmelCase			: List[Any]     					=			depths
     _UpperCAmelCase			: int     					=			is_training
     _UpperCAmelCase			: Tuple     					=			use_labels
     _UpperCAmelCase			: List[Any]     					=			intermediate_size
     _UpperCAmelCase			: List[Any]     					=			hidden_act
     _UpperCAmelCase			: Union[str, Any]     					=			type_sequence_label_size
     _UpperCAmelCase			: Dict     					=			initializer_range
     _UpperCAmelCase			: Tuple     					=			scope


 def 	snake_case__			(		self)	->						Dict:

     """simple docstring"""



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

     _UpperCAmelCase			: List[Any]     					=			None
     if self.use_labels:
         _UpperCAmelCase			: str     					=			ids_tensor([self.batch_size]							,					self.type_sequence_label_size)

     _UpperCAmelCase			: Optional[Any]     					=			self.get_config()

     return config, pixel_values, labels


 def 	snake_case__			(		self)	->						Optional[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=_A							,					initializer_range=self.initializer_range							,					)


 def 	snake_case__			(		self							,					_A							,					_A							,					_A)	->						Any:

     """simple docstring"""



     _UpperCAmelCase			: Dict     					=			TFConvNextModel(config=_A)
     _UpperCAmelCase			: Dict     					=			model(_A							,					training=_A)
     # 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							,					_A							,					_A							,					_A)	->						Optional[int]:

     """simple docstring"""



     _UpperCAmelCase			: List[Any]     					=			self.type_sequence_label_size
     _UpperCAmelCase			: Dict     					=			TFConvNextForImageClassification(_A)
     _UpperCAmelCase			: Any     					=			model(_A							,					labels=_A							,					training=_A)
     self.parent.assertEqual(result.logits.shape							,					(self.batch_size, self.type_sequence_label_size))


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

     """simple docstring"""



     _UpperCAmelCase			: Any     					=			self.prepare_config_and_inputs()
     _UpperCAmelCase			: str     					=			config_and_inputs
     _UpperCAmelCase			: Optional[Any]     					=			{'''pixel_values''': pixel_values}
     return config, inputs_dict



@require_tf
class 							__magic_name__      (  __lowercase	,				__lowercase	,				unittest.TestCase     ):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:     List[Any]	=   (TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
 _SCREAMING_SNAKE_CASE							:     Dict	=   (
     {"feature-extraction": TFConvNextModel, "image-classification": TFConvNextForImageClassification}
     if is_tf_available()
     else {}
 )

 _SCREAMING_SNAKE_CASE							:     Any	=   False
 _SCREAMING_SNAKE_CASE							:     Optional[Any]	=   False
 _SCREAMING_SNAKE_CASE							:     List[Any]	=   False
 _SCREAMING_SNAKE_CASE							:     List[Any]	=   False
 _SCREAMING_SNAKE_CASE							:     List[Any]	=   False


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

     """simple docstring"""



     _UpperCAmelCase			: Union[str, Any]     					=			TFConvNextModelTester(self)
     _UpperCAmelCase			: List[Any]     					=			ConfigTester(
         self							,					config_class=_A							,					has_text_modality=_A							,					hidden_size=37							,					)


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

     """simple docstring"""



     pass


 @unittest.skipIf(
     not is_tf_available() or len(tf.config.list_physical_devices('''GPU''')) == 0							,					reason='''TF does not support backprop for grouped convolutions on CPU.'''							,					)
 @slow
 def 	snake_case__			(		self)	->						str:

     """simple docstring"""



     super().test_keras_fit()


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

     """simple docstring"""



     pass


 def 	snake_case__			(		self)	->						Any:

     """simple docstring"""



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

     for model_class in self.all_model_classes:
         _UpperCAmelCase			: Optional[int]     					=			model_class(_A)
         _UpperCAmelCase			: List[Any]     					=			inspect.signature(model.call)
         # signature.parameters is an OrderedDict => so arg_names order is deterministic
         _UpperCAmelCase			: str     					=			[*signature.parameters.keys()]

         _UpperCAmelCase			: int     					=			['''pixel_values''']
         self.assertListEqual(arg_names[:1]							,					_A)


 def 	snake_case__			(		self)	->						str:

     """simple docstring"""



     _UpperCAmelCase			: List[Any]     					=			self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*_A)


 @unittest.skipIf(
     not is_tf_available() or len(tf.config.list_physical_devices('''GPU''')) == 0							,					reason='''TF does not support backprop for grouped convolutions on CPU.'''							,					)
 def 	snake_case__			(		self)	->						List[Any]:

     """simple docstring"""



     super().test_dataset_conversion()


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

     """simple docstring"""



     def check_hidden_states_output(_A							,					_A							,					_A):
         _UpperCAmelCase			: Optional[Any]     					=			model_class(_A)

         _UpperCAmelCase			: str     					=			model(**self._prepare_for_class(_A							,					_A))
         _UpperCAmelCase			: List[Any]     					=			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

         _UpperCAmelCase			: List[Any]     					=			self.model_tester.num_stages
         self.assertEqual(len(_A)							,					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]							,					)

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

     for model_class in self.all_model_classes:
         _UpperCAmelCase			: int     					=			True
         check_hidden_states_output(_A							,					_A							,					_A)

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

         check_hidden_states_output(_A							,					_A							,					_A)


 def 	snake_case__			(		self)	->						List[str]:

     """simple docstring"""



     _UpperCAmelCase			: int     					=			self.model_tester.prepare_config_and_inputs_for_common()

     def check_equivalence(_A							,					_A							,					_A							,					_A={}):
         _UpperCAmelCase			: int     					=			model(_A							,					return_dict=_A							,					**_A)
         _UpperCAmelCase			: List[str]     					=			model(_A							,					return_dict=_A							,					**_A).to_tuple()

         def recursive_check(_A							,					_A):
             if isinstance(_A							,					(List, Tuple)):
                 for tuple_iterable_value, dict_iterable_value in zip(_A							,					_A):
                     recursive_check(_A							,					_A)
             elif tuple_object is None:
                 return
             else:
                 self.assertTrue(
                     all(tf.equal(_A							,					_A))							,					msg=(
                         '''Tuple and dict output are not equal. Difference:'''
                         f''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object))}'''
                     )							,					)

             recursive_check(_A							,					_A)

     for model_class in self.all_model_classes:
         _UpperCAmelCase			: Any     					=			model_class(_A)

         _UpperCAmelCase			: int     					=			self._prepare_for_class(_A							,					_A)
         _UpperCAmelCase			: List[Any]     					=			self._prepare_for_class(_A							,					_A)
         check_equivalence(_A							,					_A							,					_A)

         _UpperCAmelCase			: str     					=			self._prepare_for_class(_A							,					_A							,					return_labels=_A)
         _UpperCAmelCase			: int     					=			self._prepare_for_class(_A							,					_A							,					return_labels=_A)
         check_equivalence(_A							,					_A							,					_A)

         _UpperCAmelCase			: Any     					=			self._prepare_for_class(_A							,					_A)
         _UpperCAmelCase			: Any     					=			self._prepare_for_class(_A							,					_A)
         check_equivalence(_A							,					_A							,					_A							,					{'''output_hidden_states''': True})

         _UpperCAmelCase			: Tuple     					=			self._prepare_for_class(_A							,					_A							,					return_labels=_A)
         _UpperCAmelCase			: Union[str, Any]     					=			self._prepare_for_class(_A							,					_A							,					return_labels=_A)
         check_equivalence(_A							,					_A							,					_A							,					{'''output_hidden_states''': True})


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

     """simple docstring"""



     _UpperCAmelCase			: Dict     					=			self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*_A)


 @slow
 def 	snake_case__			(		self)	->						int:

     """simple docstring"""



     _UpperCAmelCase			: Optional[int]     					=			TFConvNextModel.from_pretrained('''facebook/convnext-tiny-224''')
     self.assertIsNotNone(_A)



def        _lowerCamelCase		(  ) ->   Any:
    _UpperCAmelCase			: Optional[int]     					=			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
    return image


@require_tf
@require_vision
class 							__magic_name__      (  unittest.TestCase     ):






 '''simple docstring'''




 @cached_property
 def 	snake_case__			(		self)	->						int:

     """simple docstring"""



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


 @slow
 def 	snake_case__			(		self)	->						Tuple:

     """simple docstring"""



     _UpperCAmelCase			: Optional[int]     					=			TFConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224''')

     _UpperCAmelCase			: Optional[int]     					=			self.default_image_processor
     _UpperCAmelCase			: Optional[int]     					=			prepare_img()
     _UpperCAmelCase			: int     					=			image_processor(images=_A							,					return_tensors='''tf''')

     # forward pass
     _UpperCAmelCase			: Tuple     					=			model(**_A)

     # verify the logits
     _UpperCAmelCase			: Any     					=			tf.TensorShape((1, 1000))
     self.assertEqual(outputs.logits.shape							,					_A)

     _UpperCAmelCase			: int     					=			tf.constant([-0.0260, -0.4739, 0.1911])

     tf.debugging.assert_near(outputs.logits[0, :3]							,					_A							,					atol=1e-4)












from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


SCREAMING_SNAKE_CASE								=  logging.get_logger(__name__)

SCREAMING_SNAKE_CASE								=  {
    'MBZUAI/swiftformer-xs': 'https://huggingface.co/MBZUAI/swiftformer-xs/resolve/main/config.json',
}
class 							A_      (  __lowercase     ):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:     Dict	=   "swiftformer"


 def __init__(		self							,					_A=3							,					_A=[3, 3, 6, 4]							,					_A=[48, 56, 112, 220]							,					_A=4							,					_A=[True, True, True, True]							,					_A="gelu"							,					_A=3							,					_A=2							,					_A=1							,					_A=0.0							,					_A=True							,					_A=1e-5							,					_A=1e-5							,					**_A							,					)	->						List[Any]:

     """simple docstring"""



     super().__init__(**_A)
     _UpperCAmelCase			: Tuple     					=			num_channels
     _UpperCAmelCase			: Optional[int]     					=			depths
     _UpperCAmelCase			: Union[str, Any]     					=			embed_dims
     _UpperCAmelCase			: Dict     					=			mlp_ratio
     _UpperCAmelCase			: Tuple     					=			downsamples
     _UpperCAmelCase			: str     					=			hidden_act
     _UpperCAmelCase			: int     					=			down_patch_size
     _UpperCAmelCase			: Dict     					=			down_stride
     _UpperCAmelCase			: Dict     					=			down_pad
     _UpperCAmelCase			: Tuple     					=			drop_path_rate
     _UpperCAmelCase			: Tuple     					=			use_layer_scale
     _UpperCAmelCase			: int     					=			layer_scale_init_value
     _UpperCAmelCase			: int     					=			batch_norm_eps



class 							A_      (  __lowercase     ):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:     List[Any]	=   version.parse("1.11"     )


 @property
 def 	snake_case__			(		self)	->						Mapping[str, Mapping[int, str]]:

     """simple docstring"""



     return OrderedDict(
         [
             ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
         ])


 @property
 def 	snake_case__			(		self)	->						float:

     """simple docstring"""



     return 1e-4




