






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

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







							'''simple docstring'''





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

	def 		UpperCAmelCase  (							self       )->					str:







							'''simple docstring'''





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

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

	def 		UpperCAmelCase  (							self       )->					int:







							'''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=__UpperCAmelCase		,    initializer_range=self.initializer_range		,    out_features=self.out_features		,    out_indices=self.out_indices		,    num_labels=self.num_labels		,    )

	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase		,    __UpperCAmelCase		,    __UpperCAmelCase       )->					Tuple:







							'''simple docstring'''





							lowerCAmelCase__       =						ConvNextModel(config=__UpperCAmelCase       )
							model.to(__UpperCAmelCase       )
							model.eval()
							lowerCAmelCase__       =						model(__UpperCAmelCase       )
							# 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 		UpperCAmelCase  (							self		,    __UpperCAmelCase		,    __UpperCAmelCase		,    __UpperCAmelCase       )->					Union[str, Any]:







							'''simple docstring'''





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

	def 		UpperCAmelCase  (							self		,    __UpperCAmelCase		,    __UpperCAmelCase		,    __UpperCAmelCase       )->					Tuple:







							'''simple docstring'''





							lowerCAmelCase__       =						ConvNextBackbone(config=__UpperCAmelCase       )
							model.to(__UpperCAmelCase       )
							model.eval()
							lowerCAmelCase__       =						model(__UpperCAmelCase       )

							# 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
							lowerCAmelCase__       =						None
							lowerCAmelCase__       =						ConvNextBackbone(config=__UpperCAmelCase       )
							model.to(__UpperCAmelCase       )
							model.eval()
							lowerCAmelCase__       =						model(__UpperCAmelCase       )

							# 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 		UpperCAmelCase  (							self       )->					Optional[Any]:







							'''simple docstring'''





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





@require_torch
class      lowercase__     (			_UpperCAmelCase,					_UpperCAmelCase,					unittest.TestCase	):
	a_         =(
	    (
	        ConvNextModel,
	        ConvNextForImageClassification,
	        ConvNextBackbone,
	    )
	    if is_torch_available()
	    else ()
	)
	a_         =(
	    {"""feature-extraction""": ConvNextModel, """image-classification""": ConvNextForImageClassification}
	    if is_torch_available()
	    else {}
	)

	a_         =True
	a_         =False
	a_         =False
	a_         =False
	a_         =False

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







							'''simple docstring'''





							lowerCAmelCase__       =						ConvNextModelTester(self       )
							lowerCAmelCase__       =						ConfigTester(self		,    config_class=__UpperCAmelCase		,    has_text_modality=__UpperCAmelCase		,    hidden_size=37       )

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







							'''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 		UpperCAmelCase  (							self       )->					Optional[Any]:







							'''simple docstring'''





							return

	@unittest.skip(reason="ConvNext does not use inputs_embeds"       )
	def 		UpperCAmelCase  (							self       )->					str:







							'''simple docstring'''





							pass

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







							'''simple docstring'''





							pass

	@unittest.skip(reason="ConvNext does not use feedforward chunking"       )
	def 		UpperCAmelCase  (							self       )->					str:







							'''simple docstring'''





							pass

	def 		UpperCAmelCase  (							self       )->					Optional[Any]:







							'''simple docstring'''





							lowerCAmelCase__      ,							lowerCAmelCase__       =						self.model_tester.prepare_config_and_inputs_for_common()

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

													lowerCAmelCase__       =						["pixel_values"]
													self.assertListEqual(arg_names[:1]		,    __UpperCAmelCase       )

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







							'''simple docstring'''





							lowerCAmelCase__       =						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__UpperCAmelCase       )

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







							'''simple docstring'''





							lowerCAmelCase__       =						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_backbone(*__UpperCAmelCase       )

	def 		UpperCAmelCase  (							self       )->					str:







							'''simple docstring'''





							def check_hidden_states_output(__UpperCAmelCase		,    __UpperCAmelCase		,    __UpperCAmelCase       ):
													lowerCAmelCase__       =						model_class(__UpperCAmelCase       )
													model.to(__UpperCAmelCase       )
													model.eval()

													with torch.no_grad():
																			lowerCAmelCase__       =						model(**self._prepare_for_class(__UpperCAmelCase		,    __UpperCAmelCase       )       )

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

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

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

													check_hidden_states_output(__UpperCAmelCase		,    __UpperCAmelCase		,    __UpperCAmelCase       )

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







							'''simple docstring'''





							lowerCAmelCase__       =						self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase       )


	@slow
	def 		UpperCAmelCase  (							self       )->					Union[str, Any]:







							'''simple docstring'''





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





def        _a  (     ) ->   Optional[Any]:
						"""simple docstring"""







						lowerCAmelCase__       =						Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"   )
						return image


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

	@cached_property
	def 		UpperCAmelCase  (							self       )->					Optional[int]:







							'''simple docstring'''





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


	@slow
	def 		UpperCAmelCase  (							self       )->					List[Any]:







							'''simple docstring'''





							lowerCAmelCase__       =						ConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"       ).to(__UpperCAmelCase       )

							lowerCAmelCase__       =						self.default_image_processor
							lowerCAmelCase__       =						prepare_img()
							lowerCAmelCase__       =						image_processor(images=__UpperCAmelCase		,    return_tensors="pt"       ).to(__UpperCAmelCase       )

							# forward pass
							with torch.no_grad():
													lowerCAmelCase__       =						model(**__UpperCAmelCase       )

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

							lowerCAmelCase__       =						torch.tensor([-0.0_260, -0.4_739, 0.1_911]       ).to(__UpperCAmelCase       )

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





@require_torch
class      lowercase__     (			unittest.TestCase,					_UpperCAmelCase	):
	a_         =(ConvNextBackbone,) if is_torch_available() else ()
	a_         =ConvNextConfig

	a_         =False

	def 		UpperCAmelCase  (							self       )->					Optional[Any]:







							'''simple docstring'''





							lowerCAmelCase__       =						ConvNextModelTester(self       )














from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_tokenizers_available,
    is_torch_available,
)


a_							=    {'''configuration_plbart''': ['''PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''PLBartConfig''']}

try:
	if not is_sentencepiece_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	a_							=    ['''PLBartTokenizer''']

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	a_							=    [
	    '''PLBART_PRETRAINED_MODEL_ARCHIVE_LIST''',
	    '''PLBartForCausalLM''',
	    '''PLBartForConditionalGeneration''',
	    '''PLBartForSequenceClassification''',
	    '''PLBartModel''',
	    '''PLBartPreTrainedModel''',
	]


if TYPE_CHECKING:
	from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig

	try:
		if not is_sentencepiece_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .tokenization_plbart import PLBartTokenizer

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_plbart import (
		    PLBART_PRETRAINED_MODEL_ARCHIVE_LIST,
		    PLBartForCausalLM,
		    PLBartForConditionalGeneration,
		    PLBartForSequenceClassification,
		    PLBartModel,
		    PLBartPreTrainedModel,
		)


else:
	import sys

	a_							=    _LazyModule(__name__, globals()['''__file__'''], _import_structure)






