





'''simple docstring'''






from sklearn.metrics import matthews_corrcoef

import datasets


__UpperCamelCase					    =	"\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false positives and negatives and is generally\nregarded as a balanced measure which can be used even if the classes are of\nvery different sizes. The MCC is in essence a correlation coefficient value\nbetween -1 and +1. A coefficient of +1 represents a perfect prediction, 0\nan average random prediction and -1 an inverse prediction.  The statistic\nis also known as the phi coefficient. [source: Wikipedia]\n"

__UpperCamelCase					    =	"\nArgs:\n    predictions (list of int): Predicted labels, as returned by a model.\n    references (list of int): Ground truth labels.\n    sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.\nReturns:\n    matthews_correlation (dict containing float): Matthews correlation.\nExamples:\n    Example 1, a basic example with only predictions and references as inputs:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3])\n        >>> print(round(results['matthews_correlation'], 2))\n        0.54\n\n    Example 2, the same example as above, but also including sample weights:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 3, 1, 1, 1, 2])\n        >>> print(round(results['matthews_correlation'], 2))\n        0.1\n\n    Example 3, the same example as above, but with sample weights that cause a negative correlation:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 1, 0, 0, 0, 1])\n        >>> print(round(results['matthews_correlation'], 2))\n        -0.25\n"

__UpperCamelCase					    =	"\\n@article{scikit-learn,\n  title={Scikit-learn: Machine Learning in {P}ython},\n  author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n  journal={Journal of Machine Learning Research},\n  volume={12},\n  pages={2825--2830},\n  year={2011}\n}\n"




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,					_KWARGS_DESCRIPTION		)
class  _A (					datasets.Metric		):

		def 	lowercase__     (   self					:   Tuple			)					->    Dict:


					"""simple docstring"""

					return datasets.MetricInfo(
					    description=_DESCRIPTION  ,      citation=_CITATION  ,      inputs_description=_KWARGS_DESCRIPTION  ,      features=datasets.Features(
					        {
					            """predictions""": datasets.Value("""int32"""			),
					            """references""": datasets.Value("""int32"""			),
					        }			)  ,      reference_urls=[
					        """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html"""
					    ]  ,      )

		def 	lowercase__     (   self					:   List[Any]  ,      __magic_name__					:   Tuple  ,      __magic_name__					:   List[Any]  ,      __magic_name__					:   Union[str, Any]=None			)					->    Optional[int]:


					"""simple docstring"""

					return {
					    "matthews_correlation": float(matthews_corrcoef(__magic_name__  ,      __magic_name__  ,      sample_weight=__magic_name__			)			),
					}






'''simple docstring'''


import inspect
import unittest

from transformers import ViTHybridConfig
from transformers.testing_utils import require_accelerate, 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, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch
      from torch import nn

      from transformers import ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel
      from transformers.models.vit_hybrid.modeling_vit_hybrid import VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image







