


from sklearn.metrics import fa_score

import datasets


a					  =     '\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n'


a					  =     '\nArgs:\n    predictions (`list` of `int`): Predicted labels.\n    references (`list` of `int`): Ground truth labels.\n    labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.\n\n        - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n        - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n        - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n        - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n        - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n    sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n    f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n    Example 1-A simple binary example\n        >>> f1_metric = datasets.load_metric("f1")\n        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n        >>> print(results)\n        {\'f1\': 0.5}\n\n    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n        >>> f1_metric = datasets.load_metric("f1")\n        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n        >>> print(round(results[\'f1\'], 2))\n        0.67\n\n    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n        >>> f1_metric = datasets.load_metric("f1")\n        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n        >>> print(round(results[\'f1\'], 2))\n        0.35\n\n    Example 4-A multiclass example, with different values for the `average` input.\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro")\n        >>> print(round(results[\'f1\'], 2))\n        0.27\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro")\n        >>> print(round(results[\'f1\'], 2))\n        0.33\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted")\n        >>> print(round(results[\'f1\'], 2))\n        0.27\n        >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print(results)\n        {\'f1\': array([0.8, 0. , 0. ])}\n'


a					  =     '\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        UpperCamelCase__   (	datasets.Metric   ):

					def   UpperCAmelCase__       (     self       :   Any       ):






										'''simple docstring'''






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







					def   UpperCAmelCase__       (     self       :   List[Any]							,					UpperCamelCase__       :   Optional[Any]							,					UpperCamelCase__       :   List[Any]							,					UpperCamelCase__       :   Dict=None							,					UpperCamelCase__       :   Optional[Any]=1							,					UpperCamelCase__       :   List[str]="binary"							,					UpperCamelCase__       :   str=None       ):






										'''simple docstring'''






										lowercase_  							=			fa_score(
										    UpperCAmelCase__							,					UpperCAmelCase__							,					labels=UpperCAmelCase__							,					pos_label=UpperCAmelCase__							,					average=UpperCAmelCase__							,					sample_weight=UpperCAmelCase__       )
										return {"f1": float(UpperCAmelCase__       ) if score.size == 1 else score}










import inspect
import unittest
import warnings

from transformers import DeiTConfig
from transformers.models.auto import get_values
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_gpu,
    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 torch import nn

							from transformers import (
							    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
							    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
							    MODEL_MAPPING,
							    DeiTForImageClassification,
							    DeiTForImageClassificationWithTeacher,
							    DeiTForMaskedImageModeling,
							    DeiTModel,
							)
							from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import DeiTImageProcessor







