






import datasets

from .nmt_bleu import compute_bleu  # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py


__lowerCamelCase :      Union[str, Any]										=				"""\
@INPROCEEDINGS{Papineni02bleu:a,
    author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},
    title = {BLEU: a Method for Automatic Evaluation of Machine Translation},
    booktitle = {},
    year = {2002},
    pages = {311--318}
}
@inproceedings{lin-och-2004-orange,
    title = \"{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation\",
    author = \"Lin, Chin-Yew  and
      Och, Franz Josef\",
    booktitle = \"{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics\",
    month = \"aug 23{--}aug 27\",
    year = \"2004\",
    address = \"Geneva, Switzerland\",
    publisher = \"COLING\",
    url = \"https://www.aclweb.org/anthology/C04-1072\",
    pages = \"501--507\",
}
"""

__lowerCamelCase :      List[Any]										=				"""\
BLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.
Quality is considered to be the correspondence between a machine's output and that of a human: \"the closer a machine translation is to a professional human translation,
the better it is\" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and
remains one of the most popular automated and inexpensive metrics.

Scores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.
Those scores are then averaged over the whole corpus to reach an estimate of the translation's overall quality. Intelligibility or grammatical correctness
are not taken into account[citation needed].

BLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1
representing more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the
reference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional
reference translations will increase the BLEU score.
"""

__lowerCamelCase :      Dict										=				"""
Computes BLEU score of translated segments against one or more references.
Args:
    predictions: list of translations to score.
        Each translation should be tokenized into a list of tokens.
    references: list of lists of references for each translation.
        Each reference should be tokenized into a list of tokens.
    max_order: Maximum n-gram order to use when computing BLEU score.
    smooth: Whether or not to apply Lin et al. 2004 smoothing.
Returns:
    'bleu': bleu score,
    'precisions': geometric mean of n-gram precisions,
    'brevity_penalty': brevity penalty,
    'length_ratio': ratio of lengths,
    'translation_length': translation_length,
    'reference_length': reference_length
Examples:

    >>> predictions = [
    ...     [\"hello\", \"there\", \"general\", \"kenobi\"],                             # tokenized prediction of the first sample
    ...     [\"foo\", \"bar\", \"foobar\"]                                             # tokenized prediction of the second sample
    ... ]
    >>> references = [
    ...     [[\"hello\", \"there\", \"general\", \"kenobi\"], [\"hello\", \"there\", \"!\"]],  # tokenized references for the first sample (2 references)
    ...     [[\"foo\", \"bar\", \"foobar\"]]                                           # tokenized references for the second sample (1 reference)
    ... ]
    >>> bleu = datasets.load_metric(\"bleu\")
    >>> results = bleu.compute(predictions=predictions, references=references)
    >>> print(results[\"bleu\"])
    1.0
"""



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





					"""simple docstring"""






					def 	_lowercase					( self					:  int	):
						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"	),
						        }	)							,		codebase_urls=["https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py"]							,		reference_urls=[
						        "https://en.wikipedia.org/wiki/BLEU",
						        "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213",
						    ]							,		)






					def 	_lowercase					( self					:  Any							,		__A					:  List[Any]							,		__A					:  Optional[int]							,		__A					:  Optional[int]=4							,		__A					:  List[Any]=False	):
						snake_case__			:				Any       =  compute_bleu(
						    reference_corpus=__A							,		translation_corpus=__A							,		max_order=__A							,		smooth=__A	)
						((snake_case__),						(snake_case__),						(snake_case__),						(snake_case__),						(snake_case__),						(snake_case__))			:				Any       =  score
						return {
						    "bleu": bleu,
						    "precisions": precisions,
						    "brevity_penalty": bp,
						    "length_ratio": ratio,
						    "translation_length": translation_length,
						    "reference_length": reference_length,
						}











import random
import timeit
from functools import wraps
from typing import Callable, Optional

