'''simple docstring'''




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     __magic_name__						:







			def __init__(	self				:  List[Any]				,			lowercase_				:  Optional[Any]				,			lowercase_				:  Optional[Any]=13				,			lowercase_				:  Optional[int]=30				,			lowercase_				:  Union[str, Any]=2				,			lowercase_				:  Dict=3				,			lowercase_				:  List[Any]=True				,			lowercase_				:  Optional[Any]=True				,			lowercase_				:  int=32				,			lowercase_				:  Union[str, Any]=5				,			lowercase_				:  Dict=4				,			lowercase_				:  List[str]=37				,			lowercase_				:  List[str]="gelu"				,			lowercase_				:  List[str]=0.1				,			lowercase_				:  Any=0.1				,			lowercase_				:  List[str]=10				,			lowercase_				:  Any=0.02				,			lowercase_				:  List[str]=None				,			lowercase_				:  str=2				,			):
										lowercase_					:			List[Any]										=       parent
										lowercase_					:			Any										=       batch_size
										lowercase_					:			Union[str, Any]										=       image_size
										lowercase_					:			Tuple										=       patch_size
										lowercase_					:			int										=       num_channels
										lowercase_					:			str										=       is_training
										lowercase_					:			Union[str, Any]										=       use_labels
										lowercase_					:			Optional[int]										=       hidden_size
										lowercase_					:			Optional[int]										=       num_hidden_layers
										lowercase_					:			List[Any]										=       num_attention_heads
										lowercase_					:			Optional[int]										=       intermediate_size
										lowercase_					:			int										=       hidden_act
										lowercase_					:			str										=       hidden_dropout_prob
										lowercase_					:			Union[str, Any]										=       attention_probs_dropout_prob
										lowercase_					:			List[str]										=       type_sequence_label_size
										lowercase_					:			Optional[int]										=       initializer_range
										lowercase_					:			Tuple										=       scope
										lowercase_					:			List[Any]										=       encoder_stride

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







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[int]    ):
										lowercase_					:			List[str]										=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

										lowercase_					:			str										=       self.get_config()

										return config, pixel_values, labels







			def 	SCREAMING_SNAKE_CASE_     (	self				:  int    ):
										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=lowercase_				,			initializer_range=self.initializer_range				,			encoder_stride=self.encoder_stride				,			)







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[int]				,			lowercase_				:  str				,			lowercase_				:  List[str]				,			lowercase_				:  Union[str, Any]    ):
										lowercase_					:			Tuple										=       ViTModel(config=lowercase_    )
										model.to(lowercase_    )
										model.eval()
										lowercase_					:			Optional[int]										=       model(lowercase_    )
										self.parent.assertEqual(result.last_hidden_state.shape				,			(self.batch_size, self.seq_length, self.hidden_size)    )







			def 	SCREAMING_SNAKE_CASE_     (	self				:  List[str]				,			lowercase_				:  str				,			lowercase_				:  Optional[Any]				,			lowercase_				:  Optional[int]    ):
										lowercase_					:			int										=       ViTForMaskedImageModeling(config=lowercase_    )
										model.to(lowercase_    )
										model.eval()
										lowercase_					:			Tuple										=       model(lowercase_    )
										self.parent.assertEqual(
										    result.reconstruction.shape				,			(self.batch_size, self.num_channels, self.image_size, self.image_size)    )

										# test greyscale images
										lowercase_					:			List[str]										=       1
										lowercase_					:			List[str]										=       ViTForMaskedImageModeling(lowercase_    )
										model.to(lowercase_    )
										model.eval()

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







			def 	SCREAMING_SNAKE_CASE_     (	self				:  str				,			lowercase_				:  Dict				,			lowercase_				:  Dict				,			lowercase_				:  List[str]    ):
										lowercase_					:			Dict										=       self.type_sequence_label_size
										lowercase_					:			Any										=       ViTForImageClassification(lowercase_    )
										model.to(lowercase_    )
										model.eval()
										lowercase_					:			int										=       model(lowercase_				,			labels=lowercase_    )
										self.parent.assertEqual(result.logits.shape				,			(self.batch_size, self.type_sequence_label_size)    )

										# test greyscale images
										lowercase_					:			int										=       1
										lowercase_					:			Optional[Any]										=       ViTForImageClassification(lowercase_    )
										model.to(lowercase_    )
										model.eval()

										lowercase_					:			Optional[int]										=       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]    )
										lowercase_					:			str										=       model(lowercase_    )
										self.parent.assertEqual(result.logits.shape				,			(self.batch_size, self.type_sequence_label_size)    )







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[int]    ):
										lowercase_					:			Dict										=       self.prepare_config_and_inputs()
										(
										    (
										    lowercase_
										)						,						(
										    lowercase_
										)						,						(
										    lowercase_
										)						,						
										)					:			Union[str, Any]										=       config_and_inputs
										lowercase_					:			Optional[Any]										=       {"""pixel_values""": pixel_values}
										return config, inputs_dict





