






import logging
import os
from typing import Dict, List, Optional, Union

import torch
import torch.nn as nn

from accelerate.utils.imports import (
    is_abit_bnb_available,
    is_abit_bnb_available,
    is_bnb_available,
)

from ..big_modeling import dispatch_model, init_empty_weights
from .dataclasses import BnbQuantizationConfig
from .modeling import (
    find_tied_parameters,
    get_balanced_memory,
    infer_auto_device_map,
    load_checkpoint_in_model,
    offload_weight,
    set_module_tensor_to_device,
)


if is_bnb_available():
					import bitsandbytes as bnb

from copy import deepcopy


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







def 		_UpperCamelCase				(      UpperCamelCase_    :   torch.nn.Module      ,    UpperCamelCase_    :   BnbQuantizationConfig      ,    UpperCamelCase_    :   Union[str, os.PathLike] = None      ,    UpperCamelCase_    :   Optional[Dict[str, Union[int, str, torch.device]]] = None      ,    UpperCamelCase_    :   Optional[List[str]] = None      ,    UpperCamelCase_    :   Optional[Dict[Union[int, str], Union[int, str]]] = None      ,    UpperCamelCase_    :   Optional[Union[str, os.PathLike]] = None      ,    UpperCamelCase_    :   bool = False      ,    )					->				Optional[int]:

						"""simple docstring"""



						lowerCAmelCase__        =  bnb_quantization_config.load_in_abit
						lowerCAmelCase__        =  bnb_quantization_config.load_in_abit

						if load_in_abit and not is_abit_bnb_available():
												raise ImportError(
												    'You have a version of `bitsandbytes` that is not compatible with 8bit quantization,'
												    ' make sure you have the latest version of `bitsandbytes` installed.'						)
						if load_in_abit and not is_abit_bnb_available():
												raise ValueError(
												    'You have a version of `bitsandbytes` that is not compatible with 4bit quantization,'
												    'make sure you have the latest version of `bitsandbytes` installed.'						)

						lowerCAmelCase__        =  []
						# custom device map
						if isinstance(UpperCamelCase_      ,    UpperCamelCase_						) and len(device_map.keys()						) > 1:
												lowerCAmelCase__        =  [key for key, value in device_map.items() if value in ['disk', 'cpu']]

						# We keep some modules such as the lm_head in their original dtype for numerical stability reasons
						if bnb_quantization_config.skip_modules is None:
												lowerCAmelCase__        =  get_keys_to_not_convert(UpperCamelCase_						)

						# add cpu modules to skip modules only for 4-bit modules
						if load_in_abit:
												bnb_quantization_config.skip_modules.extend(UpperCamelCase_						)
						lowerCAmelCase__        =  bnb_quantization_config.skip_modules

						# We add the modules we want to keep in full precision
						if bnb_quantization_config.keep_in_fpaa_modules is None:
												lowerCAmelCase__        =  []
						lowerCAmelCase__        =  bnb_quantization_config.keep_in_fpaa_modules
						modules_to_not_convert.extend(UpperCamelCase_						)

						# compatibility with peft
						lowerCAmelCase__        =  load_in_abit
						lowerCAmelCase__        =  load_in_abit

						lowerCAmelCase__        =  get_parameter_device(UpperCamelCase_						)
						if model_device.type != "meta":
												# quantization of an already loaded model
												logger.warning(
												    'It is not recommended to quantize a loaded model. '
												    'The model should be instantiated under the `init_empty_weights` context manager.'						)
												lowerCAmelCase__        =  replace_with_bnb_layers(UpperCamelCase_      ,    UpperCamelCase_      ,    modules_to_not_convert=UpperCamelCase_						)
												# convert param to the right dtype
												lowerCAmelCase__        =  bnb_quantization_config.torch_dtype
												for name, param in model.state_dict().items():
																		if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules						):
																								param.to(torch.floataa						)
																								if param.dtype != torch.floataa:
																														lowerCAmelCase__        =  name.replace('.weight'      ,    ''						).replace('.bias'      ,    ''						)
																														lowerCAmelCase__        =  getattr(UpperCamelCase_      ,    UpperCamelCase_      ,    UpperCamelCase_						)
																														if param is not None:
																																				param.to(torch.floataa						)
																		elif torch.is_floating_point(UpperCamelCase_						):
																								param.to(UpperCamelCase_						)
												if model_device.type == "cuda":
																		# move everything to cpu in the first place because we can't do quantization if the weights are already on cuda
																		model.cuda(torch.cuda.current_device()						)
																		torch.cuda.empty_cache()
												elif torch.cuda.is_available():
																		model.to(torch.cuda.current_device()						)
												else:
																		raise RuntimeError('No GPU found. A GPU is needed for quantization.'						)
												logger.info(
												    F"The model device type is {model_device.type}. However, cuda is needed for quantization."
												    'We move the model to cuda.'						)
												return model

						elif weights_location is None:
												raise RuntimeError(
												    F"`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} "						)

						else:
												with init_empty_weights():
																		lowerCAmelCase__        =  replace_with_bnb_layers(
																		    UpperCamelCase_      ,    UpperCamelCase_      ,    modules_to_not_convert=UpperCamelCase_						)

												lowerCAmelCase__        =  get_quantized_model_device_map(
												    UpperCamelCase_      ,    UpperCamelCase_      ,    UpperCamelCase_      ,    max_memory=UpperCamelCase_      ,    no_split_module_classes=UpperCamelCase_      ,    )
												if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
																		lowerCAmelCase__        =  True

												lowerCAmelCase__        =  any(x in list(device_map.values()						) for x in ['cpu', 'disk']						)

												load_checkpoint_in_model(
												    UpperCamelCase_      ,    UpperCamelCase_      ,    UpperCamelCase_      ,    dtype=bnb_quantization_config.torch_dtype      ,    offload_folder=UpperCamelCase_      ,    offload_state_dict=UpperCamelCase_      ,    keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules      ,    offload_abit_bnb=load_in_abit and offload      ,    )
												return dispatch_model(UpperCamelCase_      ,    device_map=UpperCamelCase_      ,    offload_dir=UpperCamelCase_						)







