


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






			"""simple docstring"""






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

						'''simple docstring'''


						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__       =							num_labels
						UpperCamelCase__       =							initializer_range
						UpperCamelCase__       =							out_features
						UpperCamelCase__       =							out_indices
						UpperCamelCase__       =							scope




			def 					snake_case__					(				self  ):

						'''simple docstring'''


						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.num_labels  )

						UpperCamelCase__       =							self.get_config()
						return config, pixel_values, labels




			def 					snake_case__					(				self  ):

						'''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=_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   ,    snake_case   ,    snake_case   ,    snake_case  ):

						'''simple docstring'''


						UpperCamelCase__       =							ConvNextModel(config=_lowercase  )
						model.to(_lowercase  )
						model.eval()
						UpperCamelCase__       =							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   ,    snake_case   ,    snake_case   ,    snake_case  ):

						'''simple docstring'''


						UpperCamelCase__       =							ConvNextForImageClassification(_lowercase  )
						model.to(_lowercase  )
						model.eval()
						UpperCamelCase__       =							model(_lowercase   ,    labels=_lowercase  )
						self.parent.assertEqual(result.logits.shape   ,    (self.batch_size, self.num_labels)  )




			def 					snake_case__					(				self   ,    snake_case   ,    snake_case   ,    snake_case  ):

						'''simple docstring'''


						UpperCamelCase__       =							ConvNextBackbone(config=_lowercase  )
						model.to(_lowercase  )
						model.eval()
						UpperCamelCase__       =							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
						UpperCamelCase__       =							None
						UpperCamelCase__       =							ConvNextBackbone(config=_lowercase  )
						model.to(_lowercase  )
						model.eval()
						UpperCamelCase__       =							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  ):

						'''simple docstring'''


						UpperCamelCase__       =							self.prepare_config_and_inputs()
						UpperCamelCase__       =							config_and_inputs
						UpperCamelCase__       =							{"pixel_values": pixel_values}
						return config, inputs_dict







@require_torch
class 							lowerCamelCase__						(				SCREAMING_SNAKE_CASE__       ,						SCREAMING_SNAKE_CASE__       ,						unittest.TestCase   ):






			"""simple docstring"""






			_UpperCamelCase		:       Any 			=		(
			    (
			        ConvNextModel,
			        ConvNextForImageClassification,
			        ConvNextBackbone,
			    )
			    if is_torch_available()
			    else ()
			)
			_UpperCamelCase		:       Any 			=		(
			    {'feature-extraction': ConvNextModel, 'image-classification': ConvNextForImageClassification}
			    if is_torch_available()
			    else {}
			)

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




			def 					snake_case__					(				self  ):

						'''simple docstring'''


						UpperCamelCase__       =							ConvNextModelTester(self  )
						UpperCamelCase__       =							ConfigTester(self   ,    config_class=_lowercase   ,    has_text_modality=_lowercase   ,    hidden_size=37  )




			def 					snake_case__					(				self  ):

						'''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 					snake_case__					(				self  ):

						'''simple docstring'''


						return




			@unittest.skip(reason="ConvNext does not use inputs_embeds"  )
			def 					snake_case__					(				self  ):

						'''simple docstring'''


						pass




			@unittest.skip(reason="ConvNext does not support input and output embeddings"  )
			def 					snake_case__					(				self  ):

						'''simple docstring'''


						pass




			@unittest.skip(reason="ConvNext does not use feedforward chunking"  )
			def 					snake_case__					(				self  ):

						'''simple docstring'''


						pass




			def 					snake_case__					(				self  ):

						'''simple docstring'''


						UpperCamelCase__       =							self.model_tester.prepare_config_and_inputs_for_common()

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

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




			def 					snake_case__					(				self  ):

						'''simple docstring'''


						UpperCamelCase__       =							self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*_lowercase  )




			def 					snake_case__					(				self  ):

						'''simple docstring'''


						UpperCamelCase__       =							self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_backbone(*_lowercase  )




			def 					snake_case__					(				self  ):

						'''simple docstring'''


						def check_hidden_states_output(snake_case   ,    snake_case   ,    snake_case  ):
									UpperCamelCase__       =							model_class(_lowercase  )
									model.to(_lowercase  )
									model.eval()

									with torch.no_grad():
												UpperCamelCase__       =							model(**self._prepare_for_class(_lowercase   ,    _lowercase  )  )

									UpperCamelCase__       =							outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

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

						UpperCamelCase__       =							self.model_tester.prepare_config_and_inputs_for_common()

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

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

									check_hidden_states_output(_lowercase   ,    _lowercase   ,    _lowercase  )




			def 					snake_case__					(				self  ):

						'''simple docstring'''


						UpperCamelCase__       =							self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*_lowercase  )







			@slow
			def 					snake_case__					(				self  ):

						'''simple docstring'''


						for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									UpperCamelCase__       =							ConvNextModel.from_pretrained(_lowercase  )
									self.assertIsNotNone(_lowercase  )