class        UpperCamelCase__   :

					def __init__(     self       :   Union[str, Any]							,					UpperCamelCase__       :   List[str]							,					UpperCamelCase__       :   Tuple=13							,					UpperCamelCase__       :   Tuple=30							,					UpperCamelCase__       :   List[Any]=2							,					UpperCamelCase__       :   Union[str, Any]=3							,					UpperCamelCase__       :   Union[str, Any]=True							,					UpperCamelCase__       :   Tuple=True							,					UpperCamelCase__       :   int=32							,					UpperCamelCase__       :   Tuple=5							,					UpperCamelCase__       :   List[Any]=4							,					UpperCamelCase__       :   Dict=37							,					UpperCamelCase__       :   Tuple="gelu"							,					UpperCamelCase__       :   Union[str, Any]=0.1							,					UpperCamelCase__       :   Optional[int]=0.1							,					UpperCamelCase__       :   Any=10							,					UpperCamelCase__       :   Optional[int]=0.02							,					UpperCamelCase__       :   Dict=3							,					UpperCamelCase__       :   List[str]=None							,					UpperCamelCase__       :   Union[str, Any]=2							,					):






										'''simple docstring'''






										lowercase_  							=			parent
										lowercase_  							=			batch_size
										lowercase_  							=			image_size
										lowercase_  							=			patch_size
										lowercase_  							=			num_channels
										lowercase_  							=			is_training
										lowercase_  							=			use_labels
										lowercase_  							=			hidden_size
										lowercase_  							=			num_hidden_layers
										lowercase_  							=			num_attention_heads
										lowercase_  							=			intermediate_size
										lowercase_  							=			hidden_act
										lowercase_  							=			hidden_dropout_prob
										lowercase_  							=			attention_probs_dropout_prob
										lowercase_  							=			type_sequence_label_size
										lowercase_  							=			initializer_range
										lowercase_  							=			scope
										lowercase_  							=			encoder_stride

										# in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
										lowercase_  							=			(image_size // patch_size) ** 2
										lowercase_  							=			num_patches + 2

					def   UpperCAmelCase__       (     self       :   Optional[int]       ):






										'''simple docstring'''






										lowercase_  							=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

										lowercase_  							=			None
										if self.use_labels:
															lowercase_  							=			ids_tensor([self.batch_size]							,					self.type_sequence_label_size       )

										lowercase_  							=			self.get_config()

										return config, pixel_values, labels

					def   UpperCAmelCase__       (     self       :   Optional[Any]       ):






										'''simple docstring'''






										return DeiTConfig(
										    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=UpperCamelCase__							,					initializer_range=self.initializer_range							,					encoder_stride=self.encoder_stride							,					)

					def   UpperCAmelCase__       (     self       :   Tuple							,					UpperCamelCase__       :   Tuple							,					UpperCamelCase__       :   Tuple							,					UpperCamelCase__       :   Tuple       ):






										'''simple docstring'''






										lowercase_  							=			DeiTModel(config=UpperCamelCase__       )
										model.to(UpperCamelCase__       )
										model.eval()
										lowercase_  							=			model(UpperCamelCase__       )
										self.parent.assertEqual(result.last_hidden_state.shape							,					(self.batch_size, self.seq_length, self.hidden_size)       )

					def   UpperCAmelCase__       (     self       :   Optional[int]							,					UpperCamelCase__       :   Optional[int]							,					UpperCamelCase__       :   List[str]							,					UpperCamelCase__       :   str       ):






										'''simple docstring'''






										lowercase_  							=			DeiTForMaskedImageModeling(config=UpperCamelCase__       )
										model.to(UpperCamelCase__       )
										model.eval()
										lowercase_  							=			model(UpperCamelCase__       )
										self.parent.assertEqual(
										    result.reconstruction.shape							,					(self.batch_size, self.num_channels, self.image_size, self.image_size)       )

										# test greyscale images
										lowercase_  							=			1
										lowercase_  							=			DeiTForMaskedImageModeling(UpperCamelCase__       )
										model.to(UpperCamelCase__       )
										model.eval()

										lowercase_  							=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
										lowercase_  							=			model(UpperCamelCase__       )
										self.parent.assertEqual(result.reconstruction.shape							,					(self.batch_size, 1, self.image_size, self.image_size)       )

					def   UpperCAmelCase__       (     self       :   Tuple							,					UpperCamelCase__       :   str							,					UpperCamelCase__       :   List[str]							,					UpperCamelCase__       :   List[str]       ):






										'''simple docstring'''






										lowercase_  							=			self.type_sequence_label_size
										lowercase_  							=			DeiTForImageClassification(UpperCamelCase__       )
										model.to(UpperCamelCase__       )
										model.eval()
										lowercase_  							=			model(UpperCamelCase__							,					labels=UpperCamelCase__       )
										self.parent.assertEqual(result.logits.shape							,					(self.batch_size, self.type_sequence_label_size)       )

										# test greyscale images
										lowercase_  							=			1
										lowercase_  							=			DeiTForImageClassification(UpperCamelCase__       )
										model.to(UpperCamelCase__       )
										model.eval()

										lowercase_  							=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
										lowercase_  							=			model(UpperCamelCase__							,					labels=UpperCamelCase__       )
										self.parent.assertEqual(result.logits.shape							,					(self.batch_size, self.type_sequence_label_size)       )







					def   UpperCAmelCase__       (     self       :   int       ):






										'''simple docstring'''






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







@require_torch
class        UpperCamelCase__   (	__magic_name__							,				__magic_name__							,				unittest.TestCase   ):
					__SCREAMING_SNAKE_CASE       :  Any						=   (
					    (
					        DeiTModel,
					        DeiTForImageClassification,
					        DeiTForImageClassificationWithTeacher,
					        DeiTForMaskedImageModeling,
					    )
					    if is_torch_available()
					    else ()
					)
					__SCREAMING_SNAKE_CASE       :  str						=   (
					    {
					        'feature-extraction': DeiTModel,
					        'image-classification': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher),
					    }
					    if is_torch_available()
					    else {}
					)

					__SCREAMING_SNAKE_CASE       :  Dict						=   False
					__SCREAMING_SNAKE_CASE       :  List[Any]						=   False
					__SCREAMING_SNAKE_CASE       :  List[Any]						=   False

					def   UpperCAmelCase__       (     self       :   Union[str, Any]       ):






										'''simple docstring'''






										lowercase_  							=			DeiTModelTester(self       )
										lowercase_  							=			ConfigTester(self							,					config_class=UpperCamelCase__							,					has_text_modality=UpperCamelCase__							,					hidden_size=37       )

					def   UpperCAmelCase__       (     self       :   int       ):






										'''simple docstring'''






										self.config_tester.run_common_tests()

					@unittest.skip(reason="""DeiT does not use inputs_embeds"""       )
					def   UpperCAmelCase__       (     self       :   int       ):






										'''simple docstring'''






										pass

					def   UpperCAmelCase__       (     self       :   Tuple       ):






										'''simple docstring'''






										lowercase_							,					lowercase_  							=			self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
															lowercase_  							=			model_class(UpperCamelCase__       )
															self.assertIsInstance(model.get_input_embeddings()							,					(nn.Module)       )
															lowercase_  							=			model.get_output_embeddings()
															self.assertTrue(x is None or isinstance(UpperCamelCase__							,					nn.Linear       )       )

					def   UpperCAmelCase__       (     self       :   Any       ):






										'''simple docstring'''






										lowercase_							,					lowercase_  							=			self.model_tester.prepare_config_and_inputs_for_common()

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

															lowercase_  							=			["""pixel_values"""]
															self.assertListEqual(arg_names[:1]							,					UpperCamelCase__       )

					def   UpperCAmelCase__       (     self       :   Union[str, Any]       ):






										'''simple docstring'''






										lowercase_  							=			self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*UpperCamelCase__       )

					def   UpperCAmelCase__       (     self       :   Optional[Any]       ):






										'''simple docstring'''






										lowercase_  							=			self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_masked_image_modeling(*UpperCamelCase__       )

					def   UpperCAmelCase__       (     self       :   Optional[Any]       ):






										'''simple docstring'''






										lowercase_  							=			self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__       )

					def   UpperCAmelCase__       (     self       :   List[Any]							,					UpperCamelCase__       :   str							,					UpperCamelCase__       :   Any							,					UpperCamelCase__       :   Union[str, Any]=False       ):






										'''simple docstring'''






										lowercase_  							=			super()._prepare_for_class(UpperCamelCase__							,					UpperCamelCase__							,					return_labels=UpperCamelCase__       )

										if return_labels:
															if model_class.__name__ == "DeiTForImageClassificationWithTeacher":
																				del inputs_dict["labels"]

										return inputs_dict

					def   UpperCAmelCase__       (     self       :   Optional[Any]       ):






										'''simple docstring'''






										if not self.model_tester.is_training:
															return

										lowercase_							,					lowercase_  							=			self.model_tester.prepare_config_and_inputs_for_common()
										lowercase_  							=			True

										for model_class in self.all_model_classes:
															# DeiTForImageClassificationWithTeacher supports inference-only
															if (
															    model_class in get_values(UpperCamelCase__       )
															    or model_class.__name__ == "DeiTForImageClassificationWithTeacher"
															):
																				continue
															lowercase_  							=			model_class(UpperCamelCase__       )
															model.to(UpperCamelCase__       )
															model.train()
															lowercase_  							=			self._prepare_for_class(UpperCamelCase__							,					UpperCamelCase__							,					return_labels=UpperCamelCase__       )
															lowercase_  							=			model(**UpperCamelCase__       ).loss
															loss.backward()

					def   UpperCAmelCase__       (     self       :   List[str]       ):






										'''simple docstring'''






										lowercase_							,					lowercase_  							=			self.model_tester.prepare_config_and_inputs_for_common()
										if not self.model_tester.is_training:
															return

										lowercase_  							=			False
										lowercase_  							=			True

										for model_class in self.all_model_classes:
															if model_class in get_values(UpperCamelCase__       ) or not model_class.supports_gradient_checkpointing:
																				continue
															# DeiTForImageClassificationWithTeacher supports inference-only
															if model_class.__name__ == "DeiTForImageClassificationWithTeacher":
																				continue
															lowercase_  							=			model_class(UpperCamelCase__       )
															model.gradient_checkpointing_enable()
															model.to(UpperCamelCase__       )
															model.train()
															lowercase_  							=			self._prepare_for_class(UpperCamelCase__							,					UpperCamelCase__							,					return_labels=UpperCamelCase__       )
															lowercase_  							=			model(**UpperCamelCase__       ).loss
															loss.backward()

					def   UpperCAmelCase__       (     self       :   Optional[int]       ):






										'''simple docstring'''






										lowercase_							,					lowercase_  							=			self.model_tester.prepare_config_and_inputs_for_common()

										lowercase_  							=			[
										    {"""title""": """multi_label_classification""", """num_labels""": 2, """dtype""": torch.float},
										    {"""title""": """single_label_classification""", """num_labels""": 1, """dtype""": torch.long},
										    {"""title""": """regression""", """num_labels""": 1, """dtype""": torch.float},
										]

										for model_class in self.all_model_classes:
															if (
															    model_class
															    not in [
															        *get_values(UpperCamelCase__       ),
															        *get_values(UpperCamelCase__       ),
															    ]
															    or model_class.__name__ == "DeiTForImageClassificationWithTeacher"
															):
																				continue

															for problem_type in problem_types:
																				with self.subTest(msg=F'''Testing {model_class} with {problem_type["title"]}'''       ):
																									lowercase_  							=			problem_type["""title"""]
																									lowercase_  							=			problem_type["""num_labels"""]

																									lowercase_  							=			model_class(UpperCamelCase__       )
																									model.to(UpperCamelCase__       )
																									model.train()

																									lowercase_  							=			self._prepare_for_class(UpperCamelCase__							,					UpperCamelCase__							,					return_labels=UpperCamelCase__       )

																									if problem_type["num_labels"] > 1:
																														lowercase_  							=			inputs["""labels"""].unsqueeze(1       ).repeat(1							,					problem_type["""num_labels"""]       )

																									lowercase_  							=			inputs["""labels"""].to(problem_type["""dtype"""]       )

																									# This tests that we do not trigger the warning form PyTorch "Using a target size that is different
																									# to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
																									# they have the same size." which is a symptom something in wrong for the regression problem.
																									# See https://github.com/huggingface/transformers/issues/11780
																									with warnings.catch_warnings(record=UpperCamelCase__       ) as warning_list:
																														lowercase_  							=			model(**UpperCamelCase__       ).loss
																									for w in warning_list:
																														if "Using a target size that is different to the input size" in str(w.message       ):
																																			raise ValueError(
																																			    F'''Something is going wrong in the regression problem: intercepted {w.message}'''       )

																									loss.backward()







					@slow
					def   UpperCAmelCase__       (     self       :   int       ):






										'''simple docstring'''






										for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															lowercase_  							=			DeiTModel.from_pretrained(UpperCamelCase__       )
															self.assertIsNotNone(UpperCamelCase__       )



