


'''simple docstring'''



import json
import pathlib
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
      import torch

if is_vision_available():
      from PIL import Image

      from transformers import DetaImageProcessor





class   UpperCAmelCase_    (unittest.TestCase    ):





    """simple docstring"""






    def __init__(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_=7     ,	SCREAMING_SNAKE_CASE_=3     ,	SCREAMING_SNAKE_CASE_=30     ,	SCREAMING_SNAKE_CASE_=4_00     ,	SCREAMING_SNAKE_CASE_=True     ,	SCREAMING_SNAKE_CASE_=None     ,	SCREAMING_SNAKE_CASE_=True     ,	SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5]     ,	SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5]     ,	SCREAMING_SNAKE_CASE_=True     ,	SCREAMING_SNAKE_CASE_=1 / 2_55     ,	SCREAMING_SNAKE_CASE_=True     ,	)							->	int:
         # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
         __lowerCamelCase  :      int														=						size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33}
         __lowerCamelCase  :      Optional[int]														=						parent
         __lowerCamelCase  :      Union[str, Any]														=						batch_size
         __lowerCamelCase  :      str														=						num_channels
         __lowerCamelCase  :      Union[str, Any]														=						min_resolution
         __lowerCamelCase  :      int														=						max_resolution
         __lowerCamelCase  :      str														=						do_resize
         __lowerCamelCase  :      Tuple														=						size
         __lowerCamelCase  :      str														=						do_normalize
         __lowerCamelCase  :      Optional[int]														=						image_mean
         __lowerCamelCase  :      int														=						image_std
         __lowerCamelCase  :      Union[str, Any]														=						do_rescale
         __lowerCamelCase  :      Optional[Any]														=						rescale_factor
         __lowerCamelCase  :      Optional[int]														=						do_pad







    def  lowercase_							(				self      )							->	str:
         return {
             "do_resize": self.do_resize,
             "size": self.size,
             "do_normalize": self.do_normalize,
             "image_mean": self.image_mean,
             "image_std": self.image_std,
             "do_rescale": self.do_rescale,
             "rescale_factor": self.rescale_factor,
             "do_pad": self.do_pad,
         }







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_=False      )							->	Any:
         if not batched:
              __lowerCamelCase  :      str														=						image_inputs[0]
              if isinstance(SCREAMING_SNAKE_CASE_     ,	Image.Image      ):
                   __lowerCamelCase							,			__lowerCamelCase  :      Union[str, Any]														=						image.size
              else:
                   __lowerCamelCase							,			__lowerCamelCase  :      Optional[int]														=						image.shape[1], image.shape[2]
              if w < h:
                   __lowerCamelCase  :      List[Any]														=						int(self.size['shortest_edge'] * h / w      )
                   __lowerCamelCase  :      str														=						self.size['shortest_edge']
              elif w > h:
                   __lowerCamelCase  :      Optional[int]														=						self.size['shortest_edge']
                   __lowerCamelCase  :      List[str]														=						int(self.size['shortest_edge'] * w / h      )
              else:
                   __lowerCamelCase  :      Any														=						self.size['shortest_edge']
                   __lowerCamelCase  :      List[str]														=						self.size['shortest_edge']

         else:
              __lowerCamelCase  :      Optional[Any]														=						[]
              for image in image_inputs:
                   __lowerCamelCase							,			__lowerCamelCase  :      Dict														=						self.get_expected_values([image]      )
                   expected_values.append((expected_height, expected_width)      )
              __lowerCamelCase  :      Any														=						max(SCREAMING_SNAKE_CASE_     ,	key=lambda SCREAMING_SNAKE_CASE_      : item[0]      )[0]
              __lowerCamelCase  :      Any														=						max(SCREAMING_SNAKE_CASE_     ,	key=lambda SCREAMING_SNAKE_CASE_      : item[1]      )[1]

         return expected_height, expected_width







