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


       """simple docstring"""







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



       def SCREAMING_SNAKE_CASE_				(     self					:			Tuple       )					->   List[Any]:
         _lowerCAmelCase						=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

         _lowerCAmelCase						=		None
         if self.use_labels:
           _lowerCAmelCase						=		ids_tensor([self.batch_size]  ,      self.type_sequence_label_size       )

         _lowerCAmelCase						=		self.get_config()

         return config, pixel_values, labels



       def SCREAMING_SNAKE_CASE_				(     self					:			List[Any]       )					->   int:
         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=_lowerCAmelCase  ,      initializer_range=self.initializer_range  ,      )



       def SCREAMING_SNAKE_CASE_				(     self					:			Dict  ,      _lowerCAmelCase					:			List[Any]  ,      _lowerCAmelCase					:			Union[str, Any]  ,      _lowerCAmelCase					:			Union[str, Any]       )					->   Optional[Any]:
         _lowerCAmelCase						=		TFConvNextModel(config=_lowerCAmelCase       )
         _lowerCAmelCase						=		model(_lowerCAmelCase  ,      training=_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 SCREAMING_SNAKE_CASE_				(     self					:			Optional[int]  ,      _lowerCAmelCase					:			Optional[Any]  ,      _lowerCAmelCase					:			Union[str, Any]  ,      _lowerCAmelCase					:			Optional[int]       )					->   int:
         _lowerCAmelCase						=		self.type_sequence_label_size
         _lowerCAmelCase						=		TFConvNextForImageClassification(_lowerCAmelCase       )
         _lowerCAmelCase						=		model(_lowerCAmelCase  ,      labels=_lowerCAmelCase  ,      training=_lowerCAmelCase       )
         self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.type_sequence_label_size)       )






       def SCREAMING_SNAKE_CASE_				(     self					:			List[str]       )					->   List[Any]:
         _lowerCAmelCase						=		self.prepare_config_and_inputs()
         _lowerCAmelCase	,       _lowerCAmelCase	,       _lowerCAmelCase						=		config_and_inputs
         _lowerCAmelCase						=		{'pixel_values': pixel_values}
         return config, inputs_dict





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


       """simple docstring"""







       UpperCamelCase_				 =							(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
       UpperCamelCase_				 =							(
           {'''feature-extraction''': TFConvNextModel, '''image-classification''': TFConvNextForImageClassification}
           if is_tf_available()
           else {}
       )

       UpperCamelCase_				 =							False
       UpperCamelCase_				 =							False
       UpperCamelCase_				 =							False
       UpperCamelCase_				 =							False
       UpperCamelCase_				 =							False



       def SCREAMING_SNAKE_CASE_				(     self					:			str       )					->   List[Any]:
         _lowerCAmelCase						=		TFConvNextModelTester(self       )
         _lowerCAmelCase						=		ConfigTester(
             self  ,      config_class=_lowerCAmelCase  ,      has_text_modality=_lowerCAmelCase  ,      hidden_size=37  ,      )



       @unittest.skip(reason='ConvNext does not use inputs_embeds'       )
       def SCREAMING_SNAKE_CASE_				(     self					:			int       )					->   Optional[Any]:
         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 SCREAMING_SNAKE_CASE_				(     self					:			Optional[Any]       )					->   List[Any]:
         super().test_keras_fit()



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



       def SCREAMING_SNAKE_CASE_				(     self					:			int       )					->   Optional[int]:
         _lowerCAmelCase	,       _lowerCAmelCase						=		self.model_tester.prepare_config_and_inputs_for_common()

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

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



       def SCREAMING_SNAKE_CASE_				(     self					:			Optional[Any]       )					->   Optional[Any]:
         _lowerCAmelCase						=		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_lowerCAmelCase       )



       @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 SCREAMING_SNAKE_CASE_				(     self					:			int       )					->   Any:
         super().test_dataset_conversion()



       def SCREAMING_SNAKE_CASE_				(     self					:			Union[str, Any]       )					->   List[Any]:
         def check_hidden_states_output(_lowerCAmelCase					:			List[str]  ,      _lowerCAmelCase					:			Dict  ,      _lowerCAmelCase					:			Dict       ):
           _lowerCAmelCase						=		model_class(_lowerCAmelCase       )

           _lowerCAmelCase						=		model(**self._prepare_for_class(_lowerCAmelCase  ,      _lowerCAmelCase       )       )
           _lowerCAmelCase						=		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

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

         _lowerCAmelCase	,       _lowerCAmelCase						=		self.model_tester.prepare_config_and_inputs_for_common()

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

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

           check_hidden_states_output(_lowerCAmelCase  ,      _lowerCAmelCase  ,      _lowerCAmelCase       )



       def SCREAMING_SNAKE_CASE_				(     self					:			Optional[Any]       )					->   Tuple:
         _lowerCAmelCase	,       _lowerCAmelCase						=		self.model_tester.prepare_config_and_inputs_for_common()

         def check_equivalence(_lowerCAmelCase					:			Union[str, Any]  ,      _lowerCAmelCase					:			str  ,      _lowerCAmelCase					:			Optional[int]  ,      _lowerCAmelCase					:			Optional[Any]={}       ):
           _lowerCAmelCase						=		model(_lowerCAmelCase  ,      return_dict=_lowerCAmelCase  ,      **_lowerCAmelCase       )
           _lowerCAmelCase						=		model(_lowerCAmelCase  ,      return_dict=_lowerCAmelCase  ,      **_lowerCAmelCase       ).to_tuple()

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

             recursive_check(_lowerCAmelCase  ,      _lowerCAmelCase       )

         for model_class in self.all_model_classes:
           _lowerCAmelCase						=		model_class(_lowerCAmelCase       )

           _lowerCAmelCase						=		self._prepare_for_class(_lowerCAmelCase  ,      _lowerCAmelCase       )
           _lowerCAmelCase						=		self._prepare_for_class(_lowerCAmelCase  ,      _lowerCAmelCase       )
           check_equivalence(_lowerCAmelCase  ,      _lowerCAmelCase  ,      _lowerCAmelCase       )

           _lowerCAmelCase						=		self._prepare_for_class(_lowerCAmelCase  ,      _lowerCAmelCase  ,      return_labels=_lowerCAmelCase       )
           _lowerCAmelCase						=		self._prepare_for_class(_lowerCAmelCase  ,      _lowerCAmelCase  ,      return_labels=_lowerCAmelCase       )
           check_equivalence(_lowerCAmelCase  ,      _lowerCAmelCase  ,      _lowerCAmelCase       )

           _lowerCAmelCase						=		self._prepare_for_class(_lowerCAmelCase  ,      _lowerCAmelCase       )
           _lowerCAmelCase						=		self._prepare_for_class(_lowerCAmelCase  ,      _lowerCAmelCase       )
           check_equivalence(_lowerCAmelCase  ,      _lowerCAmelCase  ,      _lowerCAmelCase  ,      {'output_hidden_states': True}       )

           _lowerCAmelCase						=		self._prepare_for_class(_lowerCAmelCase  ,      _lowerCAmelCase  ,      return_labels=_lowerCAmelCase       )
           _lowerCAmelCase						=		self._prepare_for_class(_lowerCAmelCase  ,      _lowerCAmelCase  ,      return_labels=_lowerCAmelCase       )
           check_equivalence(_lowerCAmelCase  ,      _lowerCAmelCase  ,      _lowerCAmelCase  ,      {'output_hidden_states': True}       )



       def SCREAMING_SNAKE_CASE_				(     self					:			Dict       )					->   Optional[int]:
         _lowerCAmelCase						=		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase       )






       @slow
       def SCREAMING_SNAKE_CASE_				(     self					:			Optional[int]       )					->   Optional[int]:
         _lowerCAmelCase						=		TFConvNextModel.from_pretrained('facebook/convnext-tiny-224'       )
         self.assertIsNotNone(_lowerCAmelCase       )



