





import comet  # From: unbabel-comet
import torch

import datasets


_UpperCAmelCase       =				datasets.logging.get_logger(__name__)

_UpperCAmelCase       =				"\\n@inproceedings{rei-EtAl:2020:WMT,\n   author    = {Rei, Ricardo  and  Stewart, Craig  and  Farinha, Ana C  and  Lavie, Alon},\n   title     = {Unbabel's Participation in the WMT20 Metrics Shared Task},\n   booktitle      = {Proceedings of the Fifth Conference on Machine Translation},\n   month          = {November},\n   year           = {2020},\n   address        = {Online},\n   publisher      = {Association for Computational Linguistics},\n   pages     = {909--918},\n}\n@inproceedings{rei-etal-2020-comet,\n   title = \"{COMET}: A Neural Framework for {MT} Evaluation\",\n   author = \"Rei, Ricardo  and\n      Stewart, Craig  and\n      Farinha, Ana C  and\n      Lavie, Alon\",\n   booktitle = \"Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)\",\n   month = nov,\n   year = \"2020\",\n   address = \"Online\",\n   publisher = \"Association for Computational Linguistics\",\n   url = \"https://www.aclweb.org/anthology/2020.emnlp-main.213\",\n   pages = \"2685--2702\",\n}\n"

_UpperCAmelCase       =				"\\nCrosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA's or MQM).\nWith the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition.\n\nSee the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.\n"

_UpperCAmelCase       =				"\nCOMET score.\n\nArgs:\n\n`sources` (list of str): Source sentences\n`predictions` (list of str): candidate translations\n`references` (list of str): reference translations\n`cuda` (bool): If set to True, runs COMET using GPU\n`show_progress` (bool): Shows progress\n`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.\n\nReturns:\n    `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.\n    `scores`: List of scores.\n\nExamples:\n\n    >>> comet_metric = datasets.load_metric('comet')\n    >>> # comet_metric = load_metric('comet', 'wmt20-comet-da')  # you can also choose which model to use\n    >>> source = [\"Dem Feuer konnte Einhalt geboten werden\", \"Schulen und Kindergärten wurden eröffnet.\"]\n    >>> hypothesis = [\"The fire could be stopped\", \"Schools and kindergartens were open\"]\n    >>> reference = [\"They were able to control the fire.\", \"Schools and kindergartens opened\"]\n    >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)\n    >>> print([round(v, 2) for v in results[\"scores\"]])\n    [0.19, 0.92]\n"






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






  def  UpperCAmelCase__		(				self					:	Optional[Any]     )->Any:






   '''simple docstring'''

   return datasets.MetricInfo(
       description=_DESCRIPTION  ,    citation=_CITATION  ,    homepage="""https://unbabel.github.io/COMET/html/index.html"""  ,    inputs_description=_KWARGS_DESCRIPTION  ,    features=datasets.Features(
           {
               """sources""": datasets.Value("""string"""  ,    id="""sequence"""     ),
               """predictions""": datasets.Value("""string"""  ,    id="""sequence"""     ),
               """references""": datasets.Value("""string"""  ,    id="""sequence"""     ),
           }     )  ,    codebase_urls=["""https://github.com/Unbabel/COMET"""]  ,    reference_urls=[
           """https://github.com/Unbabel/COMET""",
           """https://www.aclweb.org/anthology/2020.emnlp-main.213/""",
           """http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6""",
       ]  ,    )






  def  UpperCAmelCase__		(				self					:	Optional[Any]  ,    _snake_case					:	Optional[Any]     )->Tuple:






   '''simple docstring'''

   if self.config_name == "default":
    __lowerCAmelCase	:			str         =  comet.load_from_checkpoint(comet.download_model("""wmt20-comet-da"""     )     )
   else:
    __lowerCAmelCase	:			Optional[int]         =  comet.load_from_checkpoint(comet.download_model(self.config_name     )     )






  def  UpperCAmelCase__		(				self					:	List[Any]  ,    _snake_case					:	Optional[int]  ,    _snake_case					:	Tuple  ,    _snake_case					:	List[str]  ,    _snake_case					:	int=None  ,    _snake_case					:	Optional[int]=False     )->Union[str, Any]:






   '''simple docstring'''

   if gpus is None:
    __lowerCAmelCase	:			Union[str, Any]         =  1 if torch.cuda.is_available() else 0
   __lowerCAmelCase	:			Optional[Any]         =  {"""src""": sources, """mt""": predictions, """ref""": references}
   __lowerCAmelCase	:			Optional[int]         =  [dict(zip(__UpperCAmelCase  ,    __UpperCAmelCase     )     ) for t in zip(*data.values()     )]
   __lowerCAmelCase   ,	__lowerCAmelCase	:			List[Any]         =  self.scorer.predict(__UpperCAmelCase  ,    gpus=__UpperCAmelCase  ,    progress_bar=__UpperCAmelCase     )
   return {"mean_score": mean_score, "scores": scores}


