'''simple docstring'''




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


__lowercase        =    logging.getLogger(__name__)






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

		'''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(_A ,  _A					) 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(_A					)

		# add cpu modules to skip modules only for 4-bit modules
		if load_in_abit:
				bnb_quantization_config.skip_modules.extend(_A					)
		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(_A					)

		# compatibility with peft
		lowerCAmelCase     =    load_in_abit
		lowerCAmelCase     =    load_in_abit

		lowerCAmelCase     =    get_parameter_device(_A					)
		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(_A ,  _A ,  modules_to_not_convert=_A					)
				# 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(_A ,  _A ,  _A					)
										if param is not None:
												param.to(torch.floataa					)
						elif torch.is_floating_point(_A					):
								param.to(_A					)
				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(
						    _A ,  _A ,  modules_to_not_convert=_A					)

				lowerCAmelCase     =    get_quantized_model_device_map(
				    _A ,  _A ,  _A ,  max_memory=_A ,  no_split_module_classes=_A ,  )
				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(
				    _A ,  _A ,  _A ,  dtype=bnb_quantization_config.torch_dtype ,  offload_folder=_A ,  offload_state_dict=_A ,  keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules ,  offload_abit_bnb=load_in_abit and offload ,  )
				return dispatch_model(_A ,  device_map=_A ,  offload_dir=_A					)






def 							snake_case__				(     _A:   str ,  _A:   str ,  _A:   List[str]=None ,  _A:   List[str]=None ,  _A:   Optional[int]=None					)       ->      int:

		'''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(_A ,  _A					):
				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(
						    _A ,  low_zero=(device_map == """balanced_low_0""") ,  max_memory=_A ,  **_A ,  )

				lowerCAmelCase     =    max_memory
				lowerCAmelCase     =    infer_auto_device_map(_A ,  **_A					)

		if isinstance(_A ,  _A					):
				# 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(
										    """
                        Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit
                        the quantized model. If you want to dispatch the model on the CPU or the disk while keeping
                        these modules in `torch_dtype`, you need to pass a custom `device_map` to
                        `load_and_quantize_model`. Check
                        https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk
                        for more details.
                        """					)
								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 							snake_case__				(     _A:   List[Any] ,  _A:   Any ,  _A:   List[str]=None ,  _A:   List[str]=None					)       ->      Optional[int]:

		'''simple docstring'''


		if modules_to_not_convert is None:
				lowerCAmelCase     =    []

		lowerCAmelCase   ,	lowerCAmelCase     =    _replace_with_bnb_layers(
		    _A ,  _A ,  _A ,  _A					)
		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 							snake_case__				(     _A:   List[str] ,  _A:   List[Any] ,  _A:   Dict=None ,  _A:   str=None ,  )       ->      Tuple:

		'''simple docstring'''


		lowerCAmelCase     =    False
		for name, module in model.named_children():
				if current_key_name is None:
						lowerCAmelCase     =    []
				current_key_name.append(_A					)
				if isinstance(_A ,  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(_A					)
						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=_A ,  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_(_A					)
								setattr(_A ,  _A ,  _A					)
								lowerCAmelCase     =    True
				if len(list(module.children()					)					) > 0:
						lowerCAmelCase   ,	lowerCAmelCase     =    _replace_with_bnb_layers(
						    _A ,  _A ,  _A ,  _A					)
						lowerCAmelCase     =    has_been_replaced | _has_been_replaced
				# Remove the last key for recursion
				current_key_name.pop(-1					)
		return model, has_been_replaced






def 							snake_case__				(     _A:   Optional[Any]					)       ->      Dict:

		'''simple docstring'''


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

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

		# Check if it is a base model
		lowerCAmelCase     =    False
		if hasattr(_A ,  """base_model_prefix"""					):
				lowerCAmelCase     =    not hasattr(_A ,  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(_A					) - set(_A					)
		lowerCAmelCase     =    list(set(_A					)					) + list(_A					)

		# 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(_A ,  """"""					)
				filtered_module_names.append(_A					)

		return filtered_module_names






def 							snake_case__				(     _A:   Optional[int]					)       ->      str:

		'''simple docstring'''


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






def 							snake_case__				(     _A:   nn.Module					)       ->      str:

		'''simple docstring'''


		return next(parameter.parameters()					).device






def 							snake_case__				(     _A:   Optional[Any] ,  _A:   Union[str, Any] ,  _A:   str ,  _A:   str ,  _A:   Union[str, Any] ,  _A:   Any ,  _A:   Optional[Any]					)       ->      Tuple:

		'''simple docstring'''


		if fpaa_statistics is None:
				set_module_tensor_to_device(_A ,  _A ,  0 ,  dtype=_A ,  value=_A					)
				lowerCAmelCase     =    param_name
				lowerCAmelCase     =    model
				if "." in tensor_name:
						lowerCAmelCase     =    tensor_name.split("""."""					)
						for split in splits[:-1]:
								lowerCAmelCase     =    getattr(_A ,  _A					)
								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] ,  _A ,  _A ,  index=_A					)
				if hasattr(module._parameters[tensor_name] ,  """SCB"""					):
						offload_weight(
						    module._parameters[tensor_name].SCB ,  param_name.replace("""weight""" ,  """SCB"""					) ,  _A ,  index=_A ,  )
		else:
				offload_weight(_A ,  _A ,  _A ,  index=_A					)
				offload_weight(_A ,  param_name.replace("""weight""" ,  """SCB"""					) ,  _A ,  index=_A					)

		set_module_tensor_to_device(_A ,  _A ,  """meta""" ,  dtype=_A ,  value=torch.empty(*param.size()					)					)





'''simple docstring'''




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

import datasets


__lowercase        =    '''\
@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",
}
'''

__lowercase        =    '''\
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.
'''

__lowercase        =    '''
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 							a__(   datasets.Metric      ):


			'''simple docstring'''






			def 				a_			(  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 				a_			(  self			,       __lowerCAmelCase			,       __lowerCAmelCase			,       __lowerCAmelCase = False			,       __lowerCAmelCase = False			,       __lowerCAmelCase = False			,       __lowerCAmelCase = False			,       ):




					"""simple docstring"""


					lowerCAmelCase     =    len(references[0])
					if any(len(__lowerCAmelCase) != 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(__lowerCAmelCase)]

					lowerCAmelCase     =    TER(
					    normalized=__lowerCAmelCase			,       no_punct=__lowerCAmelCase			,       asian_support=__lowerCAmelCase			,       case_sensitive=__lowerCAmelCase			,       )
					lowerCAmelCase     =    sb_ter.corpus_score(__lowerCAmelCase			,       __lowerCAmelCase)

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