@require_torch
class     __magic_name__						(    _UpperCAmelCase,     _UpperCAmelCase,     unittest.TestCase):
			UpperCamelCase__				=       (
			    (
			        ViTModel,
			        ViTForImageClassification,
			        ViTForMaskedImageModeling,
			    )
			    if is_torch_available()
			    else ()
			)
			UpperCamelCase__				=       (
			    {'''feature-extraction''': ViTModel, '''image-classification''': ViTForImageClassification}
			    if is_torch_available()
			    else {}
			)
			UpperCamelCase__				=       True

			UpperCamelCase__				=       False
			UpperCamelCase__				=       False
			UpperCamelCase__				=       False







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Any    ):
										lowercase_					:			Any										=       ViTModelTester(self    )
										lowercase_					:			str										=       ConfigTester(self				,			config_class=lowercase_				,			has_text_modality=lowercase_				,			hidden_size=37    )







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[int]    ):
										self.config_tester.run_common_tests()







			@unittest.skip(reason="""ViT does not use inputs_embeds"""    )
			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[Any]    ):
										pass







			def 	SCREAMING_SNAKE_CASE_     (	self				:  List[str]    ):
										lowercase_						,						lowercase_					:			Union[str, Any]										=       self.model_tester.prepare_config_and_inputs_for_common()

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







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Tuple    ):
										lowercase_						,						lowercase_					:			Tuple										=       self.model_tester.prepare_config_and_inputs_for_common()

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

																	lowercase_					:			Union[str, Any]										=       ["""pixel_values"""]
																	self.assertListEqual(arg_names[:1]				,			lowercase_    )







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[int]    ):
										lowercase_					:			Optional[int]										=       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowercase_    )







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Union[str, Any]    ):
										lowercase_					:			Any										=       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_masked_image_modeling(*lowercase_    )







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[Any]    ):
										lowercase_					:			List[Any]										=       self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*lowercase_    )







			@slow
			def 	SCREAMING_SNAKE_CASE_     (	self				:  Union[str, Any]    ):
										for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	lowercase_					:			List[Any]										=       ViTModel.from_pretrained(lowercase_    )
																	self.assertIsNotNone(lowercase_    )




