





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




					def __init__(    self     ,   __lowerCAmelCase     ,   __lowerCAmelCase=13     ,   __lowerCAmelCase=32     ,   __lowerCAmelCase=3     ,   __lowerCAmelCase=4     ,   __lowerCAmelCase=[10, 20, 30, 40]     ,   __lowerCAmelCase=[2, 2, 3, 2]     ,   __lowerCAmelCase=True     ,   __lowerCAmelCase=True     ,   __lowerCAmelCase=37     ,   __lowerCAmelCase="gelu"     ,   __lowerCAmelCase=10     ,   __lowerCAmelCase=0.0_2     ,   __lowerCAmelCase=3     ,   __lowerCAmelCase=None     ,   )    ->	Tuple:
							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__								=						type_sequence_label_size
							UpperCamelCase__								=						initializer_range
							UpperCamelCase__								=						scope




					def 						snake_case_		(    self							)    ->	str:
							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.type_sequence_label_size							)

							UpperCamelCase__								=						self.get_config()

							return config, pixel_values, labels




					def 						snake_case_		(    self							)    ->	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 						snake_case_		(    self     ,   __lowerCAmelCase     ,   __lowerCAmelCase     ,   __lowerCAmelCase							)    ->	Tuple:
							UpperCamelCase__								=						TFConvNextModel(config=__lowerCAmelCase							)
							UpperCamelCase__								=						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 						snake_case_		(    self     ,   __lowerCAmelCase     ,   __lowerCAmelCase     ,   __lowerCAmelCase							)    ->	Optional[Any]:
							UpperCamelCase__								=						self.type_sequence_label_size
							UpperCamelCase__								=						TFConvNextForImageClassification(__lowerCAmelCase							)
							UpperCamelCase__								=						model(__lowerCAmelCase     ,   labels=__lowerCAmelCase     ,   training=__lowerCAmelCase							)
							self.parent.assertEqual(result.logits.shape     ,   (self.batch_size, self.type_sequence_label_size)							)




					def 						snake_case_		(    self							)    ->	Dict:
							UpperCamelCase__								=						self.prepare_config_and_inputs()
							UpperCamelCase__	,      UpperCamelCase__	,      UpperCamelCase__								=						config_and_inputs
							UpperCamelCase__								=						{"""pixel_values""": pixel_values}
							return config, inputs_dict




@require_tf
class 	_UpperCAmelCase						( _lowercase			,							_lowercase			,							unittest.TestCase       ):
					__A        = (TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
					__A        = (
					    {"feature-extraction": TFConvNextModel, "image-classification": TFConvNextForImageClassification}
					    if is_tf_available()
					    else {}
					)

					__A        = False
					__A        = False
					__A        = False
					__A        = False
					__A        = False




					def 						snake_case_		(    self							)    ->	Optional[int]:
							UpperCamelCase__								=						TFConvNextModelTester(self							)
							UpperCamelCase__								=						ConfigTester(
							    self     ,   config_class=__lowerCAmelCase     ,   has_text_modality=__lowerCAmelCase     ,   hidden_size=37     ,   )




					@unittest.skip(reason="""ConvNext does not use inputs_embeds"""							)
					def 						snake_case_		(    self							)    ->	Dict:
							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							)    ->	int:
							super().test_keras_fit()




					@unittest.skip(reason="""ConvNext does not support input and output embeddings"""							)
					def 						snake_case_		(    self							)    ->	str:
							pass




					def 						snake_case_		(    self							)    ->	Any:
							UpperCamelCase__	,      UpperCamelCase__								=						self.model_tester.prepare_config_and_inputs_for_common()

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

									UpperCamelCase__								=						["""pixel_values"""]
									self.assertListEqual(arg_names[:1]     ,   __lowerCAmelCase							)




					def 						snake_case_		(    self							)    ->	List[Any]:
							UpperCamelCase__								=						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 						snake_case_		(    self							)    ->	Any:
							super().test_dataset_conversion()




					def 						snake_case_		(    self							)    ->	List[str]:
							def check_hidden_states_output(__lowerCAmelCase     ,   __lowerCAmelCase     ,   __lowerCAmelCase							):
									UpperCamelCase__								=						model_class(__lowerCAmelCase							)

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

									UpperCamelCase__								=						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]     ,   )

							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(__lowerCAmelCase     ,   __lowerCAmelCase     ,   __lowerCAmelCase							)

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

									check_hidden_states_output(__lowerCAmelCase     ,   __lowerCAmelCase     ,   __lowerCAmelCase							)




					def 						snake_case_		(    self							)    ->	int:
							UpperCamelCase__	,      UpperCamelCase__								=						self.model_tester.prepare_config_and_inputs_for_common()

							def check_equivalence(__lowerCAmelCase     ,   __lowerCAmelCase     ,   __lowerCAmelCase     ,   __lowerCAmelCase={}							):
									UpperCamelCase__								=						model(__lowerCAmelCase     ,   return_dict=__lowerCAmelCase     ,   **__lowerCAmelCase							)
									UpperCamelCase__								=						model(__lowerCAmelCase     ,   return_dict=__lowerCAmelCase     ,   **__lowerCAmelCase							).to_tuple()

									def recursive_check(__lowerCAmelCase     ,   __lowerCAmelCase							):
											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:
									UpperCamelCase__								=						model_class(__lowerCAmelCase							)

									UpperCamelCase__								=						self._prepare_for_class(__lowerCAmelCase     ,   __lowerCAmelCase							)
									UpperCamelCase__								=						self._prepare_for_class(__lowerCAmelCase     ,   __lowerCAmelCase							)
									check_equivalence(__lowerCAmelCase     ,   __lowerCAmelCase     ,   __lowerCAmelCase							)

									UpperCamelCase__								=						self._prepare_for_class(__lowerCAmelCase     ,   __lowerCAmelCase     ,   return_labels=__lowerCAmelCase							)
									UpperCamelCase__								=						self._prepare_for_class(__lowerCAmelCase     ,   __lowerCAmelCase     ,   return_labels=__lowerCAmelCase							)
									check_equivalence(__lowerCAmelCase     ,   __lowerCAmelCase     ,   __lowerCAmelCase							)

									UpperCamelCase__								=						self._prepare_for_class(__lowerCAmelCase     ,   __lowerCAmelCase							)
									UpperCamelCase__								=						self._prepare_for_class(__lowerCAmelCase     ,   __lowerCAmelCase							)
									check_equivalence(__lowerCAmelCase     ,   __lowerCAmelCase     ,   __lowerCAmelCase     ,   {"""output_hidden_states""": True}							)

									UpperCamelCase__								=						self._prepare_for_class(__lowerCAmelCase     ,   __lowerCAmelCase     ,   return_labels=__lowerCAmelCase							)
									UpperCamelCase__								=						self._prepare_for_class(__lowerCAmelCase     ,   __lowerCAmelCase     ,   return_labels=__lowerCAmelCase							)
									check_equivalence(__lowerCAmelCase     ,   __lowerCAmelCase     ,   __lowerCAmelCase     ,   {"""output_hidden_states""": True}							)




					def 						snake_case_		(    self							)    ->	int:
							UpperCamelCase__								=						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase							)




					@slow
					def 						snake_case_		(    self							)    ->	Optional[Any]:
							UpperCamelCase__								=						TFConvNextModel.from_pretrained("""facebook/convnext-tiny-224"""							)
							self.assertIsNotNone(__lowerCAmelCase							)



