'''simple docstring'''

from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


UpperCamelCase__  :						Tuple					=      '\\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__  :						List[Any]					=      '\\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__  :						Dict					=      '\\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 					_lowercase						(   datasets.Metric ):
      '''simple docstring'''


      def 		lowerCAmelCase__       (					self				)      ->      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 		lowerCAmelCase__       (					self       ,lowerCamelCase_       ,lowerCamelCase_       ,lowerCamelCase_ = 1       ,lowerCamelCase_ = 4       ,)      ->      Dict[str, float]:



         '''simple docstring'''



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






"""simple docstring"""





import inspect
import unittest

from huggingface_hub import hf_hub_download

from transformers import ConvNextConfig, UperNetConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import UperNetForSemanticSegmentation
				from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import AutoImageProcessor






class        _UpperCAmelCase:



		def __init__(   self							,						__a							,						__a=13							,						__a=32							,						__a=3							,						__a=4							,						__a=[10, 20, 30, 40]							,						__a=[2, 2, 3, 2]							,						__a=True							,						__a=True							,						__a=37							,						__a="gelu"							,						__a=10							,						__a=0.02							,						__a=["stage2", "stage3", "stage4"]							,						__a=3							,						__a=None							,						)			->			Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase									=    parent
							_UpperCamelCase									=    batch_size
							_UpperCamelCase									=    image_size
							_UpperCamelCase									=    num_channels
							_UpperCamelCase									=    num_stages
							_UpperCamelCase									=    hidden_sizes
							_UpperCamelCase									=    depths
							_UpperCamelCase									=    is_training
							_UpperCamelCase									=    use_labels
							_UpperCamelCase									=    intermediate_size
							_UpperCamelCase									=    hidden_act
							_UpperCamelCase									=    type_sequence_label_size
							_UpperCamelCase									=    initializer_range
							_UpperCamelCase									=    out_features
							_UpperCamelCase									=    num_labels
							_UpperCamelCase									=    scope
							_UpperCamelCase									=    num_stages



		def 		UpperCAmelCase				(   self)			->			List[str]:






							'''simple docstring'''
							_UpperCamelCase									=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

							_UpperCamelCase									=    self.get_config()

							return config, pixel_values, labels



		def 		UpperCAmelCase				(   self)			->			Any:






							'''simple docstring'''
							return ConvNextConfig(
							    num_channels=self.num_channels							,						num_stages=self.num_stages							,						hidden_sizes=self.hidden_sizes							,						depths=self.depths							,						is_training=self.is_training							,						intermediate_size=self.intermediate_size							,						hidden_act=self.hidden_act							,						out_features=self.out_features							,						)



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






							'''simple docstring'''
							return UperNetConfig(
							    backbone_config=self.get_backbone_config()							,						hidden_size=5_12							,						pool_scales=[1, 2, 3, 6]							,						use_auxiliary_head=__a							,						auxiliary_loss_weight=0.4							,						auxiliary_in_channels=40							,						auxiliary_channels=2_56							,						auxiliary_num_convs=1							,						auxiliary_concat_input=__a							,						loss_ignore_index=2_55							,						num_labels=self.num_labels							,						)



		def 		UpperCAmelCase				(   self							,						__a							,						__a							,						__a)			->			Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase									=    UperNetForSemanticSegmentation(config=__a)
							model.to(__a)
							model.eval()
							_UpperCamelCase									=    model(__a)
							self.parent.assertEqual(
							    result.logits.shape							,						(self.batch_size, self.num_labels, self.image_size, self.image_size))




		def 		UpperCAmelCase				(   self)			->			Dict:






							'''simple docstring'''
							_UpperCamelCase									=    self.prepare_config_and_inputs()
							(
							    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    (
							    _UpperCamelCase
							)					,    
							)									=    config_and_inputs
							_UpperCamelCase									=    {'''pixel_values''': pixel_values}
							return config, inputs_dict






