



import os
import tempfile
import unittest

from transformers import FlaubertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device

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 (
		    FlaubertForMultipleChoice,
		    FlaubertForQuestionAnswering,
		    FlaubertForQuestionAnsweringSimple,
		    FlaubertForSequenceClassification,
		    FlaubertForTokenClassification,
		    FlaubertModel,
		    FlaubertWithLMHeadModel,
		)
		from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST






class 		lowercase						(			__lowercase):






	"""simple docstring"""


	def __init__(     self     :						List[str]						,  __UpperCAmelCase     :						int						,  __UpperCAmelCase     :						Optional[Any]=13						,  __UpperCAmelCase     :						str=7						,  __UpperCAmelCase     :						List[str]=True						,  __UpperCAmelCase     :						int=True						,  __UpperCAmelCase     :						Union[str, Any]=True						,  __UpperCAmelCase     :						Optional[int]=True						,  __UpperCAmelCase     :						List[Any]=True						,  __UpperCAmelCase     :						Optional[int]=False						,  __UpperCAmelCase     :						str=False						,  __UpperCAmelCase     :						Tuple=False						,  __UpperCAmelCase     :						int=2						,  __UpperCAmelCase     :						int=99						,  __UpperCAmelCase     :						Dict=0						,  __UpperCAmelCase     :						str=32						,  __UpperCAmelCase     :						Union[str, Any]=5						,  __UpperCAmelCase     :						Dict=4						,  __UpperCAmelCase     :						Optional[int]=0.1						,  __UpperCAmelCase     :						Optional[Any]=0.1						,  __UpperCAmelCase     :						Any=512						,  __UpperCAmelCase     :						List[str]=12						,  __UpperCAmelCase     :						Tuple=2						,  __UpperCAmelCase     :						List[str]=0.02						,  __UpperCAmelCase     :						int=3						,  __UpperCAmelCase     :						str=4						,  __UpperCAmelCase     :						Any="last"						,  __UpperCAmelCase     :						Any=None						,  __UpperCAmelCase     :						Optional[Any]=None						,  )      ->			List[str]:
							UpperCAmelCase_=       parent
							UpperCAmelCase_=       batch_size
							UpperCAmelCase_=       seq_length
							UpperCAmelCase_=       is_training
							UpperCAmelCase_=       use_input_lengths
							UpperCAmelCase_=       use_token_type_ids
							UpperCAmelCase_=       use_labels
							UpperCAmelCase_=       gelu_activation
							UpperCAmelCase_=       sinusoidal_embeddings
							UpperCAmelCase_=       causal
							UpperCAmelCase_=       asm
							UpperCAmelCase_=       n_langs
							UpperCAmelCase_=       vocab_size
							UpperCAmelCase_=       n_special
							UpperCAmelCase_=       hidden_size
							UpperCAmelCase_=       num_hidden_layers
							UpperCAmelCase_=       num_attention_heads
							UpperCAmelCase_=       hidden_dropout_prob
							UpperCAmelCase_=       attention_probs_dropout_prob
							UpperCAmelCase_=       max_position_embeddings
							UpperCAmelCase_=       type_vocab_size
							UpperCAmelCase_=       type_sequence_label_size
							UpperCAmelCase_=       initializer_range
							UpperCAmelCase_=       num_labels
							UpperCAmelCase_=       num_choices
							UpperCAmelCase_=       summary_type
							UpperCAmelCase_=       use_proj
							UpperCAmelCase_=       scope




	def   _SCREAMING_SNAKE_CASE		(     self     :						List[Any]					)      ->			Optional[int]:
							UpperCAmelCase_=       ids_tensor([self.batch_size, self.seq_length]						,  self.vocab_size					)
							UpperCAmelCase_=       random_attention_mask([self.batch_size, self.seq_length]					)

							UpperCAmelCase_=       None
							if self.use_input_lengths:
													UpperCAmelCase_=       (
													    ids_tensor([self.batch_size]						,  vocab_size=2					) + self.seq_length - 2
													)  # small variation of seq_length

							UpperCAmelCase_=       None
							if self.use_token_type_ids:
													UpperCAmelCase_=       ids_tensor([self.batch_size, self.seq_length]						,  self.n_langs					)

							UpperCAmelCase_=       None
							UpperCAmelCase_=       None
							UpperCAmelCase_=       None
							if self.use_labels:
													UpperCAmelCase_=       ids_tensor([self.batch_size]						,  self.type_sequence_label_size					)
													UpperCAmelCase_=       ids_tensor([self.batch_size, self.seq_length]						,  self.num_labels					)
													UpperCAmelCase_=       ids_tensor([self.batch_size]						,  2					).float()
													UpperCAmelCase_=       ids_tensor([self.batch_size]						,  self.num_choices					)

							UpperCAmelCase_=       self.get_config()

							return (
							    config,
							    input_ids,
							    token_type_ids,
							    input_lengths,
							    sequence_labels,
							    token_labels,
							    is_impossible_labels,
							    choice_labels,
							    input_mask,
							)




	def   _SCREAMING_SNAKE_CASE		(     self     :						str					)      ->			Union[str, Any]:
							return FlaubertConfig(
							    vocab_size=self.vocab_size						,  n_special=self.n_special						,  emb_dim=self.hidden_size						,  n_layers=self.num_hidden_layers						,  n_heads=self.num_attention_heads						,  dropout=self.hidden_dropout_prob						,  attention_dropout=self.attention_probs_dropout_prob						,  gelu_activation=self.gelu_activation						,  sinusoidal_embeddings=self.sinusoidal_embeddings						,  asm=self.asm						,  causal=self.causal						,  n_langs=self.n_langs						,  max_position_embeddings=self.max_position_embeddings						,  initializer_range=self.initializer_range						,  summary_type=self.summary_type						,  use_proj=self.use_proj						,  )




	def   _SCREAMING_SNAKE_CASE		(     self     :						Dict						,  __UpperCAmelCase     :						str						,  __UpperCAmelCase     :						int						,  __UpperCAmelCase     :						int						,  __UpperCAmelCase     :						Union[str, Any]						,  __UpperCAmelCase     :						Any						,  __UpperCAmelCase     :						Dict						,  __UpperCAmelCase     :						Union[str, Any]						,  __UpperCAmelCase     :						Union[str, Any]						,  __UpperCAmelCase     :						List[Any]						,  )      ->			Optional[int]:
							UpperCAmelCase_=       FlaubertModel(config=__UpperCAmelCase					)
							model.to(__UpperCAmelCase					)
							model.eval()
							UpperCAmelCase_=       model(__UpperCAmelCase						,  lengths=__UpperCAmelCase						,  langs=__UpperCAmelCase					)
							UpperCAmelCase_=       model(__UpperCAmelCase						,  langs=__UpperCAmelCase					)
							UpperCAmelCase_=       model(__UpperCAmelCase					)
							self.parent.assertEqual(result.last_hidden_state.shape						,  (self.batch_size, self.seq_length, self.hidden_size)					)




	def   _SCREAMING_SNAKE_CASE		(     self     :						Optional[Any]						,  __UpperCAmelCase     :						Tuple						,  __UpperCAmelCase     :						Dict						,  __UpperCAmelCase     :						Optional[Any]						,  __UpperCAmelCase     :						str						,  __UpperCAmelCase     :						Union[str, Any]						,  __UpperCAmelCase     :						List[str]						,  __UpperCAmelCase     :						List[str]						,  __UpperCAmelCase     :						Any						,  __UpperCAmelCase     :						List[Any]						,  )      ->			int:
							UpperCAmelCase_=       FlaubertWithLMHeadModel(__UpperCAmelCase					)
							model.to(__UpperCAmelCase					)
							model.eval()

							UpperCAmelCase_=       model(__UpperCAmelCase						,  token_type_ids=__UpperCAmelCase						,  labels=__UpperCAmelCase					)
							self.parent.assertEqual(result.loss.shape						,  ()					)
							self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.seq_length, self.vocab_size)					)




	def   _SCREAMING_SNAKE_CASE		(     self     :						Optional[int]						,  __UpperCAmelCase     :						Dict						,  __UpperCAmelCase     :						Dict						,  __UpperCAmelCase     :						Optional[Any]						,  __UpperCAmelCase     :						Union[str, Any]						,  __UpperCAmelCase     :						Dict						,  __UpperCAmelCase     :						Union[str, Any]						,  __UpperCAmelCase     :						List[str]						,  __UpperCAmelCase     :						int						,  __UpperCAmelCase     :						Any						,  )      ->			Tuple:
							UpperCAmelCase_=       FlaubertForQuestionAnsweringSimple(__UpperCAmelCase					)
							model.to(__UpperCAmelCase					)
							model.eval()

							UpperCAmelCase_=       model(__UpperCAmelCase					)

							UpperCAmelCase_=       model(__UpperCAmelCase						,  start_positions=__UpperCAmelCase						,  end_positions=__UpperCAmelCase					)
							self.parent.assertEqual(result.start_logits.shape						,  (self.batch_size, self.seq_length)					)
							self.parent.assertEqual(result.end_logits.shape						,  (self.batch_size, self.seq_length)					)




	def   _SCREAMING_SNAKE_CASE		(     self     :						Union[str, Any]						,  __UpperCAmelCase     :						List[Any]						,  __UpperCAmelCase     :						str						,  __UpperCAmelCase     :						Dict						,  __UpperCAmelCase     :						Tuple						,  __UpperCAmelCase     :						int						,  __UpperCAmelCase     :						Union[str, Any]						,  __UpperCAmelCase     :						Tuple						,  __UpperCAmelCase     :						Optional[Any]						,  __UpperCAmelCase     :						Union[str, Any]						,  )      ->			int:
							UpperCAmelCase_=       FlaubertForQuestionAnswering(__UpperCAmelCase					)
							model.to(__UpperCAmelCase					)
							model.eval()

							UpperCAmelCase_=       model(__UpperCAmelCase					)

							UpperCAmelCase_=       model(
							    __UpperCAmelCase						,  start_positions=__UpperCAmelCase						,  end_positions=__UpperCAmelCase						,  cls_index=__UpperCAmelCase						,  is_impossible=__UpperCAmelCase						,  p_mask=__UpperCAmelCase						,  )

							UpperCAmelCase_=       model(
							    __UpperCAmelCase						,  start_positions=__UpperCAmelCase						,  end_positions=__UpperCAmelCase						,  cls_index=__UpperCAmelCase						,  is_impossible=__UpperCAmelCase						,  )

							(UpperCAmelCase_      )=       result_with_labels.to_tuple()

							UpperCAmelCase_=       model(__UpperCAmelCase						,  start_positions=__UpperCAmelCase						,  end_positions=__UpperCAmelCase					)

							(UpperCAmelCase_      )=       result_with_labels.to_tuple()

							self.parent.assertEqual(result_with_labels.loss.shape						,  ()					)
							self.parent.assertEqual(result.start_top_log_probs.shape						,  (self.batch_size, model.config.start_n_top)					)
							self.parent.assertEqual(result.start_top_index.shape						,  (self.batch_size, model.config.start_n_top)					)
							self.parent.assertEqual(
							    result.end_top_log_probs.shape						,  (self.batch_size, model.config.start_n_top * model.config.end_n_top)					)
							self.parent.assertEqual(
							    result.end_top_index.shape						,  (self.batch_size, model.config.start_n_top * model.config.end_n_top)					)
							self.parent.assertEqual(result.cls_logits.shape						,  (self.batch_size,)					)




	def   _SCREAMING_SNAKE_CASE		(     self     :						Optional[Any]						,  __UpperCAmelCase     :						List[str]						,  __UpperCAmelCase     :						List[Any]						,  __UpperCAmelCase     :						int						,  __UpperCAmelCase     :						List[Any]						,  __UpperCAmelCase     :						Tuple						,  __UpperCAmelCase     :						Any						,  __UpperCAmelCase     :						str						,  __UpperCAmelCase     :						Tuple						,  __UpperCAmelCase     :						str						,  )      ->			str:
							UpperCAmelCase_=       FlaubertForSequenceClassification(__UpperCAmelCase					)
							model.to(__UpperCAmelCase					)
							model.eval()

							UpperCAmelCase_=       model(__UpperCAmelCase					)
							UpperCAmelCase_=       model(__UpperCAmelCase						,  labels=__UpperCAmelCase					)

							self.parent.assertEqual(result.loss.shape						,  ()					)
							self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.type_sequence_label_size)					)




	def   _SCREAMING_SNAKE_CASE		(     self     :						Dict						,  __UpperCAmelCase     :						Optional[Any]						,  __UpperCAmelCase     :						List[str]						,  __UpperCAmelCase     :						List[str]						,  __UpperCAmelCase     :						str						,  __UpperCAmelCase     :						int						,  __UpperCAmelCase     :						Tuple						,  __UpperCAmelCase     :						Tuple						,  __UpperCAmelCase     :						str						,  __UpperCAmelCase     :						int						,  )      ->			List[Any]:
							UpperCAmelCase_=       self.num_labels
							UpperCAmelCase_=       FlaubertForTokenClassification(__UpperCAmelCase					)
							model.to(__UpperCAmelCase					)
							model.eval()

							UpperCAmelCase_=       model(__UpperCAmelCase						,  attention_mask=__UpperCAmelCase						,  labels=__UpperCAmelCase					)
							self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.seq_length, self.num_labels)					)




	def   _SCREAMING_SNAKE_CASE		(     self     :						Dict						,  __UpperCAmelCase     :						Union[str, Any]						,  __UpperCAmelCase     :						Tuple						,  __UpperCAmelCase     :						Optional[int]						,  __UpperCAmelCase     :						List[Any]						,  __UpperCAmelCase     :						Tuple						,  __UpperCAmelCase     :						Tuple						,  __UpperCAmelCase     :						Optional[int]						,  __UpperCAmelCase     :						Any						,  __UpperCAmelCase     :						Union[str, Any]						,  )      ->			Tuple:
							UpperCAmelCase_=       self.num_choices
							UpperCAmelCase_=       FlaubertForMultipleChoice(config=__UpperCAmelCase					)
							model.to(__UpperCAmelCase					)
							model.eval()
							UpperCAmelCase_=       input_ids.unsqueeze(1					).expand(-1						,  self.num_choices						,  -1					).contiguous()
							UpperCAmelCase_=       token_type_ids.unsqueeze(1					).expand(-1						,  self.num_choices						,  -1					).contiguous()
							UpperCAmelCase_=       input_mask.unsqueeze(1					).expand(-1						,  self.num_choices						,  -1					).contiguous()
							UpperCAmelCase_=       model(
							    __UpperCAmelCase						,  attention_mask=__UpperCAmelCase						,  token_type_ids=__UpperCAmelCase						,  labels=__UpperCAmelCase						,  )
							self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.num_choices)					)




	def   _SCREAMING_SNAKE_CASE		(     self     :						Tuple					)      ->			str:
							UpperCAmelCase_=       self.prepare_config_and_inputs()
							(
							    UpperCAmelCase_      
							)=       config_and_inputs
							UpperCAmelCase_=       {
							    """input_ids""": input_ids,
							    """token_type_ids""": token_type_ids,
							    """lengths""": input_lengths,
							    """attention_mask""": input_mask,
							}
							return config, inputs_dict