def 		_UpperCamelCase				(      UpperCamelCase_    :   Tuple      ,    UpperCamelCase_    :   List[str]      ,    UpperCamelCase_    :   str=None      ,    UpperCamelCase_    :   int=None      ,    UpperCamelCase_    :   str=None						)					->				List[Any]:

						"""simple docstring"""



						if device_map is None:
												if torch.cuda.is_available():
																		lowerCAmelCase__        =  {'': torch.cuda.current_device()}
												else:
																		raise RuntimeError('No GPU found. A GPU is needed for quantization.'						)
												logger.info('The device_map was not initialized.' 'Setting device_map to `{\'\':torch.cuda.current_device()}`.'						)

						if isinstance(UpperCamelCase_      ,    UpperCamelCase_						):
												if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
																		raise ValueError(
																		    'If passing a string for `device_map`, please choose \'auto\', \'balanced\', \'balanced_low_0\' or '
																		    '\'sequential\'.'						)

												lowerCAmelCase__        =  {}
												special_dtypes.update(
												    {
												        name: bnb_quantization_config.torch_dtype
												        for name, _ in model.named_parameters()
												        if any(m in name for m in bnb_quantization_config.skip_modules						)
												    }						)
												special_dtypes.update(
												    {
												        name: torch.floataa
												        for name, _ in model.named_parameters()
												        if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules						)
												    }						)

												lowerCAmelCase__        =  {}
												lowerCAmelCase__        =  special_dtypes
												lowerCAmelCase__        =  no_split_module_classes
												lowerCAmelCase__        =  bnb_quantization_config.target_dtype

												# get max_memory for each device.
												if device_map != "sequential":
																		lowerCAmelCase__        =  get_balanced_memory(
																		    UpperCamelCase_      ,    low_zero=(device_map == 'balanced_low_0')      ,    max_memory=UpperCamelCase_      ,    **UpperCamelCase_      ,    )

												lowerCAmelCase__        =  max_memory
												lowerCAmelCase__        =  infer_auto_device_map(UpperCamelCase_      ,    **UpperCamelCase_						)

						if isinstance(UpperCamelCase_      ,    UpperCamelCase_						):
												# check if don't have any quantized module on the cpu
												lowerCAmelCase__        =  bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules

												lowerCAmelCase__        =  {
												    key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert
												}
												for device in ["cpu", "disk"]:
																		if device in device_map_without_some_modules.values():
																								if bnb_quantization_config.load_in_abit:
																														raise ValueError(
																														    '\n                        Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n                        the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n                        these modules in `torch_dtype`, you need to pass a custom `device_map` to\n                        `load_and_quantize_model`. Check\n                        https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n                        for more details.\n                        '						)
																								else:
																														logger.info(
																														    'Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit'						)
												del device_map_without_some_modules
						return device_map