@require_torch
@require_vision
class   UpperCAmelCase_    (_UpperCAmelCase   ,						unittest.TestCase    ):





    """simple docstring"""






    lowerCamelCase    :   Union[str, Any]					=     DetaImageProcessor if is_vision_available() else None







    def  lowercase_							(				self      )							->	str:
         __lowerCamelCase  :      Dict														=						DetaImageProcessingTester(self      )







    @property
    def  lowercase_							(				self      )							->	Tuple:
         return self.image_processor_tester.prepare_image_processor_dict()







    def  lowercase_							(				self      )							->	str:
         __lowerCamelCase  :      Dict														=						self.image_processing_class(**self.image_processor_dict      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'image_mean'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'image_std'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'do_normalize'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'do_resize'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'do_rescale'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'do_pad'      )      )
         self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,	'size'      )      )







    def  lowercase_							(				self      )							->	int:
         __lowerCamelCase  :      Dict														=						self.image_processing_class.from_dict(self.image_processor_dict      )
         self.assertEqual(image_processor.size     ,	{'shortest_edge': 18, 'longest_edge': 13_33}      )
         self.assertEqual(image_processor.do_pad     ,	SCREAMING_SNAKE_CASE_      )







    def  lowercase_							(				self      )							->	List[str]:
         pass







    def  lowercase_							(				self      )							->	Union[str, Any]:
         # Initialize image_processing
         __lowerCamelCase  :      List[Any]														=						self.image_processing_class(**self.image_processor_dict      )
         # create random PIL images
         __lowerCamelCase  :      Dict														=						prepare_image_inputs(self.image_processor_tester     ,	equal_resolution=SCREAMING_SNAKE_CASE_      )
         for image in image_inputs:
              self.assertIsInstance(SCREAMING_SNAKE_CASE_     ,	Image.Image      )

         # Test not batched input
         __lowerCamelCase  :      Dict														=						image_processing(image_inputs[0]     ,	return_tensors='pt'      ).pixel_values

         __lowerCamelCase							,			__lowerCamelCase  :      List[str]														=						self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE_      )

         self.assertEqual(
             encoded_images.shape     ,	(1, self.image_processor_tester.num_channels, expected_height, expected_width)     ,	)

         # Test batched
         __lowerCamelCase							,			__lowerCamelCase  :      Optional[int]														=						self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE_     ,	batched=SCREAMING_SNAKE_CASE_      )

         __lowerCamelCase  :      str														=						image_processing(SCREAMING_SNAKE_CASE_     ,	return_tensors='pt'      ).pixel_values
         self.assertEqual(
             encoded_images.shape     ,	(
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )     ,	)







    def  lowercase_							(				self      )							->	Tuple:
         # Initialize image_processing
         __lowerCamelCase  :      List[Any]														=						self.image_processing_class(**self.image_processor_dict      )
         # create random numpy tensors
         __lowerCamelCase  :      Union[str, Any]														=						prepare_image_inputs(self.image_processor_tester     ,	equal_resolution=SCREAMING_SNAKE_CASE_     ,	numpify=SCREAMING_SNAKE_CASE_      )
         for image in image_inputs:
              self.assertIsInstance(SCREAMING_SNAKE_CASE_     ,	np.ndarray      )

         # Test not batched input
         __lowerCamelCase  :      List[Any]														=						image_processing(image_inputs[0]     ,	return_tensors='pt'      ).pixel_values

         __lowerCamelCase							,			__lowerCamelCase  :      int														=						self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE_      )

         self.assertEqual(
             encoded_images.shape     ,	(1, self.image_processor_tester.num_channels, expected_height, expected_width)     ,	)

         # Test batched
         __lowerCamelCase  :      Tuple														=						image_processing(SCREAMING_SNAKE_CASE_     ,	return_tensors='pt'      ).pixel_values

         __lowerCamelCase							,			__lowerCamelCase  :      List[str]														=						self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE_     ,	batched=SCREAMING_SNAKE_CASE_      )

         self.assertEqual(
             encoded_images.shape     ,	(
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )     ,	)







    def  lowercase_							(				self      )							->	Optional[Any]:
         # Initialize image_processing
         __lowerCamelCase  :      List[Any]														=						self.image_processing_class(**self.image_processor_dict      )
         # create random PyTorch tensors
         __lowerCamelCase  :      Optional[Any]														=						prepare_image_inputs(self.image_processor_tester     ,	equal_resolution=SCREAMING_SNAKE_CASE_     ,	torchify=SCREAMING_SNAKE_CASE_      )
         for image in image_inputs:
              self.assertIsInstance(SCREAMING_SNAKE_CASE_     ,	torch.Tensor      )

         # Test not batched input
         __lowerCamelCase  :      Optional[Any]														=						image_processing(image_inputs[0]     ,	return_tensors='pt'      ).pixel_values

         __lowerCamelCase							,			__lowerCamelCase  :      Optional[Any]														=						self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE_      )

         self.assertEqual(
             encoded_images.shape     ,	(1, self.image_processor_tester.num_channels, expected_height, expected_width)     ,	)

         # Test batched
         __lowerCamelCase  :      Optional[Any]														=						image_processing(SCREAMING_SNAKE_CASE_     ,	return_tensors='pt'      ).pixel_values

         __lowerCamelCase							,			__lowerCamelCase  :      str														=						self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE_     ,	batched=SCREAMING_SNAKE_CASE_      )

         self.assertEqual(
             encoded_images.shape     ,	(
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )     ,	)







    @slow
    def  lowercase_							(				self      )							->	List[Any]:
         # prepare image and target
         __lowerCamelCase  :      Dict														=						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'      )
         with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt'     ,	'r'      ) as f:
              __lowerCamelCase  :      List[Any]														=						json.loads(f.read()      )

         __lowerCamelCase  :      List[str]														=						{'image_id': 3_97_69, 'annotations': target}

         # encode them
         __lowerCamelCase  :      Union[str, Any]														=						DetaImageProcessor()
         __lowerCamelCase  :      int														=						image_processing(images=SCREAMING_SNAKE_CASE_     ,	annotations=SCREAMING_SNAKE_CASE_     ,	return_tensors='pt'      )

         # verify pixel values
         __lowerCamelCase  :      Optional[int]														=						torch.Size([1, 3, 8_00, 10_66]      )
         self.assertEqual(encoding['pixel_values'].shape     ,	SCREAMING_SNAKE_CASE_      )

         __lowerCamelCase  :      int														=						torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1]      )
         self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3]     ,	SCREAMING_SNAKE_CASE_     ,	atol=1E-4      )      )

         # verify area
         __lowerCamelCase  :      Optional[Any]														=						torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8]      )
         self.assertTrue(torch.allclose(encoding['labels'][0]['area']     ,	SCREAMING_SNAKE_CASE_      )      )
         # verify boxes
         __lowerCamelCase  :      Optional[Any]														=						torch.Size([6, 4]      )
         self.assertEqual(encoding['labels'][0]['boxes'].shape     ,	SCREAMING_SNAKE_CASE_      )
         __lowerCamelCase  :      int														=						torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5]      )
         self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0]     ,	SCREAMING_SNAKE_CASE_     ,	atol=1E-3      )      )
         # verify image_id
         __lowerCamelCase  :      Union[str, Any]														=						torch.tensor([3_97_69]      )
         self.assertTrue(torch.allclose(encoding['labels'][0]['image_id']     ,	SCREAMING_SNAKE_CASE_      )      )
         # verify is_crowd
         __lowerCamelCase  :      List[Any]														=						torch.tensor([0, 0, 0, 0, 0, 0]      )
         self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd']     ,	SCREAMING_SNAKE_CASE_      )      )
         # verify class_labels
         __lowerCamelCase  :      Optional[int]														=						torch.tensor([75, 75, 63, 65, 17, 17]      )
         self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels']     ,	SCREAMING_SNAKE_CASE_      )      )
         # verify orig_size
         __lowerCamelCase  :      List[Any]														=						torch.tensor([4_80, 6_40]      )
         self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size']     ,	SCREAMING_SNAKE_CASE_      )      )
         # verify size
         __lowerCamelCase  :      Optional[Any]														=						torch.tensor([8_00, 10_66]      )
         self.assertTrue(torch.allclose(encoding['labels'][0]['size']     ,	SCREAMING_SNAKE_CASE_      )      )







    @slow
    def  lowercase_							(				self      )							->	Optional[Any]:
         # prepare image, target and masks_path
         __lowerCamelCase  :      List[str]														=						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'      )
         with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt'     ,	'r'      ) as f:
              __lowerCamelCase  :      Any														=						json.loads(f.read()      )

         __lowerCamelCase  :      int														=						{'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target}

         __lowerCamelCase  :      List[Any]														=						pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic'      )

         # encode them
         __lowerCamelCase  :      Union[str, Any]														=						DetaImageProcessor(format='coco_panoptic'      )
         __lowerCamelCase  :      Optional[Any]														=						image_processing(images=SCREAMING_SNAKE_CASE_     ,	annotations=SCREAMING_SNAKE_CASE_     ,	masks_path=SCREAMING_SNAKE_CASE_     ,	return_tensors='pt'      )

         # verify pixel values
         __lowerCamelCase  :      List[str]														=						torch.Size([1, 3, 8_00, 10_66]      )
         self.assertEqual(encoding['pixel_values'].shape     ,	SCREAMING_SNAKE_CASE_      )

         __lowerCamelCase  :      int														=						torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1]      )
         self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3]     ,	SCREAMING_SNAKE_CASE_     ,	atol=1E-4      )      )

         # verify area
         __lowerCamelCase  :      Optional[Any]														=						torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7]      )
         self.assertTrue(torch.allclose(encoding['labels'][0]['area']     ,	SCREAMING_SNAKE_CASE_      )      )
         # verify boxes
         __lowerCamelCase  :      int														=						torch.Size([6, 4]      )
         self.assertEqual(encoding['labels'][0]['boxes'].shape     ,	SCREAMING_SNAKE_CASE_      )
         __lowerCamelCase  :      Optional[Any]														=						torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5]      )
         self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0]     ,	SCREAMING_SNAKE_CASE_     ,	atol=1E-3      )      )
         # verify image_id
         __lowerCamelCase  :      Optional[int]														=						torch.tensor([3_97_69]      )
         self.assertTrue(torch.allclose(encoding['labels'][0]['image_id']     ,	SCREAMING_SNAKE_CASE_      )      )
         # verify is_crowd
         __lowerCamelCase  :      Union[str, Any]														=						torch.tensor([0, 0, 0, 0, 0, 0]      )
         self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd']     ,	SCREAMING_SNAKE_CASE_      )      )
         # verify class_labels
         __lowerCamelCase  :      Optional[Any]														=						torch.tensor([17, 17, 63, 75, 75, 93]      )
         self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels']     ,	SCREAMING_SNAKE_CASE_      )      )
         # verify masks
         __lowerCamelCase  :      Any														=						82_28_73
         self.assertEqual(encoding['labels'][0]['masks'].sum().item()     ,	SCREAMING_SNAKE_CASE_      )
         # verify orig_size
         __lowerCamelCase  :      Tuple														=						torch.tensor([4_80, 6_40]      )
         self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size']     ,	SCREAMING_SNAKE_CASE_      )      )
         # verify size
         __lowerCamelCase  :      Tuple														=						torch.tensor([8_00, 10_66]      )
         self.assertTrue(torch.allclose(encoding['labels'][0]['size']     ,	SCREAMING_SNAKE_CASE_      )      )










