
'''simple docstring'''







import random






class  lowerCAmelCase__   :






					@staticmethod
					def 	_snake_case    (   __SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											lowercase_	:     Dict													=       [ord(__SCREAMING_SNAKE_CASE		) for i in text]
											lowercase_	:     Optional[Any]													=       []
											lowercase_	:     Union[str, Any]													=       []
											for i in plain:
																	lowercase_	:     List[str]													=       random.randint(1				,							3_00		)
																	lowercase_	:     Optional[int]													=       (i + k) * k
																	cipher.append(__SCREAMING_SNAKE_CASE		)
																	key.append(__SCREAMING_SNAKE_CASE		)
											return cipher, key






					@staticmethod
					def 	_snake_case    (   __SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											lowercase_	:     Tuple													=       []
											for i in range(len(__SCREAMING_SNAKE_CASE		)		):
																	lowercase_	:     Union[str, Any]													=       int((cipher[i] - (key[i]) ** 2) / key[i]		)
																	plain.append(chr(__SCREAMING_SNAKE_CASE		)		)
											return "".join(__SCREAMING_SNAKE_CASE		)


if __name__ == "__main__":
							_lowercase							,  _lowercase :  Optional[int]    							=       Onepad().encrypt("Hello")
							print(c, k)
							print(Onepad().decrypt(c, k))






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


snake_case_			  = logging.getLogger(__name__)

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

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Tuple			):



     '''simple docstring'''





     lowercase__    :   str      =       parser.add_argument_group('quant_trainer arguments'			)
     group.add_argument('--wprec'	,     type=SCREAMING_SNAKE_CASE_	,     default=8	,     help='weight precision'			)
     group.add_argument('--aprec'	,     type=SCREAMING_SNAKE_CASE_	,     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=SCREAMING_SNAKE_CASE_	,     nargs='+'	,     help='disable quantizers by keyword'			)
     group.add_argument('--quant-disable-layer-module'	,     type=SCREAMING_SNAKE_CASE_	,     help='disable quantizers by keyword under layer.'			)
     group.add_argument('--quant-enable-layer-module'	,     type=SCREAMING_SNAKE_CASE_	,     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=SCREAMING_SNAKE_CASE_	,     type=SCREAMING_SNAKE_CASE_	,     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=SCREAMING_SNAKE_CASE_	,     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__			(    SCREAMING_SNAKE_CASE_		:    List[Any]			):



     '''simple docstring'''





     if args.calibrator == "max":
          lowercase__    :   Optional[int]      =       'max'
     elif args.calibrator == "percentile":
          if args.percentile is None:
               raise ValueError('Specify --percentile when using percentile calibrator'			)
          lowercase__    :   Optional[Any]      =       'histogram'
     elif args.calibrator == "mse":
          lowercase__    :   int      =       'histogram'
     else:
          raise ValueError(f"""Invalid calibrator {args.calibrator}"""			)

     lowercase__    :   Any      =       QuantDescriptor(num_bits=args.aprec	,     calib_method=SCREAMING_SNAKE_CASE_			)
     lowercase__    :   List[Any]      =       QuantDescriptor(num_bits=args.wprec	,     axis=(None if args.quant_per_tensor else (0,))			)
     quant_nn.QuantLinear.set_default_quant_desc_input(SCREAMING_SNAKE_CASE_			)
     quant_nn.QuantLinear.set_default_quant_desc_weight(SCREAMING_SNAKE_CASE_			)

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Optional[Any]	,     SCREAMING_SNAKE_CASE_		:    List[str]	,     SCREAMING_SNAKE_CASE_		:    Union[str, Any]=False	,     SCREAMING_SNAKE_CASE_		:    Any=False			):



     '''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(SCREAMING_SNAKE_CASE_	,     ['embeddings']	,     which='weight'	,     _disabled=SCREAMING_SNAKE_CASE_			)

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

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

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

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

          if args.recalibrate_weights:
               recalibrate_weights(SCREAMING_SNAKE_CASE_			)

          if args.fuse_qkv:
               fuse_qkv(SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_			)

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

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

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Dict			):



     '''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__			(    SCREAMING_SNAKE_CASE_		:    Optional[Any]	,     SCREAMING_SNAKE_CASE_		:    Union[str, Any]			):



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

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Any	,     SCREAMING_SNAKE_CASE_		:    Optional[Any]			):



     '''simple docstring'''





     def fusea(SCREAMING_SNAKE_CASE_		:    Any	,     SCREAMING_SNAKE_CASE_		:    str	,     SCREAMING_SNAKE_CASE_		:    List[str]			):
          for mod in [qq, qk, qv]:
               if not hasattr(SCREAMING_SNAKE_CASE_	,     '_amax'			):
                    print('          WARNING: NO AMAX BUFFER'			)
                    return
          lowercase__    :   List[Any]      =       qq._amax.detach().item()
          lowercase__    :   Optional[int]      =       qk._amax.detach().item()
          lowercase__    :   List[str]      =       qv._amax.detach().item()

          lowercase__    :   Tuple      =       max(SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_			)
          qq._amax.fill_(SCREAMING_SNAKE_CASE_			)
          qk._amax.fill_(SCREAMING_SNAKE_CASE_			)
          qv._amax.fill_(SCREAMING_SNAKE_CASE_			)
          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__			(    SCREAMING_SNAKE_CASE_		:    List[Any]	,     SCREAMING_SNAKE_CASE_		:    Optional[int]			):



     '''simple docstring'''





     for name, mod in model.named_modules():
          if name.endswith('.output.dense'			) and not name.endswith('attention.output.dense'			):
               lowercase__    :   Any      =       mod._input_quantizer._amax.data.detach().item()
               mod._input_quantizer._amax.data.detach().clamp_(max=SCREAMING_SNAKE_CASE_			)
               lowercase__    :   List[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__			(    SCREAMING_SNAKE_CASE_		:    Optional[int]			):



     '''simple docstring'''





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

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Union[str, Any]			):



     '''simple docstring'''





     for name, mod in model.named_modules():
          if hasattr(SCREAMING_SNAKE_CASE_	,     '_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__    :   Dict      =       set() if mod._weight_quantizer.axis is None else set(mod._weight_quantizer.axis			)
               lowercase__    :   Union[str, Any]      =       set(range(len(mod.weight.size()			)			)			) - axis_set
               lowercase__    :   str      =       pytorch_quantization.utils.reduce_amax(mod.weight	,     axis=SCREAMING_SNAKE_CASE_	,     keepdims=SCREAMING_SNAKE_CASE_			).detach()
               logger.info(f"""RECALIB: {name:{name_width}} {mod._weight_quantizer._amax.flatten()} -> {amax.flatten()}"""			)
               lowercase__    :   Union[str, Any]      =       amax

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Dict	,     SCREAMING_SNAKE_CASE_		:    Optional[Any]=25	,     SCREAMING_SNAKE_CASE_		:    Any=180	,     SCREAMING_SNAKE_CASE_		:    Optional[int]=None			):



     '''simple docstring'''





     if ignore is None:
          lowercase__    :   Tuple      =       []
     elif not isinstance(SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_			):
          lowercase__    :   str      =       [ignore]

     lowercase__    :   Optional[Any]      =       0
     for name, mod in model.named_modules():
          if not hasattr(SCREAMING_SNAKE_CASE_	,     'weight'			):
               continue
          lowercase__    :   Optional[Any]      =       max(SCREAMING_SNAKE_CASE_	,     len(SCREAMING_SNAKE_CASE_			)			)

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

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    int			):



     '''simple docstring'''





     lowercase__    :   List[str]      =       0
     for name, mod in model.named_modules():
          if isinstance(SCREAMING_SNAKE_CASE_	,     pytorch_quantization.nn.TensorQuantizer			):
               print(f"""{name:80} {mod}"""			)
               count += 1
     print(f"""{count} TensorQuantizers found in model"""			)

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Optional[Any]	,     SCREAMING_SNAKE_CASE_		:    int	,     SCREAMING_SNAKE_CASE_		:    str	,     SCREAMING_SNAKE_CASE_		:    List[str]	,     SCREAMING_SNAKE_CASE_		:    Optional[int]			):



     '''simple docstring'''





     lowercase__    :   Dict      =       getattr(SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_			)
     if quantizer_mod is not None:
          assert hasattr(SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_			)
          setattr(SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_			)
     else:
          logger.warning(f"""{name} has no {quantizer}"""			)

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    List[Any]	,     SCREAMING_SNAKE_CASE_		:    Optional[int]	,     SCREAMING_SNAKE_CASE_		:    List[Any]="both"	,     **SCREAMING_SNAKE_CASE_		:    Tuple			):



     '''simple docstring'''





     lowercase__    :   Optional[int]      =       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(SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_	,     '_input_quantizer'	,     SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_			)
          if which in ["weight", "both"]:
               set_quantizer(SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_	,     '_weight_quantizer'	,     SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_			)
     logger.info(SCREAMING_SNAKE_CASE_			)

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Optional[Any]	,     SCREAMING_SNAKE_CASE_		:    Dict	,     **SCREAMING_SNAKE_CASE_		:    List[str]			):



     '''simple docstring'''





     for name, mod in model.named_modules():
          if hasattr(SCREAMING_SNAKE_CASE_	,     '_input_quantizer'			) or hasattr(SCREAMING_SNAKE_CASE_	,     '_weight_quantizer'			):
               for n in names:
                    if re.search(SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_			):
                         set_quantizers(SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_	,     **SCREAMING_SNAKE_CASE_			)
          elif name.endswith('_quantizer'			):
               for n in names:
                    if re.search(SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_			):
                         lowercase__    :   Any      =       f"""Warning: changing {name:{name_width}}"""
                         for k, v in kwargs.items():
                              s += f""" {k}={v}"""
                              setattr(SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_			)
                         logger.info(SCREAMING_SNAKE_CASE_			)

