





import inspect
import unittest

from transformers import ViTConfig
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 ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
					from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import ViTImageProcessor


class   A			:
			'''simple docstring'''




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







					"""simple docstring"""






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

					# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
					A__        =   (image_size // patch_size) ** 2
					A__        =   num_patches + 1






			def    a_       (			self   :    Any   )	->	Optional[int]:







					"""simple docstring"""






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

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

					A__        =   self.get_config()

					return config, pixel_values, labels






			def    a_       (			self   :    int   )	->	Union[str, Any]:







					"""simple docstring"""






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






			def    a_       (			self   :    Optional[int]							,	__lowerCAmelCase   :    int							,	__lowerCAmelCase   :    Optional[Any]							,	__lowerCAmelCase   :    List[str]   )	->	Optional[Any]:







					"""simple docstring"""






					A__        =   ViTModel(config=__lowerCAmelCase   )
					model.to(__lowerCAmelCase   )
					model.eval()
					A__        =   model(__lowerCAmelCase   )
					self.parent.assertEqual(result.last_hidden_state.shape							,	(self.batch_size, self.seq_length, self.hidden_size)   )






			def    a_       (			self   :    Optional[Any]							,	__lowerCAmelCase   :    Optional[Any]							,	__lowerCAmelCase   :    Dict							,	__lowerCAmelCase   :    List[str]   )	->	Union[str, Any]:







					"""simple docstring"""






					A__        =   ViTForMaskedImageModeling(config=__lowerCAmelCase   )
					model.to(__lowerCAmelCase   )
					model.eval()
					A__        =   model(__lowerCAmelCase   )
					self.parent.assertEqual(
					    result.reconstruction.shape							,	(self.batch_size, self.num_channels, self.image_size, self.image_size)   )

					# test greyscale images
					A__        =   1
					A__        =   ViTForMaskedImageModeling(__lowerCAmelCase   )
					model.to(__lowerCAmelCase   )
					model.eval()

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






			def    a_       (			self   :    Optional[int]							,	__lowerCAmelCase   :    Optional[int]							,	__lowerCAmelCase   :    List[Any]							,	__lowerCAmelCase   :    Union[str, Any]   )	->	List[Any]:







					"""simple docstring"""






					A__        =   self.type_sequence_label_size
					A__        =   ViTForImageClassification(__lowerCAmelCase   )
					model.to(__lowerCAmelCase   )
					model.eval()
					A__        =   model(__lowerCAmelCase							,	labels=__lowerCAmelCase   )
					self.parent.assertEqual(result.logits.shape							,	(self.batch_size, self.type_sequence_label_size)   )

					# test greyscale images
					A__        =   1
					A__        =   ViTForImageClassification(__lowerCAmelCase   )
					model.to(__lowerCAmelCase   )
					model.eval()

					A__        =   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]   )
					A__        =   model(__lowerCAmelCase   )
					self.parent.assertEqual(result.logits.shape							,	(self.batch_size, self.type_sequence_label_size)   )







			def    a_       (			self   :    str   )	->	Union[str, Any]:







					"""simple docstring"""






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


@require_torch
class   A			(SCREAMING_SNAKE_CASE   ,     SCREAMING_SNAKE_CASE   ,     unittest.TestCase    ):
			'''simple docstring'''




			__lowerCamelCase	:       Any							=    (
			    (
			        ViTModel,
			        ViTForImageClassification,
			        ViTForMaskedImageModeling,
			    )
			    if is_torch_available()
			    else ()
			)
			__lowerCamelCase	:       List[str]							=    (
			    {'''feature-extraction''': ViTModel, '''image-classification''': ViTForImageClassification}
			    if is_torch_available()
			    else {}
			)
			__lowerCamelCase	:       Optional[Any]							=    True

			__lowerCamelCase	:       Optional[int]							=    False
			__lowerCamelCase	:       Any							=    False
			__lowerCamelCase	:       List[Any]							=    False






			def    a_       (			self   :    str   )	->	Dict:







					"""simple docstring"""






					A__        =   ViTModelTester(self   )
					A__        =   ConfigTester(self							,	config_class=__lowerCAmelCase							,	has_text_modality=__lowerCAmelCase							,	hidden_size=37   )






			def    a_       (			self   :    List[Any]   )	->	Dict:







					"""simple docstring"""






					self.config_tester.run_common_tests()






			@unittest.skip(reason="""ViT does not use inputs_embeds"""   )
			def    a_       (			self   :    Any   )	->	str:







					"""simple docstring"""






					pass






			def    a_       (			self   :    str   )	->	Optional[Any]:







					"""simple docstring"""






					A__      ,			A__        =   self.model_tester.prepare_config_and_inputs_for_common()

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






			def    a_       (			self   :    Tuple   )	->	int:







					"""simple docstring"""






					A__      ,			A__        =   self.model_tester.prepare_config_and_inputs_for_common()

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

							A__        =   ["""pixel_values"""]
							self.assertListEqual(arg_names[:1]							,	__lowerCAmelCase   )






			def    a_       (			self   :    str   )	->	int:







					"""simple docstring"""






					A__        =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*__lowerCAmelCase   )






			def    a_       (			self   :    int   )	->	Optional[int]:







					"""simple docstring"""






					A__        =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_masked_image_modeling(*__lowerCAmelCase   )






			def    a_       (			self   :    Optional[Any]   )	->	Optional[int]:







					"""simple docstring"""






					A__        =   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase   )







			@slow
			def    a_       (			self   :    Dict   )	->	Optional[Any]:







					"""simple docstring"""






					for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							A__        =   ViTModel.from_pretrained(__lowerCAmelCase   )
							self.assertIsNotNone(__lowerCAmelCase   )







