






from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


_a     : Optional[Any]   	=      logging.get_logger(__name__)

_a     : Tuple   	=      {
    """facebook/convnextv2-tiny-1k-224""": """https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json""",
}







class 						_UpperCAmelCase	(	lowerCAmelCase__					,				lowerCAmelCase__		):




      """simple docstring"""



      A    =     '''convnextv2'''
      def __init__( self     ,						_lowerCAmelCase=3     ,						_lowerCAmelCase=4     ,						_lowerCAmelCase=4     ,						_lowerCAmelCase=None     ,						_lowerCAmelCase=None     ,						_lowerCAmelCase="gelu"     ,						_lowerCAmelCase=0.02     ,						_lowerCAmelCase=1e-12     ,						_lowerCAmelCase=0.0     ,						_lowerCAmelCase=224     ,						_lowerCAmelCase=None     ,						_lowerCAmelCase=None     ,						**_lowerCAmelCase     ,						):



          '''simple docstring'''
          super().__init__(**_lowerCamelCase		)

          lowerCAmelCase__ :List[Any]   				=					num_channels
          lowerCAmelCase__ :Tuple   				=					patch_size
          lowerCAmelCase__ :str   				=					num_stages
          lowerCAmelCase__ :str   				=					[96, 192, 384, 768] if hidden_sizes is None else hidden_sizes
          lowerCAmelCase__ :Tuple   				=					[3, 3, 9, 3] if depths is None else depths
          lowerCAmelCase__ :Optional[Any]   				=					hidden_act
          lowerCAmelCase__ :List[Any]   				=					initializer_range
          lowerCAmelCase__ :int   				=					layer_norm_eps
          lowerCAmelCase__ :Optional[Any]   				=					drop_path_rate
          lowerCAmelCase__ :Optional[Any]   				=					image_size
          lowerCAmelCase__ :Union[str, Any]   				=					["""stem"""] + [f'''stage{idx}''' for idx in range(1     ,						len(self.depths		) + 1		)]
          lowerCAmelCase__ :str   				=					get_aligned_output_features_output_indices(
              out_features=_lowerCamelCase     ,						out_indices=_lowerCamelCase     ,						stage_names=self.stage_names		)






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


_A							=  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__   ):


  '''simple docstring'''







  def __init__(self							,       *_lowerCamelCase							,       _lowerCamelCase=None							,       _lowerCamelCase=None							,       _lowerCamelCase=None							,       **_lowerCamelCase	):


        """simple docstring"""

        super().__init__(*_lowerCamelCase							,       **_lowerCamelCase	)
        UpperCAmelCase__			:							Any							=    eval_examples
        UpperCAmelCase__			:							Union[str, Any]							=    post_process_function
        UpperCAmelCase__			:							int							=    quant_trainer_args
        UpperCAmelCase__			:							Dict							=    128  # 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."""	)
        UpperCAmelCase__			:							List[str]							=    calib_dataset if calib_dataset is not None else self.calib_dataset

        UpperCAmelCase__			:							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"""

        UpperCAmelCase__			:							int							=    self.train_dataset if calib_dataset is None else calib_dataset
        UpperCAmelCase__			:							List[str]							=    self.get_calib_dataloader(_lowerCamelCase	)

        UpperCAmelCase__			:							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
              UpperCAmelCase__					,		UpperCAmelCase__					,		UpperCAmelCase__			:							List[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	)
        UpperCAmelCase__			:							Tuple							=    model



  def  _a      (self							,       _lowerCamelCase=None							,       _lowerCamelCase=None							,       _lowerCamelCase=None							,       _lowerCamelCase = "eval"	):


        """simple docstring"""

        UpperCAmelCase__			:							Tuple							=    self.eval_dataset if eval_dataset is None else eval_dataset
        UpperCAmelCase__			:							List[Any]							=    self.get_eval_dataloader(_lowerCamelCase	)
        UpperCAmelCase__			:							Tuple							=    self.eval_examples if eval_examples is None else eval_examples

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

        if self.post_process_function is not None and self.compute_metrics is not None:
              UpperCAmelCase__			:							int							=    self.post_process_function(_lowerCamelCase							,       _lowerCamelCase							,       output.predictions	)
              UpperCAmelCase__			:							List[Any]							=    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}_"""	):
                          UpperCAmelCase__			:							Optional[int]							=    metrics.pop(_lowerCamelCase	)

              self.log(_lowerCamelCase	)
        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__			:							Optional[int]							=    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"""

        UpperCAmelCase__			:							Union[str, Any]							=    self.get_test_dataloader(_lowerCamelCase	)

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

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

        UpperCAmelCase__			:							Dict							=    self.post_process_function(_lowerCamelCase							,       _lowerCamelCase							,       output.predictions							,       """predict"""	)
        UpperCAmelCase__			:							Any							=    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}_"""	):
                    UpperCAmelCase__			:							Any							=    metrics.pop(_lowerCamelCase	)

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




  def  _a      (self							,       _lowerCamelCase="./"	):


        """simple docstring"""

        UpperCAmelCase__			:							Tuple							=    self.eval_dataset
        UpperCAmelCase__			:							int							=    self.get_eval_dataloader(_lowerCamelCase	)

        UpperCAmelCase__			:							Union[str, Any]							=    next(iter(_lowerCamelCase	)	)

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

        # convert to tuple
        UpperCAmelCase__			:							List[Any]							=    tuple(v.to(_lowerCamelCase	) for k, v in batch.items()	)

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

        UpperCAmelCase__			:							Optional[Any]							=    True

        UpperCAmelCase__			:							Tuple							=    self.model.to(_lowerCamelCase	)

        model.eval()
        model.float()

        UpperCAmelCase__			:							str							=    model.module if hasattr(_lowerCamelCase							,       """module"""	) else model
        quant_trainer.configure_model(_lowerCamelCase							,       self.quant_trainer_args	)

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

        UpperCAmelCase__			:							Optional[Any]							=    {0: """batch_size""", 1: """seq_len"""}

        torch.onnx.export(
            _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase							,       export_params=_lowerCamelCase							,       opset_version=13							,       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"""	)