class 							__magic_name__	:

     """simple docstring"""






     def __init__(   self			,     lowerCamelCase			,     lowerCamelCase=13			,     lowerCamelCase=64			,     lowerCamelCase=2			,     lowerCamelCase=3			,     lowerCamelCase=True			,     lowerCamelCase=True			,     lowerCamelCase=32			,     lowerCamelCase=5			,     lowerCamelCase=4			,     lowerCamelCase=37			,     lowerCamelCase="gelu"			,     lowerCamelCase=0.1			,     lowerCamelCase=0.1			,     lowerCamelCase=10			,     lowerCamelCase=0.02			,     lowerCamelCase=[1, 16, 4, 4]			,     lowerCamelCase=None			,     ):


          '''simple docstring'''





          __A	:       Any      =							parent
          __A	:       Union[str, Any]      =							batch_size
          __A	:       Any      =							image_size
          __A	:       Dict      =							patch_size
          __A	:       Dict      =							num_channels
          __A	:       Dict      =							is_training
          __A	:       Optional[Any]      =							use_labels
          __A	:       Any      =							hidden_size
          __A	:       Optional[Any]      =							num_hidden_layers
          __A	:       Optional[int]      =							num_attention_heads
          __A	:       str      =							intermediate_size
          __A	:       int      =							hidden_act
          __A	:       Any      =							hidden_dropout_prob
          __A	:       int      =							attention_probs_dropout_prob
          __A	:       Any      =							type_sequence_label_size
          __A	:       Union[str, Any]      =							initializer_range
          __A	:       Dict      =							scope
          __A	:       Union[str, Any]      =							backbone_featmap_shape

          # in ViT hybrid, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
          # the number of patches is based on the feature map of the backbone, which by default uses an output stride
          # of 32, which means that the feature map has a spatial resolution of 1/32 of the input image size
          __A	:       int      =							(self.image_size // 32) ** 2
          __A	:       Union[str, Any]      =							num_patches + 1


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A	:       str      =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

          __A	:       Any      =							None
          if self.use_labels:
               __A	:       Optional[Any]      =							ids_tensor([self.batch_size]			,     self.type_sequence_label_size		)

          __A	:       Any      =							self.get_config()

          return config, pixel_values, labels


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A	:       Union[str, Any]      =							{
              "global_padding": "same",
              "layer_type": "bottleneck",
              "depths": [3, 4, 9],
              "out_features": ["stage1", "stage2", "stage3"],
              "embedding_dynamic_padding": True,
              "hidden_sizes": [4, 8, 16, 32],
              "num_groups": 2,
          }

          return ViTHybridConfig(
              image_size=self.image_size			,     patch_size=self.patch_size			,     num_channels=self.num_channels			,     hidden_size=self.hidden_size			,     num_hidden_layers=self.num_hidden_layers			,     num_attention_heads=self.num_attention_heads			,     intermediate_size=self.intermediate_size			,     hidden_act=self.hidden_act			,     hidden_dropout_prob=self.hidden_dropout_prob			,     attention_probs_dropout_prob=self.attention_probs_dropout_prob			,     is_decoder=lowerCamelCase			,     initializer_range=self.initializer_range			,     backbone_featmap_shape=self.backbone_featmap_shape			,     backbone_config=lowerCamelCase			,     )


     def lowerCAmelCase__  (   self			,     lowerCamelCase			,     lowerCamelCase			,     lowerCamelCase		):


          '''simple docstring'''





          __A	:       int      =							ViTHybridModel(config=lowerCamelCase		)
          model.to(lowerCamelCase		)
          model.eval()
          __A	:       Optional[Any]      =							model(lowerCamelCase		)
          self.parent.assertEqual(result.last_hidden_state.shape			,     (self.batch_size, self.seq_length, self.hidden_size)		)


     def lowerCAmelCase__  (   self			,     lowerCamelCase			,     lowerCamelCase			,     lowerCamelCase		):


          '''simple docstring'''





          __A	:       Any      =							self.type_sequence_label_size
          __A	:       int      =							ViTHybridForImageClassification(lowerCamelCase		)
          model.to(lowerCamelCase		)
          model.eval()
          __A	:       Any      =							model(lowerCamelCase			,     labels=lowerCamelCase		)
          self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.type_sequence_label_size)		)


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





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







