






from __future__ import annotations

from collections.abc import Callable
from typing import Generic, TypeVar

SCREAMING_SNAKE_CASE__   :      str				=		TypeVar("""T""")
SCREAMING_SNAKE_CASE__   :      int				=		TypeVar("""U""")
class     lowerCamelCase_					(   Generic[T, U]			):







				def __init__(    self							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:Tuple   =   key
								__magic_name__		:List[str]   =   val
								__magic_name__		:DoubleLinkedListNode[T, U] | None   =   None
								__magic_name__		:DoubleLinkedListNode[T, U] | None   =   None







				def __repr__(    self  ):
								"""simple docstring"""
								return (
								    F'''Node: key: {self.key}, val: {self.val}, '''
								    F'''has next: {bool(self.next  )}, has prev: {bool(self.prev  )}'''
								)







class     lowerCamelCase_					(   Generic[T, U]			):







				def __init__(    self  ):
								"""simple docstring"""
								__magic_name__		:DoubleLinkedListNode[T, U]   =   DoubleLinkedListNode(__lowerCAmelCase							,       __lowerCAmelCase  )
								__magic_name__		:DoubleLinkedListNode[T, U]   =   DoubleLinkedListNode(__lowerCAmelCase							,       __lowerCAmelCase  )
								__magic_name__  ,					__magic_name__		:Union[str, Any]   =   self.rear, self.head







				def __repr__(    self  ):
								"""simple docstring"""
								__magic_name__		:Any   =   ['''DoubleLinkedList''']
								__magic_name__		:Any   =   self.head
								while node.next is not None:
												rep.append(str(__lowerCAmelCase  )  )
												__magic_name__		:Optional[int]   =   node.next
								rep.append(str(self.rear  )  )
								return ",\n    ".join(__lowerCAmelCase  )







				def       A						(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:List[Any]   =   self.rear.prev

								# All nodes other than self.head are guaranteed to have non-None previous
								assert previous is not None

								__magic_name__		:str   =   node
								__magic_name__		:str   =   previous
								__magic_name__		:Dict   =   node
								__magic_name__		:Optional[Any]   =   self.rear







				def       A						(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""

								if node.prev is None or node.next is None:
												return None

								__magic_name__		:str   =   node.next
								__magic_name__		:Any   =   node.prev
								__magic_name__		:int   =   None
								__magic_name__		:List[str]   =   None
								return node







class     lowerCamelCase_					(   Generic[T, U]			):
				a__       							=	{}







				def __init__(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:DoubleLinkedList[T, U]   =   DoubleLinkedList()
								__magic_name__		:Dict   =   capacity
								__magic_name__		:Union[str, Any]   =   0
								__magic_name__		:Dict   =   0
								__magic_name__		:Optional[Any]   =   0
								__magic_name__		:dict[T, DoubleLinkedListNode[T, U]]   =   {}







				def __repr__(    self  ):
								"""simple docstring"""
								return (
								    F'''CacheInfo(hits={self.hits}, misses={self.miss}, '''
								    F'''capacity={self.capacity}, current size={self.num_keys})'''
								)







				def __contains__(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""
								return key in self.cache







				def       A						(    self							,       __lowerCAmelCase  ):
								"""simple docstring"""
								# Note: pythonic interface would throw KeyError rather than return None

								if key in self.cache:
												self.hits += 1
												__magic_name__		:DoubleLinkedListNode[T, U]   =   self.cache[key]
												__magic_name__		:int   =   self.list.remove(self.cache[key]  )
												assert node == value_node

												# node is guaranteed not None because it is in self.cache
												assert node is not None
												self.list.add(__lowerCAmelCase  )
												return node.val
								self.miss += 1
								return None







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""

								if key not in self.cache:
												if self.num_keys >= self.capacity:
																# delete first node (oldest) when over capacity
																__magic_name__		:Union[str, Any]   =   self.list.head.next

																# guaranteed to have a non-None first node when num_keys > 0
																# explain to type checker via assertions
																assert first_node is not None
																assert first_node.key is not None
																assert (
																    self.list.remove(__lowerCAmelCase  ) is not None
																)  # node guaranteed to be in list assert node.key is not None

																del self.cache[first_node.key]
																self.num_keys -= 1
												__magic_name__		:List[Any]   =   DoubleLinkedListNode(__lowerCAmelCase							,       __lowerCAmelCase  )
												self.list.add(self.cache[key]  )
												self.num_keys += 1

								else:
												# bump node to the end of the list, update value
												__magic_name__		:str   =   self.list.remove(self.cache[key]  )
												assert node is not None  # node guaranteed to be in list
												__magic_name__		:Any   =   value
												self.list.add(__lowerCAmelCase  )







				@classmethod
				def       A						(    cls							,       __lowerCAmelCase = 1_2_8  ):
								"""simple docstring"""

								def cache_decorator_inner(__lowerCAmelCase  ) -> Callable[..., U]:
												def cache_decorator_wrapper(*__lowerCAmelCase  ) -> U:
																if func not in cls.decorator_function_to_instance_map:
																				__magic_name__		:List[str]   =   LRUCache(__lowerCAmelCase  )

																__magic_name__		:Optional[Any]   =   cls.decorator_function_to_instance_map[func].get(args[0]  )
																if result is None:
																				__magic_name__		:Optional[Any]   =   func(*__lowerCAmelCase  )
																				cls.decorator_function_to_instance_map[func].put(args[0]							,       __lowerCAmelCase  )
																return result

												def cache_info() -> LRUCache[T, U]:
																return cls.decorator_function_to_instance_map[func]

												setattr(__lowerCAmelCase							,       '''cache_info'''							,       __lowerCAmelCase  )  # noqa: B010

												return cache_decorator_wrapper

								return cache_decorator_inner


if __name__ == "__main__":
					import doctest

					doctest.testmod()














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


SCREAMING_SNAKE_CASE__   :      List[str]				=		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_					(   lowerCamelCase			):







				def __init__(    self							,       *__lowerCAmelCase							,       __lowerCAmelCase=None							,       __lowerCAmelCase=None							,       __lowerCAmelCase=None							,       **__lowerCAmelCase  ):
								"""simple docstring"""
								super().__init__(*__lowerCAmelCase							,       **__lowerCAmelCase  )
								__magic_name__		:Any   =   eval_examples
								__magic_name__		:str   =   post_process_function
								__magic_name__		:int   =   quant_trainer_args
								__magic_name__		:List[str]   =   1_2_8  # default number of calibration samples







				def       A						(    self							,       __lowerCAmelCase=None  ):
								"""simple docstring"""
								if calib_dataset is None and self.calib_dataset is None:
												raise ValueError('''Trainer: calibration requires an calib_dataset.'''  )
								__magic_name__		:Optional[Any]   =   calib_dataset if calib_dataset is not None else self.calib_dataset

								__magic_name__		:Optional[int]   =   self._remove_unused_columns(__lowerCAmelCase							,       description='''Calibration'''  )

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







				def       A						(    self							,       __lowerCAmelCase=None  ):
								"""simple docstring"""
								__magic_name__		:Dict   =   self.train_dataset if calib_dataset is None else calib_dataset
								__magic_name__		:Any   =   self.get_calib_dataloader(__lowerCAmelCase  )

								__magic_name__		:List[str]   =   self.model
								quant_trainer.configure_model(__lowerCAmelCase							,       self.quant_trainer_args							,       calib=__lowerCAmelCase  )
								model.eval()
								quant_trainer.enable_calibration(__lowerCAmelCase  )

								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(__lowerCAmelCase  ):
												# Prediction step
												__magic_name__  ,					__magic_name__  ,					__magic_name__		:str   =   self.prediction_step(__lowerCAmelCase							,       __lowerCAmelCase							,       prediction_loss_only=__lowerCAmelCase  )
												if (step + 1) * calib_dataloader.batch_size >= self.calib_num:
																break

								quant_trainer.finish_calibration(__lowerCAmelCase							,       self.quant_trainer_args  )
								__magic_name__		:Any   =   model







				def       A						(    self							,       __lowerCAmelCase=None							,       __lowerCAmelCase=None							,       __lowerCAmelCase=None							,       __lowerCAmelCase = "eval"  ):
								"""simple docstring"""
								__magic_name__		:Tuple   =   self.eval_dataset if eval_dataset is None else eval_dataset
								__magic_name__		:Optional[Any]   =   self.get_eval_dataloader(__lowerCAmelCase  )
								__magic_name__		:str   =   self.eval_examples if eval_examples is None else eval_examples

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

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

												self.log(__lowerCAmelCase  )
								else:
												__magic_name__		:List[str]   =   {}

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

								__magic_name__		:Optional[Any]   =   self.callback_handler.on_evaluate(self.args							,       self.state							,       self.control							,       __lowerCAmelCase  )
								return metrics







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase=None							,       __lowerCAmelCase = "test"  ):
								"""simple docstring"""
								__magic_name__		:int   =   self.get_test_dataloader(__lowerCAmelCase  )

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

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

								__magic_name__		:Optional[Any]   =   self.post_process_function(__lowerCAmelCase							,       __lowerCAmelCase							,       output.predictions							,       '''predict'''  )
								__magic_name__		: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}_'''  ):
																__magic_name__		:List[str]   =   metrics.pop(__lowerCAmelCase  )

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







				def       A						(    self							,       __lowerCAmelCase="./"  ):
								"""simple docstring"""
								__magic_name__		:List[Any]   =   self.eval_dataset
								__magic_name__		:Any   =   self.get_eval_dataloader(__lowerCAmelCase  )

								__magic_name__		:int   =   next(iter(__lowerCAmelCase  )  )

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

								# convert to tuple
								__magic_name__		:int   =   tuple(v.to(__lowerCAmelCase  ) for k, v in batch.items()  )

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

								__magic_name__		:Any   =   True

								__magic_name__		:Optional[int]   =   self.model.to(__lowerCAmelCase  )

								model.eval()
								model.float()

								__magic_name__		:Any   =   model.module if hasattr(__lowerCAmelCase							,       '''module'''  ) else model
								quant_trainer.configure_model(__lowerCAmelCase							,       self.quant_trainer_args  )

								__magic_name__		:int   =   os.path.join(__lowerCAmelCase							,       '''model.onnx'''  )
								logger.info(F'''exporting model to {output_model_file}'''  )

								__magic_name__		:Dict   =   {0: '''batch_size''', 1: '''seq_len'''}

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






