


'''simple docstring'''







# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import importlib.metadata
import json
import os
from dataclasses import dataclass
from typing import Any, Dict, Union

from packaging import version

from ..utils import is_torch_available, logging


if is_torch_available():
       import torch


lowerCAmelCase     :  int											=    logging.get_logger(__name__)
@dataclass
class 						UpperCamelCase__       :



     """simple docstring"""






     def __init__(			self   ,						snake_case__=False   ,						snake_case__=False   ,						snake_case__=6.0   ,						snake_case__=None   ,						snake_case__=False   ,						snake_case__=False   ,						snake_case__=None   ,						snake_case__="fp4"   ,						snake_case__=False   ,						**snake_case__   ,						):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							load_in_abit
            _lowerCAmelCase     :				Dict       =							load_in_abit
            _lowerCAmelCase     :				List[Any]       =							llm_inta_threshold
            _lowerCAmelCase     :				Tuple       =							llm_inta_skip_modules
            _lowerCAmelCase     :				List[Any]       =							llm_inta_enable_fpaa_cpu_offload
            _lowerCAmelCase     :				List[str]       =							llm_inta_has_fpaa_weight
            _lowerCAmelCase     :				int       =							bnb_abit_quant_type
            _lowerCAmelCase     :				List[Any]       =							bnb_abit_use_double_quant

            if bnb_abit_compute_dtype is None:
                   _lowerCAmelCase     :				List[Any]       =							torch.floataa
            elif isinstance(snake_case__   ,						snake_case__ ):
                   _lowerCAmelCase     :				str       =							getattr(snake_case__   ,						snake_case__ )
            elif isinstance(snake_case__   ,						torch.dtype ):
                   _lowerCAmelCase     :				Any       =							bnb_abit_compute_dtype
            else:
                   raise ValueError('bnb_4bit_compute_dtype must be a string or a torch.dtype' )

            self.post_init()







     def a						(			self ):

            '''simple docstring'''

            if not isinstance(self.llm_inta_threshold   ,						snake_case__ ):
                   raise ValueError('llm_int8_threshold must be a float' )

            if self.llm_inta_skip_modules is not None and not isinstance(self.llm_inta_skip_modules   ,						snake_case__ ):
                   raise ValueError('llm_int8_skip_modules must be a list of strings' )
            if not isinstance(self.llm_inta_enable_fpaa_cpu_offload   ,						snake_case__ ):
                   raise ValueError('llm_int8_enable_fp32_cpu_offload must be a boolean' )

            if not isinstance(self.llm_inta_has_fpaa_weight   ,						snake_case__ ):
                   raise ValueError('llm_int8_has_fp16_weight must be a boolean' )

            if self.bnb_abit_compute_dtype is not None and not isinstance(self.bnb_abit_compute_dtype   ,						torch.dtype ):
                   raise ValueError('bnb_4bit_compute_dtype must be torch.dtype' )

            if not isinstance(self.bnb_abit_quant_type   ,						snake_case__ ):
                   raise ValueError('bnb_4bit_quant_type must be a string' )

            if not isinstance(self.bnb_abit_use_double_quant   ,						snake_case__ ):
                   raise ValueError('bnb_4bit_use_double_quant must be a boolean' )

            if self.load_in_abit and not version.parse(importlib.metadata.version('bitsandbytes' ) ) >= version.parse(
                '0.39.0' ):
                   raise ValueError(
                       '4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version' )







     def a						(			self ):

            '''simple docstring'''

            return self.load_in_abit or self.load_in_abit







     def a						(			self ):

            '''simple docstring'''

            if self.load_in_abit:
                   return "llm_int8"
            elif self.load_in_abit and self.bnb_abit_quant_type == "fp4":
                   return "fp4"
            elif self.load_in_abit and self.bnb_abit_quant_type == "nf4":
                   return "nf4"
            else:
                   return None







     @classmethod
     def a						(			cls   ,						snake_case__   ,						snake_case__   ,						**snake_case__ ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							cls(**snake_case__ )

            _lowerCAmelCase     :				str       =							[]
            for key, value in kwargs.items():
                   if hasattr(snake_case__   ,						snake_case__ ):
                          setattr(snake_case__   ,						snake_case__   ,						snake_case__ )
                          to_remove.append(snake_case__ )
            for key in to_remove:
                   kwargs.pop(snake_case__   ,						snake_case__ )

            if return_unused_kwargs:
                   return config, kwargs
            else:
                   return config







     def a						(			self   ,						snake_case__ ):

            '''simple docstring'''

            with open(snake_case__   ,						'w'   ,						encoding='utf-8' ) as writer:
                   _lowerCAmelCase     :				Dict       =							self.to_dict()
                   _lowerCAmelCase     :				List[Any]       =							json.dumps(snake_case__   ,						indent=2   ,						sort_keys=snake_case__ ) + '\n'

                   writer.write(snake_case__ )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[Any]       =							copy.deepcopy(self.__dict__ )
            _lowerCAmelCase     :				Tuple       =							str(output['bnb_4bit_compute_dtype'] ).split('.' )[1]

            return output







     def __repr__(			self ):

            '''simple docstring'''

            return F'{self.__class__.__name__} {self.to_json_string()}'







     def a						(			self   ,						snake_case__ = True ):

            '''simple docstring'''

            if use_diff is True:
                   _lowerCAmelCase     :				Optional[Any]       =							self.to_diff_dict()
            else:
                   _lowerCAmelCase     :				Optional[Any]       =							self.to_dict()
            return json.dumps(snake_case__   ,						indent=2   ,						sort_keys=snake_case__ ) + "\n"







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				int       =							self.to_dict()

            # get the default config dict
            _lowerCAmelCase     :				str       =							BitsAndBytesConfig().to_dict()

            _lowerCAmelCase     :				Optional[int]       =							{}

            # only serialize values that differ from the default config
            for key, value in config_dict.items():
                   if value != default_config_dict[key]:
                          _lowerCAmelCase     :				List[Any]       =							value

            return serializable_config_dict





'''simple docstring'''







import os

from bleurt import score  # From: git+https://github.com/google-research/bleurt.git

import datasets


lowerCAmelCase     :  Optional[int]											=    datasets.logging.get_logger(__name__)


lowerCAmelCase     :  List[str]											=    """\
@inproceedings{bleurt,
  title={BLEURT: Learning Robust Metrics for Text Generation},
  author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh},
  booktitle={ACL},
  year={2020},
  url={https://arxiv.org/abs/2004.04696}
}
"""

lowerCAmelCase     :  List[Any]											=    """\
BLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018)
and then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune
it for your specific application (the latter is expected to perform better).

See the project's README at https://github.com/google-research/bleurt#readme for more information.
"""

lowerCAmelCase     :  str											=    """
BLEURT score.

Args:
    `predictions` (list of str): prediction/candidate sentences
    `references` (list of str): reference sentences
    `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None.

Returns:
    'scores': List of scores.
Examples:

    >>> predictions = [\"hello there\", \"general kenobi\"]
    >>> references = [\"hello there\", \"general kenobi\"]
    >>> bleurt = datasets.load_metric(\"bleurt\")
    >>> results = bleurt.compute(predictions=predictions, references=references)
    >>> print([round(v, 2) for v in results[\"scores\"]])
    [1.03, 1.04]
"""

lowerCAmelCase     :  Optional[Any]											=    {
    """bleurt-tiny-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip""",
    """bleurt-tiny-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip""",
    """bleurt-base-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip""",
    """bleurt-base-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip""",
    """bleurt-large-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip""",
    """bleurt-large-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip""",
    """BLEURT-20-D3""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip""",
    """BLEURT-20-D6""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip""",
    """BLEURT-20-D12""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip""",
    """BLEURT-20""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip""",
}
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,       _KWARGS_DESCRIPTION						)
class 						UpperCamelCase__       (			datasets.Metric						):



     """simple docstring"""






     def a						(			self ):

            '''simple docstring'''

            return datasets.MetricInfo(
                description=_DESCRIPTION   ,						citation=_CITATION   ,						homepage='https://github.com/google-research/bleurt'   ,						inputs_description=_KWARGS_DESCRIPTION   ,						features=datasets.Features(
                    {
                        'predictions': datasets.Value('string'   ,						id='sequence' ),
                        'references': datasets.Value('string'   ,						id='sequence' ),
                    } )   ,						codebase_urls=['https://github.com/google-research/bleurt']   ,						reference_urls=['https://github.com/google-research/bleurt', 'https://arxiv.org/abs/2004.04696']   ,						)







     def a						(			self   ,						snake_case__ ):

            '''simple docstring'''

            if self.config_name == "default":
                   logger.warning(
                       'Using default BLEURT-Base checkpoint for sequence maximum length 128. '
                       'You can use a bigger model for better results with e.g.: datasets.load_metric(\'bleurt\', \'bleurt-large-512\').' )
                   _lowerCAmelCase     :				Tuple       =							'bleurt-base-128'

            if self.config_name.lower() in CHECKPOINT_URLS:
                   _lowerCAmelCase     :				int       =							self.config_name.lower()

            elif self.config_name.upper() in CHECKPOINT_URLS:
                   _lowerCAmelCase     :				str       =							self.config_name.upper()

            else:
                   raise KeyError(
                       F'{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}' )

            # download the model checkpoint specified by self.config_name and set up the scorer
            _lowerCAmelCase     :				Optional[Any]       =							dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] )
            _lowerCAmelCase     :				str       =							score.BleurtScorer(os.path.join(snake_case__   ,						snake_case__ ) )







     def a						(			self   ,						snake_case__   ,						snake_case__ ):

            '''simple docstring'''

            _lowerCAmelCase     :				Tuple       =							self.scorer.score(references=snake_case__   ,						candidates=snake_case__ )
            return {"scores": scores}