@require_torch
class 		lowercase						(			__lowercase			,   __lowercase			,   unittest.TestCase):






	"""simple docstring"""


	a__				: int		       =							(
	    (
	        FlaubertModel,
	        FlaubertWithLMHeadModel,
	        FlaubertForQuestionAnswering,
	        FlaubertForQuestionAnsweringSimple,
	        FlaubertForSequenceClassification,
	        FlaubertForTokenClassification,
	        FlaubertForMultipleChoice,
	    )
	    if is_torch_available()
	    else ()
	)
	a__				: List[str]		       =							(
	    {
	        '''feature-extraction''': FlaubertModel,
	        '''fill-mask''': FlaubertWithLMHeadModel,
	        '''question-answering''': FlaubertForQuestionAnsweringSimple,
	        '''text-classification''': FlaubertForSequenceClassification,
	        '''token-classification''': FlaubertForTokenClassification,
	        '''zero-shot''': FlaubertForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)




	def   _SCREAMING_SNAKE_CASE		(     self     :						int						,  __UpperCAmelCase     :						Tuple						,  __UpperCAmelCase     :						Optional[int]						,  __UpperCAmelCase     :						Optional[Any]						,  __UpperCAmelCase     :						Union[str, Any]						,  __UpperCAmelCase     :						Tuple					)      ->			List[Any]:

							if (
							    pipeline_test_casse_name == "QAPipelineTests"
							    and tokenizer_name is not None
							    and not tokenizer_name.endswith("""Fast"""					)
							):
													# `QAPipelineTests` fails for a few models when the slower tokenizer are used.
													# (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
													# TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
													return True

							return False




	def   _SCREAMING_SNAKE_CASE		(     self     :						Optional[Any]						,  __UpperCAmelCase     :						List[Any]						,  __UpperCAmelCase     :						Dict						,  __UpperCAmelCase     :						Tuple=False					)      ->			Optional[int]:
							UpperCAmelCase_=       super()._prepare_for_class(__UpperCAmelCase						,  __UpperCAmelCase						,  return_labels=__UpperCAmelCase					)

							if return_labels:
													if model_class.__name__ == "FlaubertForQuestionAnswering":
																			UpperCAmelCase_=       torch.zeros(
																			    self.model_tester.batch_size						,  dtype=torch.long						,  device=__UpperCAmelCase					)
																			UpperCAmelCase_=       torch.zeros(
																			    self.model_tester.batch_size						,  dtype=torch.long						,  device=__UpperCAmelCase					)

							return inputs_dict




	def   _SCREAMING_SNAKE_CASE		(     self     :						Union[str, Any]					)      ->			List[str]:
							UpperCAmelCase_=       FlaubertModelTester(self					)
							UpperCAmelCase_=       ConfigTester(self						,  config_class=__UpperCAmelCase						,  emb_dim=37					)




	def   _SCREAMING_SNAKE_CASE		(     self     :						Dict					)      ->			Optional[Any]:
							self.config_tester.run_common_tests()




	def   _SCREAMING_SNAKE_CASE		(     self     :						int					)      ->			Any:
							UpperCAmelCase_=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_model(*__UpperCAmelCase					)




	def   _SCREAMING_SNAKE_CASE		(     self     :						List[str]					)      ->			Optional[int]:
							UpperCAmelCase_=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_lm_head(*__UpperCAmelCase					)




	def   _SCREAMING_SNAKE_CASE		(     self     :						Optional[int]					)      ->			Optional[Any]:
							UpperCAmelCase_=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_simple_qa(*__UpperCAmelCase					)




	def   _SCREAMING_SNAKE_CASE		(     self     :						str					)      ->			List[str]:
							UpperCAmelCase_=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_qa(*__UpperCAmelCase					)




	def   _SCREAMING_SNAKE_CASE		(     self     :						Dict					)      ->			str:
							UpperCAmelCase_=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_sequence_classif(*__UpperCAmelCase					)




	def   _SCREAMING_SNAKE_CASE		(     self     :						Optional[Any]					)      ->			Dict:
							UpperCAmelCase_=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_token_classif(*__UpperCAmelCase					)




	def   _SCREAMING_SNAKE_CASE		(     self     :						str					)      ->			List[str]:
							UpperCAmelCase_=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_flaubert_multiple_choice(*__UpperCAmelCase					)




	@slow
	def   _SCREAMING_SNAKE_CASE		(     self     :						str					)      ->			Any:

							for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													UpperCAmelCase_=       FlaubertModel.from_pretrained(__UpperCAmelCase					)
													self.assertIsNotNone(__UpperCAmelCase					)




	@slow
	@require_torch_gpu
	def   _SCREAMING_SNAKE_CASE		(     self     :						int					)      ->			int:
							UpperCAmelCase_=       self.model_tester.prepare_config_and_inputs_for_common()
							for model_class in self.all_model_classes:
													# FlauBertForMultipleChoice behaves incorrectly in JIT environments.
													if model_class == FlaubertForMultipleChoice:
																			return

													UpperCAmelCase_=       True
													UpperCAmelCase_=       model_class(config=__UpperCAmelCase					)

													UpperCAmelCase_=       self._prepare_for_class(__UpperCAmelCase						,  __UpperCAmelCase					)
													UpperCAmelCase_=       torch.jit.trace(
													    __UpperCAmelCase						,  (inputs_dict["""input_ids"""].to("""cpu"""					), inputs_dict["""attention_mask"""].to("""cpu"""					))					)

													with tempfile.TemporaryDirectory() as tmp:
																			torch.jit.save(__UpperCAmelCase						,  os.path.join(__UpperCAmelCase						,  """traced_model.pt"""					)					)
																			UpperCAmelCase_=       torch.jit.load(os.path.join(__UpperCAmelCase						,  """traced_model.pt"""					)						,  map_location=__UpperCAmelCase					)
																			loaded(inputs_dict["""input_ids"""].to(__UpperCAmelCase					)						,  inputs_dict["""attention_mask"""].to(__UpperCAmelCase					)					)






@require_torch
class 		lowercase						(			unittest.TestCase):






	"""simple docstring"""


	@slow
	def   _SCREAMING_SNAKE_CASE		(     self     :						Optional[int]					)      ->			List[Any]:
							UpperCAmelCase_=       FlaubertModel.from_pretrained("""flaubert/flaubert_base_cased"""					)
							UpperCAmelCase_=       torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]]					)
							with torch.no_grad():
													UpperCAmelCase_=       model(__UpperCAmelCase					)[0]
							UpperCAmelCase_=       torch.Size((1, 11, 768)					)
							self.assertEqual(output.shape						,  __UpperCAmelCase					)
							UpperCAmelCase_=       torch.tensor(
							    [[[-2.6_251, -1.4_298, -0.0_227], [-2.8_510, -1.6_387, 0.2_258], [-2.8_114, -1.1_832, -0.3_066]]]					)

							self.assertTrue(torch.allclose(output[:, :3, :3]						,  __UpperCAmelCase						,  atol=1E-4					)					)









