



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

UpperCAmelCase							 =					logging.get_logger(__name__)

def 			A_      (	__a     :				int ,		__a     :				Union[str, Any] ,		__a     :				Optional[Any] ,		__a     :				str=None ,		__a     :				Optional[Any]=None		):

				"""simple docstring"""
				# Recurse if needed
				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 			A_      (	__a     :				Optional[Any] ,		__a     :				List[Any]=None ,		__a     :				Any=None ,		__a     :				List[Any]=None ,		__a     :				Optional[int]=False		):

				"""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 			A_      (	__a     :				Union[str, Any] ,		__a     :				Any=None ,		__a     :				List[str]=None ,		__a     :				Union[str, Any]=None		):

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

				"""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 			A_      (	__a     :				Optional[int]		):

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

import torch
from torch import nn

from ..configuration_utils import ConfigMixin, register_to_config
from .attention_processor import Attention
from .embeddings import get_timestep_embedding
from .modeling_utils import ModelMixin

class  __snake_case      (   SCREAMING_SNAKE_CASE			,SCREAMING_SNAKE_CASE):







							'''simple docstring'''






							@register_to_config
							def __init__(							self  ,  a_ = 128  ,  a_ = 256  ,  a_ = 2_000.0  ,  a_ = 768  ,  a_ = 12  ,  a_ = 12  ,  a_ = 64  ,  a_ = 2_048  ,  a_ = 0.1  ,  ):
											super().__init__()

											a__				      =		nn.Sequential(
											    nn.Linear(a_  ,  d_model * 4  ,  bias=a_		)  ,  nn.SiLU()  ,  nn.Linear(d_model * 4  ,  d_model * 4  ,  bias=a_		)  ,  nn.SiLU()  ,  )

											a__				      =		nn.Embedding(a_  ,  a_		)
											a__				      =		False

											a__				      =		nn.Linear(a_  ,  a_  ,  bias=a_		)

											a__				      =		nn.Dropout(p=a_		)

											a__				      =		nn.ModuleList()
											for lyr_num in range(a_		):
															# FiLM conditional T5 decoder
															a__				      =		DecoderLayer(d_model=a_  ,  d_kv=a_  ,  num_heads=a_  ,  d_ff=a_  ,  dropout_rate=a_		)
															self.decoders.append(a_		)

											a__				      =		TaLayerNorm(a_		)

											a__				      =		nn.Dropout(p=a_		)
											a__				      =		nn.Linear(a_  ,  a_  ,  bias=a_		)


							def _a      (							self  ,  a_  ,  a_		):
											a__				      =		torch.mul(query_input.unsqueeze(-1		)  ,  key_input.unsqueeze(-2		)		)
											return mask.unsqueeze(-3		)







							def _a      (							self  ,  a_  ,  a_  ,  a_		):
											a__      ,			a__      ,			a__				      =		decoder_input_tokens.shape
											assert decoder_noise_time.shape == (batch,)

											# decoder_noise_time is in [0, 1), so rescale to expected timing range.
											a__				      =		get_timestep_embedding(
											    decoder_noise_time * self.config.max_decoder_noise_time  ,  embedding_dim=self.config.d_model  ,  max_period=self.config.max_decoder_noise_time  ,  ).to(dtype=self.dtype		)

											a__				      =		self.conditioning_emb(a_		).unsqueeze(1		)

											assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4)

											a__				      =		decoder_input_tokens.shape[1]

											# If we want to use relative positions for audio context, we can just offset
											# this sequence by the length of encodings_and_masks.
											a__				      =		torch.broadcast_to(
											    torch.arange(a_  ,  device=decoder_input_tokens.device		)  ,  (batch, seq_length)  ,  )

											a__				      =		self.position_encoding(a_		)

											a__				      =		self.continuous_inputs_projection(a_		)
											inputs += position_encodings
											a__				      =		self.dropout(a_		)

											# decoder: No padding present.
											a__				      =		torch.ones(
											    decoder_input_tokens.shape[:2]  ,  device=decoder_input_tokens.device  ,  dtype=inputs.dtype		)

											# Translate encoding masks to encoder-decoder masks.
											a__				      =		[(x, self.encoder_decoder_mask(a_  ,  a_		)) for x, y in encodings_and_masks]

											# cross attend style: concat encodings
											a__				      =		torch.cat([x[0] for x in encodings_and_encdec_masks]  ,  dim=1		)
											a__				      =		torch.cat([x[1] for x in encodings_and_encdec_masks]  ,  dim=-1		)

											for lyr in self.decoders:
															a__				      =		lyr(
															    a_  ,  conditioning_emb=a_  ,  encoder_hidden_states=a_  ,  encoder_attention_mask=a_  ,  )[0]

											a__				      =		self.decoder_norm(a_		)
											a__				      =		self.post_dropout(a_		)

											a__				      =		self.spec_out(a_		)
											return spec_out




