


'''simple docstring'''






import copy
from typing import Dict, List, Optional

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


__UpperCAmelCase       =							{
    '''facebook/mask2former-swin-small-coco-instance''': (
        '''https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json'''
    )
    # See all Mask2Former models at https://huggingface.co/models?filter=mask2former
}

__UpperCAmelCase       =							logging.get_logger(__name__)




class 		a__    (							a__  ):





							'''simple docstring'''






							lowercase__      :       Union[str, Any]     						=				"mask2former"
							lowercase__      :       Dict     						=				["swin"]
							lowercase__      :       List[Any]     						=				{"hidden_size": "hidden_dim"}







							def __init__(		self ,   lowerCamelCase_ = None ,   lowerCamelCase_ = 2_56 ,   lowerCamelCase_ = 2_56 ,   lowerCamelCase_ = 2_56 ,   lowerCamelCase_ = 10_24 ,   lowerCamelCase_ = "relu" ,   lowerCamelCase_ = 6 ,   lowerCamelCase_ = 10 ,   lowerCamelCase_ = 8 ,   lowerCamelCase_ = 0.0 ,   lowerCamelCase_ = 20_48 ,   lowerCamelCase_ = False ,   lowerCamelCase_ = False ,   lowerCamelCase_ = 4 ,   lowerCamelCase_ = 2_55 ,   lowerCamelCase_ = 1_00 ,   lowerCamelCase_ = 0.1 ,   lowerCamelCase_ = 2.0 ,   lowerCamelCase_ = 5.0 ,   lowerCamelCase_ = 5.0 ,   lowerCamelCase_ = 1_25_44 ,   lowerCamelCase_ = 3.0 ,   lowerCamelCase_ = 0.75 ,   lowerCamelCase_ = 0.02 ,   lowerCamelCase_ = 1.0 ,   lowerCamelCase_ = True ,   lowerCamelCase_ = [4, 8, 16, 32] ,   lowerCamelCase_ = None ,   **lowerCamelCase_ ,   )	->							Optional[Any]:
														if backbone_config is None:
																					logger.info('''`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.'''       )
																					lowerCAmelCase__	       =     CONFIG_MAPPING['''swin'''](
																					    image_size=2_24 ,   in_channels=3 ,   patch_size=4 ,   embed_dim=96 ,   depths=[2, 2, 18, 2] ,   num_heads=[3, 6, 12, 24] ,   window_size=7 ,   drop_path_rate=0.3 ,   use_absolute_embeddings=lowerCamelCase_ ,   out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] ,   )

														if isinstance(lowerCamelCase_ ,   lowerCamelCase_       ):
																					lowerCAmelCase__	       =     backbone_config.pop('''model_type'''       )
																					lowerCAmelCase__	       =     CONFIG_MAPPING[backbone_model_type]
																					lowerCAmelCase__	       =     config_class.from_dict(lowerCamelCase_       )

														# verify that the backbone is supported
														if backbone_config.model_type not in self.backbones_supported:
																					logger.warning_once(
																					    F"""Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. """
																					    F"""Supported model types: {",".join(self.backbones_supported       )}"""       )

														lowerCAmelCase__	       =     backbone_config
														lowerCAmelCase__	       =     feature_size
														lowerCAmelCase__	       =     mask_feature_size
														lowerCAmelCase__	       =     hidden_dim
														lowerCAmelCase__	       =     encoder_feedforward_dim
														lowerCAmelCase__	       =     activation_function
														lowerCAmelCase__	       =     encoder_layers
														lowerCAmelCase__	       =     decoder_layers
														lowerCAmelCase__	       =     num_attention_heads
														lowerCAmelCase__	       =     dropout
														lowerCAmelCase__	       =     dim_feedforward
														lowerCAmelCase__	       =     pre_norm
														lowerCAmelCase__	       =     enforce_input_projection
														lowerCAmelCase__	       =     common_stride
														lowerCAmelCase__	       =     ignore_value
														lowerCAmelCase__	       =     num_queries
														lowerCAmelCase__	       =     no_object_weight
														lowerCAmelCase__	       =     class_weight
														lowerCAmelCase__	       =     mask_weight
														lowerCAmelCase__	       =     dice_weight
														lowerCAmelCase__	       =     train_num_points
														lowerCAmelCase__	       =     oversample_ratio
														lowerCAmelCase__	       =     importance_sample_ratio
														lowerCAmelCase__	       =     init_std
														lowerCAmelCase__	       =     init_xavier_std
														lowerCAmelCase__	       =     use_auxiliary_loss
														lowerCAmelCase__	       =     feature_strides
														lowerCAmelCase__	       =     output_auxiliary_logits
														lowerCAmelCase__	       =     decoder_layers

														super().__init__(**lowerCamelCase_       )







							@classmethod
							def   __SCREAMING_SNAKE_CASE							(		cls ,   lowerCamelCase_ ,   **lowerCamelCase_       )	->							List[str]:
														return cls(
														    backbone_config=lowerCamelCase_ ,   **lowerCamelCase_ ,   )







							def   __SCREAMING_SNAKE_CASE							(		self       )	->							Dict[str, any]:
														lowerCAmelCase__	       =     copy.deepcopy(self.__dict__       )
														lowerCAmelCase__	       =     self.backbone_config.to_dict()
														lowerCAmelCase__	       =     self.__class__.model_type
														return output