def 			UpperCAmelCase_				(      ):
					lowercase_  							=			Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""  )
					return image







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

					@cached_property
					def   UpperCAmelCase__       (     self       :   Optional[int]       ):






										'''simple docstring'''






										return (
										    DeiTImageProcessor.from_pretrained("""facebook/deit-base-distilled-patch16-224"""       )
										    if is_vision_available()
										    else None
										)

					@slow
					def   UpperCAmelCase__       (     self       :   Dict       ):






										'''simple docstring'''






										lowercase_  							=			DeiTForImageClassificationWithTeacher.from_pretrained("""facebook/deit-base-distilled-patch16-224"""       ).to(
										    UpperCamelCase__       )

										lowercase_  							=			self.default_image_processor
										lowercase_  							=			prepare_img()
										lowercase_  							=			image_processor(images=UpperCamelCase__							,					return_tensors="""pt"""       ).to(UpperCamelCase__       )

										# forward pass
										with torch.no_grad():
															lowercase_  							=			model(**UpperCamelCase__       )

										# verify the logits
										lowercase_  							=			torch.Size((1, 1_000)       )
										self.assertEqual(outputs.logits.shape							,					UpperCamelCase__       )

										lowercase_  							=			torch.tensor([-1.0_266, 0.1_912, -1.2_861]       ).to(UpperCamelCase__       )

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







					@slow
					@require_accelerate
					@require_torch_gpu
					def   UpperCAmelCase__       (     self       :   Optional[Any]       ):






										'''simple docstring'''






										lowercase_  							=			DeiTModel.from_pretrained(
										    """facebook/deit-base-distilled-patch16-224"""							,					torch_dtype=torch.floataa							,					device_map="""auto"""       )
										lowercase_  							=			self.default_image_processor

										lowercase_  							=			prepare_img()
										lowercase_  							=			image_processor(images=UpperCamelCase__							,					return_tensors="""pt"""       )
										lowercase_  							=			inputs.pixel_values.to(UpperCamelCase__       )

										# forward pass to make sure inference works in fp16
										with torch.no_grad():
															lowercase_  							=			model(UpperCamelCase__       )