@require_torch
class        _UpperCAmelCase(       lowerCamelCase ,	lowerCamelCase ,	unittest.TestCase      ):
		lowercase__         = (UperNetForSemanticSegmentation,) if is_torch_available() else ()
		lowercase__         = {'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {}
		lowercase__         = False
		lowercase__         = False
		lowercase__         = False
		lowercase__         = False
		lowercase__         = False
		lowercase__         = False



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






							'''simple docstring'''
							_UpperCamelCase									=    UperNetModelTester(self)
							_UpperCamelCase									=    ConfigTester(self							,						config_class=__a							,						has_text_modality=__a							,						hidden_size=37)



		def 		UpperCAmelCase				(   self)			->			Dict:






							'''simple docstring'''
							self.create_and_test_config_common_properties()
							self.config_tester.create_and_test_config_to_json_string()
							self.config_tester.create_and_test_config_to_json_file()
							self.config_tester.create_and_test_config_from_and_save_pretrained()
							self.config_tester.create_and_test_config_with_num_labels()
							self.config_tester.check_config_can_be_init_without_params()
							self.config_tester.check_config_arguments_init()



		def 		UpperCAmelCase				(   self)			->			List[Any]:






							'''simple docstring'''
							return



		def 		UpperCAmelCase				(   self)			->			str:






							'''simple docstring'''
							_UpperCamelCase					,    _UpperCamelCase									=    self.model_tester.prepare_config_and_inputs_for_common()

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

												_UpperCamelCase									=    ['''pixel_values''']
												self.assertListEqual(arg_names[:1]							,						__a)



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






							'''simple docstring'''
							_UpperCamelCase									=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_semantic_segmentation(*__a)



		@unittest.skip(reason='''UperNet does not use inputs_embeds''')
		def 		UpperCAmelCase				(   self)			->			Any:






							'''simple docstring'''
							pass



		@unittest.skip(reason='''UperNet does not support input and output embeddings''')
		def 		UpperCAmelCase				(   self)			->			List[Any]:






							'''simple docstring'''
							pass



		@unittest.skip(reason='''UperNet does not have a base model''')
		def 		UpperCAmelCase				(   self)			->			Tuple:






							'''simple docstring'''
							pass



		@unittest.skip(reason='''UperNet does not have a base model''')
		def 		UpperCAmelCase				(   self)			->			int:






							'''simple docstring'''
							pass



		@require_torch_multi_gpu
		@unittest.skip(reason='''UperNet has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''')
		def 		UpperCAmelCase				(   self)			->			Union[str, Any]:






							'''simple docstring'''
							pass



		@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''')
		def 		UpperCAmelCase				(   self)			->			Any:






							'''simple docstring'''
							pass



		def 		UpperCAmelCase				(   self)			->			List[Any]:






							'''simple docstring'''
							def check_hidden_states_output(__a							,						__a							,						__a):
												_UpperCamelCase									=    model_class(__a)
												model.to(__a)
												model.eval()

												with torch.no_grad():
																	_UpperCamelCase									=    model(**self._prepare_for_class(__a							,						__a))

												_UpperCamelCase									=    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

												_UpperCamelCase									=    self.model_tester.num_stages
												self.assertEqual(len(__a)							,						expected_num_stages + 1)

												# ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
												self.assertListEqual(
												    list(hidden_states[0].shape[-2:])							,						[self.model_tester.image_size // 4, self.model_tester.image_size // 4]							,						)

							_UpperCamelCase					,    _UpperCamelCase									=    self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												_UpperCamelCase									=    True
												check_hidden_states_output(__a							,						__a							,						__a)

												# check that output_hidden_states also work using config
												del inputs_dict["output_hidden_states"]
												_UpperCamelCase									=    True

												check_hidden_states_output(__a							,						__a							,						__a)



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






							'''simple docstring'''
							_UpperCamelCase					,    _UpperCamelCase									=    self.model_tester.prepare_config_and_inputs_for_common()

							_UpperCamelCase									=    _config_zero_init(__a)
							_UpperCamelCase									=    _config_zero_init(configs_no_init.backbone_config)
							for model_class in self.all_model_classes:
												_UpperCamelCase									=    model_class(config=__a)
												for name, param in model.named_parameters():
																	if param.requires_grad:
																						self.assertIn(
																						    ((param.data.mean() * 1e9).round() / 1e9).item()							,						[0.0, 1.0]							,						msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''							,						)



		@unittest.skip(reason='''UperNet does not have tied weights''')
		def 		UpperCAmelCase				(   self)			->			Optional[int]:






							'''simple docstring'''
							pass




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






							'''simple docstring'''
							for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												_UpperCamelCase									=    UperNetForSemanticSegmentation.from_pretrained(__a)
												self.assertIsNotNone(__a)





def  lowerCamelCase__						(     )				->						int:


					"""simple docstring"""





					_UpperCamelCase									=    hf_hub_download(
					    repo_id='''hf-internal-testing/fixtures_ade20k''',	repo_type='''dataset''',	filename='''ADE_val_00000001.jpg'''      )
					_UpperCamelCase									=    Image.open(__snake_case      ).convert('''RGB'''      )
					return image






@require_torch
@require_vision
@slow
class        _UpperCAmelCase(       unittest.TestCase      ):



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






							'''simple docstring'''
							_UpperCamelCase									=    AutoImageProcessor.from_pretrained('''openmmlab/upernet-swin-tiny''')
							_UpperCamelCase									=    UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-swin-tiny''').to(__a)

							_UpperCamelCase									=    prepare_img()
							_UpperCamelCase									=    processor(images=__a							,						return_tensors='''pt''').to(__a)

							with torch.no_grad():
												_UpperCamelCase									=    model(**__a)

							_UpperCamelCase									=    torch.Size((1, model.config.num_labels, 5_12, 5_12))
							self.assertEqual(outputs.logits.shape							,						__a)

							_UpperCamelCase									=    torch.tensor(
							    [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]]).to(__a)
							self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]							,						__a							,						atol=1e-4))




		def 		UpperCAmelCase				(   self)			->			List[Any]:






							'''simple docstring'''
							_UpperCamelCase									=    AutoImageProcessor.from_pretrained('''openmmlab/upernet-convnext-tiny''')
							_UpperCamelCase									=    UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-convnext-tiny''').to(__a)

							_UpperCamelCase									=    prepare_img()
							_UpperCamelCase									=    processor(images=__a							,						return_tensors='''pt''').to(__a)

							with torch.no_grad():
												_UpperCamelCase									=    model(**__a)

							_UpperCamelCase									=    torch.Size((1, model.config.num_labels, 5_12, 5_12))
							self.assertEqual(outputs.logits.shape							,						__a)

							_UpperCamelCase									=    torch.tensor(
							    [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]]).to(__a)
							self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]							,						__a							,						atol=1e-4))






