


'''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						=logging.get_logger(__name__)







def      _UpperCamelCase   (		UpperCamelCase__			,   UpperCamelCase__			,   UpperCamelCase__			,   UpperCamelCase__=None			,   UpperCamelCase__=None       ):
			# Recurse if needed
			if "." in tensor_name:
						UpperCAmelCase__	:       List[str]   =  tensor_name.split("""."""       )
						for split in splits[:-1]:
									UpperCAmelCase__	:       Optional[Any]   =  getattr(UpperCamelCase__			,   UpperCamelCase__       )
									if new_module is None:
												raise ValueError(f'''{module} has no attribute {split}.'''       )
									UpperCAmelCase__	:       Union[str, Any]   =  new_module
						UpperCAmelCase__	:       List[str]   =  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}.'''       )
			UpperCAmelCase__	:       List[Any]   =  tensor_name in module._buffers
			UpperCAmelCase__	:       Optional[Any]   =  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}.'''       )

			UpperCAmelCase__	:       Optional[int]   =  False
			UpperCAmelCase__	:       List[Any]   =  False
			if is_buffer or not is_bitsandbytes_available():
						UpperCAmelCase__	:       Dict   =  False
						UpperCAmelCase__	:       int   =  False
			else:
						UpperCAmelCase__	:       Optional[Any]   =  hasattr(bnb.nn			,   """Params4bit"""       ) and isinstance(module._parameters[tensor_name]			,   bnb.nn.Paramsabit       )
						UpperCAmelCase__	:       str   =  isinstance(module._parameters[tensor_name]			,   bnb.nn.IntaParams       )

			if is_abit or is_abit:
						UpperCAmelCase__	:       Tuple   =  module._parameters[tensor_name]
						if param.device.type != "cuda":
									if value is None:
												UpperCAmelCase__	:       Optional[int]   =  old_value.to(UpperCamelCase__       )
									elif isinstance(UpperCamelCase__			,   torch.Tensor       ):
												UpperCAmelCase__	:       Tuple   =  value.to("""cpu"""       )
												if value.dtype == torch.inta:
															UpperCAmelCase__	:       Any   =  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:
												UpperCAmelCase__	:       List[Any]   =  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:
												UpperCAmelCase__	:       Optional[Any]   =  new_value.T

									UpperCAmelCase__	:       Any   =  old_value.__dict__
									if is_abit:
												UpperCAmelCase__	:       List[Any]   =  bnb.nn.IntaParams(UpperCamelCase__			,   requires_grad=UpperCamelCase__			,   **UpperCamelCase__       ).to(UpperCamelCase__       )
									elif is_abit:
												UpperCAmelCase__	:       Any   =  bnb.nn.Paramsabit(UpperCamelCase__			,   requires_grad=UpperCamelCase__			,   **UpperCamelCase__       ).to(UpperCamelCase__       )

									UpperCAmelCase__	:       Any   =  new_value
									if fpaa_statistics is not None:
												setattr(module.weight			,   """SCB"""			,   fpaa_statistics.to(UpperCamelCase__       )       )

			else:
						if value is None:
									UpperCAmelCase__	:       Optional[Any]   =  old_value.to(UpperCamelCase__       )
						elif isinstance(UpperCamelCase__			,   torch.Tensor       ):
									UpperCAmelCase__	:       int   =  value.to(UpperCamelCase__       )
						else:
									UpperCAmelCase__	:       Dict   =  torch.tensor(UpperCamelCase__			,   device=UpperCamelCase__       )

						if is_buffer:
									UpperCAmelCase__	:       List[Any]   =  new_value
						else:
									UpperCAmelCase__	:       Tuple   =  nn.Parameter(UpperCamelCase__			,   requires_grad=old_value.requires_grad       )
									UpperCAmelCase__	:       Dict   =  new_value







def      _UpperCamelCase   (		UpperCamelCase__			,   UpperCamelCase__=None			,   UpperCamelCase__=None			,   UpperCamelCase__=None			,   UpperCamelCase__=False       ):
			for name, module in model.named_children():
						if current_key_name is None:
									UpperCAmelCase__	:       Tuple   =  []
						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__       ):
																		UpperCAmelCase__	:       str   =  module.weight.shape
															else:
																		UpperCAmelCase__	:       List[Any]   =  module.in_features
																		UpperCAmelCase__	:       Any   =  module.out_features

															if quantization_config.quantization_method() == "llm_int8":
																		UpperCAmelCase__	:       Dict   =  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			,   )
																		UpperCAmelCase__	:       List[str]   =  True
															else:
																		if (
																		    quantization_config.llm_inta_skip_modules is not None
																		    and name in quantization_config.llm_inta_skip_modules
																		):
																					pass
																		else:
																					UpperCAmelCase__	:       List[Any]   =  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			,   )
																					UpperCAmelCase__	:       Optional[int]   =  True
                    # Store the module class in case we need to transpose the weight later
															UpperCAmelCase__	:       Union[str, Any]   =  type(UpperCamelCase__       )
															# Force requires grad to False to avoid unexpected errors
															model._modules[name].requires_grad_(UpperCamelCase__       )
						if len(list(module.children()       )       ) > 0:
									UpperCAmelCase__	:       Tuple   =  _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      _UpperCamelCase   (		UpperCamelCase__			,   UpperCamelCase__=None			,   UpperCamelCase__=None			,   UpperCamelCase__=None       ):
			UpperCAmelCase__	:       Dict   =  ["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert
			UpperCAmelCase__	:       List[str]   =  _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      _UpperCamelCase   (		*UpperCamelCase__			,   **UpperCamelCase__       ):
			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      _UpperCamelCase   (		*UpperCamelCase__			,   **UpperCamelCase__       ):
			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      _UpperCamelCase   (		UpperCamelCase__       ):
			UpperCAmelCase__	:       List[str]   =  deepcopy(UpperCamelCase__       )  # this has 0 cost since it is done inside `init_empty_weights` context manager`
			tied_model.tie_weights()

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

			# Check if it is a base model
			UpperCAmelCase__	:       Tuple   =  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
			UpperCAmelCase__	:       int   =  list(model.named_children()       )
			UpperCAmelCase__	:       str   =  [list_modules[-1][0]]

			# add last module together with tied weights
			UpperCAmelCase__	:       str   =  set(UpperCamelCase__       ) - set(UpperCamelCase__       )
			UpperCAmelCase__	:       List[str]   =  list(set(UpperCamelCase__       )       ) + list(UpperCamelCase__       )

			# remove ".weight" from the keys
			UpperCAmelCase__	:       Optional[int]   =  [""".weight""", """.bias"""]
			UpperCAmelCase__	:       Union[str, Any]   =  []
			for name in list_untouched:
						for name_to_remove in names_to_remove:
									if name_to_remove in name:
												UpperCAmelCase__	:       Dict   =  name.replace(UpperCamelCase__			,   """"""       )
						filtered_module_names.append(UpperCamelCase__       )

			return filtered_module_names





import importlib
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
import transformers.models.auto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.bert.configuration_bert import BertConfig
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils'''))