def 	_a  (					):






  """simple docstring"""




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





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


       """simple docstring"""







       @cached_property
       def SCREAMING_SNAKE_CASE_				(     self					:			List[Any]       )					->   Any:
         return ConvNextImageProcessor.from_pretrained('facebook/convnext-tiny-224'       ) if is_vision_available() else None






       @slow
       def SCREAMING_SNAKE_CASE_				(     self					:			Dict       )					->   Optional[int]:
         _lowerCAmelCase						=		TFConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'       )

         _lowerCAmelCase						=		self.default_image_processor
         _lowerCAmelCase						=		prepare_img()
         _lowerCAmelCase						=		image_processor(images=_lowerCAmelCase  ,      return_tensors='tf'       )

         # forward pass
         _lowerCAmelCase						=		model(**_lowerCAmelCase       )

         # verify the logits
         _lowerCAmelCase						=		tf.TensorShape((1, 1000)       )
         self.assertEqual(outputs.logits.shape  ,      _lowerCAmelCase       )

         _lowerCAmelCase						=		tf.constant([-0.0260, -0.4739, 0.1911]       )

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


import copy
from typing import Dict, Optional

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


_UpperCamelCase:					str     =logging.get_logger(__name__)

_UpperCamelCase:					Optional[Any]     ={
    'shi-labs/oneformer_ade20k_swin_tiny': (
        'https://huggingface.co/shi-labs/oneformer_ade20k_swin_tiny/blob/main/config.json'
    ),
    # See all OneFormer models at https://huggingface.co/models?filter=oneformer
}





