


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


a			:			Optional[int]												=					logging.getLogger(__name__)

a			:			Any												=					50  # max width of layer names
a			:			Tuple												=					70  # max width of quantizer names


def 		lowercase_	(  _UpperCamelCase	):


			'''simple docstring'''







			__lowercase			       = parser.add_argument_group('''quant_trainer arguments'''	)
			group.add_argument('''--wprec'''							,      type=_UpperCamelCase							,      default=8							,      help='''weight precision'''	)
			group.add_argument('''--aprec'''							,      type=_UpperCamelCase							,      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=_UpperCamelCase							,      nargs='''+'''							,      help='''disable quantizers by keyword'''	)
			group.add_argument('''--quant-disable-layer-module'''							,      type=_UpperCamelCase							,      help='''disable quantizers by keyword under layer.'''	)
			group.add_argument('''--quant-enable-layer-module'''							,      type=_UpperCamelCase							,      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=_UpperCamelCase							,      type=_UpperCamelCase							,      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=_UpperCamelCase							,      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 		lowercase_	(  _UpperCamelCase	):


			'''simple docstring'''







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

			__lowercase			       = QuantDescriptor(num_bits=args.aprec							,      calib_method=_UpperCamelCase	)
			__lowercase			       = QuantDescriptor(num_bits=args.wprec							,      axis=(None if args.quant_per_tensor else (0,))	)
			quant_nn.QuantLinear.set_default_quant_desc_input(_UpperCamelCase	)
			quant_nn.QuantLinear.set_default_quant_desc_weight(_UpperCamelCase	)


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase=False							,      _UpperCamelCase=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(_UpperCamelCase							,      ['''embeddings''']							,      which='''weight'''							,      _disabled=_UpperCamelCase	)

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

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

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

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

						if args.recalibrate_weights:
									recalibrate_weights(_UpperCamelCase	)

						if args.fuse_qkv:
									fuse_qkv(_UpperCamelCase							,      _UpperCamelCase	)

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

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


def 		lowercase_	(  _UpperCamelCase	):


			'''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 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase	):


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


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase	):


			'''simple docstring'''







			def fusea(_UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase	):
						for mod in [qq, qk, qv]:
									if not hasattr(_UpperCamelCase							,      '''_amax'''	):
												print('''          WARNING: NO AMAX BUFFER'''	)
												return
						__lowercase			       = qq._amax.detach().item()
						__lowercase			       = qk._amax.detach().item()
						__lowercase			       = qv._amax.detach().item()

						__lowercase			       = max(_UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase	)
						qq._amax.fill_(_UpperCamelCase	)
						qk._amax.fill_(_UpperCamelCase	)
						qv._amax.fill_(_UpperCamelCase	)
						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 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase	):


			'''simple docstring'''







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


def 		lowercase_	(  _UpperCamelCase	):


			'''simple docstring'''







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


def 		lowercase_	(  _UpperCamelCase	):


			'''simple docstring'''







			for name, mod in model.named_modules():
						if hasattr(_UpperCamelCase							,      '''_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			       = set() if mod._weight_quantizer.axis is None else set(mod._weight_quantizer.axis	)
									__lowercase			       = set(range(len(mod.weight.size()	)	)	) - axis_set
									__lowercase			       = pytorch_quantization.utils.reduce_amax(mod.weight							,      axis=_UpperCamelCase							,      keepdims=_UpperCamelCase	).detach()
									logger.info(F'RECALIB: {name:{name_width}} {mod._weight_quantizer._amax.flatten()} -> {amax.flatten()}'	)
									__lowercase			       = amax


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase=25							,      _UpperCamelCase=1_80							,      _UpperCamelCase=None	):


			'''simple docstring'''







			if ignore is None:
						__lowercase			       = []
			elif not isinstance(_UpperCamelCase							,      _UpperCamelCase	):
						__lowercase			       = [ignore]

			__lowercase			       = 0
			for name, mod in model.named_modules():
						if not hasattr(_UpperCamelCase							,      '''weight'''	):
									continue
						__lowercase			       = max(_UpperCamelCase							,      len(_UpperCamelCase	)	)

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


def 		lowercase_	(  _UpperCamelCase	):


			'''simple docstring'''







			__lowercase			       = 0
			for name, mod in model.named_modules():
						if isinstance(_UpperCamelCase							,      pytorch_quantization.nn.TensorQuantizer	):
									print(F'{name:80} {mod}'	)
									count += 1
			print(F'{count} TensorQuantizers found in model'	)


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase	):


			'''simple docstring'''







			__lowercase			       = getattr(_UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase	)
			if quantizer_mod is not None:
						assert hasattr(_UpperCamelCase							,      _UpperCamelCase	)
						setattr(_UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase	)
			else:
						logger.warning(F'{name} has no {quantizer}'	)


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase="both"							,      **_UpperCamelCase	):


			'''simple docstring'''







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





def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase							,      **_UpperCamelCase	):


			'''simple docstring'''







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






import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List