def 		_UpperCamelCase				(      UpperCamelCase_    :   Optional[Any]      ,    UpperCamelCase_    :   Optional[int]      ,    UpperCamelCase_    :   Dict=None      ,    UpperCamelCase_    :   Optional[Any]=None						)					->				Dict:

						"""simple docstring"""



						if modules_to_not_convert is None:
												lowerCAmelCase__        =  []

						lowerCAmelCase__  ,    lowerCAmelCase__        =  _replace_with_bnb_layers(
						    UpperCamelCase_      ,    UpperCamelCase_      ,    UpperCamelCase_      ,    UpperCamelCase_						)
						if not has_been_replaced:
												logger.warning(
												    'You are loading your model in 8bit or 4bit but no linear modules were found in your model.'
												    ' this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.'
												    ' Please double check your model architecture, or submit an issue on github if you think this is'
												    ' a bug.'						)
						return model







def 		_UpperCamelCase				(      UpperCamelCase_    :   List[str]      ,    UpperCamelCase_    :   str      ,    UpperCamelCase_    :   List[str]=None      ,    UpperCamelCase_    :   int=None      ,    )					->				int:

						"""simple docstring"""



						lowerCAmelCase__        =  False
						for name, module in model.named_children():
												if current_key_name is None:
																		lowerCAmelCase__        =  []
												current_key_name.append(UpperCamelCase_						)
												if isinstance(UpperCamelCase_      ,    nn.Linear						) and name not in modules_to_not_convert:
																		# Check if the current key is not in the `modules_to_not_convert`
																		lowerCAmelCase__        =  '.'.join(UpperCamelCase_						)
																		lowerCAmelCase__        =  True
																		for key in modules_to_not_convert:
																								if (
																								    (key in current_key_name_str) and (key + "." in current_key_name_str)
																								) or key == current_key_name_str:
																														lowerCAmelCase__        =  False
																														break
																		if proceed:
																								# Load bnb module with empty weight and replace ``nn.Linear` module
																								if bnb_quantization_config.load_in_abit:
																														lowerCAmelCase__        =  bnb.nn.LinearabitLt(
																														    module.in_features      ,    module.out_features      ,    module.bias is not None      ,    has_fpaa_weights=UpperCamelCase_      ,    threshold=bnb_quantization_config.llm_inta_threshold      ,    )
																								elif bnb_quantization_config.load_in_abit:
																														lowerCAmelCase__        =  bnb.nn.Linearabit(
																														    module.in_features      ,    module.out_features      ,    module.bias is not None      ,    bnb_quantization_config.bnb_abit_compute_dtype      ,    compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant      ,    quant_type=bnb_quantization_config.bnb_abit_quant_type      ,    )
																								else:
																														raise ValueError('load_in_8bit and load_in_4bit can\'t be both False'						)
																								lowerCAmelCase__        =  module.weight.data
																								if module.bias is not None:
																														lowerCAmelCase__        =  module.bias.data
																								bnb_module.requires_grad_(UpperCamelCase_						)
																								setattr(UpperCamelCase_      ,    UpperCamelCase_      ,    UpperCamelCase_						)
																								lowerCAmelCase__        =  True
												if len(list(module.children()						)						) > 0:
																		lowerCAmelCase__  ,    lowerCAmelCase__        =  _replace_with_bnb_layers(
																		    UpperCamelCase_      ,    UpperCamelCase_      ,    UpperCamelCase_      ,    UpperCamelCase_						)
																		lowerCAmelCase__        =  has_been_replaced | _has_been_replaced
												# Remove the last key for recursion
												current_key_name.pop(-1						)
						return model, has_been_replaced