'''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


lowerCAmelCase   : Dict             =				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        _UpperCamelCase	(    SCREAMING_SNAKE_CASE):


				'''simple docstring'''


				def __init__(     self							,      *a_							,      a_=None							,      a_=None							,      a_=None							,      **a_							)    ->  Any:
					super().__init__(*a_							,      **a_							)
					lowercase						:		Optional[Any]   					=		eval_examples
					lowercase						:		Any   					=		post_process_function
					lowercase						:		Dict   					=		quant_trainer_args
					lowercase						:		List[Any]   					=		1_2_8  # default number of calibration samples

				def 	a__		(     self							,      a_=None							)    ->  List[str]:
					if calib_dataset is None and self.calib_dataset is None:
						raise ValueError("Trainer: calibration requires an calib_dataset."							)
					lowercase						:		Dict   					=		calib_dataset if calib_dataset is not None else self.calib_dataset

					lowercase						:		Optional[int]   					=		self._remove_unused_columns(a_							,      description="Calibration"							)

					return DataLoader(
					    a_							,      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=a_							,      )

				def 	a__		(     self							,      a_=None							)    ->  str:
					lowercase						:		Optional[Any]   					=		self.train_dataset if calib_dataset is None else calib_dataset
					lowercase						:		Optional[Any]   					=		self.get_calib_dataloader(a_							)

					lowercase						:		Union[str, Any]   					=		self.model
					quant_trainer.configure_model(a_							,      self.quant_trainer_args							,      calib=a_							)
					model.eval()
					quant_trainer.enable_calibration(a_							)

					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(a_							):
						# Prediction step
						lowercase					,		lowercase					,		lowercase						:		Union[str, Any]   					=		self.prediction_step(a_							,      a_							,      prediction_loss_only=a_							)
						if (step + 1) * calib_dataloader.batch_size >= self.calib_num:
							break

					quant_trainer.finish_calibration(a_							,      self.quant_trainer_args							)
					lowercase						:		List[Any]   					=		model

				def 	a__		(     self							,      a_=None							,      a_=None							,      a_=None							,      a_ = "eval"							)    ->  int:
					lowercase						:		List[str]   					=		self.eval_dataset if eval_dataset is None else eval_dataset
					lowercase						:		Union[str, Any]   					=		self.get_eval_dataloader(a_							)
					lowercase						:		Tuple   					=		self.eval_examples if eval_examples is None else eval_examples

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

					if self.post_process_function is not None and self.compute_metrics is not None:
						lowercase						:		Union[str, Any]   					=		self.post_process_function(a_							,      a_							,      output.predictions							)
						lowercase						:		Union[str, Any]   					=		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}_'''							):
								lowercase						:		Dict   					=		metrics.pop(a_							)

						self.log(a_							)
					else:
						lowercase						:		Tuple   					=		{}

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

					lowercase						:		int   					=		self.callback_handler.on_evaluate(self.args							,      self.state							,      self.control							,      a_							)
					return metrics

				def 	a__		(     self							,      a_							,      a_							,      a_=None							,      a_ = "test"							)    ->  Optional[int]:
					lowercase						:		Dict   					=		self.get_test_dataloader(a_							)

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

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

					lowercase						:		List[str]   					=		self.post_process_function(a_							,      a_							,      output.predictions							,      "predict"							)
					lowercase						:		Dict   					=		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}_'''							):
							lowercase						:		Union[str, Any]   					=		metrics.pop(a_							)

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


				def 	a__		(     self							,      a_="./"							)    ->  Optional[Any]:
					lowercase						:		str   					=		self.eval_dataset
					lowercase						:		Dict   					=		self.get_eval_dataloader(a_							)

					lowercase						:		Any   					=		next(iter(a_							)							)

					# saving device - to make it consistent
					lowercase						:		List[Any]   					=		torch.device("cuda" if torch.cuda.is_available() else "cpu"							)

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

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

					lowercase						:		Optional[Any]   					=		True

					lowercase						:		int   					=		self.model.to(a_							)

					model.eval()
					model.float()

					lowercase						:		Union[str, Any]   					=		model.module if hasattr(a_							,      "module"							) else model
					quant_trainer.configure_model(a_							,      self.quant_trainer_args							)

					lowercase						:		List[str]   					=		os.path.join(a_							,      "model.onnx"							)
					logger.info(F'''exporting model to {output_model_file}'''							)

					lowercase						:		Any   					=		{0: "batch_size", 1: "seq_len"}

					torch.onnx.export(
					    a_							,      a_							,      a_							,      export_params=a_							,      opset_version=1_3							,      do_constant_folding=a_							,      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=a_							,      )
					logger.info("onnx export finished"							)


