

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


A_ :				Union[str, Any]						 =    logging.getLogger(__name__)

def 		UpperCamelCase      (lowercase_:				torch.nn.Module					,   lowercase_:				BnbQuantizationConfig					,   lowercase_:				Union[str, os.PathLike] = None					,   lowercase_:				Optional[Dict[str, Union[int, str, torch.device]]] = None					,   lowercase_:				Optional[List[str]] = None					,   lowercase_:				Optional[Dict[Union[int, str], Union[int, str]]] = None					,   lowercase_:				Optional[Union[str, os.PathLike]] = None					,   lowercase_:				bool = False					,   )  ->   int:
	A__							:					Union[str, Any]       =	bnb_quantization_config.load_in_abit
	A__							:					Optional[int]       =	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."""      )

	A__							:					Any       =	[]
	# custom device map
	if isinstance(lowercase_					,   lowercase_      ) and len(device_map.keys()      ) > 1:
		A__							:					Dict       =	[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:
		A__							:					str       =	get_keys_to_not_convert(lowercase_      )

	# add cpu modules to skip modules only for 4-bit modules
	if load_in_abit:
		bnb_quantization_config.skip_modules.extend(lowercase_      )
	A__							:					Any       =	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:
		A__							:					Optional[int]       =	[]
	A__							:					List[str]       =	bnb_quantization_config.keep_in_fpaa_modules
	modules_to_not_convert.extend(lowercase_      )

	# compatibility with peft
	A__							:					Optional[Any]       =	load_in_abit
	A__							:					Any       =	load_in_abit

	A__							:					Tuple       =	get_parameter_device(lowercase_      )
	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."""      )
		A__							:					List[str]       =	replace_with_bnb_layers(lowercase_					,   lowercase_					,   modules_to_not_convert=lowercase_      )
		# convert param to the right dtype
		A__							:					Dict       =	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:
					A__							:					Optional[Any]       =	name.replace(""".weight"""					,   """"""      ).replace(""".bias"""					,   """"""      )
					A__							:					Union[str, Any]       =	getattr(lowercase_					,   lowercase_					,   lowercase_      )
					if param is not None:
						param.to(torch.floataa      )
			elif torch.is_floating_point(lowercase_      ):
				param.to(lowercase_      )
		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():
			A__							:					str       =	replace_with_bnb_layers(
			    lowercase_					,   lowercase_					,   modules_to_not_convert=lowercase_      )

		A__							:					int       =	get_quantized_model_device_map(
		    lowercase_					,   lowercase_					,   lowercase_					,   max_memory=lowercase_					,   no_split_module_classes=lowercase_					,   )
		if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
			A__							:					Tuple       =	True

		A__							:					Tuple       =	any(x in list(device_map.values()      ) for x in ["""cpu""", """disk"""]      )

		load_checkpoint_in_model(
		    lowercase_					,   lowercase_					,   lowercase_					,   dtype=bnb_quantization_config.torch_dtype					,   offload_folder=lowercase_					,   offload_state_dict=lowercase_					,   keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules					,   offload_abit_bnb=load_in_abit and offload					,   )
		return dispatch_model(lowercase_					,   device_map=lowercase_					,   offload_dir=lowercase_      )