import git
import torch
from torch.utils.data import Dataset

from transformers import BartTokenizer, RagTokenizer, TaTokenizer


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase=True							,      _UpperCamelCase="pt"	):


			'''simple docstring'''







			__lowercase			       = {'''add_prefix_space''': True} if isinstance(_UpperCamelCase							,      _UpperCamelCase	) and not line.startswith(''' '''	) else {}
			__lowercase			       = padding_side
			return tokenizer(
			    [line]							,      max_length=_UpperCamelCase							,      padding='''max_length''' if pad_to_max_length else None							,      truncation=_UpperCamelCase							,      return_tensors=_UpperCamelCase							,      add_special_tokens=_UpperCamelCase							,      **_UpperCamelCase							,      )


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase=None							,      ):


			'''simple docstring'''







			__lowercase			       = input_ids.ne(_UpperCamelCase	).any(dim=0	)
			if attention_mask is None:
						return input_ids[:, keep_column_mask]
			else:
						return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])
class 						lowerCamelCase_							(					lowerCAmelCase__					):



					'''simple docstring'''







					def __init__(					self			,							snake_case_			,							snake_case_			,							snake_case_			,							snake_case_			,							snake_case_="train"			,							snake_case_=None			,							snake_case_=None			,							snake_case_=None			,							snake_case_=""			,							) ->      Tuple:







								'''simple docstring'''

								super().__init__()
								__lowercase			       = Path(snake_case_    ).joinpath(type_path + '''.source'''    )
								__lowercase			       = Path(snake_case_    ).joinpath(type_path + '''.target'''    )
								__lowercase			       = self.get_char_lens(self.src_file    )
								__lowercase			       = max_source_length
								__lowercase			       = max_target_length
								assert min(self.src_lens    ) > 0, F'found empty line in {self.src_file}'
								__lowercase			       = tokenizer
								__lowercase			       = prefix
								if n_obs is not None:
											__lowercase			       = self.src_lens[:n_obs]
								__lowercase			       = src_lang
								__lowercase			       = tgt_lang






					def __len__(					self    ) ->      List[Any]:







								'''simple docstring'''

								return len(self.src_lens    )






					def __getitem__(					self			,							snake_case_    ) ->      Dict[str, torch.Tensor]:







								'''simple docstring'''

								__lowercase			       = index + 1  # linecache starts at 1
								__lowercase			       = self.prefix + linecache.getline(str(self.src_file    )			,							snake_case_    ).rstrip('''\n'''    )
								__lowercase			       = linecache.getline(str(self.tgt_file    )			,							snake_case_    ).rstrip('''\n'''    )
								assert source_line, F'empty source line for index {index}'
								assert tgt_line, F'empty tgt line for index {index}'

								# Need to add eos token manually for T5
								if isinstance(self.tokenizer			,							snake_case_    ):
											source_line += self.tokenizer.eos_token
											tgt_line += self.tokenizer.eos_token

								# Pad source and target to the right
								__lowercase			       = (
								    self.tokenizer.question_encoder if isinstance(self.tokenizer			,							snake_case_    ) else self.tokenizer
								)
								__lowercase			       = self.tokenizer.generator if isinstance(self.tokenizer			,							snake_case_    ) else self.tokenizer

								__lowercase			       = encode_line(snake_case_			,							snake_case_			,							self.max_source_length			,							'''right'''    )
								__lowercase			       = encode_line(snake_case_			,							snake_case_			,							self.max_target_length			,							'''right'''    )

								__lowercase			       = source_inputs['''input_ids'''].squeeze()
								__lowercase			       = target_inputs['''input_ids'''].squeeze()
								__lowercase			       = source_inputs['''attention_mask'''].squeeze()
								return {
								    "input_ids": source_ids,
								    "attention_mask": src_mask,
								    "decoder_input_ids": target_ids,
								}






					@staticmethod
					def A   (					snake_case_    ) ->      Any:







								'''simple docstring'''

								return [len(snake_case_    ) for x in Path(snake_case_    ).open().readlines()]






					def A   (					self			,							snake_case_    ) ->      Dict[str, torch.Tensor]:







								'''simple docstring'''

								__lowercase			       = torch.stack([x['''input_ids'''] for x in batch]    )
								__lowercase			       = torch.stack([x['''attention_mask'''] for x in batch]    )
								__lowercase			       = torch.stack([x['''decoder_input_ids'''] for x in batch]    )
								__lowercase			       = (
								    self.tokenizer.generator.pad_token_id
								    if isinstance(self.tokenizer			,							snake_case_    )
								    else self.tokenizer.pad_token_id
								)
								__lowercase			       = (
								    self.tokenizer.question_encoder.pad_token_id
								    if isinstance(self.tokenizer			,							snake_case_    )
								    else self.tokenizer.pad_token_id
								)
								__lowercase			       = trim_batch(snake_case_			,							snake_case_    )
								__lowercase       ,			__lowercase			       = trim_batch(snake_case_			,							snake_case_			,							attention_mask=snake_case_    )
								__lowercase			       = {
								    '''input_ids''': source_ids,
								    '''attention_mask''': source_mask,
								    '''decoder_input_ids''': y,
								}
								return batch