'''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.
__UpperCAmelCase       =							{'''LayoutLMv2Config''', '''LayoutLMv3Config'''}




@is_pipeline_test
class 		a__    (							unittest.TestCase  ):





							'''simple docstring'''






							lowercase__      :       Optional[Any]     						=				MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
							lowercase__      :       List[Any]     						=				TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

							if model_mapping is not None:
														lowercase__      :       Optional[Any]     						=				{config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
							if tf_model_mapping is not None:
														lowercase__      :       Tuple     						=				{
														    config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
														}







							@require_torch
							def   __SCREAMING_SNAKE_CASE							(		self       )	->							Optional[int]:
														lowerCAmelCase__	       =     pipeline(
														    task='''text-classification''' ,   model='''hf-internal-testing/tiny-random-distilbert''' ,   framework='''pt'''       )

														lowerCAmelCase__	       =     text_classifier('''This is great !'''       )
														self.assertEqual(nested_simplify(lowerCamelCase_       ) ,   [{'''label''': '''LABEL_0''', '''score''': 0.504}]       )

														lowerCAmelCase__	       =     text_classifier('''This is great !''' ,   top_k=2       )
														self.assertEqual(
														    nested_simplify(lowerCamelCase_       ) ,   [{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}]       )

														lowerCAmelCase__	       =     text_classifier(['''This is great !''', '''This is bad'''] ,   top_k=2       )
														self.assertEqual(
														    nested_simplify(lowerCamelCase_       ) ,   [
														        [{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}],
														        [{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}],
														    ] ,   )

														lowerCAmelCase__	       =     text_classifier('''This is great !''' ,   top_k=1       )
														self.assertEqual(nested_simplify(lowerCamelCase_       ) ,   [{'''label''': '''LABEL_0''', '''score''': 0.504}]       )

														# Legacy behavior
														lowerCAmelCase__	       =     text_classifier('''This is great !''' ,   return_all_scores=lowerCamelCase_       )
														self.assertEqual(nested_simplify(lowerCamelCase_       ) ,   [{'''label''': '''LABEL_0''', '''score''': 0.504}]       )

														lowerCAmelCase__	       =     text_classifier('''This is great !''' ,   return_all_scores=lowerCamelCase_       )
														self.assertEqual(
														    nested_simplify(lowerCamelCase_       ) ,   [[{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}]]       )

														lowerCAmelCase__	       =     text_classifier(['''This is great !''', '''Something else'''] ,   return_all_scores=lowerCamelCase_       )
														self.assertEqual(
														    nested_simplify(lowerCamelCase_       ) ,   [
														        [{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}],
														        [{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}],
														    ] ,   )

														lowerCAmelCase__	       =     text_classifier(['''This is great !''', '''Something else'''] ,   return_all_scores=lowerCamelCase_       )
														self.assertEqual(
														    nested_simplify(lowerCamelCase_       ) ,   [
														        {'''label''': '''LABEL_0''', '''score''': 0.504},
														        {'''label''': '''LABEL_0''', '''score''': 0.504},
														    ] ,   )







							@require_torch
							def   __SCREAMING_SNAKE_CASE							(		self       )	->							int:
														import torch

														lowerCAmelCase__	       =     pipeline(
														    task='''text-classification''' ,   model='''hf-internal-testing/tiny-random-distilbert''' ,   framework='''pt''' ,   device=torch.device('''cpu'''       ) ,   )

														lowerCAmelCase__	       =     text_classifier('''This is great !'''       )
														self.assertEqual(nested_simplify(lowerCamelCase_       ) ,   [{'''label''': '''LABEL_0''', '''score''': 0.504}]       )







							@require_tf
							def   __SCREAMING_SNAKE_CASE							(		self       )	->							str:
														lowerCAmelCase__	       =     pipeline(
														    task='''text-classification''' ,   model='''hf-internal-testing/tiny-random-distilbert''' ,   framework='''tf'''       )

														lowerCAmelCase__	       =     text_classifier('''This is great !'''       )
														self.assertEqual(nested_simplify(lowerCamelCase_       ) ,   [{'''label''': '''LABEL_0''', '''score''': 0.504}]       )







							@slow
							@require_torch
							def   __SCREAMING_SNAKE_CASE							(		self       )	->							Dict:
														lowerCAmelCase__	       =     pipeline('''text-classification'''       )

														lowerCAmelCase__	       =     text_classifier('''This is great !'''       )
														self.assertEqual(nested_simplify(lowerCamelCase_       ) ,   [{'''label''': '''POSITIVE''', '''score''': 1.0}]       )
														lowerCAmelCase__	       =     text_classifier('''This is bad !'''       )
														self.assertEqual(nested_simplify(lowerCamelCase_       ) ,   [{'''label''': '''NEGATIVE''', '''score''': 1.0}]       )
														lowerCAmelCase__	       =     text_classifier('''Birds are a type of animal'''       )
														self.assertEqual(nested_simplify(lowerCamelCase_       ) ,   [{'''label''': '''POSITIVE''', '''score''': 0.988}]       )







							@slow
							@require_tf
							def   __SCREAMING_SNAKE_CASE							(		self       )	->							Optional[Any]:
														lowerCAmelCase__	       =     pipeline('''text-classification''' ,   framework='''tf'''       )

														lowerCAmelCase__	       =     text_classifier('''This is great !'''       )
														self.assertEqual(nested_simplify(lowerCamelCase_       ) ,   [{'''label''': '''POSITIVE''', '''score''': 1.0}]       )
														lowerCAmelCase__	       =     text_classifier('''This is bad !'''       )
														self.assertEqual(nested_simplify(lowerCamelCase_       ) ,   [{'''label''': '''NEGATIVE''', '''score''': 1.0}]       )
														lowerCAmelCase__	       =     text_classifier('''Birds are a type of animal'''       )
														self.assertEqual(nested_simplify(lowerCamelCase_       ) ,   [{'''label''': '''POSITIVE''', '''score''': 0.988}]       )







							def   __SCREAMING_SNAKE_CASE							(		self ,   lowerCamelCase_ ,   lowerCamelCase_ ,   lowerCamelCase_       )	->							Tuple:
														lowerCAmelCase__	       =     TextClassificationPipeline(model=lowerCamelCase_ ,   tokenizer=lowerCamelCase_       )
														return text_classifier, ["HuggingFace is in", "This is another test"]







							def   __SCREAMING_SNAKE_CASE							(		self ,   lowerCamelCase_ ,   lowerCamelCase_       )	->							Union[str, Any]:
														lowerCAmelCase__	       =     text_classifier.model
														# Small inputs because BartTokenizer tiny has maximum position embeddings = 22
														lowerCAmelCase__	       =     '''HuggingFace is in'''
														lowerCAmelCase__	       =     text_classifier(lowerCamelCase_       )

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

														lowerCAmelCase__	       =     ['''HuggingFace is in ''', '''Paris is in France''']
														lowerCAmelCase__	       =     text_classifier(lowerCamelCase_       )
														self.assertEqual(
														    nested_simplify(lowerCamelCase_       ) ,   [{'''label''': ANY(lowerCamelCase_       ), '''score''': ANY(lowerCamelCase_       )}, {'''label''': ANY(lowerCamelCase_       ), '''score''': ANY(lowerCamelCase_       )}] ,   )
														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
														lowerCAmelCase__	       =     text_classifier(lowerCamelCase_ ,   top_k=lowerCamelCase_       )
														lowerCAmelCase__	       =     len(model.config.idalabel.values()       )
														self.assertEqual(
														    nested_simplify(lowerCamelCase_       ) ,   [[{'''label''': ANY(lowerCamelCase_       ), '''score''': ANY(lowerCamelCase_       )}] * N, [{'''label''': ANY(lowerCamelCase_       ), '''score''': ANY(lowerCamelCase_       )}] * N] ,   )

														lowerCAmelCase__	       =     {'''text''': '''HuggingFace is in ''', '''text_pair''': '''Paris is in France'''}
														lowerCAmelCase__	       =     text_classifier(lowerCamelCase_       )
														self.assertEqual(
														    nested_simplify(lowerCamelCase_       ) ,   {'''label''': ANY(lowerCamelCase_       ), '''score''': ANY(lowerCamelCase_       )} ,   )
														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.
														lowerCAmelCase__	       =     [['''HuggingFace is in ''', '''Paris is in France''']]
														with self.assertRaises(lowerCamelCase_       ):
																					text_classifier(lowerCamelCase_       )

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