def 		_UpperCamelCase				(      UpperCamelCase_    :   Union[str, Any]						)					->				Dict:

						"""simple docstring"""



						with init_empty_weights():
												lowerCAmelCase__        =  deepcopy(UpperCamelCase_						)  # this has 0 cost since it is done inside `init_empty_weights` context manager`

						lowerCAmelCase__        =  find_tied_parameters(UpperCamelCase_						)
						# For compatibility with Accelerate < 0.18
						if isinstance(UpperCamelCase_      ,    UpperCamelCase_						):
												lowerCAmelCase__        =  sum(list(tied_params.values()						)      ,    []						) + list(tied_params.keys()						)
						else:
												lowerCAmelCase__        =  sum(UpperCamelCase_      ,    []						)
						lowerCAmelCase__        =  len(UpperCamelCase_						) > 0

						# Check if it is a base model
						lowerCAmelCase__        =  False
						if hasattr(UpperCamelCase_      ,    'base_model_prefix'						):
												lowerCAmelCase__        =  not hasattr(UpperCamelCase_      ,    model.base_model_prefix						)

						# Ignore this for base models (BertModel, GPT2Model, etc.)
						if (not has_tied_params) and is_base_model:
												return []

						# otherwise they have an attached head
						lowerCAmelCase__        =  list(model.named_children()						)
						lowerCAmelCase__        =  [list_modules[-1][0]]

						# add last module together with tied weights
						lowerCAmelCase__        =  set(UpperCamelCase_						) - set(UpperCamelCase_						)
						lowerCAmelCase__        =  list(set(UpperCamelCase_						)						) + list(UpperCamelCase_						)

						# remove ".weight" from the keys
						lowerCAmelCase__        =  ['.weight', '.bias']
						lowerCAmelCase__        =  []
						for name in list_untouched:
												for name_to_remove in names_to_remove:
																		if name_to_remove in name:
																								lowerCAmelCase__        =  name.replace(UpperCamelCase_      ,    ''						)
												filtered_module_names.append(UpperCamelCase_						)

						return filtered_module_names







def 		_UpperCamelCase				(      UpperCamelCase_    :   int						)					->				int:

						"""simple docstring"""



						for m in model.modules():
												if isinstance(UpperCamelCase_      ,    bnb.nn.Linearabit						):
																		return True
						return False







def 		_UpperCamelCase				(      UpperCamelCase_    :   nn.Module						)					->				str:

						"""simple docstring"""



						return next(parameter.parameters()						).device







