




import logging
import re

import pytorch_quantization
import pytorch_quantization.nn as quant_nn
import torch
from pytorch_quantization import calib
from pytorch_quantization.tensor_quant import QuantDescriptor


lowerCAmelCase_						 =					logging.getLogger(__name__)

lowerCAmelCase_						 =					50  # max width of layer names
lowerCAmelCase_						 =					70  # max width of quantizer names






def    snake_case(							__magic_name__       )					->				List[Any]:





     '''simple docstring'''


     lowercase   :  int        =					parser.add_argument_group('''quant_trainer arguments'''       )
     group.add_argument('''--wprec'''					,						type=__lowerCamelCase					,						default=8					,						help='''weight precision'''       )
     group.add_argument('''--aprec'''					,						type=__lowerCamelCase					,						default=8					,						help='''activation precision'''       )
     group.add_argument('''--quant-per-tensor'''					,						action='''store_true'''					,						help='''per tensor weight scaling'''       )
     group.add_argument('''--quant-disable'''					,						action='''store_true'''					,						help='''disable all quantizers'''       )
     group.add_argument('''--quant-disable-embeddings'''					,						action='''store_true'''					,						help='''disable all embeddings quantizers'''       )
     group.add_argument('''--quant-disable-keyword'''					,						type=__lowerCamelCase					,						nargs='''+'''					,						help='''disable quantizers by keyword'''       )
     group.add_argument('''--quant-disable-layer-module'''					,						type=__lowerCamelCase					,						help='''disable quantizers by keyword under layer.'''       )
     group.add_argument('''--quant-enable-layer-module'''					,						type=__lowerCamelCase					,						help='''enable quantizers by keyword under layer'''       )
     group.add_argument('''--calibrator'''					,						default='''max'''					,						help='''which quantization range calibrator to use'''       )
     group.add_argument('''--percentile'''					,						default=__lowerCamelCase					,						type=__lowerCamelCase					,						help='''percentile for PercentileCalibrator'''       )
     group.add_argument('''--fuse-qkv'''					,						action='''store_true'''					,						help='''use the same scale factor for qkv'''       )
     group.add_argument('''--clip-gelu'''					,						metavar='''N'''					,						type=__lowerCamelCase					,						help='''clip gelu output maximum value to N'''       )
     group.add_argument(
         '''--recalibrate-weights'''					,						action='''store_true'''					,						help=(
             '''recalibrate weight amaxes by taking the max of the weights.'''
             ''' amaxes will be computed with the current quantization granularity (axis).'''
         )					,						)






def    snake_case(							__magic_name__       )					->				List[Any]:





     '''simple docstring'''


     if args.calibrator == "max":
          lowercase   :  Tuple        =					"max"
     elif args.calibrator == "percentile":
          if args.percentile is None:
               raise ValueError('''Specify --percentile when using percentile calibrator'''       )
          lowercase   :  Tuple        =					"histogram"
     elif args.calibrator == "mse":
          lowercase   :  List[str]        =					"histogram"
     else:
          raise ValueError(F"""Invalid calibrator {args.calibrator}"""       )

     lowercase   :  Optional[int]        =					QuantDescriptor(num_bits=args.aprec					,						calib_method=__lowerCamelCase       )
     lowercase   :  Optional[int]        =					QuantDescriptor(num_bits=args.wprec					,						axis=(None if args.quant_per_tensor else (0,))       )
     quant_nn.QuantLinear.set_default_quant_desc_input(__lowerCamelCase       )
     quant_nn.QuantLinear.set_default_quant_desc_weight(__lowerCamelCase       )






