





"""simple docstring"""






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

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

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

def       __A (     a_  :str				,    a_  :List[str]				,    a_  :Tuple=False				,    a_  :Optional[Any]=False)						->						Any:
				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(a_				,    ['''embeddings''']				,    which='''weight'''				,    _disabled=a_)

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

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

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

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

								if args.recalibrate_weights:
												recalibrate_weights(a_)

								if args.fuse_qkv:
												fuse_qkv(a_				,    a_)

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

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

def       __A (     a_  :Tuple)						->						int:
				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       __A (     a_  :Union[str, Any]				,    a_  :int)						->						int:
				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(a_)

def       __A (     a_  :List[Any]				,    a_  :Dict)						->						List[Any]:

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

								__a	:  Optional[Any]         =					max(a_				,    a_				,    a_)
								qq._amax.fill_(a_)
								qk._amax.fill_(a_)
								qv._amax.fill_(a_)
								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       __A (     a_  :Dict				,    a_  :Dict)						->						Tuple:

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

def       __A (     a_  :int)						->						List[str]:

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

def       __A (     a_  :str)						->						Any:

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

def       __A (     a_  :Union[str, Any]				,    a_  :Optional[Any]=25				,    a_  :Any=1_80				,    a_  :List[str]=None)						->						int:

				if ignore is None:
								__a	:  Optional[Any]         =					[]
				elif not isinstance(a_				,    a_):
								__a	:  List[str]         =					[ignore]

				__a	:  Optional[int]         =					0
				for name, mod in model.named_modules():
								if not hasattr(a_				,    '''weight'''):
												continue
								__a	:  str         =					max(a_				,    len(a_))

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

def       __A (     a_  :int)						->						Any:
				__a	:  int         =					0
				for name, mod in model.named_modules():
								if isinstance(a_				,    pytorch_quantization.nn.TensorQuantizer):
												print(F"""{name:80} {mod}""")
												count += 1
				print(F"""{count} TensorQuantizers found in model""")

def       __A (     a_  :Optional[int]				,    a_  :Optional[int]				,    a_  :Optional[Any]				,    a_  :Tuple				,    a_  :Tuple)						->						Union[str, Any]:
				__a	:  int         =					getattr(a_				,    a_				,    a_)
				if quantizer_mod is not None:
								assert hasattr(a_				,    a_)
								setattr(a_				,    a_				,    a_)
				else:
								logger.warning(F"""{name} has no {quantizer}""")

def       __A (     a_  :int				,    a_  :Optional[Any]				,    a_  :List[Any]="both"				,    **a_  :List[str])						->						Any:
				__a	:  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(a_				,    a_				,    '''_input_quantizer'''				,    a_				,    a_)
								if which in ["weight", "both"]:
												set_quantizer(a_				,    a_				,    '''_weight_quantizer'''				,    a_				,    a_)
				logger.info(a_)






def       __A (     a_  :Union[str, Any]				,    a_  :Tuple				,    **a_  :Optional[Any])						->						Tuple:

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






"""simple docstring"""






import comet  # From: unbabel-comet
import torch

import datasets


A	     =					datasets.logging.get_logger(__name__)

A	     =					'''\
@inproceedings{rei-EtAl:2020:WMT,
   author    = {Rei, Ricardo  and  Stewart, Craig  and  Farinha, Ana C  and  Lavie, Alon},
   title     = {Unbabel\'s Participation in the WMT20 Metrics Shared Task},
   booktitle      = {Proceedings of the Fifth Conference on Machine Translation},
   month          = {November},
   year           = {2020},
   address        = {Online},
   publisher      = {Association for Computational Linguistics},
   pages     = {909--918},
}
@inproceedings{rei-etal-2020-comet,
   title = "{COMET}: A Neural Framework for {MT} Evaluation",
   author = "Rei, Ricardo  and
      Stewart, Craig  and
      Farinha, Ana C  and
      Lavie, Alon",
   booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)",
   month = nov,
   year = "2020",
   address = "Online",
   publisher = "Association for Computational Linguistics",
   url = "https://www.aclweb.org/anthology/2020.emnlp-main.213",
   pages = "2685--2702",
}
'''

A	     =					'''\
Crosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA\'s or MQM).
With the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition.

See the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.
'''

A	     =					'''
COMET score.

Args:

`sources` (list of str): Source sentences
`predictions` (list of str): candidate translations
`references` (list of str): reference translations
`cuda` (bool): If set to True, runs COMET using GPU
`show_progress` (bool): Shows progress
`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.

Returns:
    `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.
    `scores`: List of scores.

Examples:

    >>> comet_metric = datasets.load_metric(\'comet\')
    >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\')  # you can also choose which model to use
    >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."]
    >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"]
    >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"]
    >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)
    >>> print([round(v, 2) for v in results["scores"]])
    [0.19, 0.92]
'''




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







					'''simple docstring'''




					def 	_lowerCamelCase						(  self       ):
									return datasets.MetricInfo(
									    description=_DESCRIPTION		,     citation=_CITATION		,     homepage='''https://unbabel.github.io/COMET/html/index.html'''		,     inputs_description=_KWARGS_DESCRIPTION		,     features=datasets.Features(
									        {
									            '''sources''': datasets.Value('''string'''		,     id='''sequence'''       ),
									            '''predictions''': datasets.Value('''string'''		,     id='''sequence'''       ),
									            '''references''': datasets.Value('''string'''		,     id='''sequence'''       ),
									        }       )		,     codebase_urls=['''https://github.com/Unbabel/COMET''']		,     reference_urls=[
									        '''https://github.com/Unbabel/COMET''',
									        '''https://www.aclweb.org/anthology/2020.emnlp-main.213/''',
									        '''http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6''',
									    ]		,     )







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase       ):
									if self.config_name == "default":
													__a	:  List[str]         =					comet.load_from_checkpoint(comet.download_model('''wmt20-comet-da'''       )       )
									else:
													__a	:  List[str]         =					comet.load_from_checkpoint(comet.download_model(self.config_name       )       )







					def 	_lowerCamelCase						(  self		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase		,     _UpperCAmelCase=None		,     _UpperCAmelCase=False       ):
									if gpus is None:
													__a	:  str         =					1 if torch.cuda.is_available() else 0
									__a	:  Optional[Any]         =					{'''src''': sources, '''mt''': predictions, '''ref''': references}
									__a	:  Dict         =					[dict(zip(_UpperCAmelCase		,     _UpperCAmelCase       )       ) for t in zip(*data.values()       )]
									__a    ,  __a	:  int         =					self.scorer.predict(_UpperCAmelCase		,     gpus=_UpperCAmelCase		,     progress_bar=_UpperCAmelCase       )
									return {"mean_score": mean_score, "scores": scores}