a			:			int												=					getLogger(__name__)


def 		lowercase_	(  _UpperCamelCase	):


			'''simple docstring'''







			return list(itertools.chain.from_iterable(_UpperCamelCase	)	)


def 		lowercase_	(  _UpperCamelCase	):


			'''simple docstring'''







			__lowercase			       = get_git_info()
			save_json(_UpperCamelCase							,      os.path.join(_UpperCamelCase							,      '''git_log.json'''	)	)


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase=4							,      **_UpperCamelCase	):


			'''simple docstring'''







			with open(_UpperCamelCase							,      '''w'''	) as f:
						json.dump(_UpperCamelCase							,      _UpperCamelCase							,      indent=_UpperCamelCase							,      **_UpperCamelCase	)


def 		lowercase_	(  _UpperCamelCase	):


			'''simple docstring'''







			with open(_UpperCamelCase	) as f:
						return json.load(_UpperCamelCase	)


def 		lowercase_	(  ):


			'''simple docstring'''







			__lowercase			       = git.Repo(search_parent_directories=_UpperCamelCase	)
			__lowercase			       = {
			    '''repo_id''': str(_UpperCamelCase	),
			    '''repo_sha''': str(repo.head.object.hexsha	),
			    '''repo_branch''': str(repo.active_branch	),
			    '''hostname''': str(socket.gethostname()	),
			}
			return repo_infos


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase	):


			'''simple docstring'''







			return list(map(_UpperCamelCase							,      _UpperCamelCase	)	)


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase	):


			'''simple docstring'''







			with open(_UpperCamelCase							,      '''wb'''	) as f:
						return pickle.dump(_UpperCamelCase							,      _UpperCamelCase	)


def 		lowercase_	(  _UpperCamelCase	):


			'''simple docstring'''







			def remove_articles(_UpperCamelCase	):
						return re.sub(r'''\b(a|an|the)\b'''							,      ''' '''							,      _UpperCamelCase	)

			def white_space_fix(_UpperCamelCase	):
						return " ".join(text.split()	)

			def remove_punc(_UpperCamelCase	):
						__lowercase			       = set(string.punctuation	)
						return "".join(ch for ch in text if ch not in exclude	)

			def lower(_UpperCamelCase	):
						return text.lower()

			return white_space_fix(remove_articles(remove_punc(lower(_UpperCamelCase	)	)	)	)


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase	):


			'''simple docstring'''







			__lowercase			       = normalize_answer(_UpperCamelCase	).split()
			__lowercase			       = normalize_answer(_UpperCamelCase	).split()
			__lowercase			       = Counter(_UpperCamelCase	) & Counter(_UpperCamelCase	)
			__lowercase			       = sum(common.values()	)
			if num_same == 0:
						return 0
			__lowercase			       = 1.0 * num_same / len(_UpperCamelCase	)
			__lowercase			       = 1.0 * num_same / len(_UpperCamelCase	)
			__lowercase			       = (2 * precision * recall) / (precision + recall)
			return fa


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase	):


			'''simple docstring'''







			return normalize_answer(_UpperCamelCase	) == normalize_answer(_UpperCamelCase	)


def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase	):


			'''simple docstring'''







			assert len(_UpperCamelCase	) == len(_UpperCamelCase	)
			__lowercase			       = 0
			for hypo, pred in zip(_UpperCamelCase							,      _UpperCamelCase	):
						em += exact_match_score(_UpperCamelCase							,      _UpperCamelCase	)
			if len(_UpperCamelCase	) > 0:
						em /= len(_UpperCamelCase	)
			return {"em": em}


def 		lowercase_	(  _UpperCamelCase	):


			'''simple docstring'''







			return model_prefix.startswith('''rag'''	)





def 		lowercase_	(  _UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase	):


			'''simple docstring'''







			__lowercase			       = {p: p for p in extra_params}
			# T5 models don't have `dropout` param, they have `dropout_rate` instead
			__lowercase			       = '''dropout_rate'''
			for p in extra_params:
						if getattr(_UpperCamelCase							,      _UpperCamelCase							,      _UpperCamelCase	):
									if not hasattr(_UpperCamelCase							,      _UpperCamelCase	) and not hasattr(_UpperCamelCase							,      equivalent_param[p]	):
												logger.info('''config doesn\'t have a `{}` attribute'''.format(_UpperCamelCase	)	)
												delattr(_UpperCamelCase							,      _UpperCamelCase	)
												continue
									__lowercase			       = p if hasattr(_UpperCamelCase							,      _UpperCamelCase	) else equivalent_param[p]
									setattr(_UpperCamelCase							,      _UpperCamelCase							,      getattr(_UpperCamelCase							,      _UpperCamelCase	)	)
									delattr(_UpperCamelCase							,      _UpperCamelCase	)
			return hparams, config


