


'''simple docstring'''




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				:



	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.0_2 ,					snake_case__=["stage2", "stage3", "stage4"] ,					snake_case__=[2, 3, 4] ,					snake_case__=None ,					):
		lowerCAmelCase					:    Union[str, Any]      							= parent
		lowerCAmelCase					:    Tuple      							= batch_size
		lowerCAmelCase					:    List[Any]      							= image_size
		lowerCAmelCase					:    List[Any]      							= num_channels
		lowerCAmelCase					:    Optional[int]      							= num_stages
		lowerCAmelCase					:    str      							= hidden_sizes
		lowerCAmelCase					:    str      							= depths
		lowerCAmelCase					:    List[str]      							= is_training
		lowerCAmelCase					:    List[Any]      							= use_labels
		lowerCAmelCase					:    str      							= intermediate_size
		lowerCAmelCase					:    List[str]      							= hidden_act
		lowerCAmelCase					:    Union[str, Any]      							= num_labels
		lowerCAmelCase					:    Optional[Any]      							= initializer_range
		lowerCAmelCase					:    Tuple      							= out_features
		lowerCAmelCase					:    List[Any]      							= out_indices
		lowerCAmelCase					:    Optional[int]      							= scope



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    str      							= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

		lowerCAmelCase					:    Any      							= None
		if self.use_labels:
			lowerCAmelCase					:    Dict      							= ids_tensor([self.batch_size] ,					self.num_labels    )

		lowerCAmelCase					:    Any      							= self.get_config()
		return config, pixel_values, labels



	def 				lowercase     (					self    ):
		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=snake_case__ ,					initializer_range=self.initializer_range ,					out_features=self.out_features ,					out_indices=self.out_indices ,					num_labels=self.num_labels ,					)



	def 				lowercase     (					self ,					snake_case__ ,					snake_case__ ,					snake_case__    ):
		lowerCAmelCase					:    str      							= ConvNextModel(config=snake_case__    )
		model.to(snake_case__    )
		model.eval()
		lowerCAmelCase					:    str      							= model(snake_case__    )
		# 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 				lowercase     (					self ,					snake_case__ ,					snake_case__ ,					snake_case__    ):
		lowerCAmelCase					:    List[str]      							= ConvNextForImageClassification(snake_case__    )
		model.to(snake_case__    )
		model.eval()
		lowerCAmelCase					:    int      							= model(snake_case__ ,					labels=snake_case__    )
		self.parent.assertEqual(result.logits.shape ,					(self.batch_size, self.num_labels)    )



	def 				lowercase     (					self ,					snake_case__ ,					snake_case__ ,					snake_case__    ):
		lowerCAmelCase					:    List[Any]      							= ConvNextBackbone(config=snake_case__    )
		model.to(snake_case__    )
		model.eval()
		lowerCAmelCase					:    Tuple      							= model(snake_case__    )

		# 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					:    Dict      							= None
		lowerCAmelCase					:    Any      							= ConvNextBackbone(config=snake_case__    )
		model.to(snake_case__    )
		model.eval()
		lowerCAmelCase					:    List[Any]      							= model(snake_case__    )

		# 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 				lowercase     (					self    ):
		lowerCAmelCase					:    Tuple      							= self.prepare_config_and_inputs()
		lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase					:    Optional[int]      							= config_and_inputs
		lowerCAmelCase					:    List[Any]      							= {'pixel_values': pixel_values}
		return config, inputs_dict



