



"""simple docstring"""

import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
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_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 ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
	from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import AutoImageProcessor




class SCREAMING_SNAKE_CASE__					:



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





													'''simple docstring'''

													__a		:		Tuple									=       parent
													__a		:		Any									=       batch_size
													__a		:		List[Any]									=       image_size
													__a		:		str									=       num_channels
													__a		:		Any									=       num_stages
													__a		:		Union[str, Any]									=       hidden_sizes
													__a		:		Optional[int]									=       depths
													__a		:		Dict									=       is_training
													__a		:		int									=       use_labels
													__a		:		str									=       intermediate_size
													__a		:		Any									=       hidden_act
													__a		:		Optional[Any]									=       num_labels
													__a		:		Any									=       initializer_range
													__a		:		Dict									=       out_features
													__a		:		Tuple									=       out_indices
													__a		:		Union[str, Any]									=       scope



						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		Any									=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

													__a		:		Optional[Any]									=       None
													if self.use_labels:
																				__a		:		Optional[int]									=       ids_tensor([self.batch_size]						,     self.num_labels							)

													__a		:		Any									=       self.get_config()

													return config, pixel_values, labels



						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													return ConvNextVaConfig(
													    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     lowerCAmelCase__(self						,     _lowercase						,     _lowercase						,     _lowercase							):





													'''simple docstring'''

													__a		:		Tuple									=       ConvNextVaModel(config=_lowercase							)
													model.to(_lowercase							)
													model.eval()
													__a		:		Tuple									=       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     lowerCAmelCase__(self						,     _lowercase						,     _lowercase						,     _lowercase							):





													'''simple docstring'''

													__a		:		str									=       ConvNextVaForImageClassification(_lowercase							)
													model.to(_lowercase							)
													model.eval()
													__a		:		Dict									=       model(_lowercase						,     labels=_lowercase							)
													self.parent.assertEqual(result.logits.shape						,     (self.batch_size, self.num_labels)							)



						def     lowerCAmelCase__(self						,     _lowercase						,     _lowercase						,     _lowercase							):





													'''simple docstring'''

													__a		:		Union[str, Any]									=       ConvNextVaBackbone(config=_lowercase							)
													model.to(_lowercase							)
													model.eval()
													__a		:		Optional[int]									=       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
													__a		:		Tuple									=       None
													__a		:		Tuple									=       ConvNextVaBackbone(config=_lowercase							)
													model.to(_lowercase							)
													model.eval()
													__a		:		List[str]									=       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     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		Dict									=       self.prepare_config_and_inputs()
													__a							,     __a							,     __a		:		Optional[int]									=       config_and_inputs
													__a		:		int									=       {"""pixel_values""": pixel_values}
													return config, inputs_dict





						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		Tuple									=       self.prepare_config_and_inputs()
													__a							,     __a							,     __a		:		List[Any]									=       config_and_inputs
													__a		:		str									=       {"""pixel_values""": pixel_values, """labels""": labels}
													return config, inputs_dict







@require_torch
class SCREAMING_SNAKE_CASE__					(		__snake_case     ,					__snake_case     ,					unittest.TestCase      ):
						_lowerCAmelCase							=					(
						    (
						        ConvNextVaModel,
						        ConvNextVaForImageClassification,
						        ConvNextVaBackbone,
						    )
						    if is_torch_available()
						    else ()
						)
						_lowerCAmelCase							=					(
						    {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification}
						    if is_torch_available()
						    else {}
						)

						_lowerCAmelCase							=					False
						_lowerCAmelCase							=					False
						_lowerCAmelCase							=					False
						_lowerCAmelCase							=					False
						_lowerCAmelCase							=					False



						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		Dict									=       ConvNextVaModelTester(self							)
													__a		:		Tuple									=       ConfigTester(self						,     config_class=_lowercase						,     has_text_modality=_lowercase						,     hidden_size=37							)



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





													'''simple docstring'''

													return



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





													'''simple docstring'''

													pass



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





													'''simple docstring'''

													pass



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





													'''simple docstring'''

													pass



						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													if not self.model_tester.is_training:
																				return

													for model_class in self.all_model_classes:
																				__a							,     __a		:		int									=       self.model_tester.prepare_config_and_inputs_with_labels()
																				__a		:		List[str]									=       True

																				if model_class.__name__ in [
																				    *get_values(_lowercase							),
																				    *get_values(_lowercase							),
																				]:
																											continue

																				__a		:		Optional[int]									=       model_class(_lowercase							)
																				model.to(_lowercase							)
																				model.train()
																				__a		:		Tuple									=       self._prepare_for_class(_lowercase						,     _lowercase						,     return_labels=_lowercase							)
																				__a		:		Dict									=       model(**_lowercase							).loss
																				loss.backward()



						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													if not self.model_tester.is_training:
																				return

													for model_class in self.all_model_classes:
																				__a							,     __a		:		List[str]									=       self.model_tester.prepare_config_and_inputs_with_labels()
																				__a		:		Optional[Any]									=       False
																				__a		:		List[Any]									=       True

																				if (
																				    model_class.__name__
																				    in [*get_values(_lowercase							), *get_values(_lowercase							)]
																				    or not model_class.supports_gradient_checkpointing
																				):
																											continue

																				__a		:		Optional[int]									=       model_class(_lowercase							)
																				model.to(_lowercase							)
																				model.gradient_checkpointing_enable()
																				model.train()
																				__a		:		Optional[int]									=       self._prepare_for_class(_lowercase						,     _lowercase						,     return_labels=_lowercase							)
																				__a		:		Any									=       model(**_lowercase							).loss
																				loss.backward()



						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a							,     __a		:		str									=       self.model_tester.prepare_config_and_inputs_for_common()

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

																				__a		:		Optional[int]									=       ["""pixel_values"""]
																				self.assertListEqual(arg_names[:1]						,     _lowercase							)



						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		Dict									=       self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*_lowercase							)



						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													def check_hidden_states_output(_lowercase						,     _lowercase						,     _lowercase							):
																				__a		:		Any									=       model_class(_lowercase							)
																				model.to(_lowercase							)
																				model.eval()

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

																				__a		:		Any									=       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																				__a		:		Optional[Any]									=       self.model_tester.num_stages
																				self.assertEqual(len(_lowercase							)						,     expected_num_stages + 1							)

																				# ConvNextV2'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]						,     )

													__a							,     __a		:		Optional[Any]									=       self.model_tester.prepare_config_and_inputs_for_common()

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

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

																				check_hidden_states_output(_lowercase						,     _lowercase						,     _lowercase							)



						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		Optional[int]									=       self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_image_classification(*_lowercase							)





						@slow
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				__a		:		Union[str, Any]									=       ConvNextVaModel.from_pretrained(_lowercase							)
																				self.assertIsNotNone(_lowercase							)







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







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



						@cached_property
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

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





						@slow
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		Dict									=       ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224"""							).to(_lowercase							)

													__a		:		Dict									=       self.default_image_processor
													__a		:		Union[str, Any]									=       prepare_img()
													__a		:		Union[str, Any]									=       preprocessor(images=_lowercase						,     return_tensors="""pt"""							).to(_lowercase							)

													# forward pass
													with torch.no_grad():
																				__a		:		List[Any]									=       model(**_lowercase							)

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

													__a		:		Any									=       torch.tensor([0.9996, 0.1966, -0.4386]							).to(_lowercase							)
													self.assertTrue(torch.allclose(outputs.logits[0, :3]						,     _lowercase						,     atol=1e-4							)							)






"""simple docstring"""

import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TextClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
lowercase__			   =  {"LayoutLMv2Config", "LayoutLMv3Config"}




@is_pipeline_test
class SCREAMING_SNAKE_CASE__					(		unittest.TestCase      ):
						_lowerCAmelCase							=					MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
						_lowerCAmelCase							=					TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

						if model_mapping is not None:
												_lowerCAmelCase							=					{config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
						if tf_model_mapping is not None:
												_lowerCAmelCase							=					{
												    config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
												}



						@require_torch
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		int									=       pipeline(
													    task="""text-classification"""						,     model="""hf-internal-testing/tiny-random-distilbert"""						,     framework="""pt"""							)

													__a		:		Tuple									=       text_classifier("""This is great !"""							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """LABEL_0""", """score""": 0.504}]							)

													__a		:		Optional[Any]									=       text_classifier("""This is great !"""						,     top_k=2							)
													self.assertEqual(
													    nested_simplify(_lowercase							)						,     [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}]							)

													__a		:		int									=       text_classifier(["""This is great !""", """This is bad"""]						,     top_k=2							)
													self.assertEqual(
													    nested_simplify(_lowercase							)						,     [
													        [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}],
													        [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}],
													    ]						,     )

													__a		:		List[str]									=       text_classifier("""This is great !"""						,     top_k=1							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """LABEL_0""", """score""": 0.504}]							)

													# Legacy behavior
													__a		:		Optional[int]									=       text_classifier("""This is great !"""						,     return_all_scores=_lowercase							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """LABEL_0""", """score""": 0.504}]							)

													__a		:		Tuple									=       text_classifier("""This is great !"""						,     return_all_scores=_lowercase							)
													self.assertEqual(
													    nested_simplify(_lowercase							)						,     [[{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}]]							)

													__a		:		Any									=       text_classifier(["""This is great !""", """Something else"""]						,     return_all_scores=_lowercase							)
													self.assertEqual(
													    nested_simplify(_lowercase							)						,     [
													        [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}],
													        [{"""label""": """LABEL_0""", """score""": 0.504}, {"""label""": """LABEL_1""", """score""": 0.496}],
													    ]						,     )

													__a		:		Union[str, Any]									=       text_classifier(["""This is great !""", """Something else"""]						,     return_all_scores=_lowercase							)
													self.assertEqual(
													    nested_simplify(_lowercase							)						,     [
													        {"""label""": """LABEL_0""", """score""": 0.504},
													        {"""label""": """LABEL_0""", """score""": 0.504},
													    ]						,     )



						@require_torch
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													import torch

													__a		:		Any									=       pipeline(
													    task="""text-classification"""						,     model="""hf-internal-testing/tiny-random-distilbert"""						,     framework="""pt"""						,     device=torch.device("""cpu"""							)						,     )

													__a		:		Optional[int]									=       text_classifier("""This is great !"""							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """LABEL_0""", """score""": 0.504}]							)



						@require_tf
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		List[Any]									=       pipeline(
													    task="""text-classification"""						,     model="""hf-internal-testing/tiny-random-distilbert"""						,     framework="""tf"""							)

													__a		:		List[str]									=       text_classifier("""This is great !"""							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """LABEL_0""", """score""": 0.504}]							)



						@slow
						@require_torch
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		Tuple									=       pipeline("""text-classification"""							)

													__a		:		Tuple									=       text_classifier("""This is great !"""							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """POSITIVE""", """score""": 1.0}]							)
													__a		:		Optional[int]									=       text_classifier("""This is bad !"""							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """NEGATIVE""", """score""": 1.0}]							)
													__a		:		Union[str, Any]									=       text_classifier("""Birds are a type of animal"""							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """POSITIVE""", """score""": 0.988}]							)



						@slow
						@require_tf
						def     lowerCAmelCase__(self							):





													'''simple docstring'''

													__a		:		List[str]									=       pipeline("""text-classification"""						,     framework="""tf"""							)

													__a		:		str									=       text_classifier("""This is great !"""							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """POSITIVE""", """score""": 1.0}]							)
													__a		:		Tuple									=       text_classifier("""This is bad !"""							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """NEGATIVE""", """score""": 1.0}]							)
													__a		:		str									=       text_classifier("""Birds are a type of animal"""							)
													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": """POSITIVE""", """score""": 0.988}]							)



						def     lowerCAmelCase__(self						,     _lowercase						,     _lowercase						,     _lowercase							):





													'''simple docstring'''

													__a		:		Dict									=       TextClassificationPipeline(model=_lowercase						,     tokenizer=_lowercase							)
													return text_classifier, ["HuggingFace is in", "This is another test"]





						def     lowerCAmelCase__(self						,     _lowercase						,     _lowercase							):





													'''simple docstring'''

													__a		:		List[str]									=       text_classifier.model
													# Small inputs because BartTokenizer tiny has maximum position embeddings = 22
													__a		:		Union[str, Any]									=       """HuggingFace is in"""
													__a		:		List[str]									=       text_classifier(_lowercase							)

													self.assertEqual(nested_simplify(_lowercase							)						,     [{"""label""": ANY(_lowercase							), """score""": ANY(_lowercase							)}]							)
													self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values()							)

													__a		:		Optional[int]									=       ["""HuggingFace is in """, """Paris is in France"""]
													__a		:		Dict									=       text_classifier(_lowercase							)
													self.assertEqual(
													    nested_simplify(_lowercase							)						,     [{"""label""": ANY(_lowercase							), """score""": ANY(_lowercase							)}, {"""label""": ANY(_lowercase							), """score""": ANY(_lowercase							)}]						,     )
													self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values()							)
													self.assertTrue(outputs[1]["""label"""] in model.config.idalabel.values()							)

													# Forcing to get all results with `top_k=None`
													# This is NOT the legacy format
													__a		:		Dict									=       text_classifier(_lowercase						,     top_k=_lowercase							)
													__a		:		Dict									=       len(model.config.idalabel.values()							)
													self.assertEqual(
													    nested_simplify(_lowercase							)						,     [[{"""label""": ANY(_lowercase							), """score""": ANY(_lowercase							)}] * N, [{"""label""": ANY(_lowercase							), """score""": ANY(_lowercase							)}] * N]						,     )

													__a		:		Dict									=       {"""text""": """HuggingFace is in """, """text_pair""": """Paris is in France"""}
													__a		:		Any									=       text_classifier(_lowercase							)
													self.assertEqual(
													    nested_simplify(_lowercase							)						,     {"""label""": ANY(_lowercase							), """score""": ANY(_lowercase							)}						,     )
													self.assertTrue(outputs["""label"""] in model.config.idalabel.values()							)

													# This might be used a text pair, but tokenizer + pipe interaction
													# makes it hard to understand that it's not using the pair properly
													# https://github.com/huggingface/transformers/issues/17305
													# We disabled this usage instead as it was outputting wrong outputs.
													__a		:		Dict									=       [["""HuggingFace is in """, """Paris is in France"""]]
													with self.assertRaises(_lowercase							):
																				text_classifier(_lowercase							)

													# This used to be valid for doing text pairs
													# We're keeping it working because of backward compatibility
													__a		:		Optional[int]									=       text_classifier([[["""HuggingFace is in """, """Paris is in France"""]]]							)
													self.assertEqual(
													    nested_simplify(_lowercase							)						,     [{"""label""": ANY(_lowercase							), """score""": ANY(_lowercase							)}]						,     )
													self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values()							)