"""simple docstring"""




import inspect
import unittest

import numpy as np

from transformers import ViTConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
						import jax

						from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel





class  lowerCamelCase    (unittest.TestCase      ):

			def __init__(       self					:    List[Any]     ,					__UpperCAmelCase					:    Dict     ,					__UpperCAmelCase					:    Optional[Any]=1_3     ,					__UpperCAmelCase					:    Tuple=3_0     ,					__UpperCAmelCase					:    str=2     ,					__UpperCAmelCase					:    List[Any]=3     ,					__UpperCAmelCase					:    Any=True     ,					__UpperCAmelCase					:    Dict=True     ,					__UpperCAmelCase					:    Optional[Any]=3_2     ,					__UpperCAmelCase					:    Any=5     ,					__UpperCAmelCase					:    Optional[Any]=4     ,					__UpperCAmelCase					:    Tuple=3_7     ,					__UpperCAmelCase					:    List[str]="gelu"     ,					__UpperCAmelCase					:    Union[str, Any]=0.1     ,					__UpperCAmelCase					:    List[str]=0.1     ,					__UpperCAmelCase					:    int=1_0     ,					__UpperCAmelCase					:    Any=0.02     ,					) ->     Union[str, Any]:
						SCREAMING_SNAKE_CASE__										=   parent
						SCREAMING_SNAKE_CASE__										=   batch_size
						SCREAMING_SNAKE_CASE__										=   image_size
						SCREAMING_SNAKE_CASE__										=   patch_size
						SCREAMING_SNAKE_CASE__										=   num_channels
						SCREAMING_SNAKE_CASE__										=   is_training
						SCREAMING_SNAKE_CASE__										=   use_labels
						SCREAMING_SNAKE_CASE__										=   hidden_size
						SCREAMING_SNAKE_CASE__										=   num_hidden_layers
						SCREAMING_SNAKE_CASE__										=   num_attention_heads
						SCREAMING_SNAKE_CASE__										=   intermediate_size
						SCREAMING_SNAKE_CASE__										=   hidden_act
						SCREAMING_SNAKE_CASE__										=   hidden_dropout_prob
						SCREAMING_SNAKE_CASE__										=   attention_probs_dropout_prob
						SCREAMING_SNAKE_CASE__										=   type_sequence_label_size
						SCREAMING_SNAKE_CASE__										=   initializer_range

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

			def        SCREAMING_SNAKE_CASE					(       self					:    List[str]							) ->     Any:
						SCREAMING_SNAKE_CASE__										=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

						SCREAMING_SNAKE_CASE__										=   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=__UpperCAmelCase     ,					initializer_range=self.initializer_range     ,					)

						return config, pixel_values

			def        SCREAMING_SNAKE_CASE					(       self					:    Dict     ,					__UpperCAmelCase					:    int     ,					__UpperCAmelCase					:    int							) ->     Optional[Any]:
						SCREAMING_SNAKE_CASE__										=   FlaxViTModel(config=__UpperCAmelCase							)
						SCREAMING_SNAKE_CASE__										=   model(__UpperCAmelCase							)
						# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
						SCREAMING_SNAKE_CASE__										=   (self.image_size, self.image_size)
						SCREAMING_SNAKE_CASE__										=   (self.patch_size, self.patch_size)
						SCREAMING_SNAKE_CASE__										=   (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
						self.parent.assertEqual(result.last_hidden_state.shape     ,					(self.batch_size, num_patches + 1, self.hidden_size)							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Union[str, Any]     ,					__UpperCAmelCase					:    Optional[int]     ,					__UpperCAmelCase					:    Optional[Any]							) ->     int:
						SCREAMING_SNAKE_CASE__										=   self.type_sequence_label_size
						SCREAMING_SNAKE_CASE__										=   FlaxViTForImageClassification(config=__UpperCAmelCase							)
						SCREAMING_SNAKE_CASE__										=   model(__UpperCAmelCase							)
						self.parent.assertEqual(result.logits.shape     ,					(self.batch_size, self.type_sequence_label_size)							)

						# test greyscale images
						SCREAMING_SNAKE_CASE__										=   1
						SCREAMING_SNAKE_CASE__										=   FlaxViTForImageClassification(__UpperCAmelCase							)

						SCREAMING_SNAKE_CASE__										=   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
						SCREAMING_SNAKE_CASE__										=   model(__UpperCAmelCase							)





			def        SCREAMING_SNAKE_CASE					(       self					:    Tuple							) ->     str:
						SCREAMING_SNAKE_CASE__										=   self.prepare_config_and_inputs()
						(
						    (
						    SCREAMING_SNAKE_CASE__
						)				,		(
						    SCREAMING_SNAKE_CASE__
						)				,		
						)										=   config_and_inputs
						SCREAMING_SNAKE_CASE__										=   {"""pixel_values""": pixel_values}
						return config, inputs_dict





@require_flax
class  lowerCamelCase    (A__      ,unittest.TestCase      ):
			lowerCamelCase__ :		Tuple       		=				(FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else ()

			def        SCREAMING_SNAKE_CASE					(       self					:    int							) ->     None:
						SCREAMING_SNAKE_CASE__										=   FlaxViTModelTester(self							)
						SCREAMING_SNAKE_CASE__										=   ConfigTester(self     ,					config_class=__UpperCAmelCase     ,					has_text_modality=__UpperCAmelCase     ,					hidden_size=3_7							)

			def        SCREAMING_SNAKE_CASE					(       self					:    int							) ->     Dict:
						self.config_tester.run_common_tests()

			def        SCREAMING_SNAKE_CASE					(       self					:    Optional[int]							) ->     Optional[Any]:
						SCREAMING_SNAKE_CASE__										=   self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__UpperCAmelCase							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Optional[Any]							) ->     List[str]:
						SCREAMING_SNAKE_CASE__										=   self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Any							) ->     str:
						SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__										=   self.model_tester.prepare_config_and_inputs_for_common()

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

									SCREAMING_SNAKE_CASE__										=   ["""pixel_values"""]
									self.assertListEqual(arg_names[:1]     ,					__UpperCAmelCase							)

			def        SCREAMING_SNAKE_CASE					(       self					:    Any							) ->     Optional[Any]:
						SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__										=   self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									with self.subTest(model_class.__name__							):
												SCREAMING_SNAKE_CASE__										=   self._prepare_for_class(__UpperCAmelCase     ,					__UpperCAmelCase							)
												SCREAMING_SNAKE_CASE__										=   model_class(__UpperCAmelCase							)

												@jax.jit
												def model_jitted(__UpperCAmelCase					:    int     ,					**__UpperCAmelCase					:    Tuple							):
															return model(pixel_values=__UpperCAmelCase     ,					**__UpperCAmelCase							)

												with self.subTest("""JIT Enabled"""							):
															SCREAMING_SNAKE_CASE__										=   model_jitted(**__UpperCAmelCase							).to_tuple()

												with self.subTest("""JIT Disabled"""							):
															with jax.disable_jit():
																		SCREAMING_SNAKE_CASE__										=   model_jitted(**__UpperCAmelCase							).to_tuple()

												self.assertEqual(len(__UpperCAmelCase							)     ,					len(__UpperCAmelCase							)							)
												for jitted_output, output in zip(__UpperCAmelCase     ,					__UpperCAmelCase							):
															self.assertEqual(jitted_output.shape     ,					output.shape							)





			@slow
			def        SCREAMING_SNAKE_CASE					(       self					:    Any							) ->     Dict:
						for model_class_name in self.all_model_classes:
									SCREAMING_SNAKE_CASE__										=   model_class_name.from_pretrained("""google/vit-base-patch16-224"""							)
									SCREAMING_SNAKE_CASE__										=   model(np.ones((1, 3, 2_2_4, 2_2_4)							)							)
									self.assertIsNotNone(__UpperCAmelCase							)


