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







def        __lowerCamelCase (							__a       :int   ,					__a       :Optional[Any]   ,					__a       :Any   ,					__a       :int=None   ,					__a       :List[Any]=None   )		->    Dict:






		"""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        __lowerCamelCase (							__a       :Optional[int]   ,					__a       :Dict=None   ,					__a       :List[str]=None   ,					__a       :str=None   ,					__a       :Optional[Any]=False   )		->    Dict:






		"""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        __lowerCamelCase (							__a       :List[Any]   ,					__a       :Optional[Any]=None   ,					__a       :int=None   ,					__a       :int=None   )		->    List[Any]:






		"""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        __lowerCamelCase (							*__a       :int   ,					**__a       :Any   )		->    List[Any]:






		"""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        __lowerCamelCase (							*__a       :Any   ,					**__a       :Optional[Any]   )		->    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"""   ,					__a   ,					)
		return set_module_quantized_tensor_to_device(*__a   ,					**__a   )







def        __lowerCamelCase (							__a       :int   )		->    Dict:






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










import itertools
import os
import random
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers import is_speech_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
					from transformers import WhisperFeatureExtractor

if is_torch_available():
					import torch

A   : Dict			=				random.Random()







def        __lowerCamelCase (							__a       :Dict   ,					__a       :str=1.0   ,					__a       :List[Any]=None   ,					__a       :List[str]=None   )		->    Optional[int]:






		"""simple docstring"""

		if rng is None:
				A__  				=       global_rng

		A__  				=       []
		for batch_idx in range(shape[0]   ):
				values.append([]   )
				for _ in range(shape[1]   ):
						values[-1].append(rng.random() * scale   )

		return values


@require_torch
@require_torchaudio
class   A      (unittest.TestCase   ):
			'''simple docstring'''




			def __init__(      self       :   Dict							,     __lowerCAmelCase       :   Any							,     __lowerCAmelCase       :   str=7							,     __lowerCAmelCase       :   List[Any]=4_00							,     __lowerCAmelCase       :   Optional[Any]=20_00							,     __lowerCAmelCase       :   Dict=10							,     __lowerCAmelCase       :   Union[str, Any]=1_60							,     __lowerCAmelCase       :   List[Any]=8							,     __lowerCAmelCase       :   List[Any]=0.0							,     __lowerCAmelCase       :   int=40_00							,     __lowerCAmelCase       :   Any=False							,     __lowerCAmelCase       :   List[str]=True							,     )     ->     Optional[int]:







					"""simple docstring"""






					A__  				=       parent
					A__  				=       batch_size
					A__  				=       min_seq_length
					A__  				=       max_seq_length
					A__  				=       (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
					A__  				=       padding_value
					A__  				=       sampling_rate
					A__  				=       return_attention_mask
					A__  				=       do_normalize
					A__  				=       feature_size
					A__  				=       chunk_length
					A__  				=       hop_length






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







					"""simple docstring"""






					return {
					    "feature_size": self.feature_size,
					    "hop_length": self.hop_length,
					    "chunk_length": self.chunk_length,
					    "padding_value": self.padding_value,
					    "sampling_rate": self.sampling_rate,
					    "return_attention_mask": self.return_attention_mask,
					    "do_normalize": self.do_normalize,
					}







			def        a_	(      self       :   List[str]							,     __lowerCAmelCase       :   List[Any]=False							,     __lowerCAmelCase       :   int=False       )     ->     str:







					"""simple docstring"""






					def _flatten(__lowerCAmelCase       :   Optional[int]       ):
							return list(itertools.chain(*__lowerCAmelCase       )       )

					if equal_length:
							A__  				=       [floats_list((self.max_seq_length, self.feature_size)       ) for _ in range(self.batch_size       )]
					else:
							# make sure that inputs increase in size
							A__  				=       [
							    floats_list((x, self.feature_size)       )
							    for x in range(self.min_seq_length							,     self.max_seq_length							,     self.seq_length_diff       )
							]
					if numpify:
							A__  				=       [np.asarray(__lowerCAmelCase       ) for x in speech_inputs]
					return speech_inputs


@require_torch
@require_torchaudio
class   A      (SCREAMING_SNAKE_CASE       ,					unittest.TestCase   ):
			'''simple docstring'''




			__lowerCamelCase     :	int          =   WhisperFeatureExtractor if is_speech_available() else None






			def        a_	(      self       :   Any       )     ->     str:







					"""simple docstring"""






					A__  				=       WhisperFeatureExtractionTester(self       )






			def        a_	(      self       :   Dict       )     ->     Tuple:







					"""simple docstring"""






					A__  				=       self.feature_extraction_class(**self.feat_extract_dict       )

					with tempfile.TemporaryDirectory() as tmpdirname:
							A__  				=       feat_extract_first.save_pretrained(__lowerCAmelCase       )[0]
							check_json_file_has_correct_format(__lowerCAmelCase       )
							A__  				=       self.feature_extraction_class.from_pretrained(__lowerCAmelCase       )

					A__  				=       feat_extract_first.to_dict()
					A__  				=       feat_extract_second.to_dict()
					A__  				=       feat_extract_first.mel_filters
					A__  				=       feat_extract_second.mel_filters
					self.assertTrue(np.allclose(__lowerCAmelCase							,     __lowerCAmelCase       )       )
					self.assertEqual(__lowerCAmelCase							,     __lowerCAmelCase       )






			def        a_	(      self       :   Dict       )     ->     str:







					"""simple docstring"""






					A__  				=       self.feature_extraction_class(**self.feat_extract_dict       )

					with tempfile.TemporaryDirectory() as tmpdirname:
							A__  				=       os.path.join(__lowerCAmelCase							,     """feat_extract.json"""       )
							feat_extract_first.to_json_file(__lowerCAmelCase       )
							A__  				=       self.feature_extraction_class.from_json_file(__lowerCAmelCase       )

					A__  				=       feat_extract_first.to_dict()
					A__  				=       feat_extract_second.to_dict()
					A__  				=       feat_extract_first.mel_filters
					A__  				=       feat_extract_second.mel_filters
					self.assertTrue(np.allclose(__lowerCAmelCase							,     __lowerCAmelCase       )       )
					self.assertEqual(__lowerCAmelCase							,     __lowerCAmelCase       )






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







					"""simple docstring"""






					A__  				=       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
					# create three inputs of length 800, 1000, and 1200
					A__  				=       [floats_list((1, x)       )[0] for x in range(8_00							,     14_00							,     2_00       )]
					A__  				=       [np.asarray(__lowerCAmelCase       ) for speech_input in speech_inputs]

					# Test feature size
					A__  				=       feature_extractor(__lowerCAmelCase							,     padding="""max_length"""							,     return_tensors="""np"""       ).input_features
					self.assertTrue(input_features.ndim == 3       )
					self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames       )
					self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size       )

					# Test not batched input
					A__  				=       feature_extractor(speech_inputs[0]							,     return_tensors="""np"""       ).input_features
					A__  				=       feature_extractor(np_speech_inputs[0]							,     return_tensors="""np"""       ).input_features
					self.assertTrue(np.allclose(__lowerCAmelCase							,     __lowerCAmelCase							,     atol=1e-3       )       )

					# Test batched
					A__  				=       feature_extractor(__lowerCAmelCase							,     return_tensors="""np"""       ).input_features
					A__  				=       feature_extractor(__lowerCAmelCase							,     return_tensors="""np"""       ).input_features
					for enc_seq_a, enc_seq_a in zip(__lowerCAmelCase							,     __lowerCAmelCase       ):
							self.assertTrue(np.allclose(__lowerCAmelCase							,     __lowerCAmelCase							,     atol=1e-3       )       )

					# Test 2-D numpy arrays are batched.
					A__  				=       [floats_list((1, x)       )[0] for x in (8_00, 8_00, 8_00)]
					A__  				=       np.asarray(__lowerCAmelCase       )
					A__  				=       feature_extractor(__lowerCAmelCase							,     return_tensors="""np"""       ).input_features
					A__  				=       feature_extractor(__lowerCAmelCase							,     return_tensors="""np"""       ).input_features
					for enc_seq_a, enc_seq_a in zip(__lowerCAmelCase							,     __lowerCAmelCase       ):
							self.assertTrue(np.allclose(__lowerCAmelCase							,     __lowerCAmelCase							,     atol=1e-3       )       )

					# Test truncation required
					A__  				=       [floats_list((1, x)       )[0] for x in range(2_00							,     (feature_extractor.n_samples + 5_00)							,     2_00       )]
					A__  				=       [np.asarray(__lowerCAmelCase       ) for speech_input in speech_inputs]

					A__  				=       [x[: feature_extractor.n_samples] for x in speech_inputs]
					A__  				=       [np.asarray(__lowerCAmelCase       ) for speech_input in speech_inputs_truncated]

					A__  				=       feature_extractor(__lowerCAmelCase							,     return_tensors="""np"""       ).input_features
					A__  				=       feature_extractor(__lowerCAmelCase							,     return_tensors="""np"""       ).input_features
					for enc_seq_a, enc_seq_a in zip(__lowerCAmelCase							,     __lowerCAmelCase       ):
							self.assertTrue(np.allclose(__lowerCAmelCase							,     __lowerCAmelCase							,     atol=1e-3       )       )






			def        a_	(      self       :   Dict       )     ->     Union[str, Any]:







					"""simple docstring"""






					import torch

					A__  				=       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
					A__  				=       np.random.rand(1_00							,     32       ).astype(np.floataa       )
					A__  				=       np_speech_inputs.tolist()

					for inputs in [py_speech_inputs, np_speech_inputs]:
							A__  				=       feature_extractor.pad([{"""input_features""": inputs}]							,     return_tensors="""np"""       )
							self.assertTrue(np_processed.input_features.dtype == np.floataa       )
							A__  				=       feature_extractor.pad([{"""input_features""": inputs}]							,     return_tensors="""pt"""       )
							self.assertTrue(pt_processed.input_features.dtype == torch.floataa       )






			def        a_	(      self       :   List[Any]							,     __lowerCAmelCase       :   Any       )     ->     Dict:







					"""simple docstring"""






					A__  				=       load_dataset("""hf-internal-testing/librispeech_asr_dummy"""							,     """clean"""							,     split="""validation"""       )
					# automatic decoding with librispeech
					A__  				=       ds.sort("""id"""       ).select(range(__lowerCAmelCase       )       )[:num_samples]["""audio"""]

					return [x["array"] for x in speech_samples]






			def        a_	(      self       :   Dict       )     ->     Any:







					"""simple docstring"""






					A__  				=       torch.tensor(
					    [
					        0.1_1_9_3, -0.0_9_4_6, -0.1_0_9_8, -0.0_1_9_6, 0.0_2_2_5, -0.0_6_9_0, -0.1_7_3_6, 0.0_9_5_1,
					        0.0_9_7_1, -0.0_8_1_7, -0.0_7_0_2, 0.0_1_6_2, 0.0_2_6_0, 0.0_0_1_7, -0.0_1_9_2, -0.1_6_7_8,
					        0.0_7_0_9, -0.1_8_6_7, -0.0_6_5_5, -0.0_2_7_4, -0.0_2_3_4, -0.1_8_8_4, -0.0_5_1_6, -0.0_5_5_4,
					        -0.0_2_7_4, -0.1_4_2_5, -0.1_4_2_3, 0.0_8_3_7, 0.0_3_7_7, -0.0_8_5_4
					    ]       )
					# fmt: on

					A__  				=       self._load_datasamples(1       )
					A__  				=       WhisperFeatureExtractor()
					A__  				=       feature_extractor(__lowerCAmelCase							,     return_tensors="""pt"""       ).input_features
					self.assertEqual(input_features.shape							,     (1, 80, 30_00)       )
					self.assertTrue(torch.allclose(input_features[0, 0, :30]							,     __lowerCAmelCase							,     atol=1e-4       )       )







			def        a_	(      self       :   Dict       )     ->     Tuple:







					"""simple docstring"""






					A__  				=       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
					A__  				=       self._load_datasamples(1       )[0]
					A__  				=       ((audio - audio.min()) / (audio.max() - audio.min())) * 6_55_35  # Rescale to [0, 65535] to show issue
					A__  				=       feat_extract.zero_mean_unit_var_norm([audio]							,     attention_mask=__lowerCAmelCase       )[0]

					self.assertTrue(np.all(np.mean(__lowerCAmelCase       ) < 1e-3       )       )
					self.assertTrue(np.all(np.abs(np.var(__lowerCAmelCase       ) - 1       ) < 1e-3       )       )