def    snake_case(							__magic_name__					,						__magic_name__					,						__magic_name__=False					,						__magic_name__=False       )					->				List[str]:





     '''simple docstring'''


     logger.info('''Configuring Model for Quantization'''       )
     logger.info(F"""using quantization package {pytorch_quantization.__file__}"""       )

     if not calib:
          if args.quant_disable_embeddings:
               set_quantizer_by_name(__lowerCamelCase					,						['''embeddings''']					,						which='''weight'''					,						_disabled=__lowerCamelCase       )

          if args.quant_disable:
               set_quantizer_by_name(__lowerCamelCase					,						['''''']					,						_disabled=__lowerCamelCase       )

          if args.quant_disable_keyword:
               set_quantizer_by_name(__lowerCamelCase					,						args.quant_disable_keyword					,						_disabled=__lowerCamelCase       )

          if args.quant_disable_layer_module:
               set_quantizer_by_name(__lowerCamelCase					,						[r'''layer.\d+.''' + args.quant_disable_layer_module]					,						_disabled=__lowerCamelCase       )

          if args.quant_enable_layer_module:
               set_quantizer_by_name(__lowerCamelCase					,						[r'''layer.\d+.''' + args.quant_enable_layer_module]					,						_disabled=__lowerCamelCase       )

          if args.recalibrate_weights:
               recalibrate_weights(__lowerCamelCase       )

          if args.fuse_qkv:
               fuse_qkv(__lowerCamelCase					,						__lowerCamelCase       )

     if args.clip_gelu:
          clip_gelu(__lowerCamelCase					,						args.clip_gelu       )

     # if args.local_rank in [-1, 0] and not calib:
     print_quant_summary(__lowerCamelCase       )






def    snake_case(							__magic_name__       )					->				Any:





     '''simple docstring'''


     logger.info('''Enabling Calibration'''       )
     for name, module in model.named_modules():
          if name.endswith('''_quantizer'''       ):
               if module._calibrator is not None:
                    module.disable_quant()
                    module.enable_calib()
               else:
                    module.disable()
               logger.info(F"""{name:80}: {module}"""       )






def    snake_case(							__magic_name__					,						__magic_name__       )					->				Dict:





     '''simple docstring'''


     logger.info('''Loading calibrated amax'''       )
     for name, module in model.named_modules():
          if name.endswith('''_quantizer'''       ):
               if module._calibrator is not None:
                    if isinstance(module._calibrator					,						calib.MaxCalibrator       ):
                         module.load_calib_amax()
                    else:
                         module.load_calib_amax('''percentile'''					,						percentile=args.percentile       )
                    module.enable_quant()
                    module.disable_calib()
               else:
                    module.enable()
     model.cuda()
     print_quant_summary(__lowerCamelCase       )






def    snake_case(							__magic_name__					,						__magic_name__       )					->				List[str]:





     '''simple docstring'''


     def fusea(__magic_name__					,						__magic_name__					,						__magic_name__       ):
          for mod in [qq, qk, qv]:
               if not hasattr(__lowerCamelCase					,						'''_amax'''       ):
                    print('''          WARNING: NO AMAX BUFFER'''       )
                    return
          lowercase   :  List[Any]        =					qq._amax.detach().item()
          lowercase   :  Dict        =					qk._amax.detach().item()
          lowercase   :  Tuple        =					qv._amax.detach().item()

          lowercase   :  Optional[Any]        =					max(__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase       )
          qq._amax.fill_(__lowerCamelCase       )
          qk._amax.fill_(__lowerCamelCase       )
          qv._amax.fill_(__lowerCamelCase       )
          logger.info(F"""          q={q:5.2f} k={k:5.2f} v={v:5.2f} -> {amax:5.2f}"""       )

     for name, mod in model.named_modules():
          if name.endswith('''.attention.self'''       ):
               logger.info(F"""FUSE_QKV: {name:{name_width}}"""       )
               fusea(mod.matmul_q_input_quantizer					,						mod.matmul_k_input_quantizer					,						mod.matmul_v_input_quantizer       )
               if args.quant_per_tensor:
                    fusea(mod.query._weight_quantizer					,						mod.key._weight_quantizer					,						mod.value._weight_quantizer       )






