


'''simple docstring'''
import logging
import os

import quant_trainer
import torch
from torch.utils.data import DataLoader

from transformers import Trainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput


UpperCamelCase__          = logging.getLogger(__name__)

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




class      lowerCamelCase_  (      __a ):






      def __init__(   self							:       Optional[Any]		,		*_A							:       Union[str, Any]		,		_A							:       Optional[Any]=None		,		_A							:       Tuple=None		,		_A							:       Optional[Any]=None		,		**_A							:       List[str]					):


          '''simple docstring'''


          super().__init__(*UpperCamelCase_		,		**UpperCamelCase_					)
          UpperCAmelCase__     :						Optional[int]						=							eval_examples
          UpperCAmelCase__     :						Optional[Any]						=							post_process_function
          UpperCAmelCase__     :						Optional[Any]						=							quant_trainer_args
          UpperCAmelCase__     :						str						=							128  # default number of calibration samples






      def lowercase_				(   self							:       Tuple		,		_A							:       List[Any]=None					):


          '''simple docstring'''


          if calib_dataset is None and self.calib_dataset is None:
              raise ValueError('''Trainer: calibration requires an calib_dataset.'''					)
          UpperCAmelCase__     :						str						=							calib_dataset if calib_dataset is not None else self.calib_dataset

          UpperCAmelCase__     :						Tuple						=							self._remove_unused_columns(UpperCamelCase_		,		description='''Calibration'''					)

          return DataLoader(
              UpperCamelCase_		,		batch_size=self.args.eval_batch_size		,		collate_fn=self.data_collator		,		drop_last=self.args.dataloader_drop_last		,		num_workers=self.args.dataloader_num_workers		,		pin_memory=self.args.dataloader_pin_memory		,		shuffle=UpperCamelCase_		,		)






      def lowercase_				(   self							:       List[Any]		,		_A							:       Optional[int]=None					):


          '''simple docstring'''


          UpperCAmelCase__     :						str						=							self.train_dataset if calib_dataset is None else calib_dataset
          UpperCAmelCase__     :						Dict						=							self.get_calib_dataloader(UpperCamelCase_					)

          UpperCAmelCase__     :						List[Any]						=							self.model
          quant_trainer.configure_model(UpperCamelCase_		,		self.quant_trainer_args		,		calib=UpperCamelCase_					)
          model.eval()
          quant_trainer.enable_calibration(UpperCamelCase_					)

          logger.info('''***** Running calibration *****'''					)
          logger.info(f"""  Num examples = {self.calib_num}"""					)
          logger.info(f"""  Batch size = {calib_dataloader.batch_size}"""					)

          for step, inputs in enumerate(UpperCamelCase_					):
              # Prediction step
              UpperCAmelCase__		,		UpperCAmelCase__		,		UpperCAmelCase__     :						Tuple						=							self.prediction_step(UpperCamelCase_		,		UpperCamelCase_		,		prediction_loss_only=UpperCamelCase_					)
              if (step + 1) * calib_dataloader.batch_size >= self.calib_num:
                  break

          quant_trainer.finish_calibration(UpperCamelCase_		,		self.quant_trainer_args					)
          UpperCAmelCase__     :						List[Any]						=							model






      def lowercase_				(   self							:       Any		,		_A							:       Any=None		,		_A							:       Tuple=None		,		_A							:       Optional[int]=None		,		_A							:       List[str] = "eval"					):


          '''simple docstring'''


          UpperCAmelCase__     :						str						=							self.eval_dataset if eval_dataset is None else eval_dataset
          UpperCAmelCase__     :						Union[str, Any]						=							self.get_eval_dataloader(UpperCamelCase_					)
          UpperCAmelCase__     :						str						=							self.eval_examples if eval_examples is None else eval_examples

          # Temporarily disable metric computation, we will do it in the loop here.
          UpperCAmelCase__     :						Tuple						=							self.compute_metrics
          UpperCAmelCase__     :						Any						=							None
          UpperCAmelCase__     :						Optional[int]						=							self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
          try:
              UpperCAmelCase__     :						int						=							eval_loop(
                  UpperCamelCase_		,		description='''Evaluation'''		,		prediction_loss_only=True if compute_metrics is None else None		,		ignore_keys=UpperCamelCase_		,		)
          finally:
              UpperCAmelCase__     :						Optional[int]						=							compute_metrics

          if self.post_process_function is not None and self.compute_metrics is not None:
              UpperCAmelCase__     :						int						=							self.post_process_function(UpperCamelCase_		,		UpperCamelCase_		,		output.predictions					)
              UpperCAmelCase__     :						Union[str, Any]						=							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__     :						Any						=							metrics.pop(UpperCamelCase_					)

              self.log(UpperCamelCase_					)
          else:
              UpperCAmelCase__     :						List[Any]						=							{}

          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__     :						Any						=							self.callback_handler.on_evaluate(self.args		,		self.state		,		self.control		,		UpperCamelCase_					)
          return metrics






      def lowercase_				(   self							:       Any		,		_A							:       List[str]		,		_A							:       int		,		_A							:       Dict=None		,		_A							:       Union[str, Any] = "test"					):


          '''simple docstring'''


          UpperCAmelCase__     :						int						=							self.get_test_dataloader(UpperCamelCase_					)

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

          if self.post_process_function is None or self.compute_metrics is None:
              return output

          UpperCAmelCase__     :						int						=							self.post_process_function(UpperCamelCase_		,		UpperCamelCase_		,		output.predictions		,		'''predict'''					)
          UpperCAmelCase__     :						Tuple						=							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__     :						List[Any]						=							metrics.pop(UpperCamelCase_					)

          return PredictionOutput(predictions=predictions.predictions		,		label_ids=predictions.label_ids		,		metrics=UpperCamelCase_					)






      def lowercase_				(   self							:       str		,		_A							:       Optional[int]="./"					):


          '''simple docstring'''


          UpperCAmelCase__     :						Tuple						=							self.eval_dataset
          UpperCAmelCase__     :						Dict						=							self.get_eval_dataloader(UpperCamelCase_					)

          UpperCAmelCase__     :						int						=							next(iter(UpperCamelCase_					)					)

          # saving device - to make it consistent
          UpperCAmelCase__     :						int						=							torch.device('''cuda''' if torch.cuda.is_available() else '''cpu'''					)

          # convert to tuple
          UpperCAmelCase__     :						Tuple						=							tuple(v.to(UpperCamelCase_					) for k, v in batch.items()					)

          logger.info('''Converting model to be onnx compatible'''					)
          from pytorch_quantization.nn import TensorQuantizer

          UpperCAmelCase__     :						str						=							True

          UpperCAmelCase__     :						List[str]						=							self.model.to(UpperCamelCase_					)

          model.eval()
          model.float()

          UpperCAmelCase__     :						List[Any]						=							model.module if hasattr(UpperCamelCase_		,		'''module'''					) else model
          quant_trainer.configure_model(UpperCamelCase_		,		self.quant_trainer_args					)

          UpperCAmelCase__     :						str						=							os.path.join(UpperCamelCase_		,		'''model.onnx'''					)
          logger.info(f"""exporting model to {output_model_file}"""					)

          UpperCAmelCase__     :						str						=							{0: '''batch_size''', 1: '''seq_len'''}

          torch.onnx.export(
              UpperCamelCase_		,		UpperCamelCase_		,		UpperCamelCase_		,		export_params=UpperCamelCase_		,		opset_version=13		,		do_constant_folding=UpperCamelCase_		,		input_names=['''input_ids''', '''attention_mask''', '''token_type_ids''']		,		output_names=['''output_start_logits''', '''output_end_logits''']		,		dynamic_axes={
                  '''input_ids''': axes,
                  '''attention_mask''': axes,
                  '''token_type_ids''': axes,
                  '''output_start_logits''': axes,
                  '''output_end_logits''': axes,
              }		,		verbose=UpperCamelCase_		,		)
          logger.info('''onnx export finished'''					)







'''simple docstring'''




import cmath
import math




def 						__lowerCamelCase			(	UpperCAmelCase_					,				UpperCAmelCase_					,				UpperCAmelCase_					,				UpperCAmelCase_							)   ->complex:
	snake_case__	       =   math.radians(UpperCAmelCase_							)
	snake_case__	       =   math.radians(UpperCAmelCase_							)

	# Convert voltage and current to rectangular form
	snake_case__	       =   cmath.rect(UpperCAmelCase_					,				UpperCAmelCase_							)
	snake_case__	       =   cmath.rect(UpperCAmelCase_					,				UpperCAmelCase_							)

	# Calculate apparent power
	return voltage_rect * current_rect


if __name__ == "__main__":
			import doctest

			doctest.testmod()