@require_torch
class  lowerCAmelCase				(				a      ,				a      ,				unittest.TestCase							):
	_lowerCamelCase   :					Any			      = (
	    (
	        ConvNextModel,
	        ConvNextForImageClassification,
	        ConvNextBackbone,
	    )
	    if is_torch_available()
	    else ()
	)
	_lowerCamelCase   :					Union[str, Any]			      = (
	    {"""feature-extraction""": ConvNextModel, """image-classification""": ConvNextForImageClassification}
	    if is_torch_available()
	    else {}
	)

	_lowerCamelCase   :					Union[str, Any]			      = True
	_lowerCamelCase   :					List[str]			      = False
	_lowerCamelCase   :					Dict			      = False
	_lowerCamelCase   :					str			      = False
	_lowerCamelCase   :					List[str]			      = False



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    List[Any]      							= ConvNextModelTester(self    )
		lowerCAmelCase					:    Optional[Any]      							= ConfigTester(self ,					config_class=snake_case__ ,					has_text_modality=snake_case__ ,					hidden_size=37    )



	def 				lowercase     (					self    ):
		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 				lowercase     (					self    ):
		return



	@unittest.skip(reason='ConvNext does not use inputs_embeds'    )
	def 				lowercase     (					self    ):
		pass



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



	@unittest.skip(reason='ConvNext does not use feedforward chunking'    )
	def 				lowercase     (					self    ):
		pass



	def 				lowercase     (					self    ):
		lowerCAmelCase							,   lowerCAmelCase					:    str      							= self.model_tester.prepare_config_and_inputs_for_common()

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

			lowerCAmelCase					:    int      							= ['pixel_values']
			self.assertListEqual(arg_names[:1] ,					snake_case__    )



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    List[Any]      							= self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_model(*snake_case__    )



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    str      							= self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_backbone(*snake_case__    )



	def 				lowercase     (					self    ):
		def check_hidden_states_output(snake_case__ ,					snake_case__ ,					snake_case__    ):
			lowerCAmelCase					:    Optional[Any]      							= model_class(snake_case__    )
			model.to(snake_case__    )
			model.eval()

			with torch.no_grad():
				lowerCAmelCase					:    Dict      							= model(**self._prepare_for_class(snake_case__ ,					snake_case__    )    )

			lowerCAmelCase					:    Tuple      							= outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

			lowerCAmelCase					:    List[str]      							= self.model_tester.num_stages
			self.assertEqual(len(snake_case__    ) ,					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					:    List[str]      							= self.model_tester.prepare_config_and_inputs_for_common()

		for model_class in self.all_model_classes:
			lowerCAmelCase					:    int      							= True
			check_hidden_states_output(snake_case__ ,					snake_case__ ,					snake_case__    )

			# check that output_hidden_states also work using config
			del inputs_dict["output_hidden_states"]
			lowerCAmelCase					:    Tuple      							= True

			check_hidden_states_output(snake_case__ ,					snake_case__ ,					snake_case__    )



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Optional[Any]      							= self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_for_image_classification(*snake_case__    )



	@slow
	def 				lowercase     (					self    ):
		for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
			lowerCAmelCase					:    Union[str, Any]      							= ConvNextModel.from_pretrained(snake_case__    )
			self.assertIsNotNone(snake_case__    )


def 			__UpperCamelCase    (    )    ->      int:




	"""simple docstring"""





	lowerCAmelCase					:    List[Any]      							= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
	return image



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



	@cached_property
	def 				lowercase     (					self    ):
		return AutoImageProcessor.from_pretrained('facebook/convnext-tiny-224'    ) if is_vision_available() else None



	@slow
	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Optional[int]      							= ConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'    ).to(snake_case__    )

		lowerCAmelCase					:    Union[str, Any]      							= self.default_image_processor
		lowerCAmelCase					:    str      							= prepare_img()
		lowerCAmelCase					:    Union[str, Any]      							= image_processor(images=snake_case__ ,					return_tensors='pt'    ).to(snake_case__    )

		# forward pass
		with torch.no_grad():
			lowerCAmelCase					:    Union[str, Any]      							= model(**snake_case__    )

		# verify the logits
		lowerCAmelCase					:    Optional[int]      							= torch.Size((1, 1000)    )
		self.assertEqual(outputs.logits.shape ,					snake_case__    )

		lowerCAmelCase					:    Any      							= torch.tensor([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1]    ).to(snake_case__    )

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



@require_torch
class  lowerCAmelCase				(				unittest.TestCase      ,				a							):
	_lowerCamelCase   :					int			      = (ConvNextBackbone,) if is_torch_available() else ()
	_lowerCamelCase   :					int			      = ConvNextConfig

	_lowerCamelCase   :					int			      = False



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    str      							= ConvNextModelTester(self    )




'''simple docstring'''




from collections import OrderedDict
from typing import Mapping

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


_lowerCAmelCase  :		Any		     =	logging.get_logger(__name__)

_lowerCAmelCase  :		List[str]		     =	{
    'xlm-roberta-base': 'https://huggingface.co/xlm-roberta-base/resolve/main/config.json',
    'xlm-roberta-large': 'https://huggingface.co/xlm-roberta-large/resolve/main/config.json',
    'xlm-roberta-large-finetuned-conll02-dutch': (
        'https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json'
    ),
    'xlm-roberta-large-finetuned-conll02-spanish': (
        'https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json'
    ),
    'xlm-roberta-large-finetuned-conll03-english': (
        'https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json'
    ),
    'xlm-roberta-large-finetuned-conll03-german': (
        'https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json'
    ),
}



class  lowerCAmelCase				(				a							):
	_lowerCamelCase   :					List[str]			      = """xlm-roberta"""



	def __init__(					self ,					snake_case__=3_0522 ,					snake_case__=768 ,					snake_case__=12 ,					snake_case__=12 ,					snake_case__=3072 ,					snake_case__="gelu" ,					snake_case__=0.1 ,					snake_case__=0.1 ,					snake_case__=512 ,					snake_case__=2 ,					snake_case__=0.0_2 ,					snake_case__=1e-1_2 ,					snake_case__=1 ,					snake_case__=0 ,					snake_case__=2 ,					snake_case__="absolute" ,					snake_case__=True ,					snake_case__=None ,					**snake_case__ ,					):
		super().__init__(pad_token_id=snake_case__ ,					bos_token_id=snake_case__ ,					eos_token_id=snake_case__ ,					**snake_case__    )

		lowerCAmelCase					:    Optional[Any]      							= vocab_size
		lowerCAmelCase					:    Optional[Any]      							= hidden_size
		lowerCAmelCase					:    Optional[Any]      							= num_hidden_layers
		lowerCAmelCase					:    Any      							= num_attention_heads
		lowerCAmelCase					:    Optional[int]      							= hidden_act
		lowerCAmelCase					:    Optional[int]      							= intermediate_size
		lowerCAmelCase					:    Dict      							= hidden_dropout_prob
		lowerCAmelCase					:    Union[str, Any]      							= attention_probs_dropout_prob
		lowerCAmelCase					:    Optional[Any]      							= max_position_embeddings
		lowerCAmelCase					:    Optional[int]      							= type_vocab_size
		lowerCAmelCase					:    int      							= initializer_range
		lowerCAmelCase					:    List[Any]      							= layer_norm_eps
		lowerCAmelCase					:    Union[str, Any]      							= position_embedding_type
		lowerCAmelCase					:    Union[str, Any]      							= use_cache
		lowerCAmelCase					:    List[str]      							= classifier_dropout



class  lowerCAmelCase				(				a							):



	@property
	def 				lowercase     (					self    ):
		if self.task == "multiple-choice":
			lowerCAmelCase					:    str      							= {0: 'batch', 1: 'choice', 2: 'sequence'}
		else:
			lowerCAmelCase					:    Optional[int]      							= {0: 'batch', 1: 'sequence'}
		return OrderedDict(
		    [
		        ('input_ids', dynamic_axis),
		        ('attention_mask', dynamic_axis),
		    ]    )