def    snake_case(							__magic_name__					,						__magic_name__       )					->				Tuple:





     '''simple docstring'''


     for name, mod in model.named_modules():
          if name.endswith('''.output.dense'''       ) and not name.endswith('''attention.output.dense'''       ):
               lowercase   :  Tuple        =					mod._input_quantizer._amax.data.detach().item()
               mod._input_quantizer._amax.data.detach().clamp_(max=__lowerCamelCase       )
               lowercase   :  str        =					mod._input_quantizer._amax.data.detach().item()
               logger.info(F"""CLIP_GELU: {name:{name_width}} amax: {amax_init:5.2f} -> {amax:5.2f}"""       )






def    snake_case(							__magic_name__       )					->				Optional[int]:





     '''simple docstring'''


     for name, mod in model.named_modules():
          if hasattr(__lowerCamelCase					,						'''_weight_quantizer'''       ) and mod._weight_quantizer.axis is not None:
               lowercase   :  Tuple        =					mod.weight.shape[0]
               lowercase   :  Tuple        =					mod._weight_quantizer._amax.detach()
               lowercase   :  Optional[Any]        =					torch.ones(__lowerCamelCase					,						dtype=amax.dtype					,						device=amax.device       ) * amax
               print(F"""expanding {name} {amax} -> {mod._weight_quantizer._amax}"""       )






def    snake_case(							__magic_name__       )					->				int:





     '''simple docstring'''


     for name, mod in model.named_modules():
          if hasattr(__lowerCamelCase					,						'''_weight_quantizer'''       ):
               if not hasattr(mod.weight_quantizer					,						'''_amax'''       ):
                    print('''RECALIB: {name:{name_width}} WARNING: NO AMAX BUFFER'''       )
                    continue

               # determine which axes to reduce across
               # e.g. a 4D tensor quantized per axis 0 should reduce over (1,2,3)
               lowercase   :  List[Any]        =					set() if mod._weight_quantizer.axis is None else set(mod._weight_quantizer.axis       )
               lowercase   :  Optional[Any]        =					set(range(len(mod.weight.size()       )       )       ) - axis_set
               lowercase   :  int        =					pytorch_quantization.utils.reduce_amax(mod.weight					,						axis=__lowerCamelCase					,						keepdims=__lowerCamelCase       ).detach()
               logger.info(F"""RECALIB: {name:{name_width}} {mod._weight_quantizer._amax.flatten()} -> {amax.flatten()}"""       )
               lowercase   :  List[Any]        =					amax






def    snake_case(							__magic_name__					,						__magic_name__=25					,						__magic_name__=1_80					,						__magic_name__=None       )					->				Optional[int]:





     '''simple docstring'''


     if ignore is None:
          lowercase   :  str        =					[]
     elif not isinstance(__lowerCamelCase					,						__lowerCamelCase       ):
          lowercase   :  int        =					[ignore]

     lowercase   :  Tuple        =					0
     for name, mod in model.named_modules():
          if not hasattr(__lowerCamelCase					,						'''weight'''       ):
               continue
          lowercase   :  List[str]        =					max(__lowerCamelCase					,						len(__lowerCamelCase       )       )

     for name, mod in model.named_modules():
          lowercase   :  Dict        =					getattr(__lowerCamelCase					,						'''_input_quantizer'''					,						__lowerCamelCase       )
          lowercase   :  Any        =					getattr(__lowerCamelCase					,						'''_weight_quantizer'''					,						__lowerCamelCase       )
          if not hasattr(__lowerCamelCase					,						'''weight'''       ):
               continue
          if type(__lowerCamelCase       ) in ignore:
               continue
          if [True for s in ignore if type(__lowerCamelCase       ) is str and s in name]:
               continue
          lowercase   :  str        =					F"""Act:{input_q.extra_repr()}"""
          lowercase   :  str        =					F"""Wgt:{weight_q.extra_repr()}"""
          lowercase   :  Any        =					F"""{name:{name_width}} {act_str} {wgt_str}"""
          if len(__lowerCamelCase       ) <= line_width:
               logger.info(__lowerCamelCase       )
          else:
               logger.info(F"""{name:{name_width}} {act_str}"""       )
               logger.info(F"""{'  ':{name_width}} {wgt_str}"""       )