@require_torch
class 							__magic_name__	(       lowerCAmelCase    ,		lowerCAmelCase    ,		unittest.TestCase ):

     """simple docstring"""






     lowerCamelCase__       						=				(ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else ()
     lowerCamelCase__       						=				(
         {'feature-extraction': ViTHybridModel, 'image-classification': ViTHybridForImageClassification}
         if is_torch_available()
         else {}
     )
     lowerCamelCase__       						=				False
     lowerCamelCase__       						=				False
     lowerCamelCase__       						=				False


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A	:       str      =							ViTHybridModelTester(self		)
          __A	:       Optional[Any]      =							ConfigTester(self			,     config_class=lowerCamelCase			,     has_text_modality=lowerCamelCase			,     hidden_size=37		)


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          self.config_tester.run_common_tests()


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


          '''simple docstring'''





          pass


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A  ,__A	:       Dict      =							self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               __A	:       List[str]      =							model_class(lowerCamelCase		)
               self.assertIsInstance(model.get_input_embeddings()			,     (nn.Module)		)
               __A	:       int      =							model.get_output_embeddings()
               self.assertTrue(x is None or isinstance(lowerCamelCase			,     nn.Linear		)		)


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A  ,__A	:       Any      =							self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               __A	:       Union[str, Any]      =							model_class(lowerCamelCase		)
               __A	:       Union[str, Any]      =							inspect.signature(model.forward		)
               # signature.parameters is an OrderedDict => so arg_names order is deterministic
               __A	:       Optional[Any]      =							[*signature.parameters.keys()]

               __A	:       Dict      =							["pixel_values"]
               self.assertListEqual(arg_names[:1]			,     lowerCamelCase		)


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A	:       int      =							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*lowerCamelCase		)


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A	:       Optional[int]      =							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*lowerCamelCase		)


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A  ,__A	:       Any      =							self.model_tester.prepare_config_and_inputs_for_common()

          __A	:       Dict      =							_config_zero_init(lowerCamelCase		)
          for model_class in self.all_model_classes:
               __A	:       List[str]      =							model_class(config=lowerCamelCase		)
               # Skip the check for the backbone
               for name, module in model.named_modules():
                    if module.__class__.__name__ == "ViTHybridPatchEmbeddings":
                         __A	:       int      =							[f"{name}.{key}" for key in module.state_dict().keys()]
                         break

               for name, param in model.named_parameters():
                    if param.requires_grad:
                         if name in backbone_params:
                              continue
                         self.assertIn(
                             ((param.data.mean() * 1E9).round() / 1E9).item()			,     [0.0, 1.0]			,     msg=f"Parameter {name} of model {model_class} seems not properly initialized"			,     )


     @slow
     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __A	:       Tuple      =							ViTHybridModel.from_pretrained(lowerCamelCase		)
               self.assertIsNotNone(lowerCamelCase		)


def 		_lowercase ():




     '''simple docstring'''





     __A	:       Optional[Any]      =							Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"							)
     return image







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

     """simple docstring"""






     @cached_property
     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          return (
              ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)
              if is_vision_available()
              else None
          )


     @slow
     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A	:       str      =							ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]		).to(
              lowerCamelCase		)

          __A	:       str      =							self.default_image_processor
          __A	:       Union[str, Any]      =							prepare_img()
          __A	:       List[str]      =							image_processor(images=lowerCamelCase			,     return_tensors="pt"		).to(lowerCamelCase		)

          # forward pass
          with torch.no_grad():
               __A	:       Any      =							model(**lowerCamelCase		)

          # verify the logits
          __A	:       List[str]      =							torch.Size((1, 1000)		)
          self.assertEqual(outputs.logits.shape			,     lowerCamelCase		)

          __A	:       Optional[int]      =							torch.tensor([-1.9090, -0.4993, -0.2389]		).to(lowerCamelCase		)

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


     @slow
     @require_accelerate
     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A	:       List[Any]      =							ViTHybridImageProcessor.from_pretrained("google/vit-hybrid-base-bit-384"		)
          __A	:       Optional[Any]      =							ViTHybridForImageClassification.from_pretrained("google/vit-hybrid-base-bit-384"			,     device_map="auto"		)

          __A	:       Union[str, Any]      =							prepare_img()

          __A	:       Tuple      =							image_processor(images=lowerCamelCase			,     return_tensors="pt"		)
          __A	:       Optional[Any]      =							model(**lowerCamelCase		)
          __A	:       List[Any]      =							outputs.logits
          # model predicts one of the 1000 ImageNet classes
          __A	:       Tuple      =							logits.argmax(-1		).item()

          self.assertTrue(model.config.idalabel[predicted_class_idx]			,     "tabby, tabby cat"		)