class  __snake_case      (   nn.Module):







							'''simple docstring'''






							def __init__(							self  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_=1E-6		):
											super().__init__()
											a__				      =		nn.ModuleList()

											# cond self attention: layer 0
											self.layer.append(
											    TaLayerSelfAttentionCond(d_model=a_  ,  d_kv=a_  ,  num_heads=a_  ,  dropout_rate=a_		)		)

											# cross attention: layer 1
											self.layer.append(
											    TaLayerCrossAttention(
											        d_model=a_  ,  d_kv=a_  ,  num_heads=a_  ,  dropout_rate=a_  ,  layer_norm_epsilon=a_  ,  )		)

											# Film Cond MLP + dropout: last layer
											self.layer.append(
											    TaLayerFFCond(d_model=a_  ,  d_ff=a_  ,  dropout_rate=a_  ,  layer_norm_epsilon=a_		)		)







							def _a      (							self  ,  a_  ,  a_=None  ,  a_=None  ,  a_=None  ,  a_=None  ,  a_=None  ,  ):
											a__				      =		self.layer[0](
											    a_  ,  conditioning_emb=a_  ,  attention_mask=a_  ,  )

											if encoder_hidden_states is not None:
															a__				      =		torch.where(encoder_attention_mask > 0  ,  0  ,  -1E1_0		).to(
															    encoder_hidden_states.dtype		)

															a__				      =		self.layer[1](
															    a_  ,  key_value_states=a_  ,  attention_mask=a_  ,  )

											# Apply Film Conditional Feed Forward layer
											a__				      =		self.layer[-1](a_  ,  a_		)

											return (hidden_states,)




class  __snake_case      (   nn.Module):







							'''simple docstring'''






							def __init__(							self  ,  a_  ,  a_  ,  a_  ,  a_		):
											super().__init__()
											a__				      =		TaLayerNorm(a_		)
											a__				      =		TaFiLMLayer(in_features=d_model * 4  ,  out_features=a_		)
											a__				      =		Attention(query_dim=a_  ,  heads=a_  ,  dim_head=a_  ,  out_bias=a_  ,  scale_qk=a_		)
											a__				      =		nn.Dropout(a_		)







							def _a      (							self  ,  a_  ,  a_=None  ,  a_=None  ,  ):
											# pre_self_attention_layer_norm
											a__				      =		self.layer_norm(a_		)

											if conditioning_emb is not None:
															a__				      =		self.FiLMLayer(a_  ,  a_		)

											# Self-attention block
											a__				      =		self.attention(a_		)

											a__				      =		hidden_states + self.dropout(a_		)

											return hidden_states




