

'''simple docstring'''


import os
from pickle import UnpicklingError
from typing import Dict, Tuple

import jax
import jax.numpy as jnp
import numpy as np
from flax.serialization import from_bytes
from flax.traverse_util import flatten_dict, unflatten_dict

import transformers

from .utils import logging


lowerCAmelCase__										= logging.get_logger(__name__)







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase=False  )    ->    List[str]:
	try:
		import torch  # noqa: F401
	except ImportError:
		logger.error(
		    'Loading a PyTorch model in Flax, requires both PyTorch and Flax to be installed. Please see'
		    ' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation'
		    ' instructions.'  )
		raise

	if not is_sharded:
		UpperCAmelCase_		:      List[Any]       	=					os.path.abspath(UpperCamelCase  )
		logger.info(f"""Loading PyTorch weights from {pt_path}"""  )

		UpperCAmelCase_		:      List[str]       	=					torch.load(UpperCamelCase   ,map_location='cpu'  )
		logger.info(f"""PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values()  ):,} parameters."""  )

		UpperCAmelCase_		:      Any       	=					convert_pytorch_state_dict_to_flax(UpperCamelCase   ,UpperCamelCase  )
	else:
		# model is sharded and pytorch_checkpoint_path already contains the list of .pt shard files
		UpperCAmelCase_		:      str       	=					convert_pytorch_sharded_state_dict_to_flax(UpperCamelCase   ,UpperCamelCase  )
	return flax_state_dict







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase   ,)    ->    (Tuple[str], np.ndarray):

	def is_key_or_prefix_key_in_dict(UpperCamelCase  ) -> bool:
		return len(set(UpperCamelCase  ) & {key, (model_prefix,) + key}  ) > 0

	# layer norm
	UpperCAmelCase_		:      Tuple       	=					pt_tuple_key[:-1] + ('scale',)
	if pt_tuple_key[-1] in ["weight", "gamma"] and is_key_or_prefix_key_in_dict(UpperCamelCase  ):
		return renamed_pt_tuple_key, pt_tensor

	# batch norm layer mean
	UpperCAmelCase_		:      Dict       	=					pt_tuple_key[:-1] + ('mean',)
	if pt_tuple_key[-1] == "running_mean" and not is_key_or_prefix_key_in_dict(UpperCamelCase  ):
		return renamed_pt_tuple_key, pt_tensor

	# batch norm layer var
	UpperCAmelCase_		:      Union[str, Any]       	=					pt_tuple_key[:-1] + ('var',)
	if pt_tuple_key[-1] == "running_var" and not is_key_or_prefix_key_in_dict(UpperCamelCase  ):
		return renamed_pt_tuple_key, pt_tensor

	# embedding
	UpperCAmelCase_		:      List[str]       	=					pt_tuple_key[:-1] + ('embedding',)
	if pt_tuple_key[-1] == "weight" and is_key_or_prefix_key_in_dict(UpperCamelCase  ):
		return renamed_pt_tuple_key, pt_tensor

	# conv layer
	UpperCAmelCase_		:      Union[str, Any]       	=					pt_tuple_key[:-1] + ('kernel',)
	if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4 and not is_key_or_prefix_key_in_dict(UpperCamelCase  ):
		UpperCAmelCase_		:      List[str]       	=					pt_tensor.transpose(2   ,3   ,1   ,0  )
		return renamed_pt_tuple_key, pt_tensor

	# linear layer
	UpperCAmelCase_		:      Optional[int]       	=					pt_tuple_key[:-1] + ('kernel',)
	if pt_tuple_key[-1] == "weight" and not is_key_or_prefix_key_in_dict(UpperCamelCase  ):
		UpperCAmelCase_		:      int       	=					pt_tensor.T
		return renamed_pt_tuple_key, pt_tensor

	# old PyTorch layer norm weight
	UpperCAmelCase_		:      List[str]       	=					pt_tuple_key[:-1] + ('weight',)
	if pt_tuple_key[-1] == "gamma":
		return renamed_pt_tuple_key, pt_tensor

	# old PyTorch layer norm bias
	UpperCAmelCase_		:      int       	=					pt_tuple_key[:-1] + ('bias',)
	if pt_tuple_key[-1] == "beta":
		return renamed_pt_tuple_key, pt_tensor

	# New `weight_norm` from https://github.com/huggingface/transformers/pull/24030
	UpperCAmelCase_		:      List[Any]       	=					None
	if pt_tuple_key[-3::2] == ("parametrizations", "original0"):
		UpperCAmelCase_		:      Optional[Any]       	=					pt_tuple_key[-2] + '_g'
	elif pt_tuple_key[-3::2] == ("parametrizations", "original1"):
		UpperCAmelCase_		:      str       	=					pt_tuple_key[-2] + '_v'
	if name is not None:
		UpperCAmelCase_		:      Optional[Any]       	=					pt_tuple_key[:-3] + (name,)
		return renamed_pt_tuple_key, pt_tensor

	return pt_tuple_key, pt_tensor







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase   ,UpperCamelCase  )    ->    List[Any]:
	# convert pytorch tensor to numpy
	UpperCAmelCase_		:      str       	=					{k: v.numpy() for k, v in pt_state_dict.items()}

	UpperCAmelCase_		:      Tuple       	=					flax_model.base_model_prefix

	# use params dict if the model contains batch norm layers
	if "params" in flax_model.params:
		UpperCAmelCase_		:      str       	=					flax_model.params['params']
	else:
		UpperCAmelCase_		:      Union[str, Any]       	=					flax_model.params
	UpperCAmelCase_		:      int       	=					flatten_dict(UpperCamelCase  )

	# add batch_stats keys,values to dict
	if "batch_stats" in flax_model.params:
		UpperCAmelCase_		:      Tuple       	=					flatten_dict(flax_model.params['batch_stats']  )
		random_flax_state_dict.update(UpperCamelCase  )

	UpperCAmelCase_		:      Union[str, Any]       	=					{}

	UpperCAmelCase_		:      Dict       	=					(model_prefix not in flax_model_params) and (
	    model_prefix in {k.split('.'  )[0] for k in pt_state_dict.keys()}
	)
	UpperCAmelCase_		:      Any       	=					(model_prefix in flax_model_params) and (
	    model_prefix not in {k.split('.'  )[0] for k in pt_state_dict.keys()}
	)

	# Need to change some parameters name to match Flax names
	for pt_key, pt_tensor in pt_state_dict.items():
		UpperCAmelCase_		:      List[str]       	=					tuple(pt_key.split('.'  )  )

		# remove base model prefix if necessary
		UpperCAmelCase_		:      Optional[int]       	=					pt_tuple_key[0] == model_prefix
		if load_model_with_head_into_base_model and has_base_model_prefix:
			UpperCAmelCase_		:      Any       	=					pt_tuple_key[1:]

		# Correctly rename weight parameters
		UpperCAmelCase_		:      Union[str, Any]       	=					rename_key_and_reshape_tensor(
		    UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase  )

		# add model prefix if necessary
		UpperCAmelCase_		:      int       	=					(model_prefix,) + flax_key in random_flax_state_dict
		if load_base_model_into_model_with_head and require_base_model_prefix:
			UpperCAmelCase_		:      Optional[Any]       	=					(model_prefix,) + flax_key

		if flax_key in random_flax_state_dict:
			if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
				raise ValueError(
				    f"""PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape """
				    f"""{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}."""  )

        # add batch stats if the model contains batchnorm layers
		if "batch_stats" in flax_model.params:
			if "mean" in flax_key[-1] or "var" in flax_key[-1]:
				UpperCAmelCase_		:      Any       	=					jnp.asarray(UpperCamelCase  )
				continue
			# remove num_batches_tracked key
			if "num_batches_tracked" in flax_key[-1]:
				flax_state_dict.pop(UpperCamelCase   ,UpperCamelCase  )
				continue

			# also add unexpected weight so that warning is thrown
			UpperCAmelCase_		:      str       	=					jnp.asarray(UpperCamelCase  )

		else:
			# also add unexpected weight so that warning is thrown
			UpperCAmelCase_		:      List[Any]       	=					jnp.asarray(UpperCamelCase  )

	return unflatten_dict(UpperCamelCase  )







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase   ,UpperCamelCase  )    ->    Union[str, Any]:
	import torch

	# Load the index
	UpperCAmelCase_		:      Union[str, Any]       	=					{}
	for shard_file in shard_filenames:
		# load using msgpack utils
		UpperCAmelCase_		:      Union[str, Any]       	=					torch.load(UpperCamelCase  )
		UpperCAmelCase_		:      List[str]       	=					{k: v.numpy() for k, v in pt_state_dict.items()}

		UpperCAmelCase_		:      List[Any]       	=					flax_model.base_model_prefix

		# use params dict if the model contains batch norm layers and then add batch_stats keys,values to dict
		if "batch_stats" in flax_model.params:
			UpperCAmelCase_		:      Any       	=					flax_model.params['params']

			UpperCAmelCase_		:      List[str]       	=					flatten_dict(UpperCamelCase  )
			random_flax_state_dict.update(flatten_dict(flax_model.params['batch_stats']  )  )
		else:
			UpperCAmelCase_		:      Optional[Any]       	=					flax_model.params
			UpperCAmelCase_		:      Dict       	=					flatten_dict(UpperCamelCase  )

		UpperCAmelCase_		:      Any       	=					(model_prefix not in flax_model_params) and (
		    model_prefix in {k.split('.'  )[0] for k in pt_state_dict.keys()}
		)
		UpperCAmelCase_		:      Optional[Any]       	=					(model_prefix in flax_model_params) and (
		    model_prefix not in {k.split('.'  )[0] for k in pt_state_dict.keys()}
		)
		# Need to change some parameters name to match Flax names
		for pt_key, pt_tensor in pt_state_dict.items():
			UpperCAmelCase_		:      Optional[Any]       	=					tuple(pt_key.split('.'  )  )

			# remove base model prefix if necessary
			UpperCAmelCase_		:      Union[str, Any]       	=					pt_tuple_key[0] == model_prefix
			if load_model_with_head_into_base_model and has_base_model_prefix:
				UpperCAmelCase_		:      List[str]       	=					pt_tuple_key[1:]

			# Correctly rename weight parameters
			UpperCAmelCase_		:      Dict       	=					rename_key_and_reshape_tensor(
			    UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase  )
			# add model prefix if necessary
			UpperCAmelCase_		:      str       	=					(model_prefix,) + flax_key in random_flax_state_dict
			if load_base_model_into_model_with_head and require_base_model_prefix:
				UpperCAmelCase_		:      Optional[int]       	=					(model_prefix,) + flax_key

			if flax_key in random_flax_state_dict:
				if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
					raise ValueError(
					    f"""PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape """
					    f"""{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}."""  )

            # add batch stats if the model contains batchnorm layers
			if "batch_stats" in flax_model.params:
				if "mean" in flax_key[-1]:
					UpperCAmelCase_		:      str       	=					jnp.asarray(UpperCamelCase  )
					continue
				if "var" in flax_key[-1]:
					UpperCAmelCase_		:      Dict       	=					jnp.asarray(UpperCamelCase  )
					continue
				# remove num_batches_tracked key
				if "num_batches_tracked" in flax_key[-1]:
					flax_state_dict.pop(UpperCamelCase   ,UpperCamelCase  )
					continue

				# also add unexpected weight so that warning is thrown
				UpperCAmelCase_		:      Dict       	=					jnp.asarray(UpperCamelCase  )

			else:
				# also add unexpected weight so that warning is thrown
				UpperCAmelCase_		:      List[Any]       	=					jnp.asarray(UpperCamelCase  )
	return unflatten_dict(UpperCamelCase  )







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase   ,UpperCamelCase  )    ->    Optional[int]:
	UpperCAmelCase_		:      int       	=					os.path.abspath(UpperCamelCase  )
	logger.info(f"""Loading Flax weights from {flax_checkpoint_path}"""  )

	# import correct flax class
	UpperCAmelCase_		:      Union[str, Any]       	=					getattr(UpperCamelCase   ,'Flax' + model.__class__.__name__  )

	# load flax weight dict
	with open(UpperCamelCase   ,'rb'  ) as state_f:
		try:
			UpperCAmelCase_		:      int       	=					from_bytes(UpperCamelCase   ,state_f.read()  )
		except UnpicklingError:
			raise EnvironmentError(f"""Unable to convert {flax_checkpoint_path} to Flax deserializable object. """  )

	return load_flax_weights_in_pytorch_model(UpperCamelCase   ,UpperCamelCase  )







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase   ,UpperCamelCase  )    ->    Any:

	try:
		import torch  # noqa: F401
	except ImportError:
		logger.error(
		    'Loading a Flax weights in PyTorch, requires both PyTorch and Flax to be installed. Please see'
		    ' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation'
		    ' instructions.'  )
		raise

	# check if we have bf16 weights
	UpperCAmelCase_		:      List[str]       	=					flatten_dict(jax.tree_util.tree_map(lambda UpperCamelCase  : x.dtype == jnp.bfloataa   ,UpperCamelCase  )  ).values()
	if any(UpperCamelCase  ):
		# convert all weights to fp32 if the are bf16 since torch.from_numpy can-not handle bf16
		# and bf16 is not fully supported in PT yet.
		logger.warning(
		    'Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` '
		    'before loading those in PyTorch model.'  )
		UpperCAmelCase_		:      Tuple       	=					jax.tree_util.tree_map(
		    lambda UpperCamelCase  : params.astype(np.floataa  ) if params.dtype == jnp.bfloataa else params   ,UpperCamelCase  )

	UpperCAmelCase_		:      Dict       	=					flatten_dict(UpperCamelCase  )
	UpperCAmelCase_		:      Union[str, Any]       	=					pt_model.state_dict()

	UpperCAmelCase_		:      int       	=					(pt_model.base_model_prefix in flax_state) and (
	    pt_model.base_model_prefix not in {k.split('.'  )[0] for k in pt_model_dict.keys()}
	)
	UpperCAmelCase_		:      Optional[Any]       	=					(pt_model.base_model_prefix not in flax_state) and (
	    pt_model.base_model_prefix in {k.split('.'  )[0] for k in pt_model_dict.keys()}
	)

	# keep track of unexpected & missing keys
	UpperCAmelCase_		:      List[str]       	=					[]
	UpperCAmelCase_		:      Optional[int]       	=					set(pt_model_dict.keys()  )

	for flax_key_tuple, flax_tensor in flax_state_dict.items():
		UpperCAmelCase_		:      Dict       	=					flax_key_tuple[0] == pt_model.base_model_prefix
		UpperCAmelCase_		:      Union[str, Any]       	=					'.'.join((pt_model.base_model_prefix,) + flax_key_tuple  ) in pt_model_dict

		# adapt flax_key to prepare for loading from/to base model only
		if load_model_with_head_into_base_model and has_base_model_prefix:
			UpperCAmelCase_		:      Union[str, Any]       	=					flax_key_tuple[1:]
		elif load_base_model_into_model_with_head and require_base_model_prefix:
			UpperCAmelCase_		:      Union[str, Any]       	=					(pt_model.base_model_prefix,) + flax_key_tuple

		# rename flax weights to PyTorch format
		if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 4 and ".".join(UpperCamelCase  ) not in pt_model_dict:
			# conv layer
			UpperCAmelCase_		:      int       	=					flax_key_tuple[:-1] + ('weight',)
			UpperCAmelCase_		:      Optional[int]       	=					jnp.transpose(UpperCamelCase   ,(3, 2, 0, 1)  )
		elif flax_key_tuple[-1] == "kernel" and ".".join(UpperCamelCase  ) not in pt_model_dict:
			# linear layer
			UpperCAmelCase_		:      List[str]       	=					flax_key_tuple[:-1] + ('weight',)
			UpperCAmelCase_		:      Dict       	=					flax_tensor.T
		elif flax_key_tuple[-1] in ["scale", "embedding"]:
			UpperCAmelCase_		:      int       	=					flax_key_tuple[:-1] + ('weight',)

		# adding batch stats from flax batch norm to pt
		elif "mean" in flax_key_tuple[-1]:
			UpperCAmelCase_		:      int       	=					flax_key_tuple[:-1] + ('running_mean',)
		elif "var" in flax_key_tuple[-1]:
			UpperCAmelCase_		:      Optional[Any]       	=					flax_key_tuple[:-1] + ('running_var',)

		if "batch_stats" in flax_state:
			UpperCAmelCase_		:      str       	=					'.'.join(flax_key_tuple[1:]  )  # Remove the params/batch_stats header
		else:
			UpperCAmelCase_		:      Optional[Any]       	=					'.'.join(UpperCamelCase  )

		# We also need to look at `pt_model_dict` and see if there are keys requiring further transformation.
		UpperCAmelCase_		:      Tuple       	=					{}
		# New `weight_norm` from https://github.com/huggingface/transformers/pull/24030
		for key in pt_model_dict:
			UpperCAmelCase_		:      List[Any]       	=					key.split('.'  )
			UpperCAmelCase_		:      Optional[int]       	=					None
			if key_components[-3::2] == ["parametrizations", "original0"]:
				UpperCAmelCase_		:      List[str]       	=					key_components[-2] + '_g'
			elif key_components[-3::2] == ["parametrizations", "original1"]:
				UpperCAmelCase_		:      Union[str, Any]       	=					key_components[-2] + '_v'
			if name is not None:
				UpperCAmelCase_		:      Optional[Any]       	=					key_components[:-3] + [name]
				UpperCAmelCase_		:      str       	=					'.'.join(UpperCamelCase  )
				UpperCAmelCase_		:      Optional[int]       	=					key

		if flax_key in special_pt_names:
			UpperCAmelCase_		:      List[Any]       	=					special_pt_names[flax_key]

		if flax_key in pt_model_dict:
			if flax_tensor.shape != pt_model_dict[flax_key].shape:
				raise ValueError(
				    f"""Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected """
				    f"""to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}."""  )
			else:
				# add weight to pytorch dict
				UpperCAmelCase_		:      Dict       	=					np.asarray(UpperCamelCase  ) if not isinstance(UpperCamelCase   ,np.ndarray  ) else flax_tensor
				UpperCAmelCase_		:      Any       	=					torch.from_numpy(UpperCamelCase  )
				# remove from missing keys
				missing_keys.remove(UpperCamelCase  )
		else:
			# weight is not expected by PyTorch model
			unexpected_keys.append(UpperCamelCase  )

	pt_model.load_state_dict(UpperCamelCase  )

	# re-transform missing_keys to list
	UpperCAmelCase_		:      Tuple       	=					list(UpperCamelCase  )

	if len(UpperCamelCase  ) > 0:
		logger.warning(
		    'Some weights of the Flax model were not used when initializing the PyTorch model'
		    f""" {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing"""
		    f""" {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture"""
		    ' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This'
		    f""" IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect"""
		    ' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a'
		    ' FlaxBertForSequenceClassification model).'  )
	else:
		logger.warning(f"""All Flax model weights were used when initializing {pt_model.__class__.__name__}.\n"""  )
	if len(UpperCamelCase  ) > 0:
		logger.warning(
		    f"""Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly"""
		    f""" initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to"""
		    ' use it for predictions and inference.'  )
	else:
		logger.warning(
		    f"""All the weights of {pt_model.__class__.__name__} were initialized from the Flax model.\n"""
		    'If your task is similar to the task the model of the checkpoint was trained on, '
		    f"""you can already use {pt_model.__class__.__name__} for predictions without further training."""  )

	return pt_model