from test_module.custom_configuration import CustomConfig  # noqa E402


a__		     =     get_tests_dir('''fixtures/dummy-config.json''')


class    SCREAMING_SNAKE_CASE_				(       unittest.TestCase   ):



	"""simple docstring"""


	def 					lowerCamelCase__     (					self		:						str	)	->       Dict:







						"""simple docstring"""







						__UpperCamelCase					:	Optional[Any]             =      0






	def 					lowerCamelCase__     (					self		:						Union[str, Any]	)	->       List[str]:







						"""simple docstring"""







						self.assertIsNotNone(transformers.models.auto.__spec__	)
						self.assertIsNotNone(importlib.util.find_spec("""transformers.models.auto"""	)	)






	def 					lowerCamelCase__     (					self		:						Optional[Any]	)	->       Dict:







						"""simple docstring"""







						__UpperCamelCase					:	int             =      AutoConfig.from_pretrained("""bert-base-uncased"""	)
						self.assertIsInstance(lowerCAmelCase					,     lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						List[Any]	)	->       Optional[Any]:







						"""simple docstring"""







						__UpperCamelCase					:	Dict             =      AutoConfig.from_pretrained(lowerCAmelCase	)
						self.assertIsInstance(lowerCAmelCase					,     lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						Any	)	->       Optional[int]:







						"""simple docstring"""







						__UpperCamelCase					:	Optional[int]             =      AutoConfig.from_pretrained(lowerCAmelCase	)
						self.assertIsInstance(lowerCAmelCase					,     lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						Tuple	)	->       Any:







						"""simple docstring"""







						__UpperCamelCase					:	List[Any]             =      AutoConfig.for_model("""roberta"""	)
						self.assertIsInstance(lowerCAmelCase					,     lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						int	)	->       List[Any]:







						"""simple docstring"""







						with tempfile.TemporaryDirectory() as tmp_dir:
											# This model name contains bert and roberta, but roberta ends up being picked.
											__UpperCamelCase					:	Union[str, Any]             =      os.path.join(lowerCAmelCase					,     """fake-roberta"""	)
											os.makedirs(lowerCAmelCase					,     exist_ok=lowerCAmelCase	)
											with open(os.path.join(lowerCAmelCase					,     """config.json"""	)					,     """w"""	) as f:
																f.write(json.dumps({}	)	)
											__UpperCamelCase					:	Dict             =      AutoConfig.from_pretrained(lowerCAmelCase	)
											self.assertEqual(type(lowerCAmelCase	)					,     lowerCAmelCase	)






	def 					lowerCamelCase__     (					self		:						int	)	->       str:







						"""simple docstring"""







						try:
											AutoConfig.register("""custom"""					,     lowerCAmelCase	)
											# Wrong model type will raise an error
											with self.assertRaises(lowerCAmelCase	):
																AutoConfig.register("""model"""					,     lowerCAmelCase	)
											# Trying to register something existing in the Transformers library will raise an error
											with self.assertRaises(lowerCAmelCase	):
																AutoConfig.register("""bert"""					,     lowerCAmelCase	)

											# Now that the config is registered, it can be used as any other config with the auto-API
											__UpperCamelCase					:	Optional[Any]             =      CustomConfig()
											with tempfile.TemporaryDirectory() as tmp_dir:
																config.save_pretrained(lowerCAmelCase	)
																__UpperCamelCase					:	List[str]             =      AutoConfig.from_pretrained(lowerCAmelCase	)
																self.assertIsInstance(lowerCAmelCase					,     lowerCAmelCase	)

						finally:
											if "custom" in CONFIG_MAPPING._extra_content:
																del CONFIG_MAPPING._extra_content["custom"]






	def 					lowerCamelCase__     (					self		:						int	)	->       Optional[Any]:







						"""simple docstring"""







						with self.assertRaisesRegex(
						    lowerCAmelCase					,     """bert-base is not a local folder and is not a valid model identifier"""	):
											__UpperCamelCase					:	Tuple             =      AutoConfig.from_pretrained("""bert-base"""	)






	def 					lowerCamelCase__     (					self		:						Dict	)	->       Any:







						"""simple docstring"""







						with self.assertRaisesRegex(
						    lowerCAmelCase					,     R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""	):
											__UpperCamelCase					:	Optional[Any]             =      AutoConfig.from_pretrained(lowerCAmelCase					,     revision="""aaaaaa"""	)






	def 					lowerCamelCase__     (					self		:						str	)	->       List[str]:







						"""simple docstring"""







						with self.assertRaisesRegex(
						    lowerCAmelCase					,     """hf-internal-testing/no-config-test-repo does not appear to have a file named config.json."""					,     ):
											__UpperCamelCase					:	Union[str, Any]             =      AutoConfig.from_pretrained("""hf-internal-testing/no-config-test-repo"""	)






	def 					lowerCamelCase__     (					self		:						Optional[int]	)	->       Optional[int]:







						"""simple docstring"""







						with self.assertRaises(lowerCAmelCase	):
											__UpperCamelCase					:	str             =      AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""	)
						# If remote code is disabled, we can't load this config.
						with self.assertRaises(lowerCAmelCase	):
											__UpperCamelCase					:	Tuple             =      AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""					,     trust_remote_code=lowerCAmelCase	)

						__UpperCamelCase					:	List[str]             =      AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""					,     trust_remote_code=lowerCAmelCase	)
						self.assertEqual(config.__class__.__name__					,     """NewModelConfig"""	)

						# Test config can be reloaded.
						with tempfile.TemporaryDirectory() as tmp_dir:
											config.save_pretrained(lowerCAmelCase	)
											__UpperCamelCase					:	str             =      AutoConfig.from_pretrained(lowerCAmelCase					,     trust_remote_code=lowerCAmelCase	)
						self.assertEqual(reloaded_config.__class__.__name__					,     """NewModelConfig"""	)






	def 					lowerCamelCase__     (					self		:						Optional[int]	)	->       str:







						"""simple docstring"""







						class    SCREAMING_SNAKE_CASE_				(       _UpperCamelCase   ):



							"""simple docstring"""


							__magic_name__   :       int      	=		'new-model'

						try:
											AutoConfig.register("""new-model"""					,     lowerCAmelCase	)
											# If remote code is not set, the default is to use local
											__UpperCamelCase					:	Tuple             =      AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""	)
											self.assertEqual(config.__class__.__name__					,     """NewModelConfigLocal"""	)

											# If remote code is disabled, we load the local one.
											__UpperCamelCase					:	Any             =      AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""					,     trust_remote_code=lowerCAmelCase	)
											self.assertEqual(config.__class__.__name__					,     """NewModelConfigLocal"""	)

											# If remote is enabled, we load from the Hub
											__UpperCamelCase					:	List[Any]             =      AutoConfig.from_pretrained("""hf-internal-testing/test_dynamic_model"""					,     trust_remote_code=lowerCAmelCase	)
											self.assertEqual(config.__class__.__name__					,     """NewModelConfig"""	)

						finally:
											if "new-model" in CONFIG_MAPPING._extra_content:
																del CONFIG_MAPPING._extra_content["new-model"]






