



'''simple docstring'''

import datasets

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


__lowerCAmelCase		     =  """\
@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		     =  """\
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		     =  """
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       __magic_name__		(       datasets.Metric  ):







							def 				__lowercase     (				self   :			List[Any]						):
									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   :			Union[str, Any]      ,_UpperCAmelCase   :			Any      ,_UpperCAmelCase   :			Union[str, Any]      ,_UpperCAmelCase   :			Tuple=4      ,_UpperCAmelCase   :			List[Any]=False						):
									_a	: List[str]								=				compute_bleu(
									    reference_corpus=lowerCamelCase_      ,translation_corpus=lowerCamelCase_      ,max_order=lowerCamelCase_      ,smooth=lowerCamelCase_						)
									(_a)	: List[Any]								=				score
									return {
									    "bleu": bleu,
									    "precisions": precisions,
									    "brevity_penalty": bp,
									    "length_ratio": ratio,
									    "translation_length": translation_length,
									    "reference_length": reference_length,
									}











import unittest

from parameterized import parameterized

from transformers import OpenLlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
			import torch

			from transformers import OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel


class       __lowerCAmelCase					:


	'''simple docstring'''





	def __init__(						self:						Any,					lowerCamelCase_:						Optional[Any],					lowerCamelCase_:						List[str]=13,					lowerCamelCase_:						Optional[Any]=7,					lowerCamelCase_:						Optional[Any]=True,					lowerCamelCase_:						Tuple=True,					lowerCamelCase_:						Any=False,					lowerCamelCase_:						Union[str, Any]=True,					lowerCamelCase_:						Optional[Any]=99,					lowerCamelCase_:						Tuple=32,					lowerCamelCase_:						Any=5,					lowerCamelCase_:						Tuple=4,					lowerCamelCase_:						List[Any]=37,					lowerCamelCase_:						Union[str, Any]="gelu",					lowerCamelCase_:						str=0.1,					lowerCamelCase_:						Union[str, Any]=0.1,					lowerCamelCase_:						Any=512,					lowerCamelCase_:						Union[str, Any]=16,					lowerCamelCase_:						Any=2,					lowerCamelCase_:						str=0.0_2,					lowerCamelCase_:						Union[str, Any]=3,					lowerCamelCase_:						List[str]=4,					lowerCamelCase_:						Tuple=None,					):
			lowercase__					:      List[str]      =		parent
			lowercase__					:      str      =		batch_size
			lowercase__					:      Optional[int]      =		seq_length
			lowercase__					:      List[Any]      =		is_training
			lowercase__					:      List[str]      =		use_input_mask
			lowercase__					:      Optional[int]      =		use_token_type_ids
			lowercase__					:      str      =		use_labels
			lowercase__					:      Optional[Any]      =		vocab_size
			lowercase__					:      Dict      =		hidden_size
			lowercase__					:      List[Any]      =		num_hidden_layers
			lowercase__					:      Tuple      =		num_attention_heads
			lowercase__					:      Dict      =		intermediate_size
			lowercase__					:      Tuple      =		hidden_act
			lowercase__					:      List[str]      =		hidden_dropout_prob
			lowercase__					:      List[str]      =		attention_probs_dropout_prob
			lowercase__					:      str      =		max_position_embeddings
			lowercase__					:      List[Any]      =		type_vocab_size
			lowercase__					:      Tuple      =		type_sequence_label_size
			lowercase__					:      Optional[int]      =		initializer_range
			lowercase__					:      str      =		num_labels
			lowercase__					:      Optional[int]      =		num_choices
			lowercase__					:      Dict      =		scope

	def    snake_case__(						self:						Union[str, Any]			):
			lowercase__					:      Any      =		ids_tensor([self.batch_size, self.seq_length],					self.vocab_size			)

			lowercase__					:      List[Any]      =		None
			if self.use_input_mask:
					lowercase__					:      List[str]      =		random_attention_mask([self.batch_size, self.seq_length]			)

			lowercase__					:      Optional[Any]      =		None
			if self.use_token_type_ids:
					lowercase__					:      Tuple      =		ids_tensor([self.batch_size, self.seq_length],					self.type_vocab_size			)

			lowercase__					:      str      =		None
			lowercase__					:      Union[str, Any]      =		None
			lowercase__					:      Tuple      =		None
			if self.use_labels:
					lowercase__					:      Tuple      =		ids_tensor([self.batch_size],					self.type_sequence_label_size			)
					lowercase__					:      Any      =		ids_tensor([self.batch_size, self.seq_length],					self.num_labels			)
					lowercase__					:      int      =		ids_tensor([self.batch_size],					self.num_choices			)

			lowercase__					:      Tuple      =		self.get_config()

			return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels

	def    snake_case__(						self:						Tuple			):
			return OpenLlamaConfig(
			    vocab_size=self.vocab_size,					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,					max_position_embeddings=self.max_position_embeddings,					type_vocab_size=self.type_vocab_size,					is_decoder=lowerCamelCase_,					initializer_range=self.initializer_range,					use_stable_embedding=lowerCamelCase_,					)

	def    snake_case__(						self:						Optional[int],					lowerCamelCase_:						Optional[int],					lowerCamelCase_:						List[Any],					lowerCamelCase_:						List[str],					lowerCamelCase_:						Optional[int],					lowerCamelCase_:						Dict,					lowerCamelCase_:						Optional[int],					lowerCamelCase_:						str			):
			lowercase__					:      Union[str, Any]      =		OpenLlamaModel(config=lowerCamelCase_			)
			model.to(lowerCamelCase_			)
			model.eval()
			lowercase__					:      Union[str, Any]      =		model(lowerCamelCase_,					attention_mask=lowerCamelCase_			)
			lowercase__					:      List[Any]      =		model(lowerCamelCase_			)
			self.parent.assertEqual(result.last_hidden_state.shape,					(self.batch_size, self.seq_length, self.hidden_size)			)

	def    snake_case__(						self:						str,					lowerCamelCase_:						Optional[Any],					lowerCamelCase_:						str,					lowerCamelCase_:						str,					lowerCamelCase_:						Optional[Any],					lowerCamelCase_:						Tuple,					lowerCamelCase_:						Optional[Any],					lowerCamelCase_:						List[str],					lowerCamelCase_:						Dict,					lowerCamelCase_:						Union[str, Any],					):
			lowercase__					:      Tuple      =		True
			lowercase__					:      int      =		OpenLlamaModel(lowerCamelCase_			)
			model.to(lowerCamelCase_			)
			model.eval()
			lowercase__					:      List[Any]      =		model(
			    lowerCamelCase_,					attention_mask=lowerCamelCase_,					encoder_hidden_states=lowerCamelCase_,					encoder_attention_mask=lowerCamelCase_,					)
			lowercase__					:      Optional[int]      =		model(
			    lowerCamelCase_,					attention_mask=lowerCamelCase_,					encoder_hidden_states=lowerCamelCase_,					)
			lowercase__					:      str      =		model(lowerCamelCase_,					attention_mask=lowerCamelCase_			)
			self.parent.assertEqual(result.last_hidden_state.shape,					(self.batch_size, self.seq_length, self.hidden_size)			)

	def    snake_case__(						self:						List[Any],					lowerCamelCase_:						Optional[Any],					lowerCamelCase_:						Any,					lowerCamelCase_:						str,					lowerCamelCase_:						List[str],					lowerCamelCase_:						Any,					lowerCamelCase_:						Dict,					lowerCamelCase_:						int,					lowerCamelCase_:						Any,					lowerCamelCase_:						str,					):
			lowercase__					:      Optional[Any]      =		OpenLlamaForCausalLM(config=lowerCamelCase_			)
			model.to(lowerCamelCase_			)
			model.eval()
			lowercase__					:      List[Any]      =		model(lowerCamelCase_,					attention_mask=lowerCamelCase_,					labels=lowerCamelCase_			)
			self.parent.assertEqual(result.logits.shape,					(self.batch_size, self.seq_length, self.vocab_size)			)

	def    snake_case__(						self:						Tuple,					lowerCamelCase_:						str,					lowerCamelCase_:						Optional[Any],					lowerCamelCase_:						Optional[int],					lowerCamelCase_:						str,					lowerCamelCase_:						List[Any],					lowerCamelCase_:						List[Any],					lowerCamelCase_:						str,					lowerCamelCase_:						Optional[Any],					lowerCamelCase_:						Union[str, Any],					):
			lowercase__					:      Optional[int]      =		True
			lowercase__					:      Optional[int]      =		True
			lowercase__					:      Tuple      =		OpenLlamaForCausalLM(config=lowerCamelCase_			)
			model.to(lowerCamelCase_			)
			model.eval()

			# first forward pass
			lowercase__					:      Any      =		model(
			    lowerCamelCase_,					attention_mask=lowerCamelCase_,					encoder_hidden_states=lowerCamelCase_,					encoder_attention_mask=lowerCamelCase_,					use_cache=lowerCamelCase_,					)
			lowercase__					:      str      =		outputs.past_key_values

			# create hypothetical multiple next token and extent to next_input_ids
			lowercase__					:      Optional[Any]      =		ids_tensor((self.batch_size, 3),					config.vocab_size			)
			lowercase__					:      str      =		ids_tensor((self.batch_size, 3),					vocab_size=2			)

			# append to next input_ids and
			lowercase__					:      Tuple      =		torch.cat([input_ids, next_tokens],					dim=-1			)
			lowercase__					:      List[str]      =		torch.cat([input_mask, next_mask],					dim=-1			)

			lowercase__					:      int      =		model(
			    lowerCamelCase_,					attention_mask=lowerCamelCase_,					encoder_hidden_states=lowerCamelCase_,					encoder_attention_mask=lowerCamelCase_,					output_hidden_states=lowerCamelCase_,					)['hidden_states'][0]
			lowercase__					:      int      =		model(
			    lowerCamelCase_,					attention_mask=lowerCamelCase_,					encoder_hidden_states=lowerCamelCase_,					encoder_attention_mask=lowerCamelCase_,					past_key_values=lowerCamelCase_,					output_hidden_states=lowerCamelCase_,					)['hidden_states'][0]

			# select random slice
			lowercase__					:      Tuple      =		ids_tensor((1,),					output_from_past.shape[-1]			).item()
			lowercase__					:      Union[str, Any]      =		output_from_no_past[:, -3:, random_slice_idx].detach()
			lowercase__					:      Tuple      =		output_from_past[:, :, random_slice_idx].detach()

			self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]			)

			# test that outputs are equal for slice
			self.parent.assertTrue(torch.allclose(lowerCamelCase_,					lowerCamelCase_,					atol=1E-3			)			)





	def    snake_case__(						self:						Optional[Any]			):
			lowercase__					:      Dict      =		self.prepare_config_and_inputs()
			(
			    (
			    lowercase__
			)   ,				(
			    lowercase__
			)   ,				(
			    lowercase__
			)   ,				(
			    lowercase__
			)   ,				(
			    lowercase__
			)   ,				(
			    lowercase__
			)   ,				(
			    lowercase__
			)   ,				
			)					:      List[str]      =		config_and_inputs
			lowercase__					:      Any      =		{'input_ids': input_ids, 'attention_mask': input_mask}
			return config, inputs_dict


@require_torch
class       __lowerCAmelCase					(       _UpperCamelCase   ,    _UpperCamelCase   ,    _UpperCamelCase   ,    unittest.TestCase      ):


	'''simple docstring'''





	_A													=				(
	    (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else ()
	)
	_A													=				(OpenLlamaForCausalLM,) if is_torch_available() else ()
	_A													=				(
	    {
	        "feature-extraction": OpenLlamaModel,
	        "text-classification": OpenLlamaForSequenceClassification,
	        "text-generation": OpenLlamaForCausalLM,
	        "zero-shot": OpenLlamaForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	_A													=				False
	_A													=				False

	def    snake_case__(						self:						Any			):
			lowercase__					:      List[Any]      =		OpenLlamaModelTester(self			)
			lowercase__					:      Dict      =		ConfigTester(self,					config_class=lowerCamelCase_,					hidden_size=37			)

	def    snake_case__(						self:						Any			):
			self.config_tester.run_common_tests()

	def    snake_case__(						self:						Dict			):
			lowercase__					:      Any      =		self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*lowerCamelCase_			)

	def    snake_case__(						self:						str			):
			lowercase__					:      Any      =		self.model_tester.prepare_config_and_inputs()
			for type in ["absolute", "relative_key", "relative_key_query"]:
					lowercase__					:      Dict      =		type
					self.model_tester.create_and_check_model(*lowerCamelCase_			)

	def    snake_case__(						self:						Any			):
			lowercase__   ,				lowercase__					:      List[Any]      =		self.model_tester.prepare_config_and_inputs_for_common()
			lowercase__					:      Tuple      =		3
			lowercase__					:      Union[str, Any]      =		input_dict['input_ids']
			lowercase__					:      Union[str, Any]      =		input_ids.ne(1			).to(lowerCamelCase_			)
			lowercase__					:      int      =		ids_tensor([self.model_tester.batch_size],					self.model_tester.type_sequence_label_size			)
			lowercase__					:      Optional[Any]      =		OpenLlamaForSequenceClassification(lowerCamelCase_			)
			model.to(lowerCamelCase_			)
			model.eval()
			lowercase__					:      Optional[Any]      =		model(lowerCamelCase_,					attention_mask=lowerCamelCase_,					labels=lowerCamelCase_			)
			self.assertEqual(result.logits.shape,					(self.model_tester.batch_size, self.model_tester.num_labels)			)

	def    snake_case__(						self:						Any			):
			lowercase__   ,				lowercase__					:      int      =		self.model_tester.prepare_config_and_inputs_for_common()
			lowercase__					:      str      =		3
			lowercase__					:      Optional[Any]      =		'single_label_classification'
			lowercase__					:      Union[str, Any]      =		input_dict['input_ids']
			lowercase__					:      str      =		input_ids.ne(1			).to(lowerCamelCase_			)
			lowercase__					:      Any      =		ids_tensor([self.model_tester.batch_size],					self.model_tester.type_sequence_label_size			)
			lowercase__					:      Dict      =		OpenLlamaForSequenceClassification(lowerCamelCase_			)
			model.to(lowerCamelCase_			)
			model.eval()
			lowercase__					:      Optional[int]      =		model(lowerCamelCase_,					attention_mask=lowerCamelCase_,					labels=lowerCamelCase_			)
			self.assertEqual(result.logits.shape,					(self.model_tester.batch_size, self.model_tester.num_labels)			)

	def    snake_case__(						self:						Union[str, Any]			):
			lowercase__   ,				lowercase__					:      Optional[int]      =		self.model_tester.prepare_config_and_inputs_for_common()
			lowercase__					:      Dict      =		3
			lowercase__					:      List[Any]      =		'multi_label_classification'
			lowercase__					:      Any      =		input_dict['input_ids']
			lowercase__					:      int      =		input_ids.ne(1			).to(lowerCamelCase_			)
			lowercase__					:      Optional[int]      =		ids_tensor(
			    [self.model_tester.batch_size, config.num_labels],					self.model_tester.type_sequence_label_size			).to(torch.float			)
			lowercase__					:      Optional[int]      =		OpenLlamaForSequenceClassification(lowerCamelCase_			)
			model.to(lowerCamelCase_			)
			model.eval()
			lowercase__					:      List[Any]      =		model(lowerCamelCase_,					attention_mask=lowerCamelCase_,					labels=lowerCamelCase_			)
			self.assertEqual(result.logits.shape,					(self.model_tester.batch_size, self.model_tester.num_labels)			)

	@unittest.skip('Open-Llama buffers include complex numbers, which breaks this test'			)
	def    snake_case__(						self:						List[str]			):
			pass





	@parameterized.expand([('linear',), ('dynamic',)]			)
	def    snake_case__(						self:						Any,					lowerCamelCase_:						List[Any]			):
			lowercase__   ,				lowercase__					:      Optional[Any]      =		self.model_tester.prepare_config_and_inputs_for_common()
			lowercase__					:      Optional[int]      =		ids_tensor([1, 10],					config.vocab_size			)
			lowercase__					:      Optional[Any]      =		ids_tensor([1, int(config.max_position_embeddings * 1.5			)],					config.vocab_size			)

			set_seed(42			)  # Fixed seed at init time so the two models get the same random weights
			lowercase__					:      str      =		OpenLlamaModel(lowerCamelCase_			)
			original_model.to(lowerCamelCase_			)
			original_model.eval()
			lowercase__					:      Union[str, Any]      =		original_model(lowerCamelCase_			).last_hidden_state
			lowercase__					:      List[str]      =		original_model(lowerCamelCase_			).last_hidden_state

			set_seed(42			)  # Fixed seed at init time so the two models get the same random weights
			lowercase__					:      List[str]      =		{'type': scaling_type, 'factor': 1_0.0}
			lowercase__					:      Union[str, Any]      =		OpenLlamaModel(lowerCamelCase_			)
			scaled_model.to(lowerCamelCase_			)
			scaled_model.eval()
			lowercase__					:      Dict      =		scaled_model(lowerCamelCase_			).last_hidden_state
			lowercase__					:      Union[str, Any]      =		scaled_model(lowerCamelCase_			).last_hidden_state

			# Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
			# maximum sequence length, so the outputs for the short input should match.
			if scaling_type == "dynamic":
					self.assertTrue(torch.allclose(lowerCamelCase_,					lowerCamelCase_,					atol=1E-5			)			)
			else:
					self.assertFalse(torch.allclose(lowerCamelCase_,					lowerCamelCase_,					atol=1E-5			)			)

			# The output should be different for long inputs
			self.assertFalse(torch.allclose(lowerCamelCase_,					lowerCamelCase_,					atol=1E-5			)			)