'''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

lowerCAmelCase__										= logging.get_logger(__name__)







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase   ,UpperCamelCase=None   ,UpperCamelCase=None  )    ->    Any:
	# Recurse if needed
	if "." in tensor_name:
		UpperCAmelCase_		:      Tuple       	=					tensor_name.split('.'  )
		for split in splits[:-1]:
			UpperCAmelCase_		:      Optional[int]       	=					getattr(UpperCamelCase   ,UpperCamelCase  )
			if new_module is None:
				raise ValueError(f"""{module} has no attribute {split}."""  )
			UpperCAmelCase_		:      Union[str, Any]       	=					new_module
		UpperCAmelCase_		:      int       	=					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_		:      Tuple       	=					tensor_name in module._buffers
	UpperCAmelCase_		:      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_		:      Any       	=					False
	UpperCAmelCase_		:      Any       	=					False
	if is_buffer or not is_bitsandbytes_available():
		UpperCAmelCase_		:      Dict       	=					False
		UpperCAmelCase_		:      Tuple       	=					False
	else:
		UpperCAmelCase_		:      List[str]       	=					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_		:      Union[str, Any]       	=					module._parameters[tensor_name]
		if param.device.type != "cuda":
			if value is None:
				UpperCAmelCase_		:      List[str]       	=					old_value.to(UpperCamelCase  )
			elif isinstance(UpperCamelCase   ,torch.Tensor  ):
				UpperCAmelCase_		:      Any       	=					value.to('cpu'  )
				if value.dtype == torch.inta:
					UpperCAmelCase_		:      Dict       	=					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_		:      Dict       	=					new_value.T

			UpperCAmelCase_		:      Tuple       	=					old_value.__dict__
			if is_abit:
				UpperCAmelCase_		:      Any       	=					bnb.nn.IntaParams(UpperCamelCase   ,requires_grad=UpperCamelCase   ,**UpperCamelCase  ).to(UpperCamelCase  )
			elif is_abit:
				UpperCAmelCase_		:      Optional[Any]       	=					bnb.nn.Paramsabit(UpperCamelCase   ,requires_grad=UpperCamelCase   ,**UpperCamelCase  ).to(UpperCamelCase  )

			UpperCAmelCase_		:      Optional[Any]       	=					new_value
			if fpaa_statistics is not None:
				setattr(module.weight   ,'SCB'   ,fpaa_statistics.to(UpperCamelCase  )  )

	else:
		if value is None:
			UpperCAmelCase_		:      str       	=					old_value.to(UpperCamelCase  )
		elif isinstance(UpperCamelCase   ,torch.Tensor  ):
			UpperCAmelCase_		:      Tuple       	=					value.to(UpperCamelCase  )
		else:
			UpperCAmelCase_		:      str       	=					torch.tensor(UpperCamelCase   ,device=UpperCamelCase  )

		if is_buffer:
			UpperCAmelCase_		:      Dict       	=					new_value
		else:
			UpperCAmelCase_		:      Optional[int]       	=					nn.Parameter(UpperCamelCase   ,requires_grad=old_value.requires_grad  )
			UpperCAmelCase_		:      Optional[int]       	=					new_value







def 						SCREAMING_SNAKE_CASE(  UpperCamelCase   ,UpperCamelCase=None   ,UpperCamelCase=None   ,UpperCamelCase=None   ,UpperCamelCase=False  )    ->    Tuple:
	for name, module in model.named_children():
		if current_key_name is None:
			UpperCAmelCase_		:      Optional[int]       	=					[]
		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_	,    UpperCAmelCase_		:      Optional[Any]       	=					module.weight.shape
					else:
						UpperCAmelCase_		:      Dict       	=					module.in_features
						UpperCAmelCase_		:      Any       	=					module.out_features

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

	UpperCAmelCase_		:      Tuple       	=					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_		:      Union[str, Any]       	=					sum(UpperCamelCase   ,[]  )
	UpperCAmelCase_		:      Union[str, Any]       	=					len(UpperCamelCase  ) > 0

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

	# add last module together with tied weights
	UpperCAmelCase_		:      Any       	=					set(UpperCamelCase  ) - set(UpperCamelCase  )
	UpperCAmelCase_		:      Optional[int]       	=					list(set(UpperCamelCase  )  ) + list(UpperCamelCase  )

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

	return filtered_module_names






