


"""simple docstring"""


import importlib.metadata
import warnings
from copy import deepcopy

from packaging import version

from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available


if is_bitsandbytes_available():
	import bitsandbytes as bnb
	import torch
	import torch.nn as nn

	from ..pytorch_utils import ConvaD

if is_accelerate_available():
	from accelerate import init_empty_weights
	from accelerate.utils import find_tied_parameters

A	:  Union[str, Any]            =     logging.get_logger(__name__)


def _lowerCamelCase      (						_UpperCamelCase       ,					_UpperCamelCase       ,					_UpperCamelCase       ,					_UpperCamelCase=None       ,					_UpperCamelCase=None ):

			'''simple docstring'''




			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]

			if tensor_name not in module._parameters and tensor_name not in module._buffers:
						raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}." )
			__lowerCAmelCase							       =     tensor_name in module._buffers
			__lowerCAmelCase							       =     getattr(_UpperCamelCase       ,					_UpperCamelCase )

			if old_value.device == torch.device("meta" ) and device not in ["meta", torch.device("meta" )] and value is None:
						raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {device}." )

			__lowerCAmelCase							       =     False
			__lowerCAmelCase							       =     False
			if is_buffer or not is_bitsandbytes_available():
						__lowerCAmelCase							       =     False
						__lowerCAmelCase							       =     False
			else:
						__lowerCAmelCase							       =     hasattr(bnb.nn       ,					"Params4bit" ) and isinstance(module._parameters[tensor_name]       ,					bnb.nn.Paramsabit )
						__lowerCAmelCase							       =     isinstance(module._parameters[tensor_name]       ,					bnb.nn.IntaParams )

			if is_abit or is_abit:
						__lowerCAmelCase							       =     module._parameters[tensor_name]
						if param.device.type != "cuda":
									if value is None:
												__lowerCAmelCase							       =     old_value.to(_UpperCamelCase )
									elif isinstance(_UpperCamelCase       ,					torch.Tensor ):
												__lowerCAmelCase							       =     value.to("cpu" )
												if value.dtype == torch.inta:
															__lowerCAmelCase							       =     version.parse(importlib.metadata.version("bitsandbytes" ) ) > version.parse(
															    "0.37.2" )
															if not is_abit_serializable:
																		raise ValueError(
																		    "Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. "
																		    "Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`." )
									else:
												__lowerCAmelCase							       =     torch.tensor(_UpperCamelCase       ,					device="cpu" )

									# Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
									# Since weights are saved in the correct "orientation", we skip transposing when loading.
									if issubclass(module.source_cls       ,					_UpperCamelCase ) and fpaa_statistics is None:
												__lowerCAmelCase							       =     new_value.T

									__lowerCAmelCase							       =     old_value.__dict__
									if is_abit:
												__lowerCAmelCase							       =     bnb.nn.IntaParams(_UpperCamelCase       ,					requires_grad=_UpperCamelCase       ,					**_UpperCamelCase ).to(_UpperCamelCase )
									elif is_abit:
												__lowerCAmelCase							       =     bnb.nn.Paramsabit(_UpperCamelCase       ,					requires_grad=_UpperCamelCase       ,					**_UpperCamelCase ).to(_UpperCamelCase )

									__lowerCAmelCase							       =     new_value
									if fpaa_statistics is not None:
												setattr(module.weight       ,					"SCB"       ,					fpaa_statistics.to(_UpperCamelCase ) )

			else:
						if value is None:
									__lowerCAmelCase							       =     old_value.to(_UpperCamelCase )
						elif isinstance(_UpperCamelCase       ,					torch.Tensor ):
									__lowerCAmelCase							       =     value.to(_UpperCamelCase )
						else:
									__lowerCAmelCase							       =     torch.tensor(_UpperCamelCase       ,					device=_UpperCamelCase )

						if is_buffer:
									__lowerCAmelCase							       =     new_value
						else:
									__lowerCAmelCase							       =     nn.Parameter(_UpperCamelCase       ,					requires_grad=old_value.requires_grad )
									__lowerCAmelCase							       =     new_value


