




'''simple docstring'''

import importlib.metadata
import warnings
from copy import deepcopy

from packaging import version

from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available


if is_bitsandbytes_available():
							import bitsandbytes as bnb
							import torch
							import torch.nn as nn

							from ..pytorch_utils import ConvaD

if is_accelerate_available():
							from accelerate import init_empty_weights
							from accelerate.utils import find_tied_parameters

a  :				Optional[Any]									=  logging.get_logger(__name__)


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

					'''simple docstring'''

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

					if tensor_name not in module._parameters and tensor_name not in module._buffers:
										raise ValueError(F"{module} does not have a parameter or a buffer named {tensor_name}."	)
					snake_case_									=				tensor_name in module._buffers
					snake_case_									=				getattr(__UpperCAmelCase,      __UpperCAmelCase	)

					if old_value.device == torch.device('''meta'''	) and device not in ["meta", torch.device('''meta'''	)] and value is None:
										raise ValueError(F"{tensor_name} is on the meta device, we need a `value` to put in on {device}."	)

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

					if is_abit or is_abit:
										snake_case_									=				module._parameters[tensor_name]
										if param.device.type != "cuda":
															if value is None:
																				snake_case_									=				old_value.to(__UpperCAmelCase	)
															elif isinstance(__UpperCAmelCase,      torch.Tensor	):
																				snake_case_									=				value.to('''cpu'''	)
																				if value.dtype == torch.inta:
																									snake_case_									=				version.parse(importlib.metadata.version('''bitsandbytes'''	)	) > version.parse(
																									    '''0.37.2'''	)
																									if not is_abit_serializable:
																														raise ValueError(
																														    '''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. '''
																														    '''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.'''	)
															else:
																				snake_case_									=				torch.tensor(__UpperCAmelCase,      device='''cpu'''	)

															# Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
															# Since weights are saved in the correct "orientation", we skip transposing when loading.
															if issubclass(module.source_cls,      __UpperCAmelCase	) and fpaa_statistics is None:
																				snake_case_									=				new_value.T

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

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

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

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


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

					'''simple docstring'''

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

										if (isinstance(__UpperCAmelCase,      nn.Linear	) or isinstance(__UpperCAmelCase,      __UpperCAmelCase	)) and name not in modules_to_not_convert:
															# Check if the current key is not in the `modules_to_not_convert`
															if not any(key in '''.'''.join(__UpperCAmelCase	) for key in modules_to_not_convert	):
																				with init_empty_weights():
																									if isinstance(__UpperCAmelCase,      __UpperCAmelCase	):
																														snake_case_			,snake_case_									=				module.weight.shape
																									else:
																														snake_case_									=				module.in_features
																														snake_case_									=				module.out_features

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


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

					'''simple docstring'''

					snake_case_									=				['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert
					snake_case_			,snake_case_									=				_replace_with_bnb_linear(
					    __UpperCAmelCase,      __UpperCAmelCase,      __UpperCAmelCase,      __UpperCAmelCase	)

					if not has_been_replaced:
										logger.warning(
										    '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.'''
										    ''' Please double check your model architecture, or submit an issue on github if you think this is'''
										    ''' a bug.'''	)

					return model


def 		__magic_name__    (	*__UpperCAmelCase,      **__UpperCAmelCase	)		->					Optional[Any]:

					'''simple docstring'''

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


def 		__magic_name__    (	*__UpperCAmelCase,      **__UpperCAmelCase	)		->					Dict:

					'''simple docstring'''

					warnings.warn(
					    '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead''',      __UpperCAmelCase,      )
					return set_module_quantized_tensor_to_device(*__UpperCAmelCase,      **__UpperCAmelCase	)


def 		__magic_name__    (	__UpperCAmelCase	)		->					str:

					'''simple docstring'''

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

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

					# Check if it is a base model
					snake_case_									=				not hasattr(__UpperCAmelCase,      model.base_model_prefix	)

					# Ignore this for base models (BertModel, GPT2Model, etc.)
					if (not has_tied_params) and is_base_model:
										return []

					# otherwise they have an attached head
					snake_case_									=				list(model.named_children()	)
					snake_case_									=				[list_modules[-1][0]]

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

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

					return filtered_module_names







from ...configuration_utils import PretrainedConfig
from ...utils import logging


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

lowerCamelCase__ :   List[str]					=							{
    'facebook/s2t-small-librispeech-asr': (
        'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/config.json'
    ),
    # See all Speech2Text models at https://huggingface.co/models?filter=speech_to_text
}





class        lowerCamelCase_							(      _SCREAMING_SNAKE_CASE					):


 '''simple docstring'''







 lowercase_				    =    "speech_to_text"
 lowercase_				    =    ["past_key_values"]
 lowercase_				    =    {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}



 def __init__(							self  :		Tuple				,				_lowerCAmelCase  :		List[Any]=10_000				,				_lowerCAmelCase  :		List[Any]=12				,				_lowerCAmelCase  :		Union[str, Any]=2_048				,				_lowerCAmelCase  :		Optional[int]=4				,				_lowerCAmelCase  :		Union[str, Any]=6				,				_lowerCAmelCase  :		Optional[int]=2_048				,				_lowerCAmelCase  :		Optional[Any]=4				,				_lowerCAmelCase  :		Any=0.0				,				_lowerCAmelCase  :		Optional[Any]=0.0				,				_lowerCAmelCase  :		List[str]=True				,				_lowerCAmelCase  :		List[Any]=True				,				_lowerCAmelCase  :		int="relu"				,				_lowerCAmelCase  :		Union[str, Any]=256				,				_lowerCAmelCase  :		List[str]=0.1				,				_lowerCAmelCase  :		str=0.0				,				_lowerCAmelCase  :		Tuple=0.0				,				_lowerCAmelCase  :		List[str]=0.02				,				_lowerCAmelCase  :		List[str]=2				,				_lowerCAmelCase  :		Tuple=True				,				_lowerCAmelCase  :		List[str]=1				,				_lowerCAmelCase  :		str=0				,				_lowerCAmelCase  :		str=2				,				_lowerCAmelCase  :		Union[str, Any]=6_000				,				_lowerCAmelCase  :		List[str]=1_024				,				_lowerCAmelCase  :		str=2				,				_lowerCAmelCase  :		Optional[Any]=(5, 5)				,				_lowerCAmelCase  :		str=1_024				,				_lowerCAmelCase  :		str=80				,				_lowerCAmelCase  :		Tuple=1				,				**_lowerCAmelCase  :		Any				,				):
       SCREAMING_SNAKE_CASE_							=			vocab_size
       SCREAMING_SNAKE_CASE_							=			d_model
       SCREAMING_SNAKE_CASE_							=			encoder_ffn_dim
       SCREAMING_SNAKE_CASE_							=			encoder_layers
       SCREAMING_SNAKE_CASE_							=			encoder_attention_heads
       SCREAMING_SNAKE_CASE_							=			decoder_ffn_dim
       SCREAMING_SNAKE_CASE_							=			decoder_layers
       SCREAMING_SNAKE_CASE_							=			decoder_attention_heads
       SCREAMING_SNAKE_CASE_							=			dropout
       SCREAMING_SNAKE_CASE_							=			attention_dropout
       SCREAMING_SNAKE_CASE_							=			activation_dropout
       SCREAMING_SNAKE_CASE_							=			activation_function
       SCREAMING_SNAKE_CASE_							=			init_std
       SCREAMING_SNAKE_CASE_							=			encoder_layerdrop
       SCREAMING_SNAKE_CASE_							=			decoder_layerdrop
       SCREAMING_SNAKE_CASE_							=			use_cache
       SCREAMING_SNAKE_CASE_							=			encoder_layers
       SCREAMING_SNAKE_CASE_							=			scale_embedding  # scale factor will be sqrt(d_model) if True
       SCREAMING_SNAKE_CASE_							=			max_source_positions
       SCREAMING_SNAKE_CASE_							=			max_target_positions
       SCREAMING_SNAKE_CASE_							=			num_conv_layers
       SCREAMING_SNAKE_CASE_							=			list(_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_							=			conv_channels
       SCREAMING_SNAKE_CASE_							=			input_feat_per_channel
       SCREAMING_SNAKE_CASE_							=			input_channels

       if len(self.conv_kernel_sizes						) != self.num_conv_layers:
             raise ValueError(
                 'Configuration for convolutional module is incorrect. '
                 'It is required that `len(config.conv_kernel_sizes)` == `config.num_conv_layers` '
                 F"but is `len(config.conv_kernel_sizes) = {len(self.conv_kernel_sizes						)}`, "
                 F"`config.num_conv_layers = {self.num_conv_layers}`."						)

       super().__init__(
           pad_token_id=_lowerCAmelCase				,				bos_token_id=_lowerCAmelCase				,				eos_token_id=_lowerCAmelCase				,				is_encoder_decoder=_lowerCAmelCase				,				decoder_start_token_id=_lowerCAmelCase				,				**_lowerCAmelCase				,				)