def    __lowerCamelCase					(							)		->				List[Any]:






		"""simple docstring"""

		A__        =   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    )
		return image






@require_torch
@require_vision
class   A			(unittest.TestCase    ):
			'''simple docstring'''




			@cached_property
			def    a_       (			self   :    Tuple   )	->	str:







					"""simple docstring"""






					return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224"""   ) if is_vision_available() else None






			@slow
			def    a_       (			self   :    Tuple   )	->	Dict:







					"""simple docstring"""






					A__        =   ViTForImageClassification.from_pretrained("""google/vit-base-patch16-224"""   ).to(__lowerCAmelCase   )

					A__        =   self.default_image_processor
					A__        =   prepare_img()
					A__        =   image_processor(images=__lowerCAmelCase							,	return_tensors="""pt"""   ).to(__lowerCAmelCase   )

					# forward pass
					with torch.no_grad():
							A__        =   model(**__lowerCAmelCase   )

					# verify the logits
					A__        =   torch.Size((1, 10_00)   )
					self.assertEqual(outputs.logits.shape							,	__lowerCAmelCase   )

					A__        =   torch.tensor([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6]   ).to(__lowerCAmelCase   )

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






			@slow
			def    a_       (			self   :    List[str]   )	->	List[Any]:







					"""simple docstring"""






					A__        =   ViTModel.from_pretrained("""facebook/dino-vits8"""   ).to(__lowerCAmelCase   )

					A__        =   ViTImageProcessor.from_pretrained("""facebook/dino-vits8"""							,	size=4_80   )
					A__        =   prepare_img()
					A__        =   image_processor(images=__lowerCAmelCase							,	return_tensors="""pt"""   )
					A__        =   inputs.pixel_values.to(__lowerCAmelCase   )

					# forward pass
					with torch.no_grad():
							A__        =   model(__lowerCAmelCase							,	interpolate_pos_encoding=__lowerCAmelCase   )

					# verify the logits
					A__        =   torch.Size((1, 36_01, 3_84)   )
					self.assertEqual(outputs.last_hidden_state.shape							,	__lowerCAmelCase   )

					A__        =   torch.tensor(
					    [[4.2_3_4_0, 4.3_9_0_6, -6.6_6_9_2], [4.5_4_6_3, 1.8_9_2_8, -6.7_2_5_7], [4.4_4_2_9, 0.8_4_9_6, -5.8_5_8_5]]   ).to(__lowerCAmelCase   )

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







			@slow
			@require_accelerate
			@require_torch_gpu
			def    a_       (			self   :    int   )	->	Any:







					"""simple docstring"""






					A__        =   ViTModel.from_pretrained("""facebook/dino-vits8"""							,	torch_dtype=torch.floataa							,	device_map="""auto"""   )
					A__        =   self.default_image_processor

					A__        =   prepare_img()
					A__        =   image_processor(images=__lowerCAmelCase							,	return_tensors="""pt"""   )
					A__        =   inputs.pixel_values.to(__lowerCAmelCase   )

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










from sklearn.metrics import fa_score

import datasets


A    :					Any =      '''
The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:
F1 = 2 * (precision * recall) / (precision + recall)
'''


A    :					List[Any] =      '''
Args:
    predictions (`list` of `int`): Predicted labels.
    references (`list` of `int`): Ground truth labels.
    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.
    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.
    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\'`.

        - \'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.
        - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.
        - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
        - \'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.
        - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
    sample_weight (`list` of `float`): Sample weights Defaults to None.

Returns:
    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.

Examples:

    Example 1-A simple binary example
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])
        >>> print(results)
        {\'f1\': 0.5}

    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)
        >>> print(round(results[\'f1\'], 2))
        0.67

    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.
        >>> f1_metric = datasets.load_metric("f1")
        >>> 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])
        >>> print(round(results[\'f1\'], 2))
        0.35

    Example 4-A multiclass example, with different values for the `average` input.
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro")
        >>> print(round(results[\'f1\'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro")
        >>> print(round(results[\'f1\'], 2))
        0.33
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted")
        >>> print(round(results[\'f1\'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {\'f1\': array([0.8, 0. , 0. ])}
'''


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


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION   ,     _KWARGS_DESCRIPTION    )
class   A			(datasets.Metric    ):
			'''simple docstring'''




			def    a_       (			self   :    Optional[int]   )	->	List[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    a_       (			self   :    Any							,	__lowerCAmelCase   :    Tuple							,	__lowerCAmelCase   :    Union[str, Any]							,	__lowerCAmelCase   :    Dict=None							,	__lowerCAmelCase   :    List[str]=1							,	__lowerCAmelCase   :    Any="binary"							,	__lowerCAmelCase   :    Optional[int]=None   )	->	List[Any]:







					"""simple docstring"""






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