from ..configuration_utils import PretrainedConfig
from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING
from ..utils import is_pyanvml_available, is_tf_available, logging
from .benchmark_utils import (
    Benchmark,
    Memory,
    MemorySummary,
    measure_peak_memory_cpu,
    start_memory_tracing,
    stop_memory_tracing,
)


if is_tf_available():
	import tensorflow as tf
	from tensorflow.python.framework.errors_impl import ResourceExhaustedError

	from .benchmark_args_tf import TensorFlowBenchmarkArguments

if is_pyanvml_available():
	import pyanvml.pyanvml as nvml

__lowerCamelCase :      List[Any]										=				logging.get_logger(__name__)







def 					SCREAMING_SNAKE_CASE    (			snake_case_ :							bool					,  snake_case_ :							bool       ):
	def run_func(snake_case_ :							str       ):
		@wraps(snake_case_       )
		def run_in_eager_mode(*snake_case_ :							str					,  **snake_case_ :							Union[str, Any]       ):
			return func(*snake_case_					,  **snake_case_       )

		@wraps(snake_case_       )
		@tf.function(experimental_compile=snake_case_       )
		def run_in_graph_mode(*snake_case_ :							List[Any]					,  **snake_case_ :							List[Any]       ):
			return func(*snake_case_					,  **snake_case_       )

		if do_eager_mode is True:
			if use_xla is not False:
				raise ValueError(
				    "Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`."       )
			return run_in_eager_mode
		else:
			return run_in_graph_mode

	return run_func







def 					SCREAMING_SNAKE_CASE    (			snake_case_ :							int					,  snake_case_ :							int					,  snake_case_ :							int       ):
	snake_case__			:				Dict       =  random.Random()
	snake_case__			:				List[Any]       =  [rng.randint(0					,  vocab_size - 1       ) for i in range(batch_size * sequence_length       )]
	return tf.constant(snake_case_					,  shape=(batch_size, sequence_length)					,  dtype=tf.intaa       )