import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
	import torch_xla.core.xla_model as xm
	import torch_xla.debug.metrics as met






class 		lowercase						(			snake_case__):






	"""simple docstring"""


	def __init__(     self     :						Any						,  *__UpperCAmelCase     :						Union[str, Any]						,  __UpperCAmelCase     :						List[str]=None						,  __UpperCAmelCase     :						Optional[int]=None						,  **__UpperCAmelCase     :						Dict					)      ->			Optional[int]:
							super().__init__(*__UpperCAmelCase						,  **__UpperCAmelCase					)
							UpperCAmelCase_=       eval_examples
							UpperCAmelCase_=       post_process_function




	def   _SCREAMING_SNAKE_CASE		(     self     :						Tuple						,  __UpperCAmelCase     :						Optional[Dataset] = None						,  __UpperCAmelCase     :						Optional[Any]=None						,  __UpperCAmelCase     :						Optional[List[str]] = None						,  __UpperCAmelCase     :						str = "eval"						,  **__UpperCAmelCase     :						Any						,  )      ->			Dict[str, float]:
							UpperCAmelCase_=       gen_kwargs.copy()
							UpperCAmelCase_=       (
							    gen_kwargs["""max_length"""] if gen_kwargs.get("""max_length"""					) is not None else self.args.generation_max_length
							)
							UpperCAmelCase_=       (
							    gen_kwargs["""num_beams"""] if gen_kwargs.get("""num_beams"""					) is not None else self.args.generation_num_beams
							)
							UpperCAmelCase_=       gen_kwargs

							UpperCAmelCase_=       self.eval_dataset if eval_dataset is None else eval_dataset
							UpperCAmelCase_=       self.get_eval_dataloader(__UpperCAmelCase					)
							UpperCAmelCase_=       self.eval_examples if eval_examples is None else eval_examples

							# Temporarily disable metric computation, we will do it in the loop here.
							UpperCAmelCase_=       self.compute_metrics
							UpperCAmelCase_=       None
							UpperCAmelCase_=       time.time()
							UpperCAmelCase_=       self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
							try:
													UpperCAmelCase_=       eval_loop(
													    __UpperCAmelCase						,  description="""Evaluation"""						,  prediction_loss_only=True if compute_metrics is None else None						,  ignore_keys=__UpperCAmelCase						,  metric_key_prefix=__UpperCAmelCase						,  )
							finally:
													UpperCAmelCase_=       compute_metrics
							UpperCAmelCase_=       self.args.eval_batch_size * self.args.world_size
							if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics:
													start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""]
							output.metrics.update(
							    speed_metrics(
							        __UpperCAmelCase						,  __UpperCAmelCase						,  num_samples=output.num_samples						,  num_steps=math.ceil(output.num_samples / total_batch_size					)						,  )					)

							if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
													# Only the main node write the results by default
													UpperCAmelCase_=       self.post_process_function(__UpperCAmelCase						,  __UpperCAmelCase						,  __UpperCAmelCase					)
													UpperCAmelCase_=       self.compute_metrics(__UpperCAmelCase					)

													# Prefix all keys with metric_key_prefix + '_'
													for key in list(metrics.keys()					):
																			if not key.startswith(F"""{metric_key_prefix}_"""					):
																									UpperCAmelCase_=       metrics.pop(__UpperCAmelCase					)

													metrics.update(output.metrics					)
							else:
													UpperCAmelCase_=       output.metrics

							if self.args.should_log:
													# Only the main node log the results by default
													self.log(__UpperCAmelCase					)

							if self.args.tpu_metrics_debug or self.args.debug:
													# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
													xm.master_print(met.metrics_report()					)

							UpperCAmelCase_=       self.callback_handler.on_evaluate(self.args						,  self.state						,  self.control						,  __UpperCAmelCase					)
							return metrics




	def   _SCREAMING_SNAKE_CASE		(     self     :						int						,  __UpperCAmelCase     :						Dict						,  __UpperCAmelCase     :						int						,  __UpperCAmelCase     :						Optional[int]=None						,  __UpperCAmelCase     :						str = "test"						,  **__UpperCAmelCase     :						List[str]					)      ->			Tuple:
							UpperCAmelCase_=       gen_kwargs.copy()

							UpperCAmelCase_=       self.get_test_dataloader(__UpperCAmelCase					)

							# Temporarily disable metric computation, we will do it in the loop here.
							UpperCAmelCase_=       self.compute_metrics
							UpperCAmelCase_=       None
							UpperCAmelCase_=       time.time()
							UpperCAmelCase_=       self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
							try:
													UpperCAmelCase_=       eval_loop(
													    __UpperCAmelCase						,  description="""Prediction"""						,  prediction_loss_only=True if compute_metrics is None else None						,  ignore_keys=__UpperCAmelCase						,  metric_key_prefix=__UpperCAmelCase						,  )
							finally:
													UpperCAmelCase_=       compute_metrics

							UpperCAmelCase_=       self.args.eval_batch_size * self.args.world_size
							if F"""{metric_key_prefix}_jit_compilation_time""" in output.metrics:
													start_time += output.metrics[F"""{metric_key_prefix}_jit_compilation_time"""]
							output.metrics.update(
							    speed_metrics(
							        __UpperCAmelCase						,  __UpperCAmelCase						,  num_samples=output.num_samples						,  num_steps=math.ceil(output.num_samples / total_batch_size					)						,  )					)
							if self.post_process_function is None or self.compute_metrics is None:
													return output

							UpperCAmelCase_=       self.post_process_function(__UpperCAmelCase						,  __UpperCAmelCase						,  __UpperCAmelCase						,  """predict"""					)
							UpperCAmelCase_=       self.compute_metrics(__UpperCAmelCase					)

							# Prefix all keys with metric_key_prefix + '_'
							for key in list(metrics.keys()					):
													if not key.startswith(F"""{metric_key_prefix}_"""					):
																			UpperCAmelCase_=       metrics.pop(__UpperCAmelCase					)
							metrics.update(output.metrics					)
							return PredictionOutput(predictions=predictions.predictions						,  label_ids=predictions.label_ids						,  metrics=__UpperCAmelCase					)