class  __snake_case      (   nn.Module):







							'''simple docstring'''






							def __init__(							self  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_		):
											super().__init__()
											a__				      =		Attention(query_dim=a_  ,  heads=a_  ,  dim_head=a_  ,  out_bias=a_  ,  scale_qk=a_		)
											a__				      =		TaLayerNorm(a_  ,  eps=a_		)
											a__				      =		nn.Dropout(a_		)







							def _a      (							self  ,  a_  ,  a_=None  ,  a_=None  ,  ):
											a__				      =		self.layer_norm(a_		)
											a__				      =		self.attention(
											    a_  ,  encoder_hidden_states=a_  ,  attention_mask=attention_mask.squeeze(1		)  ,  )
											a__				      =		hidden_states + self.dropout(a_		)
											return layer_output




class  __snake_case      (   nn.Module):







							'''simple docstring'''






							def __init__(							self  ,  a_  ,  a_  ,  a_  ,  a_		):
											super().__init__()
											a__				      =		TaDenseGatedActDense(d_model=a_  ,  d_ff=a_  ,  dropout_rate=a_		)
											a__				      =		TaFiLMLayer(in_features=d_model * 4  ,  out_features=a_		)
											a__				      =		TaLayerNorm(a_  ,  eps=a_		)
											a__				      =		nn.Dropout(a_		)







							def _a      (							self  ,  a_  ,  a_=None		):
											a__				      =		self.layer_norm(a_		)
											if conditioning_emb is not None:
															a__				      =		self.film(a_  ,  a_		)

											a__				      =		self.DenseReluDense(a_		)
											a__				      =		hidden_states + self.dropout(a_		)
											return hidden_states




class  __snake_case      (   nn.Module):







							'''simple docstring'''






							def __init__(							self  ,  a_  ,  a_  ,  a_		):
											super().__init__()
											a__				      =		nn.Linear(a_  ,  a_  ,  bias=a_		)
											a__				      =		nn.Linear(a_  ,  a_  ,  bias=a_		)
											a__				      =		nn.Linear(a_  ,  a_  ,  bias=a_		)
											a__				      =		nn.Dropout(a_		)
											a__				      =		NewGELUActivation()







							def _a      (							self  ,  a_		):
											a__				      =		self.act(self.wi_a(a_		)		)
											a__				      =		self.wi_a(a_		)
											a__				      =		hidden_gelu * hidden_linear
											a__				      =		self.dropout(a_		)

											a__				      =		self.wo(a_		)
											return hidden_states




class  __snake_case      (   nn.Module):







							'''simple docstring'''






							def __init__(							self  ,  a_  ,  a_=1E-6		):
											super().__init__()
											a__				      =		nn.Parameter(torch.ones(a_		)		)
											a__				      =		eps







							def _a      (							self  ,  a_		):
											# T5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean
											# Square Layer Normalization https://arxiv.org/abs/1910.07467 thus variance is calculated
											# w/o mean and there is no bias. Additionally we want to make sure that the accumulation for
											# half-precision inputs is done in fp32

											a__				      =		hidden_states.to(torch.floataa		).pow(2		).mean(-1  ,  keepdim=a_		)
											a__				      =		hidden_states * torch.rsqrt(variance + self.variance_epsilon		)

											# convert into half-precision if necessary
											if self.weight.dtype in [torch.floataa, torch.bfloataa]:
															a__				      =		hidden_states.to(self.weight.dtype		)

											return self.weight * hidden_states




class  __snake_case      (   nn.Module):







							'''simple docstring'''






							def _a      (							self  ,  a_		):
											return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi		) * (input + 0.044_715 * torch.pow(a_  ,  3.0		))		))




class  __snake_case      (   nn.Module):







							'''simple docstring'''






							def __init__(							self  ,  a_  ,  a_		):
											super().__init__()
											a__				      =		nn.Linear(a_  ,  out_features * 2  ,  bias=a_		)







							def _a      (							self  ,  a_  ,  a_		):
											a__				      =		self.scale_bias(a_		)
											a__      ,			a__				      =		torch.chunk(a_  ,  2  ,  -1		)
											a__				      =		x * (1 + scale) + shift
											return x