def 		_UpperCamelCase				(      UpperCamelCase_    :   List[Any]      ,    UpperCamelCase_    :   List[str]      ,    UpperCamelCase_    :   Optional[int]      ,    UpperCamelCase_    :   List[str]      ,    UpperCamelCase_    :   Any      ,    UpperCamelCase_    :   Union[str, Any]      ,    UpperCamelCase_    :   Any						)					->				Optional[Any]:

						"""simple docstring"""



						if fpaa_statistics is None:
												set_module_tensor_to_device(UpperCamelCase_      ,    UpperCamelCase_      ,    0      ,    dtype=UpperCamelCase_      ,    value=UpperCamelCase_						)
												lowerCAmelCase__        =  param_name
												lowerCAmelCase__        =  model
												if "." in tensor_name:
																		lowerCAmelCase__        =  tensor_name.split('.'						)
																		for split in splits[:-1]:
																								lowerCAmelCase__        =  getattr(UpperCamelCase_      ,    UpperCamelCase_						)
																								if new_module is None:
																														raise ValueError(F"{module} has no attribute {split}."						)
																								lowerCAmelCase__        =  new_module
																		lowerCAmelCase__        =  splits[-1]
												# offload weights
												lowerCAmelCase__        =  False
												offload_weight(module._parameters[tensor_name]      ,    UpperCamelCase_      ,    UpperCamelCase_      ,    index=UpperCamelCase_						)
												if hasattr(module._parameters[tensor_name]      ,    'SCB'						):
																		offload_weight(
																		    module._parameters[tensor_name].SCB      ,    param_name.replace('weight'      ,    'SCB'						)      ,    UpperCamelCase_      ,    index=UpperCamelCase_      ,    )
						else:
												offload_weight(UpperCamelCase_      ,    UpperCamelCase_      ,    UpperCamelCase_      ,    index=UpperCamelCase_						)
												offload_weight(UpperCamelCase_      ,    param_name.replace('weight'      ,    'SCB'						)      ,    UpperCamelCase_      ,    index=UpperCamelCase_						)

						set_module_tensor_to_device(UpperCamelCase_      ,    UpperCamelCase_      ,    'meta'      ,    dtype=UpperCamelCase_      ,    value=torch.empty(*param.size()						)						)













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

import datasets


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

__snake_case      :      List[str]             =       """\
TER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a
hypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu
(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found
here: https://github.com/jhclark/tercom.

The implementation here is slightly different from sacrebleu in terms of the required input format. The length of
the references and hypotheses lists need to be the same, so you may need to transpose your references compared to
sacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534

See the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.
"""

__snake_case      :      Dict             =       """
Produces TER scores alongside the number of edits and reference length.

Args:
    predictions (list of str): The system stream (a sequence of segments).
    references (list of list of str): A list of one or more reference streams (each a sequence of segments).
    normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
    ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
    support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,
                                    as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.
                                    Only applies if `normalized = True`. Defaults to `False`.
    case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.

Returns:
    'score' (float): TER score (num_edits / sum_ref_lengths * 100)
    'num_edits' (int): The cumulative number of edits
    'ref_length' (float): The cumulative average reference length

Examples:
    Example 1:
        >>> predictions = [\"does this sentence match??\",
        ...                     \"what about this sentence?\",
        ...                     \"What did the TER metric user say to the developer?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],
        ...             [\"Your jokes are...\", \"...TERrible\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         case_sensitive=True)
        >>> print(results)
        {'score': 150.0, 'num_edits': 15, 'ref_length': 10.0}

    Example 2:
        >>> predictions = [\"does this sentence match??\",
        ...                     \"what about this sentence?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         case_sensitive=True)
        >>> print(results)
        {'score': 62.5, 'num_edits': 5, 'ref_length': 8.0}

    Example 3:
        >>> predictions = [\"does this sentence match??\",
        ...                     \"what about this sentence?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         normalized=True,
        ...                         case_sensitive=True)
        >>> print(results)
        {'score': 57.14285714285714, 'num_edits': 6, 'ref_length': 10.5}

    Example 4:
        >>> predictions = [\"does this sentence match??\",
        ...                     \"what about this sentence?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         ignore_punct=True,
        ...                         case_sensitive=False)
        >>> print(results)
        {'score': 0.0, 'num_edits': 0, 'ref_length': 8.0}

    Example 5:
        >>> predictions = [\"does this sentence match??\",
        ...                    \"what about this sentence?\",
        ...                    \"What did the TER metric user say to the developer?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],
        ...             [\"Your jokes are...\", \"...TERrible\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         ignore_punct=True,
        ...                         case_sensitive=False)
        >>> print(results)
        {'score': 100.0, 'num_edits': 10, 'ref_length': 10.0}
"""


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






						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												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  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase = False       ,  _UpperCamelCase = False       ,  _UpperCamelCase = False       ,  _UpperCamelCase = False       ,  ):






												"""simple docstring"""
												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}