def _lowerCamelCase      (						_UpperCamelCase       ,					_UpperCamelCase=None       ,					_UpperCamelCase=None       ,					_UpperCamelCase=None       ,					_UpperCamelCase=False ):

			'''simple docstring'''




			for name, module in model.named_children():
						if current_key_name is None:
									__lowerCAmelCase							       =     []
						current_key_name.append(_UpperCamelCase )

						if (isinstance(_UpperCamelCase       ,					nn.Linear ) or isinstance(_UpperCamelCase       ,					_UpperCamelCase )) and name not in modules_to_not_convert:
									# Check if the current key is not in the `modules_to_not_convert`
									if not any(key in ".".join(_UpperCamelCase ) for key in modules_to_not_convert ):
												with init_empty_weights():
															if isinstance(_UpperCamelCase       ,					_UpperCamelCase ):
																		__lowerCAmelCase       ,      __lowerCAmelCase							       =     module.weight.shape
															else:
																		__lowerCAmelCase							       =     module.in_features
																		__lowerCAmelCase							       =     module.out_features

															if quantization_config.quantization_method() == "llm_int8":
																		__lowerCAmelCase							       =     bnb.nn.LinearabitLt(
																		    _UpperCamelCase       ,					_UpperCamelCase       ,					module.bias is not None       ,					has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight       ,					threshold=quantization_config.llm_inta_threshold       ,					)
																		__lowerCAmelCase							       =     True
															else:
																		if (
																		    quantization_config.llm_inta_skip_modules is not None
																		    and name in quantization_config.llm_inta_skip_modules
																		):
																					pass
																		else:
																					__lowerCAmelCase							       =     bnb.nn.Linearabit(
																					    _UpperCamelCase       ,					_UpperCamelCase       ,					module.bias is not None       ,					quantization_config.bnb_abit_compute_dtype       ,					compress_statistics=quantization_config.bnb_abit_use_double_quant       ,					quant_type=quantization_config.bnb_abit_quant_type       ,					)
																					__lowerCAmelCase							       =     True
                    # Store the module class in case we need to transpose the weight later
															__lowerCAmelCase							       =     type(_UpperCamelCase )
															# Force requires grad to False to avoid unexpected errors
															model._modules[name].requires_grad_(_UpperCamelCase )
						if len(list(module.children() ) ) > 0:
									__lowerCAmelCase       ,      __lowerCAmelCase							       =     _replace_with_bnb_linear(
									    _UpperCamelCase       ,					_UpperCamelCase       ,					_UpperCamelCase       ,					_UpperCamelCase       ,					has_been_replaced=_UpperCamelCase       ,					)
						# Remove the last key for recursion
						current_key_name.pop(-1 )
			return model, has_been_replaced


def _lowerCamelCase      (						_UpperCamelCase       ,					_UpperCamelCase=None       ,					_UpperCamelCase=None       ,					_UpperCamelCase=None ):

			'''simple docstring'''




			__lowerCAmelCase							       =     ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
			__lowerCAmelCase       ,      __lowerCAmelCase							       =     _replace_with_bnb_linear(
			    _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."
						    " Please double check your model architecture, or submit an issue on github if you think this is"
						    " a bug." )

			return model


def _lowerCamelCase      (						*_UpperCamelCase       ,					**_UpperCamelCase ):

			'''simple docstring'''




			warnings.warn(
			    "`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead"       ,					_UpperCamelCase       ,					)
			return replace_with_bnb_linear(*_UpperCamelCase       ,					**_UpperCamelCase )


def _lowerCamelCase      (						*_UpperCamelCase       ,					**_UpperCamelCase ):

			'''simple docstring'''




			warnings.warn(
			    "`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead"       ,					_UpperCamelCase       ,					)
			return set_module_quantized_tensor_to_device(*_UpperCamelCase       ,					**_UpperCamelCase )


def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			__lowerCAmelCase							       =     deepcopy(_UpperCamelCase )  # this has 0 cost since it is done inside `init_empty_weights` context manager`
			tied_model.tie_weights()

			__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							       =     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








"""simple docstring"""


import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
A	:  List[str]            =     pytest.mark.integration


A	:  Optional[Any]            =     {"comet"}
A	:  int            =     importlib.util.find_spec("fairseq") is not None

A	:  Union[str, Any]            =     {"code_eval"}
A	:  Dict            =     os.name == "nt"

A	:  Dict            =     {"bertscore", "frugalscore", "perplexity"}
A	:  Any            =     importlib.util.find_spec("transformers") is not None


def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			@wraps(_UpperCamelCase )
			def wrapper(self       ,					_UpperCamelCase ):
						if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
									self.skipTest("\"test requires Fairseq\"" )
						else:
									test_case(self       ,					_UpperCamelCase )

			return wrapper


def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			@wraps(_UpperCamelCase )
			def wrapper(self       ,					_UpperCamelCase ):
						if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
									self.skipTest("\"test requires transformers\"" )
						else:
									test_case(self       ,					_UpperCamelCase )

			return wrapper


def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			@wraps(_UpperCamelCase )
			def wrapper(self       ,					_UpperCamelCase ):
						if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
									self.skipTest("\"test not supported on Windows\"" )
						else:
									test_case(self       ,					_UpperCamelCase )

			return wrapper


def _lowerCamelCase      (						):

			'''simple docstring'''




			__lowerCAmelCase							       =     [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob("./metrics/*/" )]
			return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished
@parameterized.named_parameters(get_local_metric_names()						)
@for_all_test_methods(
    lowerCAmelCase__			,lowerCAmelCase__			,lowerCAmelCase__						)