class 						__lowercase(     SCREAMING_SNAKE_CASE   ):


       """simple docstring"""







       UpperCamelCase_				 =							'''oneformer'''
       UpperCamelCase_				 =							{'''hidden_size''': '''hidden_dim'''}



       def __init__(     self					:			Optional[Any]  ,      _lowerCAmelCase					:			Optional[Dict] = None  ,      _lowerCAmelCase					:			int = 255  ,      _lowerCAmelCase					:			int = 150  ,      _lowerCAmelCase					:			int = 0.1  ,      _lowerCAmelCase					:			float = 2.0  ,      _lowerCAmelCase					:			float = 5.0  ,      _lowerCAmelCase					:			float = 5.0  ,      _lowerCAmelCase					:			float = 0.5  ,      _lowerCAmelCase					:			float = 0.07  ,      _lowerCAmelCase					:			int = 1_2544  ,      _lowerCAmelCase					:			float = 3.0  ,      _lowerCAmelCase					:			float = 0.75  ,      _lowerCAmelCase					:			float = 0.02  ,      _lowerCAmelCase					:			float = 1.0  ,      _lowerCAmelCase					:			float = 1e-05  ,      _lowerCAmelCase					:			bool = False  ,      _lowerCAmelCase					:			bool = True  ,      _lowerCAmelCase					:			bool = True  ,      _lowerCAmelCase					:			Optional[list] = [4, 8, 16, 32]  ,      _lowerCAmelCase					:			int = 77  ,      _lowerCAmelCase					:			int = 256  ,      _lowerCAmelCase					:			int = 77  ,      _lowerCAmelCase					:			int = 6  ,      _lowerCAmelCase					:			int = 4_9408  ,      _lowerCAmelCase					:			int = 2  ,      _lowerCAmelCase					:			int = 16  ,      _lowerCAmelCase					:			int = 256  ,      _lowerCAmelCase					:			int = 256  ,      _lowerCAmelCase					:			int = 256  ,      _lowerCAmelCase					:			int = 1024  ,      _lowerCAmelCase					:			str = "GN"  ,      _lowerCAmelCase					:			int = 6  ,      _lowerCAmelCase					:			int = 10  ,      _lowerCAmelCase					:			bool = True  ,      _lowerCAmelCase					:			int = 8  ,      _lowerCAmelCase					:			float = 0.1  ,      _lowerCAmelCase					:			int = 2048  ,      _lowerCAmelCase					:			bool = False  ,      _lowerCAmelCase					:			bool = False  ,      _lowerCAmelCase					:			int = 2  ,      _lowerCAmelCase					:			int = 4  ,      **_lowerCAmelCase					:			Any  ,      )					->   Tuple:
         if backbone_config is None:
           logger.info('`backbone_config` is unset. Initializing the config with the default `Swin` backbone.'       )
           _lowerCAmelCase						=		CONFIG_MAPPING['swin'](
               image_size=224  ,      in_channels=3  ,      patch_size=4  ,      embed_dim=96  ,      depths=[2, 2, 6, 2]  ,      num_heads=[3, 6, 12, 24]  ,      window_size=7  ,      drop_path_rate=0.3  ,      use_absolute_embeddings=_lowerCAmelCase  ,      out_features=['stage1', 'stage2', 'stage3', 'stage4']  ,      )
         elif isinstance(_lowerCAmelCase  ,      _lowerCAmelCase       ):
           _lowerCAmelCase						=		backbone_config.get('model_type'       )
           _lowerCAmelCase						=		CONFIG_MAPPING[backbone_model_type]
           _lowerCAmelCase						=		config_class.from_dict(_lowerCAmelCase       )

         _lowerCAmelCase						=		backbone_config

         _lowerCAmelCase						=		ignore_value
         _lowerCAmelCase						=		num_queries
         _lowerCAmelCase						=		no_object_weight
         _lowerCAmelCase						=		class_weight
         _lowerCAmelCase						=		mask_weight
         _lowerCAmelCase						=		dice_weight
         _lowerCAmelCase						=		contrastive_weight
         _lowerCAmelCase						=		contrastive_temperature
         _lowerCAmelCase						=		train_num_points
         _lowerCAmelCase						=		oversample_ratio
         _lowerCAmelCase						=		importance_sample_ratio
         _lowerCAmelCase						=		init_std
         _lowerCAmelCase						=		init_xavier_std
         _lowerCAmelCase						=		layer_norm_eps
         _lowerCAmelCase						=		is_training
         _lowerCAmelCase						=		use_auxiliary_loss
         _lowerCAmelCase						=		output_auxiliary_logits
         _lowerCAmelCase						=		strides
         _lowerCAmelCase						=		task_seq_len
         _lowerCAmelCase						=		text_encoder_width
         _lowerCAmelCase						=		text_encoder_context_length
         _lowerCAmelCase						=		text_encoder_num_layers
         _lowerCAmelCase						=		text_encoder_vocab_size
         _lowerCAmelCase						=		text_encoder_proj_layers
         _lowerCAmelCase						=		text_encoder_n_ctx
         _lowerCAmelCase						=		conv_dim
         _lowerCAmelCase						=		mask_dim
         _lowerCAmelCase						=		hidden_dim
         _lowerCAmelCase						=		encoder_feedforward_dim
         _lowerCAmelCase						=		norm
         _lowerCAmelCase						=		encoder_layers
         _lowerCAmelCase						=		decoder_layers
         _lowerCAmelCase						=		use_task_norm
         _lowerCAmelCase						=		num_attention_heads
         _lowerCAmelCase						=		dropout
         _lowerCAmelCase						=		dim_feedforward
         _lowerCAmelCase						=		pre_norm
         _lowerCAmelCase						=		enforce_input_proj
         _lowerCAmelCase						=		query_dec_layers
         _lowerCAmelCase						=		common_stride
         _lowerCAmelCase						=		decoder_layers

         super().__init__(**_lowerCAmelCase       )






       def SCREAMING_SNAKE_CASE_				(     self					:			List[str]       )					->   Dict[str, any]:
         _lowerCAmelCase						=		copy.deepcopy(self.__dict__       )
         _lowerCAmelCase						=		self.backbone_config.to_dict()
         _lowerCAmelCase						=		self.__class__.model_type
         return output