def 							UpperCamelCase_(					)->		Union[str, Any]:
			UpperCamelCase__       =							Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
			return image







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






			"""simple docstring"""






			@cached_property
			def 					snake_case__					(				self  ):

						'''simple docstring'''


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







			@slow
			def 					snake_case__					(				self  ):

						'''simple docstring'''


						UpperCamelCase__       =							ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"  ).to(_lowercase  )

						UpperCamelCase__       =							self.default_image_processor
						UpperCamelCase__       =							prepare_img()
						UpperCamelCase__       =							image_processor(images=_lowercase   ,    return_tensors="pt"  ).to(_lowercase  )

						# forward pass
						with torch.no_grad():
									UpperCamelCase__       =							model(**_lowercase  )

						# verify the logits
						UpperCamelCase__       =							torch.Size((1, 1000)  )
						self.assertEqual(outputs.logits.shape   ,    _lowercase  )

						UpperCamelCase__       =							torch.tensor([-0.0260, -0.4739, 0.1911]  ).to(_lowercase  )

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







@require_torch
class 							lowerCamelCase__						(				unittest.TestCase       ,						SCREAMING_SNAKE_CASE__   ):






			"""simple docstring"""






			_UpperCamelCase		:       Optional[int] 			=		(ConvNextBackbone,) if is_torch_available() else ()
			_UpperCamelCase		:       List[str] 			=		ConvNextConfig

			_UpperCamelCase		:       Dict 			=		False




			def 					snake_case__					(				self  ):

						'''simple docstring'''


						UpperCamelCase__       =							ConvNextModelTester(self  )







"""simple docstring"""







import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
			from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
			from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
			from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


A		=						DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

A		=						'main'
# Default branch name
A		=						'f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'
# One particular commit (not the top of `main`)
A		=						'aaaaaaa'
# This commit does not exist, so we should 404.

A		=						'd9e9f15bc825e4b2c9249e9578f884bbcb5e3684'
# Sha-1 of config.json on the top of `main`, for checking purposes
A		=						'4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'

@contextlib.contextmanager
def  __SCREAMING_SNAKE_CASE		(			):
						"""simple docstring"""






						print("Welcome!" )
						yield
						print("Bye!" )

@contextlib.contextmanager
def  __SCREAMING_SNAKE_CASE		(			):
						"""simple docstring"""






						print("Bonjour!" )
						yield
						print("Au revoir!" )

class       _a  ( unittest.TestCase):



			def 				__lowercase					(			self							:				Dict		)							->					Optional[int]:
									# If the spec is missing, importlib would not be able to import the module dynamically.
									assert transformers.__spec__ is not None
									assert importlib.util.find_spec("transformers"		) is not None



class       _a  ( unittest.TestCase):



			@unittest.mock.patch("sys.stdout"   ,	new_callable=io.StringIO		)
			def 				__lowercase					(			self							:				Union[str, Any]   ,	_lowercase							:				Optional[int]		)							->					Optional[Any]:
									with ContextManagers([]		):
															print("Transformers are awesome!"		)
									# The print statement adds a new line at the end of the output
									self.assertEqual(mock_stdout.getvalue()   ,	"Transformers are awesome!\n"		)



			@unittest.mock.patch("sys.stdout"   ,	new_callable=io.StringIO		)
			def 				__lowercase					(			self							:				Any   ,	_lowercase							:				Any		)							->					Dict:
									with ContextManagers([context_en()]		):
															print("Transformers are awesome!"		)
									# The output should be wrapped with an English welcome and goodbye
									self.assertEqual(mock_stdout.getvalue()   ,	"Welcome!\nTransformers are awesome!\nBye!\n"		)



			@unittest.mock.patch("sys.stdout"   ,	new_callable=io.StringIO		)
			def 				__lowercase					(			self							:				str   ,	_lowercase							:				List[Any]		)							->					Optional[int]:
									with ContextManagers([context_fr(), context_en()]		):
															print("Transformers are awesome!"		)
									# The output should be wrapped with an English and French welcome and goodbye
									self.assertEqual(mock_stdout.getvalue()   ,	"Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n"		)



			@require_torch
			def 				__lowercase					(			self							:				Any		)							->					Union[str, Any]:
									self.assertEqual(find_labels(_lowercase		)   ,	["labels"]		)
									self.assertEqual(find_labels(_lowercase		)   ,	["labels", "next_sentence_label"]		)
									self.assertEqual(find_labels(_lowercase		)   ,	["start_positions", "end_positions"]		)

									class       _a  ( SCREAMING_SNAKE_CASE__):
												pass



									self.assertEqual(find_labels(_lowercase		)   ,	["labels"]		)



			@require_tf
			def 				__lowercase					(			self							:				Optional[Any]		)							->					int:
									self.assertEqual(find_labels(_lowercase		)   ,	["labels"]		)
									self.assertEqual(find_labels(_lowercase		)   ,	["labels", "next_sentence_label"]		)
									self.assertEqual(find_labels(_lowercase		)   ,	["start_positions", "end_positions"]		)

									class       _a  ( SCREAMING_SNAKE_CASE__):
												pass



									self.assertEqual(find_labels(_lowercase		)   ,	["labels"]		)



			@require_flax
			def 				__lowercase					(			self							:				Tuple		)							->					List[Any]:
									# Flax models don't have labels
									self.assertEqual(find_labels(_lowercase		)   ,	[]		)
									self.assertEqual(find_labels(_lowercase		)   ,	[]		)
									self.assertEqual(find_labels(_lowercase		)   ,	[]		)

									class       _a  ( SCREAMING_SNAKE_CASE__):
												pass



									self.assertEqual(find_labels(_lowercase		)   ,	[]		)