class 							SCREAMING_SNAKE_CASE__						(    UpperCamelCase_						):





					"""simple docstring"""






					a_     =		42
					a_     =		42
					a_     =		"TensorFlow"



					@property
					def 	_lowercase					( self					:  List[str]	):
						return tf.__version__



					def 	_lowercase					( self					:  List[str]							,		__A					:  str							,		__A					:  int							,		__A					:  int	):
						# initialize GPU on separate process
						snake_case__			:				str       =  self.args.strategy
						if strategy is None:
							raise ValueError("A device strategy has to be initialized before using TensorFlow."	)
						snake_case__			:				Dict       =  self._prepare_inference_func(__A							,		__A							,		__A	)
						return self._measure_speed(_inference	)



					def 	_lowercase					( self					:  Tuple							,		__A					:  str							,		__A					:  int							,		__A					:  int	):
						snake_case__			:				Optional[int]       =  self.args.strategy
						if strategy is None:
							raise ValueError("A device strategy has to be initialized before using TensorFlow."	)
						snake_case__			:				Any       =  self._prepare_train_func(__A							,		__A							,		__A	)
						return self._measure_speed(_train	)



					def 	_lowercase					( self					:  List[Any]							,		__A					:  str							,		__A					:  int							,		__A					:  int	):
						# initialize GPU on separate process
						if self.args.is_gpu:
							tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]							,		__A	)
						snake_case__			:				List[str]       =  self.args.strategy
						if strategy is None:
							raise ValueError("A device strategy has to be initialized before using TensorFlow."	)
						snake_case__			:				Optional[Any]       =  self._prepare_inference_func(__A							,		__A							,		__A	)
						return self._measure_memory(_inference	)



					def 	_lowercase					( self					:  str							,		__A					:  str							,		__A					:  int							,		__A					:  int	):
						if self.args.is_gpu:
							tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]							,		__A	)
						snake_case__			:				List[Any]       =  self.args.strategy
						if strategy is None:
							raise ValueError("A device strategy has to be initialized before using TensorFlow."	)

						snake_case__			:				int       =  self._prepare_train_func(__A							,		__A							,		__A	)
						return self._measure_memory(_train	)



					def 	_lowercase					( self					:  Union[str, Any]							,		__A					:  str							,		__A					:  int							,		__A					:  int	):
						snake_case__			:				int       =  self.config_dict[model_name]

						if self.args.fpaa:
							raise NotImplementedError("Mixed precision is currently not supported."	)

						snake_case__			:				Tuple       =  (
						    hasattr(__A							,		"architectures"	)
						    and isinstance(config.architectures							,		__A	)
						    and len(config.architectures	) > 0
						)
						if not self.args.only_pretrain_model and has_model_class_in_config:
							try:
								snake_case__			:				Dict       =  "TF" + config.architectures[0]  # prepend 'TF' for tensorflow model
								snake_case__			:				Union[str, Any]       =  __import__("transformers"							,		fromlist=[model_class]	)
								snake_case__			:				Any       =  getattr(__A							,		__A	)
								snake_case__			:				Dict       =  model_cls(__A	)
							except ImportError:
								raise ImportError(
								    f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
								    " set `--only_pretrain_model` or `args.only_pretrain_model=True`."	)
						else:
							snake_case__			:				Dict       =  TF_MODEL_MAPPING[config.__class__](__A	)

						# encoder-decoder has vocab size saved differently
						snake_case__			:				Optional[int]       =  config.vocab_size if hasattr(__A							,		"vocab_size"	) else config.encoder.vocab_size
						snake_case__			:				List[Any]       =  random_input_ids(__A							,		__A							,		__A	)

						@run_with_tf_optimizations(self.args.eager_mode							,		self.args.use_xla	)
						def encoder_decoder_forward():
							return model(__A							,		decoder_input_ids=__A							,		training=__A	)

						@run_with_tf_optimizations(self.args.eager_mode							,		self.args.use_xla	)
						def encoder_forward():
							return model(__A							,		training=__A	)

						snake_case__			:				Optional[int]       =  encoder_decoder_forward if config.is_encoder_decoder else encoder_forward

						return _inference



					def 	_lowercase					( self					:  List[str]							,		__A					:  str							,		__A					:  int							,		__A					:  int	):
						snake_case__			:				Optional[Any]       =  self.config_dict[model_name]

						if self.args.eager_mode is not False:
							raise ValueError("Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`."	)

						if self.args.fpaa:
							raise NotImplementedError("Mixed precision is currently not supported."	)

						snake_case__			:				Any       =  (
						    hasattr(__A							,		"architectures"	)
						    and isinstance(config.architectures							,		__A	)
						    and len(config.architectures	) > 0
						)
						if not self.args.only_pretrain_model and has_model_class_in_config:
							try:
								snake_case__			:				Dict       =  "TF" + config.architectures[0]  # prepend 'TF' for tensorflow model
								snake_case__			:				List[Any]       =  __import__("transformers"							,		fromlist=[model_class]	)
								snake_case__			:				Optional[int]       =  getattr(__A							,		__A	)
								snake_case__			:				str       =  model_cls(__A	)
							except ImportError:
								raise ImportError(
								    f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
								    " set `--only_pretrain_model` or `args.only_pretrain_model=True`."	)
						else:
							snake_case__			:				Union[str, Any]       =  TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](__A	)

						# encoder-decoder has vocab size saved differently
						snake_case__			:				Union[str, Any]       =  config.vocab_size if hasattr(__A							,		"vocab_size"	) else config.encoder.vocab_size
						snake_case__			:				List[str]       =  random_input_ids(__A							,		__A							,		__A	)

						@run_with_tf_optimizations(self.args.eager_mode							,		self.args.use_xla	)
						def encoder_decoder_train():
							snake_case__			:				str       =  model(__A							,		decoder_input_ids=__A							,		labels=__A							,		training=__A	)[0]
							snake_case__			:				Dict       =  tf.gradients(__A							,		model.trainable_variables	)
							return gradients

						@run_with_tf_optimizations(self.args.eager_mode							,		self.args.use_xla	)
						def encoder_train():
							snake_case__			:				Optional[Any]       =  model(__A							,		labels=__A							,		training=__A	)[0]
							snake_case__			:				Dict       =  tf.gradients(__A							,		model.trainable_variables	)
							return gradients

						snake_case__			:				int       =  encoder_decoder_train if config.is_encoder_decoder else encoder_train

						return _train



					def 	_lowercase					( self					:  int							,		__A					:  List[Any]	):
						with self.args.strategy.scope():
							try:
								if self.args.is_tpu or self.args.use_xla:
									# run additional 10 times to stabilize compilation for tpu
									logger.info("Do inference on TPU. Running model 5 times to stabilize compilation"	)
									timeit.repeat(__A							,		repeat=1							,		number=5	)

								# as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average
								snake_case__			:				Optional[Any]       =  timeit.repeat(
								    __A							,		repeat=self.args.repeat							,		number=1_0							,		)

								return min(__A	) / 1_0.0
							except ResourceExhaustedError as e:
								self.print_fn(f'''Doesn\'t fit on GPU. {e}'''	)






					def 	_lowercase					( self					:  str							,		__A					:  Callable[[], None]	):
						logger.info(
						    "Note that TensorFlow allocates more memory than "
						    "it might need to speed up computation. "
						    "The memory reported here corresponds to the memory "
						    "reported by `nvidia-smi`, which can vary depending "
						    "on total available memory on the GPU that is used."	)
						with self.args.strategy.scope():
							try:
								if self.args.trace_memory_line_by_line:
									if not self.args.eager_mode:
										raise ValueError(
										    "`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory"
										    " consumption line by line."	)
									snake_case__			:				Optional[int]       =  start_memory_tracing("transformers"	)

								if self.args.is_tpu:
									# tpu
									raise NotImplementedError(
									    "Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking"
									    " with `args.memory=False`"	)
								elif self.args.is_gpu:
									# gpu
									if not is_pyanvml_available():
										logger.warning(
										    "py3nvml not installed, we won't log GPU memory usage. "
										    "Install py3nvml (pip install py3nvml) to log information about GPU."	)
										snake_case__			:				List[str]       =  "N/A"
									else:
										logger.info(
										    "Measuring total GPU usage on GPU device. Make sure to not have additional processes"
										    " running on the same GPU."	)
										# init nvml
										nvml.nvmlInit()
										func()
										snake_case__			:				Any       =  nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx	)
										snake_case__			:				Optional[Any]       =  nvml.nvmlDeviceGetMemoryInfo(__A	)
										snake_case__			:				Optional[int]       =  meminfo.used
										snake_case__			:				Any       =  Memory(__A	)
										# shutdown nvml
										nvml.nvmlShutdown()
								else:
									# cpu
									if self.args.trace_memory_line_by_line:
										logger.info(
										    "When enabling line by line tracing, the max peak memory for CPU is inaccurate in"
										    " TensorFlow."	)
										snake_case__			:				int       =  None
									else:
										snake_case__			:				Any       =  measure_peak_memory_cpu(__A	)
										snake_case__			:				Tuple       =  Memory(__A	) if isinstance(__A							,		__A	) else memory_bytes
								if self.args.trace_memory_line_by_line:
									snake_case__			:				Optional[int]       =  stop_memory_tracing(__A	)
									if memory is None:
										snake_case__			:				Dict       =  summary.total
								else:
									snake_case__			:				List[str]       =  None

								return memory, summary
							except ResourceExhaustedError as e:
								self.print_fn(f'''Doesn\'t fit on GPU. {e}'''	)
								return "N/A", None