def    snake_case(							__magic_name__       )					->				List[Any]:





     '''simple docstring'''


     lowercase   :  Union[str, Any]        =					0
     for name, mod in model.named_modules():
          if isinstance(__lowerCamelCase					,						pytorch_quantization.nn.TensorQuantizer       ):
               print(F"""{name:80} {mod}"""       )
               count += 1
     print(F"""{count} TensorQuantizers found in model"""       )






def    snake_case(							__magic_name__					,						__magic_name__					,						__magic_name__					,						__magic_name__					,						__magic_name__       )					->				int:





     '''simple docstring'''


     lowercase   :  str        =					getattr(__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase       )
     if quantizer_mod is not None:
          assert hasattr(__lowerCamelCase					,						__lowerCamelCase       )
          setattr(__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase       )
     else:
          logger.warning(F"""{name} has no {quantizer}"""       )






def    snake_case(							__magic_name__					,						__magic_name__					,						__magic_name__="both"					,						**__magic_name__       )					->				int:





     '''simple docstring'''


     lowercase   :  Union[str, Any]        =					F"""Warning: changing {which} quantizers of {name:{qname_width}}"""
     for k, v in kwargs.items():
          s += F""" {k}={v}"""
          if which in ["input", "both"]:
               set_quantizer(__lowerCamelCase					,						__lowerCamelCase					,						'''_input_quantizer'''					,						__lowerCamelCase					,						__lowerCamelCase       )
          if which in ["weight", "both"]:
               set_quantizer(__lowerCamelCase					,						__lowerCamelCase					,						'''_weight_quantizer'''					,						__lowerCamelCase					,						__lowerCamelCase       )
     logger.info(__lowerCamelCase       )






def    snake_case(							__magic_name__					,						__magic_name__					,						**__magic_name__       )					->				Optional[int]:





     '''simple docstring'''


     for name, mod in model.named_modules():
          if hasattr(__lowerCamelCase					,						'''_input_quantizer'''       ) or hasattr(__lowerCamelCase					,						'''_weight_quantizer'''       ):
               for n in names:
                    if re.search(__lowerCamelCase					,						__lowerCamelCase       ):
                         set_quantizers(__lowerCamelCase					,						__lowerCamelCase					,						**__lowerCamelCase       )
          elif name.endswith('''_quantizer'''       ):
               for n in names:
                    if re.search(__lowerCamelCase					,						__lowerCamelCase       ):
                         lowercase   :  Optional[int]        =					F"""Warning: changing {name:{name_width}}"""
                         for k, v in kwargs.items():
                              s += F""" {k}={v}"""
                              setattr(__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase       )
                         logger.info(__lowerCamelCase       )

import argparse

import torch

from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert
from transformers.utils import logging


logging.set_verbosity_info()


def      UpperCamelCase   (       __lowerCamelCase	:					List[str]							,   __lowerCamelCase	:					Union[str, Any]							,   __lowerCamelCase	:					Union[str, Any]       ):
       # Initialise PyTorch model
       snake_case			:  Optional[int]     							= BertConfig.from_json_file(__lowerCamelCase       )
       print(f"""Building PyTorch model from configuration: {config}"""       )
       snake_case			:  Any     							= BertForPreTraining(__lowerCamelCase       )

       # Load weights from tf checkpoint
       load_tf_weights_in_bert(__lowerCamelCase							,   __lowerCamelCase							,   __lowerCamelCase       )

       # Save pytorch-model
       print(f"""Save PyTorch model to {pytorch_dump_path}"""       )
       torch.save(model.state_dict()							,   __lowerCamelCase       )


if __name__ == "__main__":
   __lowerCamelCase				=			argparse.ArgumentParser()
   # Required parameters
   parser.add_argument(
       """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path."""
   )
   parser.add_argument(
       """--bert_config_file""",
       default=None,
       type=str,
       required=True,
       help=(
           """The config json file corresponding to the pre-trained BERT model. \n"""
           """This specifies the model architecture."""
       ),
   )
   parser.add_argument(
       """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
   )
   __lowerCamelCase				=			parser.parse_args()
   convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)





