




'''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  :				Optional[Any]									=  logging.get_logger(__name__)


def 		__magic_name__    (	__UpperCAmelCase,      __UpperCAmelCase,      __UpperCAmelCase,      __UpperCAmelCase=None,      __UpperCAmelCase=None	)		->					Dict:

					'''simple docstring'''

					if "." in tensor_name:
										snake_case_									=				tensor_name.split('''.'''	)
										for split in splits[:-1]:
															snake_case_									=				getattr(__UpperCAmelCase,      __UpperCAmelCase	)
															if new_module is None:
																				raise ValueError(F"{module} has no attribute {split}."	)
															snake_case_									=				new_module
										snake_case_									=				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}."	)
					snake_case_									=				tensor_name in module._buffers
					snake_case_									=				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}."	)

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

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

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

															snake_case_									=				new_value
															if fpaa_statistics is not None:
																				setattr(module.weight,      '''SCB''',      fpaa_statistics.to(__UpperCAmelCase	)	)

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

										if is_buffer:
															snake_case_									=				new_value
										else:
															snake_case_									=				nn.Parameter(__UpperCAmelCase,      requires_grad=old_value.requires_grad	)
															snake_case_									=				new_value


def 		__magic_name__    (	__UpperCAmelCase,      __UpperCAmelCase=None,      __UpperCAmelCase=None,      __UpperCAmelCase=None,      __UpperCAmelCase=False	)		->					List[str]:

					'''simple docstring'''

					for name, module in model.named_children():
										if current_key_name is None:
															snake_case_									=				[]
										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	):
																														snake_case_			,snake_case_									=				module.weight.shape
																									else:
																														snake_case_									=				module.in_features
																														snake_case_									=				module.out_features

																									if quantization_config.quantization_method() == "llm_int8":
																														snake_case_									=				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,      )
																														snake_case_									=				True
																									else:
																														if (
																														    quantization_config.llm_inta_skip_modules is not None
																														    and name in quantization_config.llm_inta_skip_modules
																														):
																																			pass
																														else:
																																			snake_case_									=				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,      )
																																			snake_case_									=				True
                    # Store the module class in case we need to transpose the weight later
																									snake_case_									=				type(__UpperCAmelCase	)
																									# Force requires grad to False to avoid unexpected errors
																									model._modules[name].requires_grad_(__UpperCAmelCase	)
										if len(list(module.children()	)	) > 0:
															snake_case_			,snake_case_									=				_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 		__magic_name__    (	__UpperCAmelCase,      __UpperCAmelCase=None,      __UpperCAmelCase=None,      __UpperCAmelCase=None	)		->					str:

					'''simple docstring'''

					snake_case_									=				['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert
					snake_case_			,snake_case_									=				_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 		__magic_name__    (	*__UpperCAmelCase,      **__UpperCAmelCase	)		->					Optional[Any]:

					'''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 		__magic_name__    (	*__UpperCAmelCase,      **__UpperCAmelCase	)		->					Dict:

					'''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 		__magic_name__    (	__UpperCAmelCase	)		->					str:

					'''simple docstring'''

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

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

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

					# add last module together with tied weights
					snake_case_									=				set(__UpperCAmelCase	) - set(__UpperCAmelCase	)
					snake_case_									=				list(set(__UpperCAmelCase	)	) + list(__UpperCAmelCase	)

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

					return filtered_module_names








import pytest


__UpperCAmelCase       :   Optional[Any]				       =							"__dummy_dataset1__"

__UpperCAmelCase       :   List[str]				       =							"\nimport json\nimport os\n\nimport datasets\n\n\nREPO_URL = \"https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/\"\nURLS = {\"train\": REPO_URL + \"wikiann-bn-train.jsonl\", \"validation\": REPO_URL + \"wikiann-bn-validation.jsonl\"}\n\n\nclass __DummyDataset1__(datasets.GeneratorBasedBuilder):\n\n    def _info(self):\n        features = datasets.Features(\n            {\n                \"tokens\": datasets.Sequence(datasets.Value(\"string\")),\n                \"ner_tags\": datasets.Sequence(\n                    datasets.features.ClassLabel(\n                        names=[\n                            \"O\",\n                            \"B-PER\",\n                            \"I-PER\",\n                            \"B-ORG\",\n                            \"I-ORG\",\n                            \"B-LOC\",\n                            \"I-LOC\",\n                        ]\n                    )\n                ),\n                \"langs\": datasets.Sequence(datasets.Value(\"string\")),\n                \"spans\": datasets.Sequence(datasets.Value(\"string\")),\n            }\n        )\n        return datasets.DatasetInfo(features=features)\n\n    def _split_generators(self, dl_manager):\n        dl_path = dl_manager.download(URLS)\n        return [\n            datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={\"filepath\": dl_path[\"train\"]}),\n            datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={\"filepath\": dl_path[\"validation\"]}),\n        ]\n\n    def _generate_examples(self, filepath):\n        with open(filepath, \"r\", encoding=\"utf-8\") as f:\n            for i, line in enumerate(f):\n                yield i, json.loads(line)\n"







@pytest.fixture
def 			A__							(    )   ->    Optional[int]:
  return DATASET_LOADING_SCRIPT_NAME







@pytest.fixture
def 			A__							(    )   ->    Tuple:
  return DATASET_LOADING_SCRIPT_CODE







@pytest.fixture
def 			A__							(    SCREAMING_SNAKE_CASE__					,					SCREAMING_SNAKE_CASE__					,					SCREAMING_SNAKE_CASE__)   ->    Tuple:
  __snake_case:						List[Any]   =						dataset_loading_script_name
  __snake_case:						Any   =						tmp_path / """datasets""" / script_name
  script_dir.mkdir(parents=SCREAMING_SNAKE_CASE__)
  __snake_case:						int   =						script_dir / F'''{script_name}.py'''
  with open(SCREAMING_SNAKE_CASE__					,					"""w""") as f:
    f.write(SCREAMING_SNAKE_CASE__)
  return str(SCREAMING_SNAKE_CASE__)






