
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  =	logging.getLogger(__name__)

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






def   lowerCamelCase__							(							__lowerCAmelCase    :    Optional[Any]							):




			"""simple docstring"""


			lowerCAmelCase_         =      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   lowerCamelCase__							(							__lowerCAmelCase    :    int							):




			"""simple docstring"""


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

			lowerCAmelCase_         =      QuantDescriptor(num_bits=args.aprec       ,				calib_method=__lowerCAmelCase							)
			lowerCAmelCase_         =      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   lowerCamelCase__							(							__lowerCAmelCase    :    int       ,				__lowerCAmelCase    :    str       ,				__lowerCAmelCase    :    Any=False       ,				__lowerCAmelCase    :    Optional[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(__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   lowerCamelCase__							(							__lowerCAmelCase    :    Optional[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   lowerCamelCase__							(							__lowerCAmelCase    :    List[str]       ,				__lowerCAmelCase    :    int							):




			"""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   lowerCamelCase__							(							__lowerCAmelCase    :    Optional[Any]       ,				__lowerCAmelCase    :    Union[str, Any]							):




			"""simple docstring"""


			def fusea(__lowerCAmelCase    :    str       ,				__lowerCAmelCase    :    str       ,				__lowerCAmelCase    :    List[Any]							):
						for mod in [qq, qk, qv]:
									if not hasattr(__lowerCAmelCase       ,				"_amax"							):
												print("          WARNING: NO AMAX BUFFER"							)
												return
						lowerCAmelCase_         =      qq._amax.detach().item()
						lowerCAmelCase_         =      qk._amax.detach().item()
						lowerCAmelCase_         =      qv._amax.detach().item()

						lowerCAmelCase_         =      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   lowerCamelCase__							(							__lowerCAmelCase    :    str       ,				__lowerCAmelCase    :    Tuple							):




			"""simple docstring"""


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






def   lowerCamelCase__							(							__lowerCAmelCase    :    int							):




			"""simple docstring"""


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






def   lowerCamelCase__							(							__lowerCAmelCase    :    Optional[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)
									lowerCAmelCase_         =      set() if mod._weight_quantizer.axis is None else set(mod._weight_quantizer.axis							)
									lowerCAmelCase_         =      set(range(len(mod.weight.size()							)							)							) - axis_set
									lowerCAmelCase_         =      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()}"""							)
									lowerCAmelCase_         =      amax






def   lowerCamelCase__							(							__lowerCAmelCase    :    Tuple       ,				__lowerCAmelCase    :    Optional[Any]=25       ,				__lowerCAmelCase    :    Dict=180       ,				__lowerCAmelCase    :    Dict=None							):




			"""simple docstring"""


			if ignore is None:
						lowerCAmelCase_         =      []
			elif not isinstance(__lowerCAmelCase       ,				__lowerCAmelCase							):
						lowerCAmelCase_         =      [ignore]

			lowerCAmelCase_         =      0
			for name, mod in model.named_modules():
						if not hasattr(__lowerCAmelCase       ,				"weight"							):
									continue
						lowerCAmelCase_         =      max(__lowerCAmelCase       ,				len(__lowerCAmelCase							)							)

			for name, mod in model.named_modules():
						lowerCAmelCase_         =      getattr(__lowerCAmelCase       ,				"_input_quantizer"       ,				__lowerCAmelCase							)
						lowerCAmelCase_         =      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
						lowerCAmelCase_         =      F"""Act:{input_q.extra_repr()}"""
						lowerCAmelCase_         =      F"""Wgt:{weight_q.extra_repr()}"""
						lowerCAmelCase_         =      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   lowerCamelCase__							(							__lowerCAmelCase    :    List[Any]							):




			"""simple docstring"""


			lowerCAmelCase_         =      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   lowerCamelCase__							(							__lowerCAmelCase    :    Any       ,				__lowerCAmelCase    :    Optional[int]       ,				__lowerCAmelCase    :    List[Any]       ,				__lowerCAmelCase    :    Tuple       ,				__lowerCAmelCase    :    Any							):




			"""simple docstring"""


			lowerCAmelCase_         =      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   lowerCamelCase__							(							__lowerCAmelCase    :    Tuple       ,				__lowerCAmelCase    :    Optional[Any]       ,				__lowerCAmelCase    :    Union[str, Any]="both"       ,				**__lowerCAmelCase    :    List[Any]							):




			"""simple docstring"""


			lowerCAmelCase_         =      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   lowerCamelCase__							(							__lowerCAmelCase    :    str       ,				__lowerCAmelCase    :    Tuple       ,				**__lowerCAmelCase    :    str							):




			"""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							):
															lowerCAmelCase_         =      F"""Warning: changing {name:{name_width}}"""
															for k, v in kwargs.items():
																		s += F""" {k}={v}"""
																		setattr(__lowerCAmelCase       ,				__lowerCAmelCase       ,				__lowerCAmelCase							)
															logger.info(__lowerCAmelCase							)





import sacrebleu as scb
from packaging import version
from sacrebleu import TER

import datasets


_A  =	"\\n@inproceedings{snover-etal-2006-study,\n    title = \"A Study of Translation Edit Rate with Targeted Human Annotation\",\n    author = \"Snover, Matthew  and\n      Dorr, Bonnie  and\n      Schwartz, Rich  and\n      Micciulla, Linnea  and\n      Makhoul, John\",\n    booktitle = \"Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers\",\n    month = aug # \" 8-12\",\n    year = \"2006\",\n    address = \"Cambridge, Massachusetts, USA\",\n    publisher = \"Association for Machine Translation in the Americas\",\n    url = \"https://aclanthology.org/2006.amta-papers.25\",\n    pages = \"223--231\",\n}\n@inproceedings{post-2018-call,\n    title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n    author = \"Post, Matt\",\n    booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n    month = oct,\n    year = \"2018\",\n    address = \"Belgium, Brussels\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://www.aclweb.org/anthology/W18-6319\",\n    pages = \"186--191\",\n}\n"

_A  =	"\\nTER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a\nhypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu\n(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found\nhere: https://github.com/jhclark/tercom.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.\n"

_A  =	"\nProduces TER scores alongside the number of edits and reference length.\n\nArgs:\n    predictions (list of str): The system stream (a sequence of segments).\n    references (list of list of str): A list of one or more reference streams (each a sequence of segments).\n    normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n    ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n    support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,\n                                    as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.\n                                    Only applies if `normalized = True`. Defaults to `False`.\n    case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.\n\nReturns:\n    'score' (float): TER score (num_edits / sum_ref_lengths * 100)\n    'num_edits' (int): The cumulative number of edits\n    'ref_length' (float): The cumulative average reference length\n\nExamples:\n    Example 1:\n        >>> predictions = [\"does this sentence match??\",\n        ...                     \"what about this sentence?\",\n        ...                     \"What did the TER metric user say to the developer?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],\n        ...             [\"Your jokes are...\", \"...TERrible\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         case_sensitive=True)\n        >>> print(results)\n        {'score': 150.0, 'num_edits': 15, 'ref_length': 10.0}\n\n    Example 2:\n        >>> predictions = [\"does this sentence match??\",\n        ...                     \"what about this sentence?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         case_sensitive=True)\n        >>> print(results)\n        {'score': 62.5, 'num_edits': 5, 'ref_length': 8.0}\n\n    Example 3:\n        >>> predictions = [\"does this sentence match??\",\n        ...                     \"what about this sentence?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         normalized=True,\n        ...                         case_sensitive=True)\n        >>> print(results)\n        {'score': 57.14285714285714, 'num_edits': 6, 'ref_length': 10.5}\n\n    Example 4:\n        >>> predictions = [\"does this sentence match??\",\n        ...                     \"what about this sentence?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         ignore_punct=True,\n        ...                         case_sensitive=False)\n        >>> print(results)\n        {'score': 0.0, 'num_edits': 0, 'ref_length': 8.0}\n\n    Example 5:\n        >>> predictions = [\"does this sentence match??\",\n        ...                    \"what about this sentence?\",\n        ...                    \"What did the TER metric user say to the developer?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],\n        ...             [\"Your jokes are...\", \"...TERrible\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         ignore_punct=True,\n        ...                         case_sensitive=False)\n        >>> print(results)\n        {'score': 100.0, 'num_edits': 10, 'ref_length': 10.0}\n"





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION   , _KWARGS_DESCRIPTION			)
class       _lowerCAmelCase   (      datasets.Metric			):




				def 	__a		(   self	)							-> str:
							if version.parse(scb.__version__	) < version.parse("1.4.12"	):
										raise ImportWarning(
										    "To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"
										    "You can install it with `pip install \"sacrebleu>=1.4.12\"`."	)
							return datasets.MetricInfo(
							    description=_DESCRIPTION							,							citation=_CITATION							,							homepage="http://www.cs.umd.edu/~snover/tercom/"							,							inputs_description=_KWARGS_DESCRIPTION							,							features=datasets.Features(
							        {
							            "predictions": datasets.Value("string"							,							id="sequence"	),
							            "references": datasets.Sequence(datasets.Value("string"							,							id="sequence"	)							,							id="references"	),
							        }	)							,							codebase_urls=["https://github.com/mjpost/sacreBLEU#ter"]							,							reference_urls=[
							        "https://github.com/jhclark/tercom",
							    ]							,							)




				def 	__a		(   self							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase = False							,							_UpperCamelCase = False							,							_UpperCamelCase = False							,							_UpperCamelCase = False							,							)							-> Any:
							lowerCAmelCase_         =      len(references[0]	)
							if any(len(_UpperCamelCase	) != references_per_prediction for refs in references	):
										raise ValueError("Sacrebleu requires the same number of references for each prediction"	)
							lowerCAmelCase_         =      [[refs[i] for refs in references] for i in range(_UpperCamelCase	)]

							lowerCAmelCase_         =      TER(
							    normalized=_UpperCamelCase							,							no_punct=_UpperCamelCase							,							asian_support=_UpperCamelCase							,							case_sensitive=_UpperCamelCase							,							)
							lowerCAmelCase_         =      sb_ter.corpus_score(_UpperCamelCase							,							_UpperCamelCase	)

							return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}



