'''simple docstring'''


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 					__SCREAMING_SNAKE_CASE						(	lowerCamelCase_	):







  '''simple docstring'''






  def __init__(			self				,		*snake_case_				,		snake_case_=None				,		snake_case_=None				,		**snake_case_						):




       '''simple docstring'''

       super().__init__(*snake_case_				,		**snake_case_						)
       UpperCAmelCase_							:       int       =				eval_examples
       UpperCAmelCase_							:       Dict       =				post_process_function


  def _UpperCamelCase					(			self				,		snake_case_ = None				,		snake_case_=None				,		snake_case_ = None				,		snake_case_ = "eval"				,		**snake_case_				,		):




       '''simple docstring'''

       UpperCAmelCase_							:       Optional[int]       =				gen_kwargs.copy()
       UpperCAmelCase_							:       List[str]       =				(
           gen_kwargs['max_length'] if gen_kwargs.get('max_length'						) is not None else self.args.generation_max_length
       )
       UpperCAmelCase_							:       Optional[int]       =				(
           gen_kwargs['num_beams'] if gen_kwargs.get('num_beams'						) is not None else self.args.generation_num_beams
       )
       UpperCAmelCase_							:       int       =				gen_kwargs

       UpperCAmelCase_							:       str       =				self.eval_dataset if eval_dataset is None else eval_dataset
       UpperCAmelCase_							:       Optional[Any]       =				self.get_eval_dataloader(snake_case_						)
       UpperCAmelCase_							:       Any       =				self.eval_examples if eval_examples is None else eval_examples

       # Temporarily disable metric computation, we will do it in the loop here.
       UpperCAmelCase_							:       List[str]       =				self.compute_metrics
       UpperCAmelCase_							:       List[str]       =				None
       UpperCAmelCase_							:       Union[str, Any]       =				time.time()
       UpperCAmelCase_							:       List[Any]       =				self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
       try:
            UpperCAmelCase_							:       int       =				eval_loop(
                snake_case_				,		description='Evaluation'				,		prediction_loss_only=True if compute_metrics is None else None				,		ignore_keys=snake_case_				,		metric_key_prefix=snake_case_				,		)
       finally:
            UpperCAmelCase_							:       int       =				compute_metrics
       UpperCAmelCase_							:       Any       =				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(
               snake_case_				,		snake_case_				,		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_							:       int       =				self.post_process_function(snake_case_				,		snake_case_				,		snake_case_						)
            UpperCAmelCase_							:       str       =				self.compute_metrics(snake_case_						)

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

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

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

       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_							:       Optional[Any]       =				self.callback_handler.on_evaluate(self.args				,		self.state				,		self.control				,		snake_case_						)
       return metrics






  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_				,		snake_case_=None				,		snake_case_ = "test"				,		**snake_case_						):




       '''simple docstring'''

       UpperCAmelCase_							:       Optional[Any]       =				gen_kwargs.copy()

       UpperCAmelCase_							:       str       =				self.get_test_dataloader(snake_case_						)

       # Temporarily disable metric computation, we will do it in the loop here.
       UpperCAmelCase_							:       Any       =				self.compute_metrics
       UpperCAmelCase_							:       int       =				None
       UpperCAmelCase_							:       int       =				time.time()
       UpperCAmelCase_							:       Union[str, Any]       =				self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
       try:
            UpperCAmelCase_							:       Optional[int]       =				eval_loop(
                snake_case_				,		description='Prediction'				,		prediction_loss_only=True if compute_metrics is None else None				,		ignore_keys=snake_case_				,		metric_key_prefix=snake_case_				,		)
       finally:
            UpperCAmelCase_							:       List[str]       =				compute_metrics

       UpperCAmelCase_							:       Dict       =				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(
               snake_case_				,		snake_case_				,		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_							:       Dict       =				self.post_process_function(snake_case_				,		snake_case_				,		snake_case_				,		'predict'						)
       UpperCAmelCase_							:       Any       =				self.compute_metrics(snake_case_						)

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







'''simple docstring'''


import json
import os
import subprocess
import unittest
from ast import literal_eval

import pytest
from parameterized import parameterized_class

from . import is_sagemaker_available


if is_sagemaker_available():
 from sagemaker import Session, TrainingJobAnalytics
 from sagemaker.huggingface import HuggingFace






@pytest.mark.skipif(
    literal_eval(os.getenv('''TEST_SAGEMAKER'''						,     '''False'''	)	) is not True						,     reason='''Skipping test because should only be run when releasing minor transformers version'''						,     )
@pytest.mark.usefixtures('''sm_env'''	)
@parameterized_class(
    [
        {
            '''framework''': '''pytorch''',
            '''script''': '''run_glue.py''',
            '''model_name_or_path''': '''distilbert-base-cased''',
            '''instance_type''': '''ml.g4dn.xlarge''',
            '''results''': {'''train_runtime''': 650, '''eval_accuracy''': 0.6, '''eval_loss''': 0.9},
        },
        {
            '''framework''': '''tensorflow''',
            '''script''': '''run_tf.py''',
            '''model_name_or_path''': '''distilbert-base-cased''',
            '''instance_type''': '''ml.g4dn.xlarge''',
            '''results''': {'''train_runtime''': 600, '''eval_accuracy''': 0.3, '''eval_loss''': 0.9},
        },
    ]	)
class 					__SCREAMING_SNAKE_CASE						(	unittest.TestCase	):







  '''simple docstring'''






  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       if self.framework == "pytorch":
            subprocess.run(
                F'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split()				,		encoding='utf-8'				,		check=snake_case_				,		)
       assert hasattr(self				,		'env'						)


  def _UpperCamelCase					(			self				,		snake_case_=1						):




       '''simple docstring'''

       return HuggingFace(
           entry_point=self.script				,		source_dir=self.env.test_path				,		role=self.env.role				,		image_uri=self.env.image_uri				,		base_job_name=F'''{self.env.base_job_name}-single'''				,		instance_count=snake_case_				,		instance_type=self.instance_type				,		debugger_hook_config=snake_case_				,		hyperparameters={**self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path}				,		metric_definitions=self.env.metric_definitions				,		py_version='py36'				,		)


  def _UpperCamelCase					(			self				,		snake_case_						):




       '''simple docstring'''

       TrainingJobAnalytics(snake_case_						).export_csv(F'''{self.env.test_path}/{job_name}_metrics.csv'''						)






  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       UpperCAmelCase_							:       Union[str, Any]       =				self.create_estimator()

       # run training
       estimator.fit()

       # result dataframe
       UpperCAmelCase_							:       int       =				TrainingJobAnalytics(estimator.latest_training_job.name						).dataframe()

       # extract kpis
       UpperCAmelCase_							:       Dict       =				list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']						)
       UpperCAmelCase_							:       List[str]       =				list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']						)
       # get train time from SageMaker job, this includes starting, preprocessing, stopping
       UpperCAmelCase_							:       int       =				(
           Session().describe_training_job(estimator.latest_training_job.name						).get('TrainingTimeInSeconds'				,		9_9_9_9_9_9						)
       )

       # assert kpis
       assert train_runtime <= self.results["train_runtime"]
       assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy						)
       assert all(t <= self.results['eval_loss'] for t in eval_loss						)

       # dump tests result into json file to share in PR
       with open(F'''{estimator.latest_training_job.name}.json'''				,		'w'						) as outfile:
            json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss}				,		snake_case_						)






