


'''simple docstring'''

from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxSeqaSeqConfigWithPast
from ...utils import logging


_UpperCAmelCase					:			Any				     =					logging.get_logger(__name__)


class    a__					(			__A   ):







				"""simple docstring"""



				__UpperCamelCase     :		List[str]						=						'mt5'
				__UpperCamelCase     :		int						=						['past_key_values']




				def __init__(self							,      __lowercase=25_01_12							,      __lowercase=5_12							,      __lowercase=64							,      __lowercase=10_24							,      __lowercase=8							,      __lowercase=None							,      __lowercase=6							,      __lowercase=32							,      __lowercase=1_28							,      __lowercase=0.1							,      __lowercase=1e-6							,      __lowercase=1.0							,      __lowercase="gated-gelu"							,      __lowercase=True							,      __lowercase=True							,      __lowercase="T5Tokenizer"							,      __lowercase=False							,      __lowercase=0							,      __lowercase=1							,      __lowercase=0							,      **__lowercase							,      ):
										super().__init__(
										    is_encoder_decoder=__lowercase							,      tokenizer_class=__lowercase							,      tie_word_embeddings=__lowercase							,      pad_token_id=__lowercase							,      eos_token_id=__lowercase							,      decoder_start_token_id=__lowercase							,      **__lowercase							,      )
										__lowerCAmelCase											=					vocab_size
										__lowerCAmelCase											=					d_model
										__lowerCAmelCase											=					d_kv
										__lowerCAmelCase											=					d_ff
										__lowerCAmelCase											=					num_layers
										__lowerCAmelCase											=					(
										    num_decoder_layers if num_decoder_layers is not None else self.num_layers
										)  # default = symmetry
										__lowerCAmelCase											=					num_heads
										__lowerCAmelCase											=					relative_attention_num_buckets
										__lowerCAmelCase											=					relative_attention_max_distance
										__lowerCAmelCase											=					dropout_rate
										__lowerCAmelCase											=					layer_norm_epsilon
										__lowerCAmelCase											=					initializer_factor
										__lowerCAmelCase											=					feed_forward_proj
										__lowerCAmelCase											=					use_cache

										__lowerCAmelCase											=					self.feed_forward_proj.split('''-'''		)
										__lowerCAmelCase											=					act_info[-1]
										__lowerCAmelCase											=					act_info[0] == '''gated'''

										if len(__lowercase		) > 1 and act_info[0] != "gated" or len(__lowercase		) > 2:
																raise ValueError(
																    F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer."""
																    '''Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. '''
																    '''\'gated-gelu\' or \'relu\''''		)

										# for backwards compatibility
										if feed_forward_proj == "gated-gelu":
																__lowerCAmelCase											=					'''gelu_new'''




				@property
				def        _snake_case	(self		):
										return self.d_model




				@property
				def        _snake_case	(self		):
										return self.num_heads




				@property
				def        _snake_case	(self		):
										return self.num_layers


class    a__					(			__A   ):







				"""simple docstring"""



				@property
				# Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs
				def        _snake_case	(self		):
										__lowerCAmelCase											=					{
										    '''input_ids''': {0: '''batch''', 1: '''encoder_sequence'''},
										    '''attention_mask''': {0: '''batch''', 1: '''encoder_sequence'''},
										}
										if self.use_past:
																__lowerCAmelCase											=					'''past_encoder_sequence + sequence'''
																__lowerCAmelCase											=					{0: '''batch'''}
																__lowerCAmelCase											=					{0: '''batch''', 1: '''past_decoder_sequence + sequence'''}
										else:
																__lowerCAmelCase											=					{0: '''batch''', 1: '''decoder_sequence'''}
																__lowerCAmelCase											=					{0: '''batch''', 1: '''decoder_sequence'''}

										if self.use_past:
																self.fill_with_past_key_values_(__lowercase							,      direction='''inputs'''		)

										return common_inputs




				@property
				# Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset
				def        _snake_case	(self		):
										return 13




				@property
				def        _snake_case	(self		):
										return 5e-4





'''simple docstring'''

import inspect
from typing import Callable, List, Optional, Set, Tuple, Union

import torch
from packaging import version
from safetensors.torch import storage_ptr, storage_size
from torch import nn

from .utils import logging


_UpperCAmelCase					:			Optional[Any]				     =					[nn.LayerNorm]

_UpperCAmelCase					:			Dict				     =					logging.get_logger(__name__)

_UpperCAmelCase					:			Tuple				     =					version.parse(version.parse(torch.__version__).base_version)

_UpperCAmelCase					:			Optional[int]				     =					parsed_torch_version_base >= version.parse("""2.0""")
_UpperCAmelCase					:			Optional[int]				     =					parsed_torch_version_base >= version.parse("""1.12""")
_UpperCAmelCase					:			List[str]				     =					parsed_torch_version_base >= version.parse("""1.11""")
_UpperCAmelCase					:			Optional[int]				     =					parsed_torch_version_base < version.parse("""1.11""")

def 				__magic_name__(    lowerCamelCase,					lowerCamelCase,					lowerCamelCase,					lowerCamelCase,					self):
						from torch import _softmax_backward_data

						if is_torch_less_than_1_11:
												return _softmax_backward_data(lowerCamelCase,					lowerCamelCase,					parent.dim,					self)
						else:
												return _softmax_backward_data(lowerCamelCase,					lowerCamelCase,					parent.dim,					self.dtype)

def 				__magic_name__(    lowerCamelCase,					lowerCamelCase,					lowerCamelCase = 0):
						__lowerCAmelCase											=					index.to(layer.weight.device)
						__lowerCAmelCase											=					layer.weight.index_select(lowerCamelCase,					lowerCamelCase).clone().detach()
						if layer.bias is not None:
												if dim == 1:
																		__lowerCAmelCase											=					layer.bias.clone().detach()
												else:
																		__lowerCAmelCase											=					layer.bias[index].clone().detach()
						__lowerCAmelCase											=					list(layer.weight.size())
						__lowerCAmelCase											=					len(lowerCamelCase)
						__lowerCAmelCase											=					nn.Linear(new_size[1],					new_size[0],					bias=layer.bias is not None).to(layer.weight.device)
						__lowerCAmelCase											=					False
						new_layer.weight.copy_(W.contiguous())
						__lowerCAmelCase											=					True
						if layer.bias is not None:
												__lowerCAmelCase											=					False
												new_layer.bias.copy_(b.contiguous())
												__lowerCAmelCase											=					True
						return new_layer


class    a__					(			nn.Module   ):







				"""simple docstring"""



				def __init__(self							,      __lowercase							,      __lowercase		):
										super().__init__()
										__lowerCAmelCase											=					nf
										__lowerCAmelCase											=					nn.Parameter(torch.empty(__lowercase							,      __lowercase		)		)
										__lowerCAmelCase											=					nn.Parameter(torch.zeros(__lowercase		)		)
										nn.init.normal_(self.weight							,      std=0.0_2		)




				def        _snake_case	(self							,      __lowercase		):
										__lowerCAmelCase											=					x.size()[:-1] + (self.nf,)
										__lowerCAmelCase											=					torch.addmm(self.bias							,      x.view(-1							,      x.size(-1		)		)							,      self.weight		)
										__lowerCAmelCase											=					x.view(__lowercase		)
										return x

def 				__magic_name__(    lowerCamelCase,					lowerCamelCase,					lowerCamelCase = 1):
						__lowerCAmelCase											=					index.to(layer.weight.device)
						__lowerCAmelCase											=					layer.weight.index_select(lowerCamelCase,					lowerCamelCase).clone().detach()
						if dim == 0:
												__lowerCAmelCase											=					layer.bias.clone().detach()
						else:
												__lowerCAmelCase											=					layer.bias[index].clone().detach()
						__lowerCAmelCase											=					list(layer.weight.size())
						__lowerCAmelCase											=					len(lowerCamelCase)
						__lowerCAmelCase											=					ConvaD(new_size[1],					new_size[0]).to(layer.weight.device)
						__lowerCAmelCase											=					False
						new_layer.weight.copy_(W.contiguous())
						__lowerCAmelCase											=					True
						__lowerCAmelCase											=					False
						new_layer.bias.copy_(b.contiguous())
						__lowerCAmelCase											=					True
						return new_layer

def 				__magic_name__(    lowerCamelCase,					lowerCamelCase,					lowerCamelCase = None):
						if isinstance(lowerCamelCase,					nn.Linear):
												return prune_linear_layer(lowerCamelCase,					lowerCamelCase,					dim=0 if dim is None else dim)
						elif isinstance(lowerCamelCase,					lowerCamelCase):
												return prune_convad_layer(lowerCamelCase,					lowerCamelCase,					dim=1 if dim is None else dim)
						else:
												raise ValueError(F"""Can't prune layer of class {layer.__class__}""")

def 				__magic_name__(    lowerCamelCase,					lowerCamelCase,					lowerCamelCase,					*lowerCamelCase):
						assert len(lowerCamelCase) > 0, F"""{input_tensors} has to be a tuple/list of tensors"""

						# inspect.signature exist since python 3.5 and is a python method -> no problem with backward compatibility
						__lowerCAmelCase											=					len(inspect.signature(lowerCamelCase).parameters)
						if num_args_in_forward_chunk_fn != len(lowerCamelCase):
												raise ValueError(
												    F"""forward_chunk_fn expects {num_args_in_forward_chunk_fn} arguments, but only {len(lowerCamelCase)} input """
												    '''tensors are given''')

						if chunk_size > 0:
												__lowerCAmelCase											=					input_tensors[0].shape[chunk_dim]
												for input_tensor in input_tensors:
																		if input_tensor.shape[chunk_dim] != tensor_shape:
																								raise ValueError(
																								    F"""All input tenors have to be of the same shape: {tensor_shape}, """
																								    F"""found shape {input_tensor.shape[chunk_dim]}""")

												if input_tensors[0].shape[chunk_dim] % chunk_size != 0:
																		raise ValueError(
																		    F"""The dimension to be chunked {input_tensors[0].shape[chunk_dim]} has to be a multiple of the chunk """
																		    F"""size {chunk_size}""")

												__lowerCAmelCase											=					input_tensors[0].shape[chunk_dim] // chunk_size

												# chunk input tensor into tuples
												__lowerCAmelCase											=					tuple(input_tensor.chunk(lowerCamelCase,					dim=lowerCamelCase) for input_tensor in input_tensors)
												# apply forward fn to every tuple
												__lowerCAmelCase											=					tuple(forward_fn(*lowerCamelCase) for input_tensors_chunk in zip(*lowerCamelCase))
												# concatenate output at same dimension
												return torch.cat(lowerCamelCase,					dim=lowerCamelCase)

						return forward_fn(*lowerCamelCase)

def 				__magic_name__(    lowerCamelCase,					lowerCamelCase,					lowerCamelCase,					lowerCamelCase):
						__lowerCAmelCase											=					torch.ones(lowerCamelCase,					lowerCamelCase)
						__lowerCAmelCase											=					set(lowerCamelCase) - already_pruned_heads  # Convert to set and remove already pruned heads
						for head in heads:
												# Compute how many pruned heads are before the head and move the index accordingly
												__lowerCAmelCase											=					head - sum(1 if h < head else 0 for h in already_pruned_heads)
												__lowerCAmelCase											=					0
						__lowerCAmelCase											=					mask.view(-1).contiguous().eq(1)
						__lowerCAmelCase											=					torch.arange(len(lowerCamelCase))[mask].long()
						return heads, index

def 				__magic_name__(    *lowerCamelCase,					lowerCamelCase = None):
						return torch.meshgrid(*lowerCamelCase,					indexing=lowerCamelCase)




def 				__magic_name__(    lowerCamelCase):
						return tensor.device, storage_ptr(lowerCamelCase), storage_size(lowerCamelCase)

