


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_			(a__						):




       '''simple docstring'''



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



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

          lowerCamelCase_						:   Optional[int]		= self.eval_dataset if eval_dataset is None else eval_dataset
          lowerCamelCase_						:   Optional[int]		= self.get_eval_dataloader(__a							)
          lowerCamelCase_						:   Dict		= self.eval_examples if eval_examples is None else eval_examples

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

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

             metrics.update(output.metrics							)
          else:
             lowerCamelCase_						:   Optional[Any]		= output.metrics

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

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

          lowerCamelCase_						:   Dict		= self.callback_handler.on_evaluate(self.args		,				self.state		,				self.control		,				__a							)
          return metrics




       def 				_lowerCAmelCase							(						self				:				Tuple		,				__a				:				List[Any]		,				__a				:				int		,				__a				:				Tuple=None		,				__a				:				str = "test"		,				**__a				:				Union[str, Any]							)					->str:
          lowerCamelCase_						:   Optional[int]		= gen_kwargs.copy()

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

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

          lowerCamelCase_						:   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(
                  __a		,				__a		,				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

          lowerCamelCase_						:   Tuple		= self.post_process_function(__a		,				__a		,				__a		,				"""predict"""							)
          lowerCamelCase_						:   List[str]		= self.compute_metrics(__a							)

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









# Copyright 2023 The HuggingFace Inc. 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 copy
import importlib.metadata
import json
import os
from dataclasses import dataclass
from typing import Any, Dict, Union

from packaging import version

from ..utils import is_torch_available, logging


if is_torch_available():
      import torch


snake_case__				:	int					       =					logging.get_logger(__name__)





@dataclass
class   SCREAMING_SNAKE_CASE_			:




       '''simple docstring'''



       def __init__(						self				:				int		,				__a				:				Optional[Any]=False		,				__a				:				Tuple=False		,				__a				:				Tuple=6.0		,				__a				:				str=None		,				__a				:				List[str]=False		,				__a				:				str=False		,				__a				:				Optional[Any]=None		,				__a				:				Dict="fp4"		,				__a				:				Optional[int]=False		,				**__a				:				Dict		,				)					->str:
          lowerCamelCase_						:   str		= load_in_abit
          lowerCamelCase_						:   Union[str, Any]		= load_in_abit
          lowerCamelCase_						:   Tuple		= llm_inta_threshold
          lowerCamelCase_						:   int		= llm_inta_skip_modules
          lowerCamelCase_						:   List[str]		= llm_inta_enable_fpaa_cpu_offload
          lowerCamelCase_						:   Optional[Any]		= llm_inta_has_fpaa_weight
          lowerCamelCase_						:   Dict		= bnb_abit_quant_type
          lowerCamelCase_						:   int		= bnb_abit_use_double_quant

          if bnb_abit_compute_dtype is None:
             lowerCamelCase_						:   int		= torch.floataa
          elif isinstance(__a		,				__a							):
             lowerCamelCase_						:   Tuple		= getattr(__a		,				__a							)
          elif isinstance(__a		,				torch.dtype							):
             lowerCamelCase_						:   List[str]		= bnb_abit_compute_dtype
          else:
             raise ValueError("""bnb_4bit_compute_dtype must be a string or a torch.dtype"""							)

          self.post_init()



       def 				_lowerCAmelCase							(						self				:				Any							)					->Union[str, Any]:
          if not isinstance(self.llm_inta_threshold		,				__a							):
             raise ValueError("""llm_int8_threshold must be a float"""							)

          if self.llm_inta_skip_modules is not None and not isinstance(self.llm_inta_skip_modules		,				__a							):
             raise ValueError("""llm_int8_skip_modules must be a list of strings"""							)
          if not isinstance(self.llm_inta_enable_fpaa_cpu_offload		,				__a							):
             raise ValueError("""llm_int8_enable_fp32_cpu_offload must be a boolean"""							)

          if not isinstance(self.llm_inta_has_fpaa_weight		,				__a							):
             raise ValueError("""llm_int8_has_fp16_weight must be a boolean"""							)

          if self.bnb_abit_compute_dtype is not None and not isinstance(self.bnb_abit_compute_dtype		,				torch.dtype							):
             raise ValueError("""bnb_4bit_compute_dtype must be torch.dtype"""							)

          if not isinstance(self.bnb_abit_quant_type		,				__a							):
             raise ValueError("""bnb_4bit_quant_type must be a string"""							)

          if not isinstance(self.bnb_abit_use_double_quant		,				__a							):
             raise ValueError("""bnb_4bit_use_double_quant must be a boolean"""							)

          if self.load_in_abit and not version.parse(importlib.metadata.version("""bitsandbytes"""							)							) >= version.parse(
              """0.39.0"""							):
             raise ValueError(
                 """4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version"""							)



       def 				_lowerCAmelCase							(						self				:				Optional[int]							)					->int:
          return self.load_in_abit or self.load_in_abit



       def 				_lowerCAmelCase							(						self				:				List[str]							)					->List[Any]:
          if self.load_in_abit:
             return "llm_int8"
          elif self.load_in_abit and self.bnb_abit_quant_type == "fp4":
             return "fp4"
          elif self.load_in_abit and self.bnb_abit_quant_type == "nf4":
             return "nf4"
          else:
             return None



       @classmethod
       def 				_lowerCAmelCase							(						cls				:				int		,				__a				:				Dict		,				__a				:				str		,				**__a				:				Any							)					->Optional[Any]:
          lowerCamelCase_						:   Optional[Any]		= cls(**__a							)

          lowerCamelCase_						:   List[Any]		= []
          for key, value in kwargs.items():
             if hasattr(__a		,				__a							):
                setattr(__a		,				__a		,				__a							)
                to_remove.append(__a							)
          for key in to_remove:
             kwargs.pop(__a		,				__a							)

          if return_unused_kwargs:
             return config, kwargs
          else:
             return config



       def 				_lowerCAmelCase							(						self				:				Optional[Any]		,				__a				:				Union[str, os.PathLike]							)					->Any:
          with open(__a		,				"""w"""		,				encoding="""utf-8"""							) as writer:
             lowerCamelCase_						:   List[Any]		= self.to_dict()
             lowerCamelCase_						:   Dict		= json.dumps(__a		,				indent=2		,				sort_keys=__a							) + """\n"""

             writer.write(__a							)



       def 				_lowerCAmelCase							(						self				:				Tuple							)					->Dict[str, Any]:
          lowerCamelCase_						:   Dict		= copy.deepcopy(self.__dict__							)
          lowerCamelCase_						:   Tuple		= str(output["""bnb_4bit_compute_dtype"""]							).split("""."""							)[1]

          return output



       def __repr__(						self				:				List[str]							)					->Any:
          return F'''{self.__class__.__name__} {self.to_json_string()}'''



       def 				_lowerCAmelCase							(						self				:				Optional[int]		,				__a				:				bool = True							)					->str:
          if use_diff is True:
             lowerCamelCase_						:   Dict		= self.to_diff_dict()
          else:
             lowerCamelCase_						:   Any		= self.to_dict()
          return json.dumps(__a		,				indent=2		,				sort_keys=__a							) + "\n"




       def 				_lowerCAmelCase							(						self				:				Optional[Any]							)					->Dict[str, Any]:
          lowerCamelCase_						:   Any		= self.to_dict()

          # get the default config dict
          lowerCamelCase_						:   List[str]		= BitsAndBytesConfig().to_dict()

          lowerCamelCase_						:   str		= {}

          # only serialize values that differ from the default config
          for key, value in config_dict.items():
             if value != default_config_dict[key]:
                lowerCamelCase_						:   List[Any]		= value

          return serializable_config_dict