@local
class     _UpperCamelCase    (  parameterized.TestCase						):
							'''simple docstring'''







							__UpperCAmelCase		:       Any							 ={}
							__UpperCAmelCase		:       List[str]							 =None

							@pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning"      )
							@pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning"      )
							def      snake_case							(	self       ,  __a      ):
										__lowerCAmelCase							       =     "[...]"
										__lowerCAmelCase							       =     importlib.import_module(
										    datasets.load.metric_module_factory(os.path.join("metrics"       ,  __a      )      ).module_path      )
										__lowerCAmelCase							       =     datasets.load.import_main_class(metric_module.__name__       ,  dataset=__a      )
										# check parameters
										__lowerCAmelCase							       =     inspect.signature(metric._compute      ).parameters
										self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()      )      )  # no **kwargs
										# run doctest
										with self.patch_intensive_calls(__a       ,  metric_module.__name__      ):
													with self.use_local_metrics():
																try:
																			__lowerCAmelCase							       =     doctest.testmod(__a       ,  verbose=__a       ,  raise_on_error=__a      )
																except doctest.UnexpectedException as e:
																			raise e.exc_info[1]  # raise the exception that doctest caught
										self.assertEqual(results.failed       ,  0      )
										self.assertGreater(results.attempted       ,  1      )

							@slow
							def      snake_case							(	self       ,  __a      ):
										__lowerCAmelCase							       =     "[...]"
										__lowerCAmelCase							       =     importlib.import_module(
										    datasets.load.metric_module_factory(os.path.join("metrics"       ,  __a      )      ).module_path      )
										# run doctest
										with self.use_local_metrics():
													__lowerCAmelCase							       =     doctest.testmod(__a       ,  verbose=__a       ,  raise_on_error=__a      )
										self.assertEqual(results.failed       ,  0      )
										self.assertGreater(results.attempted       ,  1      )

							@contextmanager
							def      snake_case							(	self       ,  __a       ,  __a      ):
										if metric_name in self.INTENSIVE_CALLS_PATCHER:
													with self.INTENSIVE_CALLS_PATCHER[metric_name](__a      ):
																yield
										else:
													yield

							@contextmanager
							def      snake_case							(	self      ):
										def load_local_metric(__a       ,  *__a       ,  **__a      ):
													return load_metric(os.path.join("metrics"       ,  __a      )       ,  *__a       ,  **__a      )

										with patch("datasets.load_metric"      ) as mock_load_metric:
													__lowerCAmelCase							       =     load_local_metric
													yield



							@classmethod
							def      snake_case							(	cls       ,  __a      ):
										def wrapper(__a      ):
													__lowerCAmelCase							       =     contextmanager(__a      )
													__lowerCAmelCase							       =     patcher
													return patcher

										return wrapper


@LocalMetricTest.register_intensive_calls_patcher("bleurt" )
def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			import tensorflow.compat.va as tf
			from bleurt.score import Predictor

			tf.flags.DEFINE_string("sv"       ,					""       ,					"" )  # handle pytest cli flags
			class     _UpperCamelCase    (  lowerCAmelCase__						):
										'''simple docstring'''







										def      snake_case							(	self       ,  __a      ):
													assert len(input_dict["input_ids"]      ) == 2
													return np.array([1.0_3, 1.0_4]      )

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
			with patch("bleurt.score._create_predictor" ) as mock_create_predictor:
						__lowerCAmelCase							       =     MockedPredictor()
						yield


@LocalMetricTest.register_intensive_calls_patcher("bertscore" )
def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			import torch

			def bert_cos_score_idf(_UpperCamelCase       ,					_UpperCamelCase       ,					*_UpperCamelCase       ,					**_UpperCamelCase ):
						return torch.tensor([[1.0, 1.0, 1.0]] * len(_UpperCamelCase ) )

			# mock get_model which is supposed to do download a bert model
			# mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
			with patch("bert_score.scorer.get_model" ), patch(
			    "bert_score.scorer.bert_cos_score_idf" ) as mock_bert_cos_score_idf:
						__lowerCAmelCase							       =     bert_cos_score_idf
						yield


@LocalMetricTest.register_intensive_calls_patcher("comet" )
def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			def load_from_checkpoint(_UpperCamelCase ):
						class     _UpperCamelCase    :
													'''simple docstring'''







													def      snake_case							(	self       ,  __a       ,  *__a       ,  **__a      ):
																assert len(__a      ) == 2
																__lowerCAmelCase							       =     [0.1_9, 0.9_2]
																return scores, sum(__a      ) / len(__a      )
						return Model()

			# mock load_from_checkpoint which is supposed to do download a bert model
			# mock load_from_checkpoint which is supposed to do download a bert model
			with patch("comet.download_model" ) as mock_download_model:
						__lowerCAmelCase							       =     None
						with patch("comet.load_from_checkpoint" ) as mock_load_from_checkpoint:
									__lowerCAmelCase							       =     load_from_checkpoint
									yield


def _lowerCamelCase      (						):

			'''simple docstring'''




			__lowerCAmelCase							       =     load_metric(os.path.join("metrics"       ,					"seqeval" ) )
			__lowerCAmelCase							       =     "ERROR"
			__lowerCAmelCase							       =     f"Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"
			with pytest.raises(_UpperCamelCase       ,					match=re.escape(_UpperCamelCase ) ):
						metric.compute(predictions=[]       ,					references=[]       ,					scheme=_UpperCamelCase )