def 		UpperCamelCase      (lowercase_:				Optional[int]					,   lowercase_:				Any					,   lowercase_:				List[Any]=None					,   lowercase_:				int=None					,   lowercase_:				List[str]=None      )  ->   Union[str, Any]:
	if device_map is None:
		if torch.cuda.is_available():
			A__							:					Union[str, Any]       =	{"""""": 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(lowercase_					,   lowercase_      ):
		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'."""      )

		A__							:					List[Any]       =	{}
		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      )
		    }      )

		A__							:					str       =	{}
		A__							:					Tuple       =	special_dtypes
		A__							:					List[Any]       =	no_split_module_classes
		A__							:					List[Any]       =	bnb_quantization_config.target_dtype

		# get max_memory for each device.
		if device_map != "sequential":
			A__							:					str       =	get_balanced_memory(
			    lowercase_					,   low_zero=(device_map == """balanced_low_0""")					,   max_memory=lowercase_					,   **lowercase_					,   )

		A__							:					List[Any]       =	max_memory
		A__							:					Union[str, Any]       =	infer_auto_device_map(lowercase_					,   **lowercase_      )

	if isinstance(lowercase_					,   lowercase_      ):
		# check if don't have any quantized module on the cpu
		A__							:					List[str]       =	bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules

		A__							:					Union[str, Any]       =	{
		    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 		UpperCamelCase      (lowercase_:				Tuple					,   lowercase_:				Optional[int]					,   lowercase_:				List[str]=None					,   lowercase_:				Any=None      )  ->   Optional[int]:

	if modules_to_not_convert is None:
		A__							:					str       =	[]

	A__     ,     A__							:					Tuple       =	_replace_with_bnb_layers(
	    lowercase_					,   lowercase_					,   lowercase_					,   lowercase_      )
	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 		UpperCamelCase      (lowercase_:				Tuple					,   lowercase_:				Optional[Any]					,   lowercase_:				List[Any]=None					,   lowercase_:				Tuple=None					,   )  ->   Dict:
	A__							:					List[str]       =	False
	for name, module in model.named_children():
		if current_key_name is None:
			A__							:					Optional[int]       =	[]
		current_key_name.append(lowercase_      )
		if isinstance(lowercase_					,   nn.Linear      ) and name not in modules_to_not_convert:
			# Check if the current key is not in the `modules_to_not_convert`
			A__							:					List[Any]       =	""".""".join(lowercase_      )
			A__							:					Optional[int]       =	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:
					A__							:					int       =	False
					break
			if proceed:
				# Load bnb module with empty weight and replace ``nn.Linear` module
				if bnb_quantization_config.load_in_abit:
					A__							:					List[str]       =	bnb.nn.LinearabitLt(
					    module.in_features					,   module.out_features					,   module.bias is not None					,   has_fpaa_weights=lowercase_					,   threshold=bnb_quantization_config.llm_inta_threshold					,   )
				elif bnb_quantization_config.load_in_abit:
					A__							:					Optional[Any]       =	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"""      )
				A__							:					Dict       =	module.weight.data
				if module.bias is not None:
					A__							:					Union[str, Any]       =	module.bias.data
				bnb_module.requires_grad_(lowercase_      )
				setattr(lowercase_					,   lowercase_					,   lowercase_      )
				A__							:					Any       =	True
		if len(list(module.children()      )      ) > 0:
			A__     ,     A__							:					List[str]       =	_replace_with_bnb_layers(
			    lowercase_					,   lowercase_					,   lowercase_					,   lowercase_      )
			A__							:					int       =	has_been_replaced | _has_been_replaced
		# Remove the last key for recursion
		current_key_name.pop(-1      )
	return model, has_been_replaced

def 		UpperCamelCase      (lowercase_:				Dict      )  ->   Tuple:
	# Create a copy of the model
	with init_empty_weights():
		A__							:					List[Any]       =	deepcopy(lowercase_      )  # this has 0 cost since it is done inside `init_empty_weights` context manager`

	A__							:					Any       =	find_tied_parameters(lowercase_      )
	# For compatibility with Accelerate < 0.18
	if isinstance(lowercase_					,   lowercase_      ):
		A__							:					Union[str, Any]       =	sum(list(tied_params.values()      )					,   []      ) + list(tied_params.keys()      )
	else:
		A__							:					Optional[Any]       =	sum(lowercase_					,   []      )
	A__							:					str       =	len(lowercase_      ) > 0

	# Check if it is a base model
	A__							:					List[str]       =	False
	if hasattr(lowercase_					,   """base_model_prefix"""      ):
		A__							:					List[Any]       =	not hasattr(lowercase_					,   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
	A__							:					Optional[Any]       =	list(model.named_children()      )
	A__							:					Any       =	[list_modules[-1][0]]

	# add last module together with tied weights
	A__							:					List[Any]       =	set(lowercase_      ) - set(lowercase_      )
	A__							:					Optional[Any]       =	list(set(lowercase_      )      ) + list(lowercase_      )

	# remove ".weight" from the keys
	A__							:					List[Any]       =	[""".weight""", """.bias"""]
	A__							:					int       =	[]
	for name in list_untouched:
		for name_to_remove in names_to_remove:
			if name_to_remove in name:
				A__							:					List[Any]       =	name.replace(lowercase_					,   """"""      )
		filtered_module_names.append(lowercase_      )

	return filtered_module_names

def 		UpperCamelCase      (lowercase_:				str      )  ->   List[Any]:
	for m in model.modules():
		if isinstance(lowercase_					,   bnb.nn.Linearabit      ):
			return True
	return False

def 		UpperCamelCase      (lowercase_:				nn.Module      )  ->   Optional[int]:
	return next(parameter.parameters()      ).device


def 		UpperCamelCase      (lowercase_:				Dict					,   lowercase_:				str					,   lowercase_:				str					,   lowercase_:				List[Any]					,   lowercase_:				Tuple					,   lowercase_:				Tuple					,   lowercase_:				List[Any]      )  ->   int:
	# if it is not quantized, we quantize and offload the quantized weights and the SCB stats
	if fpaa_statistics is None:
		set_module_tensor_to_device(lowercase_					,   lowercase_					,   0					,   dtype=lowercase_					,   value=lowercase_      )
		A__							:					Optional[Any]       =	param_name
		A__							:					Optional[int]       =	model
		if "." in tensor_name:
			A__							:					Union[str, Any]       =	tensor_name.split("""."""      )
			for split in splits[:-1]:
				A__							:					List[Any]       =	getattr(lowercase_					,   lowercase_      )
				if new_module is None:
					raise ValueError(f"""{module} has no attribute {split}."""      )
				A__							:					Any       =	new_module
			A__							:					List[Any]       =	splits[-1]
		# offload weights
		A__							:					List[Any]       =	False
		offload_weight(module._parameters[tensor_name]					,   lowercase_					,   lowercase_					,   index=lowercase_      )
		if hasattr(module._parameters[tensor_name]					,   """SCB"""      ):
			offload_weight(
			    module._parameters[tensor_name].SCB					,   param_name.replace("""weight"""					,   """SCB"""      )					,   lowercase_					,   index=lowercase_					,   )
	else:
		offload_weight(lowercase_					,   lowercase_					,   lowercase_					,   index=lowercase_      )
		offload_weight(lowercase_					,   param_name.replace("""weight"""					,   """SCB"""      )					,   lowercase_					,   index=lowercase_      )

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






import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional

import pyarrow as pa
import pyarrow.json as paj

import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline


A_ :				Tuple						 =    datasets.utils.logging.get_logger(__name__)



@dataclass
class 					_a		(datasets.BuilderConfig       ):


					'''simple docstring'''






					UpperCAmelCase__:     Optional[datasets.Features]													= None
					UpperCAmelCase__:     str													= "utf-8"
					UpperCAmelCase__:     Optional[str]													= None
					UpperCAmelCase__:     Optional[str]													= None
					UpperCAmelCase__:     bool													= True  # deprecated
					UpperCAmelCase__:     Optional[int]													= None  # deprecated
					UpperCAmelCase__:     int													= 10 << 20  # 10MB
					UpperCAmelCase__:     Optional[bool]													= None



class 					_a		(datasets.ArrowBasedBuilder       ):


					'''simple docstring'''






					UpperCAmelCase__:     List[str]													= JsonConfig






					def 						__A    (				self    ):
						if self.config.block_size is not None:
							logger.warning("""The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead"""    )
							A__							:					Union[str, Any]       =	self.config.block_size
						if self.config.use_threads is not True:
							logger.warning(
							    """The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore."""    )
						if self.config.newlines_in_values is not None:
							raise ValueError("""The JSON loader parameter `newlines_in_values` is no longer supported"""    )
						return datasets.DatasetInfo(features=self.config.features    )






					def 						__A    (				self					, A__    ):
						if not self.config.data_files:
							raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}"""    )
						A__							:					int       =	dl_manager.download_and_extract(self.config.data_files    )
						if isinstance(A__					, (str, list, tuple)    ):
							A__							:					Optional[Any]       =	data_files
							if isinstance(A__					, A__    ):
								A__							:					List[str]       =	[files]
							A__							:					int       =	[dl_manager.iter_files(A__    ) for file in files]
							return [datasets.SplitGenerator(name=datasets.Split.TRAIN					, gen_kwargs={"""files""": files}    )]
						A__							:					List[str]       =	[]
						for split_name, files in data_files.items():
							if isinstance(A__					, A__    ):
								A__							:					Optional[int]       =	[files]
							A__							:					Optional[int]       =	[dl_manager.iter_files(A__    ) for file in files]
							splits.append(datasets.SplitGenerator(name=A__					, gen_kwargs={"""files""": files}    )    )
						return splits






					def 						__A    (				self					, A__    ):
						if self.config.features is not None:
							# adding missing columns
							for column_name in set(self.config.features    ) - set(pa_table.column_names    ):
								A__							:					Optional[Any]       =	self.config.features.arrow_schema.field(A__    ).type
								A__							:					str       =	pa_table.append_column(A__					, pa.array([None] * len(A__    )					, type=A__    )    )
							# more expensive cast to support nested structures with keys in a different order
							# allows str <-> int/float or str to Audio for example
							A__							:					Optional[int]       =	table_cast(A__					, self.config.features.arrow_schema    )
						return pa_table






					def 						__A    (				self					, A__    ):
						for file_idx, file in enumerate(itertools.chain.from_iterable(A__    )    ):
							# If the file is one json object and if we need to look at the list of items in one specific field
							if self.config.field is not None:
								with open(A__					, encoding=self.config.encoding					, errors=self.config.encoding_errors    ) as f:
									A__							:					Optional[Any]       =	json.load(A__    )

								# We keep only the field we are interested in
								A__							:					Optional[int]       =	dataset[self.config.field]

								# We accept two format: a list of dicts or a dict of lists
								if isinstance(A__					, (list, tuple)    ):
									A__							:					Union[str, Any]       =	set().union(*[row.keys() for row in dataset]    )
									A__							:					Any       =	{col: [row.get(A__    ) for row in dataset] for col in keys}
								else:
									A__							:					Any       =	dataset
								A__							:					Any       =	pa.Table.from_pydict(A__    )
								yield file_idx, self._cast_table(A__    )

							# If the file has one json object per line
							else:
								with open(A__					, """rb"""    ) as f:
									A__							:					List[str]       =	0
									# Use block_size equal to the chunk size divided by 32 to leverage multithreading
									# Set a default minimum value of 16kB if the chunk size is really small
									A__							:					List[str]       =	max(self.config.chunksize // 32					, 16 << 10    )
									A__							:					Any       =	(
									    self.config.encoding_errors if self.config.encoding_errors is not None else """strict"""
									)
									while True:
										A__							:					Dict       =	f.read(self.config.chunksize    )
										if not batch:
											break
										# Finish current line
										try:
											batch += f.readline()
										except (AttributeError, io.UnsupportedOperation):
											batch += readline(A__    )
										# PyArrow only accepts utf-8 encoded bytes
										if self.config.encoding != "utf-8":
											A__							:					List[Any]       =	batch.decode(self.config.encoding					, errors=A__    ).encode("""utf-8"""    )
										try:
											while True:
												try:
													A__							:					str       =	paj.read_json(
													    io.BytesIO(A__    )					, read_options=paj.ReadOptions(block_size=A__    )    )
													break
												except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
													if (
													    isinstance(A__					, pa.ArrowInvalid    )
													    and "straddling" not in str(A__    )
													    or block_size > len(A__    )
													):
														raise
													else:
														# Increase the block size in case it was too small.
														# The block size will be reset for the next file.
														logger.debug(
														    F"""Batch of {len(A__    )} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}."""    )
														block_size *= 2
										except pa.ArrowInvalid as e:
											try:
												with open(
												    A__					, encoding=self.config.encoding					, errors=self.config.encoding_errors    ) as f:
													A__							:					Optional[Any]       =	json.load(A__    )
											except json.JSONDecodeError:
												logger.error(F"""Failed to read file '{file}' with error {type(A__    )}: {e}"""    )
												raise e
											# If possible, parse the file as a list of json objects and exit the loop
											if isinstance(A__					, A__    ):  # list is the only sequence type supported in JSON
												try:
													A__							:					str       =	set().union(*[row.keys() for row in dataset]    )
													A__							:					List[str]       =	{col: [row.get(A__    ) for row in dataset] for col in keys}
													A__							:					int       =	pa.Table.from_pydict(A__    )
												except (pa.ArrowInvalid, AttributeError) as e:
													logger.error(F"""Failed to read file '{file}' with error {type(A__    )}: {e}"""    )
													raise ValueError(F"""Not able to read records in the JSON file at {file}."""    ) from None
												yield file_idx, self._cast_table(A__    )
												break
											else:
												logger.error(F"""Failed to read file '{file}' with error {type(A__    )}: {e}"""    )
												raise ValueError(
												    F"""Not able to read records in the JSON file at {file}. """
												    F"""You should probably indicate the field of the JSON file containing your records. """
												    F"""This JSON file contain the following fields: {str(list(dataset.keys()    )    )}. """
												    F"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """    ) from None
                        # Uncomment for debugging (will print the Arrow table size and elements)
                        # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                        # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
										yield (file_idx, batch_idx), self._cast_table(A__    )
										batch_idx += 1



