
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

SCREAMING_SNAKE_CASE							:List[str]							 =				logging.get_logger(__name__)


def 						UpperCAmelCase			(	a_		,   a_		,   a_		,   a_=None		,   a_=None						)		->	str:







				"""simple docstring"""



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

				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}.'''						)

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

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

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

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

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

								if is_buffer:
												__A   			= new_value
								else:
												__A   			= nn.Parameter(a_		,   requires_grad=old_value.requires_grad						)
												__A   			= new_value


def 						UpperCAmelCase			(	a_		,   a_=None		,   a_=None		,   a_=None		,   a_=False						)		->	Optional[int]:







				"""simple docstring"""



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

								if (isinstance(a_		,   nn.Linear						) or isinstance(a_		,   a_						)) 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(a_						) for key in modules_to_not_convert						):
																with init_empty_weights():
																				if isinstance(a_		,   a_						):
																								__A			,							__A   			= module.weight.shape
																				else:
																								__A   			= module.in_features
																								__A   			= module.out_features

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


def 						UpperCAmelCase			(	a_		,   a_=None		,   a_=None		,   a_=None						)		->	int:







				"""simple docstring"""



				__A   			= ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
				__A			,							__A   			= _replace_with_bnb_linear(
				    a_		,   a_		,   a_		,   a_						)

				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			(	*a_		,   **a_						)		->	List[str]:







				"""simple docstring"""



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


def 						UpperCAmelCase			(	*a_		,   **a_						)		->	int:







				"""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"		,   a_		,   )
				return set_module_quantized_tensor_to_device(*a_		,   **a_						)


def 						UpperCAmelCase			(	a_						)		->	List[Any]:







				"""simple docstring"""



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

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

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

				# add last module together with tied weights
				__A   			= set(a_						) - set(a_						)
				__A   			= list(set(a_						)						) + list(a_						)

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

				return filtered_module_names


# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from packaging import version

from .. import __version__
from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD
from .doc import (
    add_code_sample_docstrings,
    add_end_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    copy_func,
    replace_return_docstrings,
)
from .generic import (
    ContextManagers,
    ExplicitEnum,
    ModelOutput,
    PaddingStrategy,
    TensorType,
    add_model_info_to_auto_map,
    cached_property,
    can_return_loss,
    expand_dims,
    find_labels,
    flatten_dict,
    infer_framework,
    is_jax_tensor,
    is_numpy_array,
    is_tensor,
    is_tf_symbolic_tensor,
    is_tf_tensor,
    is_torch_device,
    is_torch_dtype,
    is_torch_tensor,
    reshape,
    squeeze,
    strtobool,
    tensor_size,
    to_numpy,
    to_py_obj,
    transpose,
    working_or_temp_dir,
)
from .hub import (
    CLOUDFRONT_DISTRIB_PREFIX,
    DISABLE_TELEMETRY,
    HF_MODULES_CACHE,
    HUGGINGFACE_CO_PREFIX,
    HUGGINGFACE_CO_RESOLVE_ENDPOINT,
    PYTORCH_PRETRAINED_BERT_CACHE,
    PYTORCH_TRANSFORMERS_CACHE,
    S3_BUCKET_PREFIX,
    TRANSFORMERS_CACHE,
    TRANSFORMERS_DYNAMIC_MODULE_NAME,
    EntryNotFoundError,
    PushToHubMixin,
    RepositoryNotFoundError,
    RevisionNotFoundError,
    cached_file,
    default_cache_path,
    define_sagemaker_information,
    download_url,
    extract_commit_hash,
    get_cached_models,
    get_file_from_repo,
    get_full_repo_name,
    has_file,
    http_user_agent,
    is_offline_mode,
    is_remote_url,
    move_cache,
    send_example_telemetry,
    try_to_load_from_cache,
)
from .import_utils import (
    ENV_VARS_TRUE_AND_AUTO_VALUES,
    ENV_VARS_TRUE_VALUES,
    TORCH_FX_REQUIRED_VERSION,
    USE_JAX,
    USE_TF,
    USE_TORCH,
    DummyObject,
    OptionalDependencyNotAvailable,
    _LazyModule,
    ccl_version,
    direct_transformers_import,
    get_torch_version,
    is_accelerate_available,
    is_apex_available,
    is_bitsandbytes_available,
    is_bsa_available,
    is_coloredlogs_available,
    is_cython_available,
    is_datasets_available,
    is_decord_available,
    is_detectrona_available,
    is_faiss_available,
    is_flax_available,
    is_ftfy_available,
    is_in_notebook,
    is_ipex_available,
    is_jieba_available,
    is_jumanpp_available,
    is_kenlm_available,
    is_keras_nlp_available,
    is_librosa_available,
    is_natten_available,
    is_ninja_available,
    is_onnx_available,
    is_openai_available,
    is_optimum_available,
    is_pandas_available,
    is_peft_available,
    is_phonemizer_available,
    is_protobuf_available,
    is_psutil_available,
    is_pyanvml_available,
    is_pyctcdecode_available,
    is_pytesseract_available,
    is_pytest_available,
    is_pytorch_quantization_available,
    is_rjieba_available,
    is_sacremoses_available,
    is_safetensors_available,
    is_sagemaker_dp_enabled,
    is_sagemaker_mp_enabled,
    is_scipy_available,
    is_sentencepiece_available,
    is_seqio_available,
    is_sklearn_available,
    is_soundfile_availble,
    is_spacy_available,
    is_speech_available,
    is_sudachi_available,
    is_tensorflow_probability_available,
    is_tensorflow_text_available,
    is_tfaonnx_available,
    is_tf_available,
    is_timm_available,
    is_tokenizers_available,
    is_torch_available,
    is_torch_bfaa_available,
    is_torch_bfaa_cpu_available,
    is_torch_bfaa_gpu_available,
    is_torch_compile_available,
    is_torch_cuda_available,
    is_torch_fx_available,
    is_torch_fx_proxy,
    is_torch_mps_available,
    is_torch_neuroncore_available,
    is_torch_tensorrt_fx_available,
    is_torch_tfaa_available,
    is_torch_tpu_available,
    is_torchaudio_available,
    is_torchdistx_available,
    is_torchdynamo_available,
    is_torchvision_available,
    is_training_run_on_sagemaker,
    is_vision_available,
    requires_backends,
    torch_only_method,
)


SCREAMING_SNAKE_CASE							:List[str]							 =				'pytorch_model.bin'
SCREAMING_SNAKE_CASE							:str							 =				'pytorch_model.bin.index.json'
SCREAMING_SNAKE_CASE							:Optional[int]							 =				'adapter_config.json'
SCREAMING_SNAKE_CASE							:Dict							 =				'adapter_model.bin'
SCREAMING_SNAKE_CASE							:Dict							 =				'adapter_model.safetensors'
SCREAMING_SNAKE_CASE							:str							 =				'tf_model.h5'
SCREAMING_SNAKE_CASE							:List[Any]							 =				'tf_model.h5.index.json'
SCREAMING_SNAKE_CASE							:str							 =				'model.ckpt'
SCREAMING_SNAKE_CASE							:List[Any]							 =				'flax_model.msgpack'
SCREAMING_SNAKE_CASE							:Optional[int]							 =				'flax_model.msgpack.index.json'
SCREAMING_SNAKE_CASE							:Tuple							 =				'model.safetensors'
SCREAMING_SNAKE_CASE							:List[Any]							 =				'model.safetensors.index.json'
SCREAMING_SNAKE_CASE							:str							 =				'config.json'
SCREAMING_SNAKE_CASE							:int							 =				'preprocessor_config.json'
SCREAMING_SNAKE_CASE							:Optional[Any]							 =				FEATURE_EXTRACTOR_NAME
SCREAMING_SNAKE_CASE							:Optional[int]							 =				'generation_config.json'
SCREAMING_SNAKE_CASE							:List[str]							 =				'modelcard.json'

SCREAMING_SNAKE_CASE							:Optional[int]							 =				'▁'
SCREAMING_SNAKE_CASE							:Optional[Any]							 =				SENTENCEPIECE_UNDERLINE  # Kept for backward compatibility

SCREAMING_SNAKE_CASE							:str							 =				[
    [[0, 1, 0, 1], [1, 0, 0, 1]]
] * 2  # Needs to have 0s and 1s only since XLM uses it for langs too.
SCREAMING_SNAKE_CASE							:Optional[Any]							 =				[[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]
SCREAMING_SNAKE_CASE							:List[Any]							 =				[[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]]


def 						UpperCAmelCase			(	a_						)		->	Dict:







				"""simple docstring"""



				if version.parse(a_						) < version.parse(a_						):
								if "dev" in min_version:
												__A   			= (
												    "This example requires a source install from HuggingFace Transformers (see "
												    "`https://huggingface.co/docs/transformers/installation#install-from-source`),"
												)
								else:
												__A   			= F'''This example requires a minimum version of {min_version},'''
								error_message += F''' but the version found is {__version__}.\n'''
								raise ImportError(
								    error_message
								    + "Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other "
								    "versions of HuggingFace Transformers."						)
