





from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


_UpperCAmelCase             =							'\\n@misc{wu2016googles,\n      title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n      author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n              and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n              Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n              Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n              Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n              and Jeffrey Dean},\n      year={2016},\n      eprint={1609.08144},\n      archivePrefix={arXiv},\n      primaryClass={cs.CL}\n}\n'

_UpperCAmelCase             =							'\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe \'GLEU score\'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore\'s range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n'

_UpperCAmelCase             =							'\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n    predictions (list of str): list of translations to score.\n        Each translation should be tokenized into a list of tokens.\n    references (list of list of str): list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\n    min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n    max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n    \'google_bleu\': google_bleu score\n\nExamples:\n    Example 1:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results["google_bleu"], 2))\n        0.44\n\n    Example 2:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n        ...          \'heed\', \'the\', \'cat\', \'commands\']\n        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n        ...          \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results["google_bleu"], 2))\n        0.61\n\n    Example 3:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n        ...          \'heed\', \'the\', \'cat\', \'commands\']\n        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n        ...          \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n        >>> print(round(results["google_bleu"], 2))\n        0.53\n\n    Example 4:\n        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n        ...          \'heed\', \'the\', \'cat\', \'commands\']\n        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n        ...          \'of\', \'the\', \'cat\']\n\n        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n        ...         \'interested\', \'in\', \'world\', \'history\']\n        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n        ...          \'because\', \'he\', \'read\', \'the\', \'book\']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric("google_bleu")\n        >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n        >>> print(round(results["google_bleu"], 2))\n        0.4\n'






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






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






			'''simple docstring'''

			return datasets.MetricInfo(
			    description=_DESCRIPTION       ,  citation=_CITATION       ,  inputs_description=_KWARGS_DESCRIPTION       ,  features=datasets.Features(
			        {
			            """predictions""": datasets.Sequence(datasets.Value("""string"""       ,  id="""token"""      )       ,  id="""sequence"""      ),
			            """references""": datasets.Sequence(
			                datasets.Sequence(datasets.Value("""string"""       ,  id="""token"""      )       ,  id="""sequence"""      )       ,  id="""references"""      ),
			        }      )       ,  )






		def 				UpperCAmelCase__						(							self			:					Tuple       ,  _snake_case			:					List[List[List[str]]]       ,  _snake_case			:					List[List[str]]       ,  _snake_case			:					int = 1       ,  _snake_case			:					int = 4       ,  )->Dict[str, float]:






			'''simple docstring'''

			return {
			    "google_bleu": gleu_score.corpus_gleu(
			        list_of_references=_snake_case       ,  hypotheses=_snake_case       ,  min_len=_snake_case       ,  max_len=_snake_case      )
			}






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        snake_case_    (		unittest.TestCase						):






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






   '''simple docstring'''

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

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






  def 				UpperCAmelCase__						(							self			:					Any      )->Any:






   '''simple docstring'''

   __lowerCAmelCase					:	List[Any]      =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

   __lowerCAmelCase					:	Tuple      =       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=_snake_case       ,  initializer_range=self.initializer_range       ,  )

   return config, pixel_values






  def 				UpperCAmelCase__						(							self			:					List[Any]       ,  _snake_case			:					List[str]       ,  _snake_case			:					List[Any]      )->Any:






   '''simple docstring'''

   __lowerCAmelCase					:	str      =       FlaxViTModel(config=_snake_case      )
   __lowerCAmelCase					:	int      =       model(_snake_case      )
   # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
   __lowerCAmelCase					:	Dict      =       (self.image_size, self.image_size)
   __lowerCAmelCase					:	Any      =       (self.patch_size, self.patch_size)
   __lowerCAmelCase					:	Any      =       (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 				UpperCAmelCase__						(							self			:					Dict       ,  _snake_case			:					str       ,  _snake_case			:					List[Any]      )->Union[str, Any]:






   '''simple docstring'''

   __lowerCAmelCase					:	Tuple      =       self.type_sequence_label_size
   __lowerCAmelCase					:	Tuple      =       FlaxViTForImageClassification(config=_snake_case      )
   __lowerCAmelCase					:	List[str]      =       model(_snake_case      )
   self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.type_sequence_label_size)      )

   # test greyscale images
   __lowerCAmelCase					:	str      =       1
   __lowerCAmelCase					:	Any      =       FlaxViTForImageClassification(_snake_case      )

   __lowerCAmelCase					:	int      =       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]      )
   __lowerCAmelCase					:	Dict      =       model(_snake_case      )






  def 				UpperCAmelCase__						(							self			:					str      )->Any:






   '''simple docstring'''

   __lowerCAmelCase					:	Any      =       self.prepare_config_and_inputs()
   (
       (
       __lowerCAmelCase
   ) ,					(
       __lowerCAmelCase
   ) ,					
   )					:	Union[str, Any]      =       config_and_inputs
   __lowerCAmelCase					:	str      =       {"""pixel_values""": pixel_values}
   return config, inputs_dict






@require_flax
class        snake_case_    (		__lowercase					,unittest.TestCase						):
  A_      							=   (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else ()






  def 				UpperCAmelCase__						(							self			:					str      )->None:






   '''simple docstring'''

   __lowerCAmelCase					:	List[str]      =       FlaxViTModelTester(self      )
   __lowerCAmelCase					:	Optional[Any]      =       ConfigTester(self       ,  config_class=_snake_case       ,  has_text_modality=_snake_case       ,  hidden_size=37      )






  def 				UpperCAmelCase__						(							self			:					Any      )->Dict:






   '''simple docstring'''

   self.config_tester.run_common_tests()






  def 				UpperCAmelCase__						(							self			:					Any      )->Any:






   '''simple docstring'''

   __lowerCAmelCase					:	Dict      =       self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*_snake_case      )






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






   '''simple docstring'''

   __lowerCAmelCase					:	Dict      =       self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*_snake_case      )






  def 				UpperCAmelCase__						(							self			:					int      )->int:






   '''simple docstring'''

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

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

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






  def 				UpperCAmelCase__						(							self			:					str      )->str:






   '''simple docstring'''

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

   for model_class in self.all_model_classes:
    with self.subTest(model_class.__name__      ):
     __lowerCAmelCase					:	Optional[int]      =       self._prepare_for_class(_snake_case       ,  _snake_case      )
     __lowerCAmelCase					:	List[str]      =       model_class(_snake_case      )

     @jax.jit
     def model_jitted(_snake_case			:					Dict       ,  **_snake_case			:					Union[str, Any]      ):
      return model(pixel_values=_snake_case       ,  **_snake_case      )

     with self.subTest("""JIT Enabled"""      ):
      __lowerCAmelCase					:	List[Any]      =       model_jitted(**_snake_case      ).to_tuple()

     with self.subTest("""JIT Disabled"""      ):
      with jax.disable_jit():
       __lowerCAmelCase					:	str      =       model_jitted(**_snake_case      ).to_tuple()

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






  @slow
  def 				UpperCAmelCase__						(							self			:					Dict      )->str:






   '''simple docstring'''

   for model_class_name in self.all_model_classes:
    __lowerCAmelCase					:	List[str]      =       model_class_name.from_pretrained("""google/vit-base-patch16-224"""      )
    __lowerCAmelCase					:	List[str]      =       model(np.ones((1, 3, 224, 224)      )      )
    self.assertIsNotNone(_snake_case      )