





import torch
from torch import nn
class      UpperCamelCase_						(					nn.Module   ):




     def __init__(						self			,  lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_=1			,  lowerCAmelCase_=False					)						->							Tuple:
          super().__init__()

          _snake_case													=			n_token
          _snake_case													=			d_embed
          _snake_case													=			d_proj

          _snake_case													=			cutoffs + [n_token]
          _snake_case													=			[0] + self.cutoffs
          _snake_case													=			div_val

          _snake_case													=			self.cutoffs[0]
          _snake_case													=			len(self.cutoffs					) - 1
          _snake_case													=			self.shortlist_size + self.n_clusters

          if self.n_clusters > 0:
               _snake_case													=			nn.Parameter(torch.zeros(self.n_clusters			,  self.d_embed					)					)
               _snake_case													=			nn.Parameter(torch.zeros(self.n_clusters					)					)

          _snake_case													=			nn.ModuleList()
          _snake_case													=			nn.ParameterList()

          if div_val == 1:
               for i in range(len(self.cutoffs					)					):
                    if d_proj != d_embed:
                         self.out_projs.append(nn.Parameter(torch.FloatTensor(lowerCAmelCase_			,  lowerCAmelCase_					)					)					)
                    else:
                         self.out_projs.append(lowerCAmelCase_					)

               self.out_layers.append(nn.Linear(lowerCAmelCase_			,  lowerCAmelCase_					)					)
          else:
               for i in range(len(self.cutoffs					)					):
                    _snake_case													=			self.cutoff_ends[i], self.cutoff_ends[i + 1]
                    _snake_case													=			d_embed // (div_val**i)

                    self.out_projs.append(nn.Parameter(torch.FloatTensor(lowerCAmelCase_			,  lowerCAmelCase_					)					)					)

                    self.out_layers.append(nn.Linear(lowerCAmelCase_			,  r_idx - l_idx					)					)

          _snake_case													=			keep_order




     def 		lowerCAmelCase     (						self			,  lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_					)						->							Any:
          if proj is None:
               _snake_case													=			nn.functional.linear(lowerCAmelCase_			,  lowerCAmelCase_			,  bias=lowerCAmelCase_					)
          else:
               # if CUDA_MAJOR <= 9 and CUDA_MINOR <= 1:
               _snake_case													=			nn.functional.linear(lowerCAmelCase_			,  proj.t().contiguous()					)
               _snake_case													=			nn.functional.linear(lowerCAmelCase_			,  lowerCAmelCase_			,  bias=lowerCAmelCase_					)
               # else:
               #     logit = torch.einsum('bd,de,ev->bv', (hidden, proj, weight.t()))
               #     if bias is not None:
               #         logit = logit + bias

          return logit




     def 		lowerCAmelCase     (						self			,  lowerCAmelCase_			,  lowerCAmelCase_=None			,  lowerCAmelCase_=False					)						->							Optional[int]:

          if labels is not None:
               # Shift so that tokens < n predict n
               _snake_case													=			hidden[..., :-1, :].contiguous()
               _snake_case													=			labels[..., 1:].contiguous()
               _snake_case													=			hidden.view(-1			,  hidden.size(-1					)					)
               _snake_case													=			labels.view(-1					)
               if hidden.size(0					) != labels.size(0					):
                    raise RuntimeError('Input and labels should have the same size in the batch dimension.'					)
          else:
               _snake_case													=			hidden.view(-1			,  hidden.size(-1					)					)

          if self.n_clusters == 0:
               _snake_case													=			self._compute_logit(lowerCAmelCase_			,  self.out_layers[0].weight			,  self.out_layers[0].bias			,  self.out_projs[0]					)
               if labels is not None:
                    _snake_case													=			labels != -100
                    _snake_case													=			torch.zeros_like(lowerCAmelCase_			,  dtype=hidden.dtype			,  device=hidden.device					)
                    _snake_case													=			(
                        -nn.functional.log_softmax(lowerCAmelCase_			,  dim=-1					)[mask].gather(1			,  labels[mask].unsqueeze(1					)					).squeeze(1					)
                    )
               else:
                    _snake_case													=			nn.functional.log_softmax(lowerCAmelCase_			,  dim=-1					)
          else:
               # construct weights and biases
               _snake_case													=			[], []
               for i in range(len(self.cutoffs					)					):
                    if self.div_val == 1:
                         _snake_case													=			self.cutoff_ends[i], self.cutoff_ends[i + 1]
                         _snake_case													=			self.out_layers[0].weight[l_idx:r_idx]
                         _snake_case													=			self.out_layers[0].bias[l_idx:r_idx]
                    else:
                         _snake_case													=			self.out_layers[i].weight
                         _snake_case													=			self.out_layers[i].bias

                    if i == 0:
                         _snake_case													=			torch.cat([weight_i, self.cluster_weight]			,  dim=0					)
                         _snake_case													=			torch.cat([bias_i, self.cluster_bias]			,  dim=0					)

                    weights.append(lowerCAmelCase_					)
                    biases.append(lowerCAmelCase_					)

               _snake_case													=			weights[0], biases[0], self.out_projs[0]

               _snake_case													=			self._compute_logit(lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_					)
               _snake_case													=			nn.functional.log_softmax(lowerCAmelCase_			,  dim=1					)

               if labels is None:
                    _snake_case													=			hidden.new_empty((head_logit.size(0					), self.n_token)					)
               else:
                    _snake_case													=			torch.zeros_like(lowerCAmelCase_			,  dtype=hidden.dtype			,  device=hidden.device					)

               _snake_case													=			0
               _snake_case													=			[0] + self.cutoffs
               for i in range(len(lowerCAmelCase_					) - 1					):
                    _snake_case													=			cutoff_values[i], cutoff_values[i + 1]

                    if labels is not None:
                         _snake_case													=			(labels >= l_idx) & (labels < r_idx)
                         _snake_case													=			mask_i.nonzero().squeeze()

                         if indices_i.numel() == 0:
                              continue

                         _snake_case													=			labels.index_select(0			,  lowerCAmelCase_					) - l_idx
                         _snake_case													=			head_logprob.index_select(0			,  lowerCAmelCase_					)
                         _snake_case													=			hidden.index_select(0			,  lowerCAmelCase_					)
                    else:
                         _snake_case													=			hidden

                    if i == 0:
                         if labels is not None:
                              _snake_case													=			head_logprob_i.gather(1			,  target_i[:, None]					).squeeze(1					)
                         else:
                              _snake_case													=			head_logprob[:, : self.cutoffs[0]]
                    else:
                         _snake_case													=			weights[i], biases[i], self.out_projs[i]

                         _snake_case													=			self._compute_logit(lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_					)
                         _snake_case													=			nn.functional.log_softmax(lowerCAmelCase_			,  dim=1					)
                         _snake_case													=			self.cutoffs[0] + i - 1  # No probability for the head cluster
                         if labels is not None:
                              _snake_case													=			head_logprob_i[:, cluster_prob_idx] + tail_logprob_i.gather(
                                  1			,  target_i[:, None]					).squeeze(1					)
                         else:
                              _snake_case													=			head_logprob[:, cluster_prob_idx, None] + tail_logprob_i
                              _snake_case													=			logprob_i

                    if labels is not None:
                         if (hasattr(self			,  'keep_order'					) and self.keep_order) or keep_order:
                              out.index_copy_(0			,  lowerCAmelCase_			,  -logprob_i					)
                         else:
                              out[offset : offset + logprob_i.size(0					)].copy_(-logprob_i					)
                         offset += logprob_i.size(0					)

          return out






     def 		lowerCAmelCase     (						self			,  lowerCAmelCase_					)						->							Union[str, Any]:
          if self.n_clusters == 0:
               _snake_case													=			self._compute_logit(lowerCAmelCase_			,  self.out_layers[0].weight			,  self.out_layers[0].bias			,  self.out_projs[0]					)
               return nn.functional.log_softmax(lowerCAmelCase_			,  dim=-1					)
          else:
               # construct weights and biases
               _snake_case													=			[], []
               for i in range(len(self.cutoffs					)					):
                    if self.div_val == 1:
                         _snake_case													=			self.cutoff_ends[i], self.cutoff_ends[i + 1]
                         _snake_case													=			self.out_layers[0].weight[l_idx:r_idx]
                         _snake_case													=			self.out_layers[0].bias[l_idx:r_idx]
                    else:
                         _snake_case													=			self.out_layers[i].weight
                         _snake_case													=			self.out_layers[i].bias

                    if i == 0:
                         _snake_case													=			torch.cat([weight_i, self.cluster_weight]			,  dim=0					)
                         _snake_case													=			torch.cat([bias_i, self.cluster_bias]			,  dim=0					)

                    weights.append(lowerCAmelCase_					)
                    biases.append(lowerCAmelCase_					)

               _snake_case													=			weights[0], biases[0], self.out_projs[0]
               _snake_case													=			self._compute_logit(lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_					)

               _snake_case													=			hidden.new_empty((head_logit.size(0					), self.n_token)					)
               _snake_case													=			nn.functional.log_softmax(lowerCAmelCase_			,  dim=1					)

               _snake_case													=			[0] + self.cutoffs
               for i in range(len(lowerCAmelCase_					) - 1					):
                    _snake_case													=			cutoff_values[i], cutoff_values[i + 1]

                    if i == 0:
                         _snake_case													=			head_logprob[:, : self.cutoffs[0]]
                    else:
                         _snake_case													=			weights[i], biases[i], self.out_projs[i]

                         _snake_case													=			self._compute_logit(lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_					)
                         _snake_case													=			nn.functional.log_softmax(lowerCAmelCase_			,  dim=1					)

                         _snake_case													=			head_logprob[:, -i] + tail_logprob_i
                         _snake_case													=			logprob_i

               return out