def 							lowerCamelCase	(      )			->      str:
							lowercase_					:			Optional[int]										=       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
							return image





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







			@cached_property
			def 	SCREAMING_SNAKE_CASE_     (	self				:  Any    ):
										return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224"""    ) if is_vision_available() else None







			@slow
			def 	SCREAMING_SNAKE_CASE_     (	self				:  Optional[int]    ):
										lowercase_					:			Any										=       ViTForImageClassification.from_pretrained("""google/vit-base-patch16-224"""    ).to(lowercase_    )

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

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

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

										lowercase_					:			List[str]										=       torch.tensor([-0.27_44, 0.82_15, -0.08_36]    ).to(lowercase_    )

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







			@slow
			def 	SCREAMING_SNAKE_CASE_     (	self				:  str    ):
										# ViT models have an `interpolate_pos_encoding` argument in their forward method,
										# allowing to interpolate the pre-trained position embeddings in order to use
										# the model on higher resolutions. The DINO model by Facebook AI leverages this
										# to visualize self-attention on higher resolution images.
										lowercase_					:			Optional[int]										=       ViTModel.from_pretrained("""facebook/dino-vits8"""    ).to(lowercase_    )

										lowercase_					:			str										=       ViTImageProcessor.from_pretrained("""facebook/dino-vits8"""				,			size=480    )
										lowercase_					:			Optional[int]										=       prepare_img()
										lowercase_					:			int										=       image_processor(images=lowercase_				,			return_tensors="""pt"""    )
										lowercase_					:			Union[str, Any]										=       inputs.pixel_values.to(lowercase_    )

										# forward pass
										with torch.no_grad():
																	lowercase_					:			Any										=       model(lowercase_				,			interpolate_pos_encoding=lowercase_    )

										# verify the logits
										lowercase_					:			List[Any]										=       torch.Size((1, 3601, 384)    )
										self.assertEqual(outputs.last_hidden_state.shape				,			lowercase_    )

										lowercase_					:			Optional[Any]										=       torch.tensor(
										    [[4.23_40, 4.39_06, -6.66_92], [4.54_63, 1.89_28, -6.72_57], [4.44_29, 0.84_96, -5.85_85]]    ).to(lowercase_    )

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







			@slow
			@require_accelerate
			@require_torch_gpu
			def 	SCREAMING_SNAKE_CASE_     (	self				:  Dict    ):
										lowercase_					:			Any										=       ViTModel.from_pretrained("""facebook/dino-vits8"""				,			torch_dtype=torch.floataa				,			device_map="""auto"""    )
										lowercase_					:			Optional[Any]										=       self.default_image_processor

										lowercase_					:			Optional[Any]										=       prepare_img()
										lowercase_					:			Union[str, Any]										=       image_processor(images=lowercase_				,			return_tensors="""pt"""    )
										lowercase_					:			Union[str, Any]										=       inputs.pixel_values.to(lowercase_    )

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






'''simple docstring'''




import sacrebleu as scb
from packaging import version
from sacrebleu import TER

import datasets


_lowercase						: List[str]						=						"\\n@inproceedings{snover-etal-2006-study,\n    title = \"A Study of Translation Edit Rate with Targeted Human Annotation\",\n    author = \"Snover, Matthew  and\n      Dorr, Bonnie  and\n      Schwartz, Rich  and\n      Micciulla, Linnea  and\n      Makhoul, John\",\n    booktitle = \"Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers\",\n    month = aug # \" 8-12\",\n    year = \"2006\",\n    address = \"Cambridge, Massachusetts, USA\",\n    publisher = \"Association for Machine Translation in the Americas\",\n    url = \"https://aclanthology.org/2006.amta-papers.25\",\n    pages = \"223--231\",\n}\n@inproceedings{post-2018-call,\n    title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n    author = \"Post, Matt\",\n    booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n    month = oct,\n    year = \"2018\",\n    address = \"Belgium, Brussels\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://www.aclweb.org/anthology/W18-6319\",\n    pages = \"186--191\",\n}\n"

_lowercase						: Tuple						=						"\\nTER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a\nhypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu\n(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found\nhere: https://github.com/jhclark/tercom.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.\n"

_lowercase						: Optional[int]						=						"\nProduces TER scores alongside the number of edits and reference length.\n\nArgs:\n    predictions (list of str): The system stream (a sequence of segments).\n    references (list of list of str): A list of one or more reference streams (each a sequence of segments).\n    normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n    ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n    support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,\n                                    as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.\n                                    Only applies if `normalized = True`. Defaults to `False`.\n    case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.\n\nReturns:\n    'score' (float): TER score (num_edits / sum_ref_lengths * 100)\n    'num_edits' (int): The cumulative number of edits\n    'ref_length' (float): The cumulative average reference length\n\nExamples:\n    Example 1:\n        >>> predictions = [\"does this sentence match??\",\n        ...                     \"what about this sentence?\",\n        ...                     \"What did the TER metric user say to the developer?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],\n        ...             [\"Your jokes are...\", \"...TERrible\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         case_sensitive=True)\n        >>> print(results)\n        {'score': 150.0, 'num_edits': 15, 'ref_length': 10.0}\n\n    Example 2:\n        >>> predictions = [\"does this sentence match??\",\n        ...                     \"what about this sentence?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         case_sensitive=True)\n        >>> print(results)\n        {'score': 62.5, 'num_edits': 5, 'ref_length': 8.0}\n\n    Example 3:\n        >>> predictions = [\"does this sentence match??\",\n        ...                     \"what about this sentence?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         normalized=True,\n        ...                         case_sensitive=True)\n        >>> print(results)\n        {'score': 57.14285714285714, 'num_edits': 6, 'ref_length': 10.5}\n\n    Example 4:\n        >>> predictions = [\"does this sentence match??\",\n        ...                     \"what about this sentence?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         ignore_punct=True,\n        ...                         case_sensitive=False)\n        >>> print(results)\n        {'score': 0.0, 'num_edits': 0, 'ref_length': 8.0}\n\n    Example 5:\n        >>> predictions = [\"does this sentence match??\",\n        ...                    \"what about this sentence?\",\n        ...                    \"What did the TER metric user say to the developer?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],\n        ...             [\"Your jokes are...\", \"...TERrible\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         ignore_punct=True,\n        ...                         case_sensitive=False)\n        >>> print(results)\n        {'score': 100.0, 'num_edits': 10, 'ref_length': 10.0}\n"





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







			def 	SCREAMING_SNAKE_CASE_     (	self				:  int    ):
										if version.parse(scb.__version__    ) < version.parse("""1.4.12"""    ):
																	raise ImportWarning(
																	    """To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"""
																	    """You can install it with `pip install \"sacrebleu>=1.4.12\"`."""    )
										return datasets.MetricInfo(
										    description=_DESCRIPTION				,			citation=_CITATION				,			homepage="""http://www.cs.umd.edu/~snover/tercom/"""				,			inputs_description=_KWARGS_DESCRIPTION				,			features=datasets.Features(
										        {
										            """predictions""": datasets.Value("""string"""				,			id="""sequence"""    ),
										            """references""": datasets.Sequence(datasets.Value("""string"""				,			id="""sequence"""    )				,			id="""references"""    ),
										        }    )				,			codebase_urls=["""https://github.com/mjpost/sacreBLEU#ter"""]				,			reference_urls=[
										        """https://github.com/jhclark/tercom""",
										    ]				,			)







			def 	SCREAMING_SNAKE_CASE_     (	self				:  Any				,			lowercase_				:  Any				,			lowercase_				:  Tuple				,			lowercase_				:  bool = False				,			lowercase_				:  bool = False				,			lowercase_				:  bool = False				,			lowercase_				:  bool = False				,			):
										lowercase_					:			int										=       len(references[0]    )
										if any(len(lowercase_    ) != references_per_prediction for refs in references    ):
																	raise ValueError("""Sacrebleu requires the same number of references for each prediction"""    )
										lowercase_					:			Optional[int]										=       [[refs[i] for refs in references] for i in range(lowercase_    )]

										lowercase_					:			List[str]										=       TER(
										    normalized=lowercase_				,			no_punct=lowercase_				,			asian_support=lowercase_				,			case_sensitive=lowercase_				,			)
										lowercase_					:			List[str]										=       sb_ter.corpus_score(lowercase_				,			lowercase_    )

										return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}