def      a    (   )  ->Optional[int]:
		UpperCamelCase__								=						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""							)
		return image




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




					@cached_property
					def 						snake_case_		(    self							)    ->	Dict:
							return ConvNextImageProcessor.from_pretrained("""facebook/convnext-tiny-224"""							) if is_vision_available() else None




					@slow
					def 						snake_case_		(    self							)    ->	Union[str, Any]:
							UpperCamelCase__								=						TFConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""							)

							UpperCamelCase__								=						self.default_image_processor
							UpperCamelCase__								=						prepare_img()
							UpperCamelCase__								=						image_processor(images=__lowerCAmelCase     ,   return_tensors="""tf"""							)

							# forward pass
							UpperCamelCase__								=						model(**__lowerCAmelCase							)

							# verify the logits
							UpperCamelCase__								=						tf.TensorShape((1, 1_000)							)
							self.assertEqual(outputs.logits.shape     ,   __lowerCAmelCase							)

							UpperCamelCase__								=						tf.constant([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1]							)

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












from ...configuration_utils import PretrainedConfig
from ...utils import logging


__lowerCAmelCase 	=      logging.get_logger(__name__)

__lowerCAmelCase 	=      {
    "MCG-NJU/videomae-base": "https://huggingface.co/MCG-NJU/videomae-base/resolve/main/config.json",
}




class 	_UpperCAmelCase						( _lowercase       ):
					__A        = "videomae"




					def __init__(    self     ,   __lowerCAmelCase=224     ,   __lowerCAmelCase=16     ,   __lowerCAmelCase=3     ,   __lowerCAmelCase=16     ,   __lowerCAmelCase=2     ,   __lowerCAmelCase=768     ,   __lowerCAmelCase=12     ,   __lowerCAmelCase=12     ,   __lowerCAmelCase=3_072     ,   __lowerCAmelCase="gelu"     ,   __lowerCAmelCase=0.0     ,   __lowerCAmelCase=0.0     ,   __lowerCAmelCase=0.0_2     ,   __lowerCAmelCase=1E-1_2     ,   __lowerCAmelCase=True     ,   __lowerCAmelCase=True     ,   __lowerCAmelCase=6     ,   __lowerCAmelCase=384     ,   __lowerCAmelCase=4     ,   __lowerCAmelCase=1_536     ,   __lowerCAmelCase=True     ,   **__lowerCAmelCase     ,   )    ->	Any:
							super().__init__(**__lowerCAmelCase							)

							UpperCamelCase__								=						image_size
							UpperCamelCase__								=						patch_size
							UpperCamelCase__								=						num_channels
							UpperCamelCase__								=						num_frames
							UpperCamelCase__								=						tubelet_size

							UpperCamelCase__								=						hidden_size
							UpperCamelCase__								=						num_hidden_layers
							UpperCamelCase__								=						num_attention_heads
							UpperCamelCase__								=						intermediate_size
							UpperCamelCase__								=						hidden_act
							UpperCamelCase__								=						hidden_dropout_prob
							UpperCamelCase__								=						attention_probs_dropout_prob
							UpperCamelCase__								=						initializer_range
							UpperCamelCase__								=						layer_norm_eps
							UpperCamelCase__								=						qkv_bias
							UpperCamelCase__								=						use_mean_pooling

							UpperCamelCase__								=						decoder_num_attention_heads
							UpperCamelCase__								=						decoder_hidden_size
							UpperCamelCase__								=						decoder_num_hidden_layers
							UpperCamelCase__								=						decoder_intermediate_size
							UpperCamelCase__								=						norm_pix_loss