from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast
from ...utils import logging


UpperCAmelCase_ 							=       logging.get_logger(__name__)

UpperCAmelCase_ 							=       {
    """EleutherAI/gpt-neo-1.3B""": """https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json""",
    # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo
}
class      UpperCamelCase_						(					_lowerCamelCase   ):
					lowerCAmelCase_							=		'''gpt_neo'''
					lowerCAmelCase_							=		['''past_key_values''']
					lowerCAmelCase_							=		{'''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''}




					def __init__(						self			,  lowerCAmelCase_=5_0257			,  lowerCAmelCase_=2048			,  lowerCAmelCase_=2048			,  lowerCAmelCase_=24			,  lowerCAmelCase_=[[["global", "local"], 12]]			,  lowerCAmelCase_=16			,  lowerCAmelCase_=None			,  lowerCAmelCase_=256			,  lowerCAmelCase_="gelu_new"			,  lowerCAmelCase_=0.0			,  lowerCAmelCase_=0.0			,  lowerCAmelCase_=0.0			,  lowerCAmelCase_=0.1			,  lowerCAmelCase_=1E-5			,  lowerCAmelCase_=0.02			,  lowerCAmelCase_=True			,  lowerCAmelCase_=5_0256			,  lowerCAmelCase_=5_0256			,  **lowerCAmelCase_			,  )						->							Tuple:
										_snake_case													=			vocab_size
										_snake_case													=			max_position_embeddings
										_snake_case													=			hidden_size
										_snake_case													=			num_layers
										_snake_case													=			num_heads
										_snake_case													=			intermediate_size
										_snake_case													=			window_size
										_snake_case													=			activation_function
										_snake_case													=			resid_dropout
										_snake_case													=			embed_dropout
										_snake_case													=			attention_dropout
										_snake_case													=			classifier_dropout
										_snake_case													=			layer_norm_epsilon
										_snake_case													=			initializer_range
										_snake_case													=			use_cache

										_snake_case													=			bos_token_id
										_snake_case													=			eos_token_id

										_snake_case													=			attention_types
										_snake_case													=			self.expand_attention_types_params(lowerCAmelCase_					)

										if len(self.attention_layers					) != self.num_layers:
															raise ValueError(
															    'Configuration for convolutional module is incorrect. '
															    'It is required that `len(config.attention_layers)` == `config.num_layers` '
															    F'''but is `len(config.attention_layers) = {len(self.attention_layers					)}`, '''
															    F'''`config.num_layers = {self.num_layers}`. '''
															    '`config.attention_layers` is prepared using `config.attention_types`. '
															    'Please verify the value of `config.attention_types` argument.'					)

										super().__init__(bos_token_id=lowerCAmelCase_			,  eos_token_id=lowerCAmelCase_			,  **lowerCAmelCase_					)






					@staticmethod
					def 		lowerCAmelCase     (						lowerCAmelCase_					)						->							Any:
										_snake_case													=			[]
										for item in attention_types:
															for _ in range(item[1]					):
																				attentions.extend(item[0]					)
										return attentions





def   lowerCamelCase__       (       UpperCamelCase__     :    Tuple    ,      UpperCamelCase__     :    int    ,      UpperCamelCase__     :    Tuple    ,      UpperCamelCase__     :    Optional[int]  )     ->	Any:



					'''simple docstring'''




					import torch

					_snake_case													=			input.size()
					_snake_case													=			len(UpperCamelCase__  )
					_snake_case													=			shape[dimension]

					_snake_case													=			torch.arange(0    ,      UpperCamelCase__    ,      UpperCamelCase__  )
					_snake_case													=			torch.div(sizedim - size    ,      UpperCamelCase__    ,      rounding_mode='floor'  ) + 1
					_snake_case													=			torch.arange(UpperCamelCase__  ) + low_indices[:min_length][:, None]

					_snake_case													=			[slice(UpperCamelCase__  )] * rank
					_snake_case													=			indices
					_snake_case													=			input[s]

					_snake_case													=			list(range(0    ,      rank + 1  )  )
					perm.append(perm.pop(dimension + 1  )  )

					return sliced.permute(UpperCamelCase__  )





def   lowerCamelCase__       (       UpperCamelCase__     :    Tuple    ,      UpperCamelCase__     :    Dict  )     ->	str:



					'''simple docstring'''




					import torch

					_snake_case													=			torch.arange(1    ,      UpperCamelCase__  )
					_snake_case													=			torch.remainder(UpperCamelCase__    ,      UpperCamelCase__  )
					_snake_case													=			remainders == 0
					_snake_case													=			candidates[divisor_indices]
					_snake_case													=			torch.max(UpperCamelCase__  )
					return largest_divisor, torch.div(UpperCamelCase__    ,      UpperCamelCase__    ,      rounding_mode='floor'  )




class      UpperCamelCase_						(					_lowerCamelCase   ):




					@property
					def 		lowerCAmelCase     (						self					)						->							Mapping[str, Mapping[int, str]]:
										_snake_case													=			OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}					)
										if self.use_past:
															self.fill_with_past_key_values_(lowerCAmelCase_			,  direction='inputs'					)
															_snake_case													=			{0: 'batch', 1: 'past_sequence + sequence'}
										else:
															_snake_case													=			{0: 'batch', 1: 'sequence'}

										return common_inputs




					@property
					def 		lowerCAmelCase     (						self					)						->							int:
										return self._config.num_heads




					def 		lowerCAmelCase     (						self			,  lowerCAmelCase_			,  lowerCAmelCase_ = -1			,  lowerCAmelCase_ = -1			,  lowerCAmelCase_ = False			,  lowerCAmelCase_ = None			,  )						->							Mapping[str, Any]:
										_snake_case													=			super(lowerCAmelCase_			,  self					).generate_dummy_inputs(
										    lowerCAmelCase_			,  batch_size=lowerCAmelCase_			,  seq_length=lowerCAmelCase_			,  is_pair=lowerCAmelCase_			,  framework=lowerCAmelCase_					)

										# We need to order the input in the way they appears in the forward()
										_snake_case													=			OrderedDict({'input_ids': common_inputs['input_ids']}					)

										# Need to add the past_keys
										if self.use_past:
															if not is_torch_available():
																				raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'					)
															else:
																				import torch

																				_snake_case							,       _snake_case													=			common_inputs['input_ids'].shape
																				# Not using the same length for past_key_values
																				_snake_case													=			seqlen + 2
																				_snake_case													=			(
																				    batch,
																				    self.num_attention_heads,
																				    past_key_values_length,
																				    self._config.hidden_size // self.num_attention_heads,
																				)
																				_snake_case													=			[
																				    (torch.zeros(lowerCAmelCase_					), torch.zeros(lowerCAmelCase_					)) for _ in range(self.num_layers					)
																				]

										_snake_case													=			common_inputs['attention_mask']
										if self.use_past:
															_snake_case													=			ordered_inputs['attention_mask'].dtype
															_snake_case													=			torch.cat(
															    [ordered_inputs['attention_mask'], torch.ones(lowerCAmelCase_			,  lowerCAmelCase_			,  dtype=lowerCAmelCase_					)]			,  dim=1					)

										return ordered_inputs






					@property
					def 		lowerCAmelCase     (						self					)						->							int:
										return 13



