jamesHD2001 commited on
Commit
cc650a6
1 Parent(s): 1e1eb6f

Upload 10 files

Browse files

update third-party huggingface compatible models for DenseMamba: https://arxiv.org/abs/2403.00818

added_tokens.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "[PAD]": 32000
3
+ }
config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoConfig": "modeling_dense_gau_retnet.DenseGauRetNetConfig",
4
+ "AutoModelForCausalLM": "modeling_dense_gau_retnet.DenseGauRetNetForCausalLM",
5
+ "AutoModelForSequenceClassification": "modeling_dense_gau_retnet.DenseGauRetNetForSequenceClassification"
6
+ },
7
+ "bos_token_id": 1,
8
+ "eos_token_id": 2,
9
+ "hidden_act": "silu",
10
+ "hidden_size": 1536,
11
+ "query_key_dim": 768,
12
+ "initializer_range": 0.02,
13
+ "max_position_embeddings": 2048,
14
+ "model_type": "DenseGauRetNet",
15
+ "num_attention_heads": 2,
16
+ "num_hidden_layers": 16,
17
+ "pad_token_id": 0,
18
+ "rms_norm_eps": 1e-06,
19
+ "layernorm_eps": 1e-5,
20
+ "retnorm": false,
21
+ "tie_word_embeddings": false,
22
+ "torch_dtype": "float16",
23
+ "transformers_version": "4.29.1",
24
+ "use_cache": false,
25
+ "vocab_size": 32001,
26
+ "v_factor": 2,
27
+ "intermediate_k_select_scale": 8,
28
+ "intermediate_v_select_scale": 32,
29
+ "dense_block_layers": 2,
30
+ "dropout": 0.1,
31
+ "deepnorm": false
32
+ }
configuration_dense_gau_retnet.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the Huggingface Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ DenseGauRetNet model configuration"""
21
+
22
+ from transformers.utils import logging
23
+ from transformers.configuration_utils import PretrainedConfig
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+ DenseGauRetNet_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
28
+
29
+
30
+ class DenseGauRetNetConfig(PretrainedConfig):
31
+ model_type = "DenseGauRetNet"
32
+ _auto_class = "AutoConfig"
33
+
34
+ def __init__(
35
+ self,
36
+ hidden_act: str = "silu",
37
+ hidden_size: int = 1536,
38
+ query_key_dim: int = 768,
39
+ initializer_range: float = 0.02,
40
+ max_position_embeddings: int = 2048,
41
+ num_attention_heads: int = 2,
42
+ num_hidden_layers: int = 16,
43
+ rms_norm_eps: float = 1e-06,
44
+ layernorm_eps: float = 1e-5,
45
+ retnorm: bool = False,
46
+ vocab_size: int = 32001,
47
+ v_factor: int = 2,
48
+ intermediate_k_select_scale: int = 8,
49
+ intermediate_v_select_scale: int = 32,
50
+ dense_block_layers: int = 2,
51
+ dropout: float = 0.1,
52
+ use_cache: bool = False,
53
+ deepnorm: bool = False,
54
+ pad_token_id=0,
55
+ bos_token_id=1,
56
+ eos_token_id=2,
57
+ tie_word_embeddings=False,
58
+
59
+ **kwargs,
60
+ ):
61
+ self.hidden_act = hidden_act
62
+ self.hidden_size = hidden_size
63
+ self.query_key_dim = query_key_dim
64
+ self.initializer_range = initializer_range
65
+ self.max_position_embeddings = max_position_embeddings
66
+ self.num_attention_heads = num_attention_heads
67
+ self.num_hidden_layers = num_hidden_layers
68
+ self.rms_norm_eps = rms_norm_eps
69
+ self.layernorm_eps = layernorm_eps
70
+ self.retnorm = retnorm
71
+ self.vocab_size = vocab_size
72
+ self.v_factor = v_factor
73
+ self.intermediate_k_select_scale = intermediate_k_select_scale
74
+ self.intermediate_v_select_scale = intermediate_v_select_scale
75
+ self.dense_block_layers = dense_block_layers
76
+ self.dropout = dropout
77
+ self.use_cache = use_cache
78
+ self.deepnorm = deepnorm
79
+
80
+ super().__init__(
81
+ pad_token_id=pad_token_id,
82
+ bos_token_id=bos_token_id,
83
+ eos_token_id=eos_token_id,
84
+ tie_word_embeddings=tie_word_embeddings,
85
+ **kwargs,
86
+ )
generation_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "pad_token_id": 0,
6
+ "transformers_version": "4.29.1",
7
+ "use_cache": false
8
+ }
modeling_dense_gau_retnet.py ADDED
@@ -0,0 +1,980 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the Huggingface Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ Pytorch DenseGAU RetNet model."""
21
+ from typing import List, Optional, Tuple, Union
22
+ import math
23
+ import torch
24
+ import torch.utils.checkpoint
25
+ import torch.nn.functional as F
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, \
29
+ SequenceClassifierOutputWithPast
30
+ from transformers.modeling_utils import PreTrainedModel
31
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, \
32
+ replace_return_docstrings
33
+ from transformers import top_k_top_p_filtering
34
+ from transformers.generation.configuration_utils import GenerationConfig
35
+ from .configuration_dense_gau_retnet import DenseGauRetNetConfig
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+ _CONFIG_FOR_DOC = "DenseGauRetNetConfig"
40
+
41
+
42
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
43
+ def _make_causal_mask(
44
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
45
+ ):
46
+ """
47
+ Make causal mask used for bi-directional self-attention.
48
+ """
49
+ bsz, tgt_len = input_ids_shape
50
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
51
+ mask_cond = torch.arange(mask.size(-1), device=device)
52
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
53
+ mask = mask.to(dtype)
54
+
55
+ if past_key_values_length > 0:
56
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
57
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
58
+
59
+
60
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
61
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
62
+ """
63
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
64
+ """
65
+ bsz, src_len = mask.size()
66
+ tgt_len = tgt_len if tgt_len is not None else src_len
67
+
68
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
69
+
70
+ inverted_mask = 1.0 - expanded_mask
71
+
72
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
73
+
74
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm
75
+ class DenseGauRetNetRMSNorm(nn.Module):
76
+ def __init__(self, hidden_size, eps=1e-6):
77
+ super().__init__()
78
+ self.weight = nn.Parameter(torch.ones(hidden_size))
79
+ self.variance_epsilon = eps
80
+
81
+ def forward(self, hidden_states):
82
+ input_dtype = hidden_states.dtype
83
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
84
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
85
+
86
+ return (self.weight * hidden_states).to(input_dtype)
87
+
88
+ # added for retention
89
+ # Copied from https://github.com/microsoft/torchscale/blob/main/torchscale/component/multiscale_retention.py
90
+ def rotate_every_two(x):
91
+ x1 = x[:, :, :, ::2]
92
+ x2 = x[:, :, :, 1::2]
93
+ x = torch.stack((-x2, x1), dim=-1)
94
+ return x.flatten(-2) # in einsum notation: rearrange(x, '... d j -> ... (d j)')\
95
+ def theta_shift(x, sin, cos):
96
+ return (x * cos) + (rotate_every_two(x) * sin)
97
+
98
+
99
+ #Parameter efficient HiddenProjection
100
+ class HiddenProjection(nn.Module):
101
+ def __init__(self, input_dim, mid_reduction_ratio=16, final_reduction_ratio=4):
102
+ super(HiddenProjection, self).__init__()
103
+ self.fc1 = nn.Linear(input_dim, input_dim // mid_reduction_ratio, bias=False)
104
+ self.fc2 = nn.Linear(input_dim // mid_reduction_ratio, int(input_dim // final_reduction_ratio), bias=False)
105
+
106
+ def forward(self, x):
107
+ fc1_output = F.silu(self.fc1(x))
108
+ fc2_output = self.fc2(fc1_output)
109
+ return fc2_output
110
+
111
+ # Copied and modified from transformers.models.bart.modeling_bart._expand_mask
112
+
113
+ class MultiScaleGauRetention(nn.Module):
114
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
115
+
116
+ def __init__(self, config: DenseGauRetNetConfig):
117
+ super().__init__()
118
+ self.config = config
119
+ self.hidden_size = config.hidden_size
120
+ self.query_key_dim = config.query_key_dim
121
+ self.num_heads = config.num_attention_heads
122
+ self.factor = config.v_factor
123
+ self.head_dim = config.hidden_size * self.factor // self.num_heads
124
+ self.max_position_embeddings = config.max_position_embeddings
125
+ self.q_proj = nn.Linear(self.hidden_size, self.query_key_dim, bias=False)
126
+ self.k_proj = nn.Linear(self.hidden_size, self.query_key_dim, bias=False)
127
+ self.key_dim = self.query_key_dim // self.num_heads
128
+ self.scaling = self.key_dim ** -0.5
129
+ self.expansion_dim = int(config.hidden_size * self.factor)
130
+ self.group_norm = DenseGauRetNetRMSNorm(self.expansion_dim // config.num_attention_heads, eps=config.rms_norm_eps)
131
+ self.to_hidden = nn.Sequential(
132
+ nn.Linear(config.hidden_size, self.expansion_dim * 2, bias=False),
133
+ nn.SiLU()
134
+ )
135
+ self.to_out = nn.Sequential(
136
+ nn.Linear(self.expansion_dim, config.hidden_size, bias=False),
137
+ nn.Dropout(0)
138
+ )
139
+ self.config = config
140
+ self.k_select = HiddenProjection(self.hidden_size, config.intermediate_k_select_scale, 2)
141
+ self.v_select = HiddenProjection(self.hidden_size, config.intermediate_v_select_scale, 0.5)
142
+ self.k_norm = DenseGauRetNetRMSNorm(self.query_key_dim, eps=config.rms_norm_eps)
143
+ self.v_norm = DenseGauRetNetRMSNorm(self.expansion_dim, eps=config.rms_norm_eps)
144
+ if config.deepnorm:
145
+ self.alpha = math.pow(2.0 * config.num_hidden_layers, 0.25)
146
+ else:
147
+ self.alpha = 1.0
148
+ self.dropout_module = torch.nn.Dropout(config.dropout)
149
+ self.reset_parameters()
150
+
151
+ #
152
+ def reset_parameters(self):
153
+ nn.init.xavier_uniform_(self.q_proj.weight, gain=2 ** -2.5)
154
+ nn.init.xavier_uniform_(self.k_proj.weight, gain=2 ** -2.5)
155
+ nn.init.xavier_uniform_(self.k_select.fc1.weight, gain=2 ** -2.5)
156
+ nn.init.xavier_uniform_(self.k_select.fc2.weight, gain=2 ** -2.5)
157
+ nn.init.xavier_uniform_(self.v_select.fc1.weight, gain=2 ** -2.5)
158
+ nn.init.xavier_uniform_(self.v_select.fc2.weight, gain=2 ** -2.5)
159
+ for module in self.to_out.modules():
160
+ if isinstance(module, nn.Linear):
161
+ nn.init.xavier_uniform_(module.weight, gain=2 ** -1)
162
+ for module in self.to_hidden.modules():
163
+ if isinstance(module, nn.Linear):
164
+ nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
165
+
166
+ def forward(
167
+ self,
168
+ forward_impl: 'parallel',
169
+ hidden_states: torch.Tensor,
170
+ rel_pos,
171
+ attention_mask: Optional[torch.Tensor] = None,
172
+ position_ids: Optional[torch.LongTensor] = None,
173
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
174
+ output_attentions: bool = False,
175
+ k_features=None, # dense
176
+ v_features=None, # dense
177
+ dense=False,
178
+ dense_layers=0,
179
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
180
+ bsz, tgt_len, _ = hidden_states.size()
181
+ (sin, cos), inner_mask = rel_pos
182
+ x = hidden_states
183
+ q = F.silu(self.q_proj(x))
184
+ k = F.silu(self.k_proj(x))
185
+ v, gate = self.to_hidden(x).chunk(2, dim=-1)
186
+
187
+ k *= self.scaling
188
+ k_curr = k
189
+ v_curr = v
190
+
191
+ if dense:
192
+ k_gate = self.k_select(hidden_states.clone())
193
+ for i, k_past in enumerate(k_features):
194
+ k = k.clone() + F.silu(k_gate) * k_past
195
+ k = self.k_norm(k)
196
+
197
+ v_gate = self.v_select(hidden_states.clone())
198
+ for i, v_past in enumerate(v_features):
199
+ v = v.clone() + F.silu(v_gate) * v_past
200
+ v = self.v_norm(v)
201
+
202
+ q = q.view(bsz, tgt_len, self.num_heads, self.key_dim).transpose(1, 2)
203
+ k = k.view(bsz, tgt_len, self.num_heads, self.key_dim).transpose(1, 2)
204
+ qr = theta_shift(q, sin, cos)
205
+ kr = theta_shift(k, sin, cos)
206
+
207
+ if forward_impl == 'parallel':
208
+ output = self.parallel_forward(qr, kr, v, inner_mask)
209
+ elif forward_impl == 'recurrent':
210
+ output, past_key_value = self.recurrent_forward(qr, kr, v, inner_mask, past_key_value=past_key_value)
211
+
212
+ output = self.group_norm(output)
213
+ output = output.reshape(bsz, tgt_len, self.expansion_dim) * gate # gate
214
+ output = self.to_out(output)
215
+ output = self.dropout_module(output)
216
+
217
+ return output, past_key_value, k_curr, v_curr
218
+
219
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
220
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
221
+
222
+ # retntion parallel forward
223
+ def recurrent_forward(
224
+ self,
225
+ qr, kr, v,
226
+ decay,
227
+ past_key_value,
228
+ ):
229
+ bsz = v.size(0)
230
+
231
+ v = v.view(bsz, self.num_heads, self.head_dim, 1)
232
+ kv = kr * v
233
+ if "prev_key_value" in past_key_value:
234
+ prev_kv = past_key_value["prev_key_value"]
235
+ prev_scale = past_key_value["scale"]
236
+ scale = prev_scale * decay + 1
237
+ kv = prev_kv * (prev_scale.sqrt() * decay / scale.sqrt()).view(self.num_heads, 1,
238
+ 1) + kv / scale.sqrt().view(self.num_heads,
239
+ 1, 1)
240
+ else:
241
+ scale = torch.ones_like(decay)
242
+
243
+ past_key_value["prev_key_value"] = kv
244
+ past_key_value["scale"] = scale
245
+
246
+ output = torch.sum(qr * kv, dim=3)
247
+ return output, past_key_value
248
+
249
+ def parallel_forward(self, qr, kr, v, mask):
250
+ bsz, tgt_len, embed_dim = v.size()
251
+
252
+ vr = v.view(bsz, tgt_len, self.num_heads, self.expansion_dim // self.num_heads).transpose(1, 2)
253
+
254
+ qk_mat = qr @ kr.transpose(-1, -2) # bsz * m * tgt_len * tgt_len
255
+ qk_mat = qk_mat * mask
256
+ # invariant after normalization
257
+ qk_mat = qk_mat / qk_mat.detach().abs().sum(dim=-1, keepdim=True).clamp(min=1, max=5e4)
258
+
259
+ output = torch.matmul(qk_mat, vr)
260
+ output = output.transpose(1, 2)
261
+ return output
262
+
263
+
264
+ class DenseGauRetNetDecoderLayer(nn.Module):
265
+ def __init__(self, config: DenseGauRetNetConfig):
266
+ super().__init__()
267
+ self.hidden_size = config.hidden_size
268
+ self.self_attn = MultiScaleGauRetention(config=config)
269
+ self.input_layernorm = DenseGauRetNetRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
270
+ if config.deepnorm:
271
+ self.alpha = math.pow(2.0 * config.num_hidden_layers, 0.25)
272
+ else:
273
+ self.alpha = 1.0
274
+
275
+ def forward(
276
+ self,
277
+ hidden_states: torch.Tensor,
278
+ rel_pos=None,
279
+ attention_mask: Optional[torch.Tensor] = None,
280
+ position_ids: Optional[torch.LongTensor] = None,
281
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
282
+ output_attentions: Optional[bool] = False,
283
+ k_features: Optional[List] = [],
284
+ v_features: Optional[List] = [],
285
+ dense=False,
286
+ dense_layers=0,
287
+ forward_impl: str = 'parallel',
288
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
289
+
290
+ residual = hidden_states
291
+ hidden_states = self.input_layernorm(hidden_states)
292
+ hidden_states, past_key_value, k_curr, v_curr = self.self_attn(
293
+
294
+ hidden_states=hidden_states,
295
+ rel_pos=rel_pos,
296
+ attention_mask=attention_mask,
297
+ position_ids=position_ids,
298
+ past_key_value=past_key_value,
299
+ output_attentions=output_attentions,
300
+ k_features=k_features,
301
+ v_features=v_features,
302
+ dense=dense,
303
+ dense_layers=dense_layers,
304
+ forward_impl=forward_impl,
305
+
306
+ )
307
+ hidden_states = residual + hidden_states
308
+
309
+ return hidden_states, past_key_value, k_curr, v_curr
310
+
311
+
312
+ DenseGauRetNet_START_DOCSTRING = r"""
313
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
314
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
315
+ etc.)
316
+
317
+ This model is also a Pytorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
318
+ Use it as a regular Pytorch Module and refer to the Pytorch documentation for all matter related to general usage
319
+ and behavior.
320
+
321
+ Parameters:
322
+ config ([`DenseGauRetNetConfig`]):
323
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
324
+ load the weights associated with the model, only the configuration. Check out the
325
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
326
+ """
327
+
328
+
329
+ @add_start_docstrings(
330
+ "The bare DenseGauRetNet Model outputting raw hidden-states without any specific head on top.",
331
+ DenseGauRetNet_START_DOCSTRING,
332
+ )
333
+ class DenseGauRetNetPreTrainedModel(PreTrainedModel):
334
+ config_class = DenseGauRetNetConfig
335
+ base_model_prefix = "model"
336
+ supports_gradient_checkpointing = True
337
+ _no_split_modules = ["DenseGauRetNetDecoderLayer"]
338
+ _skip_keys_device_placement = "past_key_values"
339
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
340
+
341
+ def _init_weights(self, module):
342
+ std = self.config.initializer_range
343
+ if isinstance(module, nn.Linear):
344
+ module.weight.data.normal_(mean=0.0, std=std)
345
+ if module.bias is not None:
346
+ module.bias.data.zero_()
347
+ elif isinstance(module, nn.Embedding):
348
+ module.weight.data.normal_(mean=0.0, std=std)
349
+ if module.padding_idx is not None:
350
+ module.weight.data[module.padding_idx].zero_()
351
+
352
+ def _set_gradient_checkpointing(self, module, value=False):
353
+ if isinstance(module, DenseGauRetNetModel):
354
+ module.gradient_checkpointing = value
355
+
356
+
357
+ DenseGauRetNet_INPUTS_DOCSTRING = r"""
358
+ Args:
359
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
360
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
361
+ it.
362
+
363
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
364
+ [`PreTrainedTokenizer.__call__`] for details.
365
+
366
+ [What are input IDs?](../glossary#input-ids)
367
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
368
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
369
+
370
+ - 1 for tokens that are **not masked**,
371
+ - 0 for tokens that are **masked**.
372
+
373
+ [What are attention masks?](../glossary#attention-mask)
374
+
375
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
376
+ [`PreTrainedTokenizer.__call__`] for details.
377
+
378
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
379
+ `past_key_values`).
380
+
381
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
382
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
383
+ information on the default strategy.
384
+
385
+ - 1 indicates the head is **not masked**,
386
+ - 0 indicates the head is **masked**.
387
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
388
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
389
+ config.n_positions - 1]`.
390
+
391
+ [What are position IDs?](../glossary#position-ids)
392
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
393
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
394
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
395
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
396
+
397
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
398
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
399
+
400
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
401
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
402
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
403
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
404
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
405
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
406
+ model's internal embedding lookup matrix.
407
+ use_cache (`bool`, *optional*):
408
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
409
+ `past_key_values`).
410
+ output_attentions (`bool`, *optional*):
411
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
412
+ tensors for more detail.
413
+ output_hidden_states (`bool`, *optional*):
414
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
415
+ more detail.
416
+ return_dict (`bool`, *optional*):
417
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
418
+ """
419
+
420
+
421
+ class RetNetRelPos(nn.Module):
422
+ def __init__(self, decoder_embed_dim, decoder_retention_heads, query_key_dim):
423
+ super().__init__()
424
+ angle = 1.0 / (10000 ** torch.linspace(0, 1, (query_key_dim // decoder_retention_heads) // 2))
425
+ angle = angle.unsqueeze(-1).repeat(1, 2).flatten()
426
+ decay = torch.log(1 - 2 ** (-5 - torch.arange(decoder_retention_heads, dtype=torch.float)))
427
+ self.register_buffer("angle", angle)
428
+ self.register_buffer("decay", decay)
429
+
430
+ def forward(self, slen, activate_recurrent=False):
431
+ if activate_recurrent:
432
+ sin = torch.sin(self.angle * (slen - 1))
433
+ cos = torch.cos(self.angle * (slen - 1))
434
+ retention_rel_pos = ((sin, cos), self.decay.exp())
435
+ else:
436
+ index = torch.arange(slen).to(self.decay)
437
+ sin = torch.sin(index[:, None] * self.angle[None, :])
438
+ cos = torch.cos(index[:, None] * self.angle[None, :])
439
+ mask = torch.tril(torch.ones(slen, slen).to(self.decay))
440
+ mask = torch.masked_fill(index[:, None] - index[None, :], ~mask.bool(), float("inf"))
441
+ mask = torch.exp(mask * self.decay[:, None, None])
442
+ mask = torch.nan_to_num(mask)
443
+ mask = mask / mask.sum(dim=-1, keepdim=True).sqrt()
444
+ retention_rel_pos = ((sin, cos), mask)
445
+
446
+ return retention_rel_pos
447
+
448
+
449
+ @add_start_docstrings(
450
+ "The bare DenseGauRetNet Model outputting raw hidden-states without any specific head on top.",
451
+ DenseGauRetNet_START_DOCSTRING,
452
+ )
453
+ class DenseGauRetNetModel(DenseGauRetNetPreTrainedModel):
454
+ """
455
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DenseGauRetNetDecoderLayer`]
456
+
457
+ Args:
458
+ config: DenseGauRetNetConfig
459
+ """
460
+
461
+ def __init__(self, config: DenseGauRetNetConfig):
462
+ super().__init__(config)
463
+ self.padding_idx = config.pad_token_id
464
+ self.vocab_size = config.vocab_size
465
+
466
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
467
+ self.layers = nn.ModuleList([DenseGauRetNetDecoderLayer(config) for _ in range(config.num_hidden_layers)])
468
+ self.norm = DenseGauRetNetRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
469
+
470
+ self.gradient_checkpointing = False
471
+ # Initialize weights and apply final processing
472
+ self.post_init()
473
+ self.retnet_rel_pos = RetNetRelPos(config.hidden_size, config.num_attention_heads,
474
+ config.query_key_dim)
475
+
476
+ if config.deepnorm:
477
+ init_scale = math.pow(8.0 * config.num_hidden_layers, 0.25)
478
+ for name, p in self.named_parameters():
479
+
480
+ if (
481
+ "fc1" in name
482
+ or "fc2" in name
483
+ or "gate_proj" in name
484
+ or "down_proj" in name
485
+ or "up_proj" in name
486
+ or "out_proj" in name
487
+ or "v_proj" in name
488
+ or "to_hidden" in name
489
+ or "to_output" in name
490
+
491
+ ):
492
+ p.data.div_(init_scale)
493
+
494
+ def get_input_embeddings(self):
495
+ return self.embed_tokens
496
+
497
+ def set_input_embeddings(self, value):
498
+ self.embed_tokens = value
499
+
500
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
501
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
502
+ # create causal mask
503
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
504
+ combined_attention_mask = None
505
+ if input_shape[-1] > 1:
506
+ combined_attention_mask = _make_causal_mask(
507
+ input_shape,
508
+ inputs_embeds.dtype,
509
+ device=inputs_embeds.device,
510
+ past_key_values_length=past_key_values_length,
511
+ )
512
+
513
+ if attention_mask is not None:
514
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
515
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
516
+ inputs_embeds.device
517
+ )
518
+ combined_attention_mask = (
519
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
520
+ )
521
+
522
+ return combined_attention_mask
523
+
524
+ def is_first_step(self, incremental_state):
525
+ if incremental_state is None:
526
+ return False
527
+ return incremental_state.get("is_first_step", False)
528
+
529
+ @add_start_docstrings_to_model_forward(DenseGauRetNet_INPUTS_DOCSTRING)
530
+ def forward(
531
+ self,
532
+ forward_impl: Optional[str] = 'parallel',
533
+ input_ids: torch.LongTensor = None,
534
+ attention_mask: Optional[torch.Tensor] = None,
535
+ position_ids: Optional[torch.LongTensor] = None,
536
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
537
+ inputs_embeds: Optional[torch.FloatTensor] = None,
538
+ use_cache: Optional[bool] = None,
539
+ output_attentions: Optional[bool] = None,
540
+ output_hidden_states: Optional[bool] = None,
541
+ return_dict: Optional[bool] = None,
542
+ sequence_offset=0,
543
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
544
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
545
+ output_hidden_states = (
546
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
547
+ )
548
+
549
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
550
+
551
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
552
+
553
+ # retrieve input_ids and inputs_embeds
554
+ if input_ids is not None and inputs_embeds is not None:
555
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
556
+ elif input_ids is not None:
557
+ batch_size, seq_length = input_ids.shape
558
+ elif inputs_embeds is not None:
559
+ batch_size, seq_length, _ = inputs_embeds.shape
560
+ else:
561
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
562
+
563
+ seq_length_with_past = seq_length
564
+ past_key_values_length = 0
565
+
566
+ if position_ids is None:
567
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
568
+ position_ids = torch.arange(
569
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
570
+ )
571
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
572
+ else:
573
+ position_ids = position_ids.view(-1, seq_length).long()
574
+
575
+ if inputs_embeds is None:
576
+ inputs_embeds = self.embed_tokens(input_ids)
577
+ # embed positions
578
+ if attention_mask is None:
579
+ attention_mask = torch.ones(
580
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
581
+ )
582
+ attention_mask = self._prepare_decoder_attention_mask(
583
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
584
+ )
585
+
586
+ hidden_states = inputs_embeds
587
+
588
+ if self.gradient_checkpointing and self.training:
589
+ if use_cache:
590
+ logger.warning_once(
591
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
592
+ )
593
+ use_cache = False
594
+
595
+ # decoder layer
596
+ all_hidden_states = () if output_hidden_states else None
597
+ all_self_attns = () if output_attentions else None
598
+ next_decoder_cache = [] if use_cache else None
599
+
600
+ #
601
+ k_features = []
602
+ v_features = []
603
+ dense_layers = 0
604
+ for idx, decoder_layer in enumerate(self.layers):
605
+ if output_hidden_states:
606
+ all_hidden_states += (hidden_states,)
607
+ past_key_value = past_key_values[idx] if past_key_values is not None and len(
608
+ past_key_values) != 0 else {}
609
+
610
+ slen = input_ids.size(1)
611
+ if forward_impl == 'recurrent':
612
+ slen = sequence_offset
613
+ rel_pos = self.retnet_rel_pos(slen, forward_impl == 'recurrent',)
614
+
615
+ if self.gradient_checkpointing and self.training:
616
+
617
+ def create_custom_forward(module):
618
+ def custom_forward(*inputs):
619
+ return module(*inputs, output_attentions, None)
620
+
621
+ return custom_forward
622
+
623
+ hidden_states = layer_outputslayer_outputs = torch.utils.checkpoint.checkpoint(
624
+ create_custom_forward(decoder_layer),
625
+ hidden_states,
626
+ attention_mask,
627
+ position_ids,
628
+ None,
629
+ )
630
+ else:
631
+ dense = False
632
+ if idx >= 1:
633
+ dense = True
634
+
635
+ layer_outputs, past_key_value, k_curr, v_curr = decoder_layer(
636
+ hidden_states,
637
+ rel_pos,
638
+ forward_impl=forward_impl,
639
+ attention_mask=attention_mask,
640
+ position_ids=position_ids,
641
+ past_key_value=past_key_value,
642
+ output_attentions=output_attentions,
643
+ k_features=k_features,
644
+ v_features=v_features,
645
+ dense=dense,
646
+ dense_layers=dense_layers,
647
+ )
648
+ dense_layers += 1
649
+ k_features.append(k_curr)
650
+ v_features.append(v_curr)
651
+ if len(k_features) > self.config.dense_block_layers:
652
+ k_features.pop(0)
653
+ if len(v_features) > self.config.dense_block_layers:
654
+ v_features.pop(0)
655
+
656
+ hidden_states = layer_outputs # used to be 3 ele,tmp 1
657
+
658
+
659
+ if use_cache:
660
+ next_decoder_cache.append(past_key_value)
661
+
662
+ if output_attentions:
663
+ all_self_attns += (layer_outputs[1],)
664
+
665
+ hidden_states = self.norm(hidden_states)
666
+
667
+ # add hidden states from the last decoder layer
668
+ if output_hidden_states:
669
+ all_hidden_states += (hidden_states,)
670
+
671
+ next_cache = next_decoder_cache if use_cache else None
672
+ if not return_dict:
673
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
674
+ return BaseModelOutputWithPast(
675
+ last_hidden_state=hidden_states,
676
+ past_key_values=next_cache,
677
+ hidden_states=all_hidden_states,
678
+ attentions=all_self_attns,
679
+ )
680
+
681
+
682
+ class DenseGauRetNetForCausalLM(DenseGauRetNetPreTrainedModel):
683
+ _auto_class = "AutoModelForCausalLM"
684
+ _tied_weights_keys = ["lm_head.weight"]
685
+
686
+ def __init__(self, config):
687
+ super().__init__(config)
688
+ self.model = DenseGauRetNetModel(config)
689
+
690
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
691
+
692
+ # Initialize weights and apply final processing
693
+ self.post_init()
694
+
695
+ def get_input_embeddings(self):
696
+ return self.model.embed_tokens
697
+
698
+ def set_input_embeddings(self, value):
699
+ self.model.embed_tokens = value
700
+
701
+ def get_output_embeddings(self):
702
+ return self.lm_head
703
+
704
+ def set_output_embeddings(self, new_embeddings):
705
+ self.lm_head = new_embeddings
706
+
707
+ def set_decoder(self, decoder):
708
+ self.model = decoder
709
+
710
+ def get_decoder(self):
711
+ return self.model
712
+
713
+ @add_start_docstrings_to_model_forward(DenseGauRetNet_INPUTS_DOCSTRING)
714
+ #@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
715
+ def forward(
716
+ self,
717
+ input_ids: torch.LongTensor = None,
718
+ attention_mask: Optional[torch.Tensor] = None,
719
+ position_ids: Optional[torch.LongTensor] = None,
720
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
721
+ inputs_embeds: Optional[torch.FloatTensor] = None,
722
+ labels: Optional[torch.LongTensor] = None,
723
+ use_cache: Optional[bool] = None,
724
+ output_attentions: Optional[bool] = None,
725
+ output_hidden_states: Optional[bool] = None,
726
+ return_dict: Optional[bool] = None,
727
+ forward_impl: str = 'parallel',
728
+ sequence_offset=0,
729
+
730
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
731
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
732
+ output_hidden_states = (
733
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
734
+ )
735
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
736
+
737
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
738
+ outputs = self.model(
739
+ forward_impl=forward_impl,
740
+ input_ids=input_ids,
741
+ attention_mask=attention_mask,
742
+ position_ids=position_ids,
743
+ past_key_values=past_key_values,
744
+ inputs_embeds=inputs_embeds,
745
+ use_cache=use_cache,
746
+ output_attentions=output_attentions,
747
+ output_hidden_states=output_hidden_states,
748
+ return_dict=return_dict,
749
+ sequence_offset=sequence_offset,
750
+ )
751
+
752
+ hidden_states = outputs[0]
753
+ logits = self.lm_head(hidden_states)
754
+
755
+ loss = None
756
+ if labels is not None:
757
+ # Shift so that tokens < n predict n
758
+ shift_logits = logits[..., :-1, :].contiguous()
759
+ shift_labels = labels[..., 1:].contiguous()
760
+ # Flatten the tokens
761
+ loss_fct = CrossEntropyLoss()
762
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
763
+ shift_labels = shift_labels.view(-1)
764
+ # Enable model parallelism
765
+ shift_labels = shift_labels.to(shift_logits.device)
766
+ loss = loss_fct(shift_logits, shift_labels)
767
+
768
+ if not return_dict:
769
+ output = (logits,) + outputs[1:]
770
+ return (loss,) + output if loss is not None else output
771
+
772
+ return CausalLMOutputWithPast(
773
+ loss=loss,
774
+ logits=logits,
775
+ past_key_values=outputs.past_key_values,
776
+ hidden_states=outputs.hidden_states,
777
+ attentions=outputs.attentions,
778
+ )
779
+
780
+ def prepare_inputs_for_generation(
781
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
782
+ ):
783
+ if past_key_values:
784
+ input_ids = input_ids[:, -1:]
785
+
786
+ position_ids = kwargs.get("position_ids", None)
787
+ if attention_mask is not None and position_ids is None:
788
+ # create position_ids on the fly for batch generation
789
+ position_ids = attention_mask.long().cumsum(-1) - 1
790
+ position_ids.masked_fill_(attention_mask == 0, 1)
791
+ if past_key_values:
792
+ position_ids = position_ids[:, -1].unsqueeze(-1)
793
+
794
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
795
+ if inputs_embeds is not None and past_key_values is None:
796
+ model_inputs = {"inputs_embeds": inputs_embeds}
797
+ else:
798
+ model_inputs = {"input_ids": input_ids}
799
+
800
+ model_inputs.update(
801
+ {
802
+ "position_ids": position_ids,
803
+ "past_key_values": past_key_values,
804
+ "use_cache": kwargs.get("use_cache"),
805
+ "attention_mask": attention_mask,
806
+ }
807
+ )
808
+ return model_inputs
809
+
810
+ @staticmethod
811
+ def _reorder_cache(past_key_values, beam_idx):
812
+ reordered_past = ()
813
+ for layer_past in past_key_values:
814
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
815
+ return reordered_past
816
+
817
+ # infer mode
818
+
819
+ def sample_token(self, logit, do_sample=False, top_k=1, top_p=1.0, temperature=1.0):
820
+ if not do_sample:
821
+ return torch.argmax(logit, dim=-1, keepdim=True)
822
+ filtered = top_k_top_p_filtering(logit / temperature, top_k=top_k, top_p=top_p)
823
+ return torch.multinomial(torch.softmax(filtered, dim=-1), num_samples=1)
824
+
825
+ @torch.inference_mode()
826
+ def generate(
827
+ self,
828
+ input_ids: Optional[torch.Tensor] = None,
829
+ parallel_compute_prompt=False,
830
+ generation_config: Optional[GenerationConfig] = None,
831
+ **kwargs,
832
+ ):
833
+ # breakpoint()
834
+ past_key_values = {}
835
+ for p_i in range(input_ids.shape[1] - 1):
836
+ outputs = self(input_ids[:, p_i:p_i + 1],
837
+ forward_impl='recurrent',
838
+ past_key_values=past_key_values,
839
+ sequence_offset=p_i,
840
+ return_dict=True,
841
+ use_cache=True)
842
+ past_key_values = outputs.past_key_values
843
+ generated = input_ids[:, -1].unsqueeze(-1) # [B, 1]
844
+ for i in range(generation_config.max_new_tokens):
845
+ outputs = self(generated[:,-1:],
846
+ forward_impl='recurrent',
847
+ past_key_values=past_key_values,
848
+ use_cache=True,
849
+ return_dict=True,
850
+ sequence_offset=input_ids.shape[-1]+generated.shape[-1]-2 #1
851
+ )
852
+ logit = outputs.logits[:, -1, :] # [batch_size, vocab_size]
853
+ past_key_values = outputs.past_key_values
854
+ token = self.sample_token(logit,
855
+ do_sample=generation_config.do_sample,
856
+ temperature=generation_config.temperature)
857
+
858
+ generated = torch.cat([generated, token], dim=-1)
859
+ return generated[:,1:]
860
+
861
+
862
+ @add_start_docstrings(
863
+ """
864
+ The DenseGauRetNet Model transformer with a sequence classification head on top (linear layer).
865
+
866
+ [`DenseGauRetNetForSequenceClassification`] uses the last token in order to do the classification, as other causal models
867
+ (e.g. GPT-2) do.
868
+
869
+ Since it does classification on the last token, it requires to know the position of the last token. If a
870
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
871
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
872
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
873
+ each row of the batch).
874
+ """,
875
+ DenseGauRetNet_START_DOCSTRING,
876
+ )
877
+ class DenseGauRetNetForSequenceClassification(DenseGauRetNetPreTrainedModel):
878
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
879
+
880
+ def __init__(self, config):
881
+ super().__init__(config)
882
+ self.num_labels = config.num_labels
883
+ self.model = DenseGauRetNetModel(config)
884
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
885
+
886
+ # Initialize weights and apply final processing
887
+ self.post_init()
888
+
889
+ def get_input_embeddings(self):
890
+ return self.model.embed_tokens
891
+
892
+ def set_input_embeddings(self, value):
893
+ self.model.embed_tokens = value
894
+
895
+ @add_start_docstrings_to_model_forward(DenseGauRetNet_INPUTS_DOCSTRING)
896
+ def forward(
897
+ self,
898
+ input_ids: torch.LongTensor = None,
899
+ attention_mask: Optional[torch.Tensor] = None,
900
+ position_ids: Optional[torch.LongTensor] = None,
901
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
902
+ inputs_embeds: Optional[torch.FloatTensor] = None,
903
+ labels: Optional[torch.LongTensor] = None,
904
+ use_cache: Optional[bool] = None,
905
+ output_attentions: Optional[bool] = None,
906
+ output_hidden_states: Optional[bool] = None,
907
+ return_dict: Optional[bool] = None,
908
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
909
+ r"""
910
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
911
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
912
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
913
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
914
+ """
915
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
916
+
917
+ transformer_outputs = self.model(
918
+ input_ids,
919
+ attention_mask=attention_mask,
920
+ position_ids=position_ids,
921
+ past_key_values=past_key_values,
922
+ inputs_embeds=inputs_embeds,
923
+ use_cache=use_cache,
924
+ output_attentions=output_attentions,
925
+ output_hidden_states=output_hidden_states,
926
+ return_dict=return_dict,
927
+ )
928
+ hidden_states = transformer_outputs[0]
929
+ logits = self.score(hidden_states)
930
+ if input_ids is not None:
931
+ batch_size = input_ids.shape[0]
932
+ else:
933
+ batch_size = inputs_embeds.shape[0]
934
+
935
+ if self.config.pad_token_id is None and batch_size != 1:
936
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
937
+ if self.config.pad_token_id is None:
938
+ sequence_lengths = -1
939
+ else:
940
+ if input_ids is not None:
941
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
942
+ else:
943
+ sequence_lengths = -1
944
+
945
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
946
+
947
+ loss = None
948
+ if labels is not None:
949
+ labels = labels.to(logits.device)
950
+ if self.config.problem_type is None:
951
+ if self.num_labels == 1:
952
+ self.config.problem_type = "regression"
953
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
954
+ self.config.problem_type = "single_label_classification"
955
+ else:
956
+ self.config.problem_type = "multi_label_classification"
957
+
958
+ if self.config.problem_type == "regression":
959
+ loss_fct = MSELoss()
960
+ if self.num_labels == 1:
961
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
962
+ else:
963
+ loss = loss_fct(pooled_logits, labels)
964
+ elif self.config.problem_type == "single_label_classification":
965
+ loss_fct = CrossEntropyLoss()
966
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
967
+ elif self.config.problem_type == "multi_label_classification":
968
+ loss_fct = BCEWithLogitsLoss()
969
+ loss = loss_fct(pooled_logits, labels)
970
+ if not return_dict:
971
+ output = (pooled_logits,) + transformer_outputs[1:]
972
+ return ((loss,) + output) if loss is not None else output
973
+
974
+ return SequenceClassifierOutputWithPast(
975
+ loss=loss,
976
+ logits=pooled_logits,
977
+ past_key_values=transformer_outputs.past_key_values,
978
+ hidden_states=transformer_outputs.hidden_states,
979
+ attentions=transformer_outputs.attentions,
980
+ )
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:78f8f3101653ca0e977ac9b9a2cbb1d3a0e04a6da567e88f1b0e3c811f1dfd59
3
+ size 1493174903
special_tokens_map.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": "[PAD]",
17
+ "unk_token": {
18
+ "content": "<unk>",
19
+ "lstrip": false,
20
+ "normalized": true,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ }
24
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
tokenizer_config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "bos_token": {
5
+ "__type": "AddedToken",
6
+ "content": "<s>",
7
+ "lstrip": false,
8
+ "normalized": true,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "clean_up_tokenization_spaces": false,
13
+ "eos_token": {
14
+ "__type": "AddedToken",
15
+ "content": "</s>",
16
+ "lstrip": false,
17
+ "normalized": true,
18
+ "rstrip": false,
19
+ "single_word": false
20
+ },
21
+ "model_max_length": 2048,
22
+ "pad_token": null,
23
+ "padding_side": "right",
24
+ "sp_model_kwargs": {},
25
+ "tokenizer_class": "LlamaTokenizer",
26
+ "unk_token": {
27
+ "__type": "AddedToken",
28
+ "content": "<unk>",
29
+ "lstrip": false,
30
+ "normalized": true,
31
+ "rstrip": false,
32
+ "single_word": false
33
+ }
34
+ }