
import math
import time

from transformers import Trainer, 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 			UpperCamelCase      (							a__  ):
     def __init__(     self  ,     *snake_case__  ,     snake_case__=None  ,     snake_case__=None  ,     **snake_case__				):




       """simple docstring"""


       super().__init__(*lowerCamelCase_  ,     **lowerCamelCase_				)
       _SCREAMING_SNAKE_CASE   :				str							    = eval_examples
       _SCREAMING_SNAKE_CASE   :				List[str]							    = post_process_function
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__=None  ,     snake_case__=None  ,     snake_case__=None  ,     snake_case__ = "eval"				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Any							    = self.eval_dataset if eval_dataset is None else eval_dataset
       _SCREAMING_SNAKE_CASE   :				int							    = self.get_eval_dataloader(lowerCamelCase_				)
       _SCREAMING_SNAKE_CASE   :				str							    = self.eval_examples if eval_examples is None else eval_examples

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

         # Prefix all keys with metric_key_prefix + '_'
         for key in list(metrics.keys()				):
           if not key.startswith(F'''{metric_key_prefix}_'''				):
             _SCREAMING_SNAKE_CASE   :				Any							    = metrics.pop(lowerCamelCase_				)
         metrics.update(output.metrics				)
       else:
         _SCREAMING_SNAKE_CASE   :				Dict							    = output.metrics

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

       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()				)

       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = self.callback_handler.on_evaluate(self.args  ,     self.state  ,     self.control  ,     lowerCamelCase_				)
       return metrics




     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__  ,     snake_case__=None  ,     snake_case__ = "test"				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = self.get_test_dataloader(lowerCamelCase_				)

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

       _SCREAMING_SNAKE_CASE   :				Optional[int]							    = self.post_process_function(lowerCamelCase_  ,     lowerCamelCase_  ,     output.predictions  ,     "predict"				)
       _SCREAMING_SNAKE_CASE   :				Dict							    = self.compute_metrics(lowerCamelCase_				)

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





"""simple docstring"""
# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse

from ...utils.dataclasses import (
    ComputeEnvironment,
    DistributedType,
    DynamoBackend,
    PrecisionType,
    SageMakerDistributedType,
)
from ..menu import BulletMenu


lowercase_       :						Tuple     					=	[
    '''EAGER''',
    '''AOT_EAGER''',
    '''INDUCTOR''',
    '''NVFUSER''',
    '''AOT_NVFUSER''',
    '''AOT_CUDAGRAPHS''',
    '''OFI''',
    '''FX2TRT''',
    '''ONNXRT''',
    '''IPEX''',
]





def    _lowerCAmelCase    (     lowerCamelCase__							:							Dict,						lowerCamelCase__							:							int=None,						lowerCamelCase__							:							Any=None,						lowerCamelCase__							:							Any=None				)  ->    Tuple:
  _SCREAMING_SNAKE_CASE   :				List[Any]							    = True
  while ask_again:
    _SCREAMING_SNAKE_CASE   :				List[str]							    = input(lowerCamelCase__				)
    try:
      if default is not None and len(lowerCamelCase__				) == 0:
        return default
      return convert_value(lowerCamelCase__				) if convert_value is not None else result
    except Exception:
      if error_message is not None:
        print(lowerCamelCase__				)





def    _lowerCAmelCase    (     lowerCamelCase__							:							Any,						lowerCamelCase__							:							Dict=[],						lowerCamelCase__							:							Optional[int]=None,						lowerCamelCase__							:							str=0				)  ->    str:
  _SCREAMING_SNAKE_CASE   :				int							    = BulletMenu(lowerCamelCase__,						lowerCamelCase__				)
  _SCREAMING_SNAKE_CASE   :				str							    = menu.run(default_choice=lowerCamelCase__				)
  return convert_value(lowerCamelCase__				) if convert_value is not None else result





def    _lowerCAmelCase    (     lowerCamelCase__							:							Optional[int]				)  ->    Optional[int]:
  _SCREAMING_SNAKE_CASE   :				str							    = int(lowerCamelCase__				)
  return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value]				)





def    _lowerCAmelCase    (     lowerCamelCase__							:							str				)  ->    List[Any]:
  _SCREAMING_SNAKE_CASE   :				str							    = int(lowerCamelCase__				)
  return DistributedType(["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "TPU"][value]				)





def    _lowerCAmelCase    (     lowerCamelCase__							:							Optional[Any]				)  ->    List[Any]:
  _SCREAMING_SNAKE_CASE   :				List[Any]							    = int(lowerCamelCase__				)
  return DynamoBackend(DYNAMO_BACKENDS[value]				).value





def    _lowerCAmelCase    (     lowerCamelCase__							:							int				)  ->    Dict:
  _SCREAMING_SNAKE_CASE   :				int							    = int(lowerCamelCase__				)
  return PrecisionType(["no", "fp16", "bf16", "fp8"][value]				)





def    _lowerCAmelCase    (     lowerCamelCase__							:							List[Any]				)  ->    Any:
  _SCREAMING_SNAKE_CASE   :				Optional[Any]							    = int(lowerCamelCase__				)
  return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value]				)





def    _lowerCAmelCase    (     lowerCamelCase__							:							List[Any]				)  ->    Optional[Any]:
  return {"yes": True, "no": False}[value.lower()]





class 			UpperCamelCase      (							argparse.RawDescriptionHelpFormatter  ):
     def 				__SCREAMING_SNAKE_CASE							(     self  ,     snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__				):




       """simple docstring"""


       _SCREAMING_SNAKE_CASE   :				Any							    = super()._format_usage(snake_case__  ,     snake_case__  ,     snake_case__  ,     snake_case__				)
       _SCREAMING_SNAKE_CASE   :				Any							    = usage.replace("<command> [<args>] "  ,     ""				)
       return usage



