JingzeShi commited on
Commit
302cbe5
1 Parent(s): c385759

Upload DogeForCausalLM

Browse files
Files changed (3) hide show
  1. config.json +1 -1
  2. model.safetensors +1 -1
  3. modeling_doge.py +1102 -0
config.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "_name_or_path": "./results/Doge-20M-registered",
3
  "architectures": [
4
  "DogeForCausalLM"
5
  ],
 
1
  {
2
+ "_name_or_path": "./results/Doge-20M/checkpoint-20000",
3
  "architectures": [
4
  "DogeForCausalLM"
5
  ],
model.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:dfd577ea7afde42a64798750dbdbc5756d41f15ee4e8a86568729feb0f59372b
3
  size 83917640
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d7cad1a7b33b82f98fa56435e1608479c6a2510dc0923ea829ff781e0b0dd668
3
  size 83917640
modeling_doge.py ADDED
@@ -0,0 +1,1102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Jingze Shi and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on the Wonderful Matrices paper implementation.
5
+ #
6
+ # https://arxiv.org/abs/2407.16958
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+ """PyTorch Doge model."""
20
+
21
+ import math
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.nn.functional as F
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
31
+ from transformers.generation import GenerationMixin
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ SequenceClassifierOutputWithPast,
36
+ )
37
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.utils import (
40
+ add_start_docstrings,
41
+ add_start_docstrings_to_model_forward,
42
+ logging,
43
+ replace_return_docstrings,
44
+ )
45
+ from .configuration_doge import DogeConfig
46
+
47
+ try:
48
+ from einx import add as einx_add
49
+ except ImportError:
50
+ einx_add = None
51
+
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ _CONFIG_FOR_DOC = "DogeConfig"
56
+
57
+
58
+ class RMSNorm(nn.Module):
59
+ def __init__(self, hidden_size, eps=1e-6):
60
+ """
61
+ RMSNorm is equivalent to T5LayerNorm
62
+ """
63
+ super().__init__()
64
+ self.weight = nn.Parameter(torch.ones(hidden_size))
65
+ self.variance_epsilon = eps
66
+
67
+ def forward(self, hidden_states):
68
+ input_dtype = hidden_states.dtype
69
+ hidden_states = hidden_states.to(torch.float32)
70
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
71
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
72
+ return self.weight * hidden_states.to(input_dtype)
73
+
74
+ def extra_repr(self):
75
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
76
+
77
+
78
+ class Residual(nn.Module):
79
+ def __init__(self, hidden_size):
80
+ super().__init__()
81
+ self.weight = nn.Parameter(torch.ones(hidden_size))
82
+
83
+ def forward(self, residual_states, hidden_states):
84
+ return self.weight * residual_states + hidden_states
85
+
86
+ def extra_repr(self):
87
+ return f"{tuple(self.weight.shape)}"
88
+
89
+
90
+ class RotaryEmbedding(nn.Module):
91
+ def __init__(self, config: Optional[DogeConfig] = None):
92
+ super().__init__()
93
+ self.rope_kwargs = {}
94
+
95
+ if config.rope_scaling is None:
96
+ self.rope_type = "default"
97
+ else:
98
+ self.rope_type = config.rope_scaling
99
+ self.max_seq_len_cached = config.max_position_embeddings
100
+ self.original_max_seq_len = config.max_position_embeddings
101
+ self.base = config.rope_theta
102
+
103
+ self.config = config
104
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
105
+
106
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, **self.rope_kwargs)
107
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
108
+ self.original_inv_freq = self.inv_freq
109
+
110
+ def _dynamic_frequency_update(self, position_ids, device):
111
+ """
112
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
113
+ 1 - growing beyond the cached sequence length (allow scaling)
114
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
115
+ """
116
+ seq_len = torch.max(position_ids) + 1
117
+ if seq_len > self.max_seq_len_cached: # growth
118
+ inv_freq, self.attention_scaling = self.rope_init_fn(
119
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
120
+ )
121
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
122
+ self.max_seq_len_cached = seq_len
123
+
124
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
125
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
126
+ self.max_seq_len_cached = self.original_max_seq_len
127
+
128
+ @torch.no_grad()
129
+ def forward(self, x, position_ids):
130
+ if "dynamic" in self.rope_type:
131
+ self._dynamic_frequency_update(position_ids, device=x.device)
132
+
133
+ # core RoPE block
134
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
135
+ position_ids_expanded = position_ids[:, None, :].float()
136
+ device_type = x.device.type
137
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
138
+ with torch.autocast(device_type=device_type, enabled=False):
139
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
140
+ emb = torch.cat((freqs, freqs), dim=-1)
141
+ cos = emb.cos()
142
+ sin = emb.sin()
143
+
144
+ cos = cos * self.attention_scaling
145
+ sin = sin * self.attention_scaling
146
+
147
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
148
+
149
+
150
+ def rotate_half(x):
151
+ """
152
+ Rotates half the hidden dims of the input.
153
+ """
154
+ x1 = x[..., : x.shape[-1] // 2]
155
+ x2 = x[..., x.shape[-1] // 2 :]
156
+ return torch.cat((-x2, x1), dim=-1)
157
+
158
+
159
+ def apply_QK_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
160
+ """Applies Rotary Position Embedding to the query and key tensors.
161
+
162
+ Args:
163
+ q (`torch.Tensor`): The query tensor.
164
+ k (`torch.Tensor`): The key tensor.
165
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
166
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
167
+ position_ids (`torch.Tensor`, *optional*):
168
+ Deprecated and unused.
169
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
170
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
171
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
172
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
173
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
174
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
175
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
176
+ Returns:
177
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
178
+ """
179
+ cos = cos.unsqueeze(unsqueeze_dim)
180
+ sin = sin.unsqueeze(unsqueeze_dim)
181
+ q_embed = (q * cos) + (rotate_half(q) * sin)
182
+ k_embed = (k * cos) + (rotate_half(k) * sin)
183
+ return q_embed, k_embed
184
+
185
+
186
+ class DogeDynamicMaskAttention(nn.Module):
187
+
188
+ def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None):
189
+ super().__init__()
190
+
191
+ self.config = config
192
+ self.layer_idx = layer_idx
193
+ if layer_idx is None:
194
+ logger.warning_once(
195
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
196
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
197
+ "when creating this class."
198
+ )
199
+
200
+ self.hidden_dim = config.hidden_size
201
+ self.num_attention_heads = config.num_attention_heads
202
+ self.attention_dropout = config.attention_dropout
203
+ self.attention_head_dim = self.hidden_dim // self.num_attention_heads
204
+
205
+ # Q K V O projections
206
+ self.q_proj = nn.Linear(
207
+ self.hidden_dim,
208
+ self.num_attention_heads * self.attention_head_dim,
209
+ bias=config.hidden_bias,
210
+ )
211
+ self.k_proj = nn.Linear(
212
+ self.hidden_dim,
213
+ self.num_attention_heads * self.attention_head_dim,
214
+ bias=config.hidden_bias,
215
+ )
216
+ # dynamic mask for the QK^T attention score matrix
217
+ self.A = nn.Parameter(
218
+ torch.ones(self.num_attention_heads)
219
+ )
220
+ self.dt_proj = nn.Linear(
221
+ self.hidden_dim,
222
+ self.num_attention_heads,
223
+ bias=config.hidden_bias,
224
+ )
225
+ self.v_proj = nn.Linear(
226
+ self.hidden_dim,
227
+ self.num_attention_heads * self.attention_head_dim,
228
+ bias=config.hidden_bias,
229
+ )
230
+ self.o_proj = nn.Linear(
231
+ self.hidden_dim,
232
+ self.hidden_dim,
233
+ bias=config.hidden_bias,
234
+ )
235
+
236
+ def forward(
237
+ self,
238
+ hidden_states: torch.Tensor,
239
+ attention_mask: Optional[torch.Tensor] = None,
240
+ position_ids: Optional[torch.LongTensor] = None,
241
+ past_key_value: Optional[Cache] = None,
242
+ cache_position: Optional[torch.LongTensor] = None,
243
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
244
+ **kwargs,
245
+ ) -> Tuple[torch.Tensor, Optional[Cache]]:
246
+ bsz, q_len, _ = hidden_states.shape
247
+
248
+ query_states = self.q_proj(hidden_states)
249
+ key_states = self.k_proj(hidden_states)
250
+ value_states = self.v_proj(hidden_states)
251
+
252
+ query_states = query_states.view(bsz, q_len, self.num_attention_heads, self.attention_head_dim).transpose(
253
+ 1, 2
254
+ )
255
+ key_states = key_states.view(bsz, q_len, self.num_attention_heads, self.attention_head_dim).transpose(
256
+ 1, 2
257
+ )
258
+ value_states = value_states.view(bsz, q_len, self.num_attention_heads, self.attention_head_dim).transpose(
259
+ 1, 2
260
+ )
261
+
262
+ cos, sin = position_embeddings
263
+ query_states, key_states = apply_QK_rotary_pos_emb(query_states, key_states, cos, sin)
264
+
265
+ if past_key_value is not None:
266
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
267
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
268
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
269
+
270
+ # compute attention scores matrix
271
+ attn_weights = torch.matmul(query_states, key_states.transpose(-1, -2)) / math.sqrt(self.attention_head_dim)
272
+
273
+ # add mask to attention scores
274
+ if attention_mask is not None:
275
+ dt_states = self.dt_proj(value_states.transpose(1, 2).reshape(bsz, value_states.shape[-2], -1))
276
+ dynamic_mask = torch.exp(self.A * F.softplus(dt_states)).transpose(-1, -2)
277
+ dynamic_mask = dynamic_mask < 1.0
278
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]].masked_fill(dynamic_mask[:, :, None, :], torch.finfo(hidden_states.dtype).min)
279
+ attn_weights = attn_weights + causal_mask
280
+
281
+ # upcast attention scores to fp32
282
+ attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
283
+ attn_weights = F.dropout(attn_weights, p=self.attention_dropout, training=self.training)
284
+
285
+ # apply attention scores to value states
286
+ attn_output = torch.matmul(attn_weights, value_states)
287
+
288
+ attn_output = attn_output.transpose(1, 2).contiguous()
289
+ attn_output = attn_output.reshape(bsz, q_len, -1)
290
+ attn_output = self.o_proj(attn_output)
291
+
292
+ return attn_output, past_key_value
293
+
294
+
295
+ class DogeSdpaDynamicMaskAttn(DogeDynamicMaskAttention):
296
+
297
+ def forward(
298
+ self,
299
+ hidden_states: torch.Tensor,
300
+ attention_mask: Optional[torch.Tensor] = None,
301
+ position_ids: Optional[torch.LongTensor] = None,
302
+ past_key_value: Optional[Cache] = None,
303
+ cache_position: Optional[torch.LongTensor] = None,
304
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
305
+ **kwargs,
306
+ ) -> Tuple[torch.Tensor, Optional[Cache]]:
307
+ bsz, q_len, _ = hidden_states.shape
308
+
309
+ query_states = self.q_proj(hidden_states)
310
+ key_states = self.k_proj(hidden_states)
311
+ value_states = self.v_proj(hidden_states)
312
+
313
+ query_states = query_states.view(bsz, q_len, self.num_attention_heads, self.attention_head_dim).transpose(1, 2)
314
+ key_states = key_states.view(bsz, q_len, self.num_attention_heads, self.attention_head_dim).transpose(1, 2)
315
+ value_states = value_states.view(bsz, q_len, self.num_attention_heads, self.attention_head_dim).transpose(1, 2)
316
+
317
+ cos, sin = position_embeddings
318
+ query_states, key_states = apply_QK_rotary_pos_emb(query_states, key_states, cos, sin)
319
+
320
+ if past_key_value is not None:
321
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
322
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
323
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
324
+
325
+ if attention_mask is not None:
326
+ dt_states = self.dt_proj(value_states.transpose(1, 2).reshape(bsz, value_states.shape[-2], -1))
327
+ dynamic_mask = torch.exp(self.A * F.softplus(dt_states)).transpose(-1, -2)
328
+ dynamic_mask = dynamic_mask < 1.0
329
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]].masked_fill(dynamic_mask[:, :, None, :], torch.finfo(hidden_states.dtype).min)
330
+
331
+ query_states = query_states.contiguous()
332
+ key_states = key_states.contiguous()
333
+ value_states = value_states.contiguous()
334
+
335
+ attn_output = F.scaled_dot_product_attention(
336
+ query_states,
337
+ key_states,
338
+ value_states,
339
+ attn_mask=causal_mask,
340
+ dropout_p=self.attention_dropout,
341
+ )
342
+
343
+ attn_output = attn_output.transpose(1, 2).contiguous()
344
+ attn_output = attn_output.view(bsz, q_len, -1)
345
+ attn_output = self.o_proj(attn_output)
346
+
347
+ return attn_output, past_key_value
348
+
349
+
350
+ DOGE_ATTENTION_CLASSES = {
351
+ "eager": DogeDynamicMaskAttention,
352
+ "sdpa": DogeSdpaDynamicMaskAttn,
353
+ }
354
+
355
+
356
+ class DogeMLP(nn.Module):
357
+
358
+ def __init__(self, config: DogeConfig):
359
+ super().__init__()
360
+ self.hidden_dim = config.hidden_size
361
+ self.intermediate_dim = config.intermediate_size
362
+ self.act_fn = ACT2FN[config.hidden_act]
363
+
364
+ self.gate_proj = nn.Linear(
365
+ self.hidden_dim,
366
+ self.intermediate_dim,
367
+ bias=config.hidden_bias,
368
+ )
369
+ self.up_proj = nn.Linear(
370
+ self.hidden_dim,
371
+ self.intermediate_dim,
372
+ bias=config.hidden_bias,
373
+ )
374
+ self.down_proj = nn.Linear(
375
+ self.intermediate_dim,
376
+ self.hidden_dim,
377
+ bias=config.hidden_bias,
378
+ )
379
+
380
+ def forward(
381
+ self,
382
+ hidden_states: torch.Tensor,
383
+ **kwargs,
384
+ ) -> torch.Tensor:
385
+ hidden_states = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))
386
+ return hidden_states
387
+
388
+
389
+ class DogeCDMoE(DogeMLP):
390
+
391
+ def __init__(self, config: DogeConfig):
392
+ super().__init__(config)
393
+ self.hidden_dim = config.hidden_size
394
+ self.act_fn = ACT2FN[config.hidden_act]
395
+
396
+ self.expert_retrieval_dim = config.expert_retrieval_size
397
+ self.num_cdmmoe_experts = config.num_cdmmoe_experts
398
+ self.num_cdmmoe_heads = config.num_cdmmoe_heads
399
+ self.num_cdmmoe_experts_per_head = config.num_cdmmoe_experts_per_head
400
+ self.num_keys = int(math.sqrt(self.num_cdmmoe_experts))
401
+
402
+ # queries and keys for retrieval experts
403
+ self.queries = nn.Linear(
404
+ self.hidden_dim,
405
+ self.num_cdmmoe_heads * self.expert_retrieval_dim,
406
+ bias=False,
407
+ )
408
+ self.keys = nn.Parameter(
409
+ torch.zeros(
410
+ self.num_cdmmoe_heads,
411
+ self.num_keys,
412
+ 2,
413
+ self.expert_retrieval_dim // 2,
414
+ )
415
+ )
416
+
417
+ # experts
418
+ self.down_embed = nn.Embedding(
419
+ self.num_cdmmoe_experts,
420
+ self.hidden_dim,
421
+ )
422
+ self.up_embed = nn.Embedding(
423
+ self.num_cdmmoe_experts,
424
+ self.hidden_dim,
425
+ )
426
+
427
+
428
+ def forward(
429
+ self,
430
+ hidden_states: torch.Tensor,
431
+ **kwargs,
432
+ ) -> torch.Tensor:
433
+ bsz, seq_len, _ = hidden_states.shape
434
+
435
+ # get similarity with queries and keys
436
+ queries = self.queries(hidden_states)
437
+ queries = queries.view(bsz, seq_len, 2, self.num_cdmmoe_heads, -1).permute(2, 0, 1, 3, 4)
438
+ sim = torch.einsum("p b t h n, h k p n -> p b t h k", queries, self.keys)
439
+
440
+ # get experts with the highest similarity
441
+ (scores_x, scores_y), (indices_x, indices_y) = sim.topk(self.num_cdmmoe_experts_per_head, dim=-1)
442
+ if einx_add is not None:
443
+ all_scores = einx_add("... i, ... j -> ... (i j)", scores_x, scores_y)
444
+ all_indices = einx_add("... i, ... j -> ... (i j)", indices_x * self.num_keys, indices_y)
445
+ else:
446
+ all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2)
447
+ all_scores = all_scores.view(*scores_x.shape[:-1], -1)
448
+ all_indices = (indices_x.unsqueeze(-1) * self.num_keys) + indices_y.unsqueeze(-2)
449
+ all_indices = all_indices.view(*indices_x.shape[:-1], -1)
450
+ scores, pk_indices = all_scores.topk(self.num_cdmmoe_experts_per_head, dim=-1)
451
+ indices = all_indices.gather(-1, pk_indices)
452
+ down_embed = self.down_embed(indices)
453
+ up_embed = self.up_embed(indices)
454
+
455
+ # mix experts states with cross domain states
456
+ experts_weights = torch.einsum("b t d, b t h k d -> b t h k", hidden_states, down_embed)
457
+ experts_weights = self.act_fn(experts_weights) * scores.softmax(dim=-1)
458
+ experts_states = torch.einsum("b t h k, b t h k d -> b t d", experts_weights, up_embed)
459
+ hidden_states = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))
460
+ hidden_states = hidden_states + experts_states
461
+ return hidden_states
462
+
463
+
464
+ class DogeDecoderLayer(nn.Module):
465
+ def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None):
466
+ super().__init__()
467
+ self.hidden_dropout = config.hidden_dropout
468
+
469
+ self.pre_sequence_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
470
+ self.attn = DOGE_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
471
+ self.post_sequence_residual = Residual(config.hidden_size)
472
+
473
+ self.pre_state_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
474
+ self.feed_forward = DogeMLP(config) if config.is_moe == False else DogeCDMoE(config)
475
+ self.post_state_residual = Residual(config.hidden_size)
476
+
477
+ def forward(
478
+ self,
479
+ hidden_states: torch.Tensor,
480
+ attention_mask: Optional[torch.Tensor] = None,
481
+ position_ids: Optional[torch.LongTensor] = None,
482
+ past_key_value: Optional[Cache] = None,
483
+ output_attentions: Optional[bool] = False,
484
+ use_cache: Optional[bool] = False,
485
+ cache_position: Optional[torch.LongTensor] = None,
486
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
487
+ **kwargs,
488
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
489
+ """
490
+ Args:
491
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
492
+ attention_mask (`torch.FloatTensor`, *optional*):
493
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
494
+ query_sequence_length, key_sequence_length)` if default attention is used.
495
+ output_attentions (`bool`, *optional*):
496
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
497
+ returned tensors for more detail.
498
+ use_cache (`bool`, *optional*):
499
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
500
+ (see `past_key_values`).
501
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
502
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
503
+ Indices depicting the position of the input sequence tokens in the sequence
504
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
505
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
506
+ with `head_dim` being the embedding dimension of each attention head.
507
+ kwargs (`dict`, *optional*):
508
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
509
+ into the model
510
+ """
511
+
512
+ # sequence transformation
513
+ residual = hidden_states
514
+ hidden_states = self.pre_sequence_layernorm(hidden_states)
515
+ hidden_states, present_key_value = self.attn(
516
+ hidden_states=hidden_states,
517
+ attention_mask=attention_mask,
518
+ position_ids=position_ids,
519
+ past_key_value=past_key_value,
520
+ cache_position=cache_position,
521
+ position_embeddings=position_embeddings,
522
+ **kwargs,
523
+ )
524
+ self_attn_weights = None
525
+ hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training)
526
+ hidden_states = self.post_sequence_residual(residual, hidden_states)
527
+
528
+ # state transformation
529
+ residual = hidden_states
530
+ hidden_states = self.pre_state_layernorm(hidden_states)
531
+ hidden_states = self.feed_forward(hidden_states)
532
+ hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training)
533
+ hidden_states = self.post_state_residual(residual, hidden_states)
534
+
535
+ outputs = (hidden_states,)
536
+
537
+ if output_attentions:
538
+ outputs += (self_attn_weights,)
539
+
540
+ if use_cache:
541
+ outputs += (present_key_value,)
542
+
543
+ return outputs
544
+
545
+
546
+ @add_start_docstrings("The bare Doge Model outputting raw hidden-states without any specific head on top.")
547
+ class DogePreTrainedModel(PreTrainedModel):
548
+ config_class = DogeConfig
549
+ base_model_prefix = "model"
550
+ supports_gradient_checkpointing = True
551
+ _no_split_modules = ["DogeDecoderLayer"]
552
+ _skip_keys_device_placement = ["past_key_values"]
553
+ _supports_sdpa = True
554
+ _supports_cache_class = True
555
+ _supports_quantized_cache = True
556
+ _supports_static_cache = True
557
+
558
+ def _init_weights(self, module):
559
+ std = self.config.initializer_range
560
+ if isinstance(module, (nn.Linear)):
561
+ module.weight.data.normal_(mean=0.0, std=std)
562
+ if module.bias is not None:
563
+ module.bias.data.zero_()
564
+ elif isinstance(module, nn.Embedding):
565
+ module.weight.data.normal_(mean=0.0, std=std)
566
+ if module.padding_idx is not None:
567
+ module.weight.data[module.padding_idx].zero_()
568
+
569
+
570
+ DOGE_INPUTS_DOCSTRING = r"""
571
+ Args:
572
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
573
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
574
+ it.
575
+
576
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
577
+ [`PreTrainedTokenizer.__call__`] for details.
578
+
579
+ [What are input IDs?](../glossary#input-ids)
580
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
581
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
582
+
583
+ - 1 for tokens that are **not masked**,
584
+ - 0 for tokens that are **masked**.
585
+
586
+ [What are attention masks?](../glossary#attention-mask)
587
+
588
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
589
+ [`PreTrainedTokenizer.__call__`] for details.
590
+
591
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
592
+ `past_key_values`).
593
+
594
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
595
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
596
+ information on the default strategy.
597
+
598
+ - 1 indicates the head is **not masked**,
599
+ - 0 indicates the head is **masked**.
600
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
601
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
602
+ config.n_positions - 1]`.
603
+
604
+ [What are position IDs?](../glossary#position-ids)
605
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
606
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
607
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
608
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
609
+
610
+ Two formats are allowed:
611
+ - a [`~cache_utils.Cache`] instance, see our
612
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
613
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
614
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
615
+ cache format.
616
+
617
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
618
+ legacy cache format will be returned.
619
+
620
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
621
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
622
+ of shape `(batch_size, sequence_length)`.
623
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
624
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
625
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
626
+ model's internal embedding lookup matrix.
627
+ use_cache (`bool`, *optional*):
628
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
629
+ `past_key_values`).
630
+ output_attentions (`bool`, *optional*):
631
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
632
+ tensors for more detail.
633
+ output_hidden_states (`bool`, *optional*):
634
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
635
+ more detail.
636
+ return_dict (`bool`, *optional*):
637
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
638
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
639
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
640
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
641
+ the complete sequence length.
642
+ """
643
+
644
+
645
+ @add_start_docstrings("The bare Doge Model outputting raw hidden-states without any specific head on top.")
646
+ class DogeModel(DogePreTrainedModel):
647
+ def __init__(self, config: DogeConfig):
648
+ super().__init__(config)
649
+ self.config = config
650
+ self.padding_idx = config.pad_token_id
651
+ self.vocab_size = config.vocab_size
652
+
653
+ self.word_embed = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
654
+ self.rotary_emb = RotaryEmbedding(config)
655
+ self.layers = nn.ModuleList(
656
+ [DogeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
657
+ )
658
+ self.final_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
659
+ self.gradient_checkpointing = False
660
+
661
+ # Initialize weights and apply final processing
662
+ self.post_init()
663
+
664
+ def get_input_embeddings(self):
665
+ return self.word_embed
666
+
667
+ def set_input_embeddings(self, value):
668
+ self.word_embed = value
669
+
670
+ @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING)
671
+ def forward(
672
+ self,
673
+ input_ids: torch.LongTensor = None,
674
+ attention_mask: Optional[torch.Tensor] = None,
675
+ position_ids: Optional[torch.LongTensor] = None,
676
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
677
+ inputs_embeds: Optional[torch.FloatTensor] = None,
678
+ use_cache: Optional[bool] = None,
679
+ output_attentions: Optional[bool] = None,
680
+ output_hidden_states: Optional[bool] = None,
681
+ return_dict: Optional[bool] = None,
682
+ cache_position: Optional[torch.LongTensor] = None,
683
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
684
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
685
+ output_hidden_states = (
686
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
687
+ )
688
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
689
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
690
+
691
+ if (input_ids is None) ^ (inputs_embeds is not None):
692
+ raise ValueError("You cannot specify both input_ids and inputs_embeds")
693
+
694
+ if self.gradient_checkpointing and self.training and use_cache:
695
+ logger.warning_once(
696
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
697
+ )
698
+ use_cache = False
699
+
700
+ if inputs_embeds is None:
701
+ inputs_embeds = self.word_embed(input_ids)
702
+
703
+ # kept for BC (non `Cache` `past_key_values` inputs)
704
+ return_legacy_cache = False
705
+ if use_cache and not isinstance(past_key_values, Cache):
706
+ return_legacy_cache = True
707
+ if past_key_values is None:
708
+ past_key_values = DynamicCache()
709
+ else:
710
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
711
+ logger.warning_once(
712
+ "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
713
+ "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
714
+ "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
715
+ )
716
+
717
+ if cache_position is None:
718
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
719
+ cache_position = torch.arange(
720
+ past_seen_tokens,
721
+ past_seen_tokens + inputs_embeds.shape[1],
722
+ device=inputs_embeds.device,
723
+ )
724
+ if position_ids is None:
725
+ position_ids = cache_position.unsqueeze(0)
726
+
727
+ causal_mask = self._update_causal_mask(
728
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
729
+ )
730
+ hidden_states = inputs_embeds
731
+
732
+ # create position embeddings to be shared across the decoder layers
733
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
734
+
735
+ # decoder layers
736
+ all_hidden_states = () if output_hidden_states else None
737
+ all_self_attns = () if output_attentions else None
738
+ next_decoder_cache = None
739
+
740
+ for decoder_layer in self.layers:
741
+ if output_hidden_states:
742
+ all_hidden_states += (hidden_states,)
743
+
744
+ if self.gradient_checkpointing and self.training:
745
+ layer_outputs = self._gradient_checkpointing_func(
746
+ decoder_layer.__call__,
747
+ hidden_states,
748
+ causal_mask,
749
+ position_ids,
750
+ past_key_values,
751
+ output_attentions,
752
+ use_cache,
753
+ cache_position,
754
+ position_embeddings,
755
+ )
756
+ else:
757
+ layer_outputs = decoder_layer(
758
+ hidden_states,
759
+ attention_mask=causal_mask,
760
+ position_ids=position_ids,
761
+ past_key_value=past_key_values,
762
+ output_attentions=output_attentions,
763
+ use_cache=use_cache,
764
+ cache_position=cache_position,
765
+ position_embeddings=position_embeddings,
766
+ )
767
+
768
+ hidden_states = layer_outputs[0]
769
+
770
+ if use_cache:
771
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
772
+
773
+ if output_attentions:
774
+ all_self_attns += (layer_outputs[1],)
775
+
776
+ hidden_states = self.final_layernorm(hidden_states)
777
+
778
+ # add hidden states from the last decoder layer
779
+ if output_hidden_states:
780
+ all_hidden_states += (hidden_states,)
781
+
782
+ next_cache = next_decoder_cache if use_cache else None
783
+ if return_legacy_cache:
784
+ next_cache = next_cache.to_legacy_cache()
785
+
786
+ if not return_dict:
787
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
788
+
789
+ return BaseModelOutputWithPast(
790
+ last_hidden_state=hidden_states,
791
+ past_key_values=next_cache,
792
+ hidden_states=all_hidden_states,
793
+ attentions=all_self_attns,
794
+ )
795
+
796
+ def _update_causal_mask(
797
+ self,
798
+ attention_mask: torch.Tensor = None,
799
+ input_tensor: torch.Tensor = None,
800
+ cache_position: torch.Tensor = None,
801
+ past_key_values: Cache = None,
802
+ output_attentions: bool = False,
803
+ ):
804
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
805
+ using_static_cache = isinstance(past_key_values, StaticCache)
806
+
807
+ dtype, device = input_tensor.dtype, input_tensor.device
808
+ sequence_length = input_tensor.shape[1]
809
+ if using_static_cache:
810
+ target_length = past_key_values.get_max_cache_shape()
811
+ else:
812
+ target_length = (
813
+ attention_mask.shape[-1]
814
+ if isinstance(attention_mask, torch.Tensor)
815
+ else past_seen_tokens + sequence_length + 1
816
+ )
817
+
818
+ # in case the provided `attention` mask is 2D, we generate a causal mask here (4D).
819
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position_and_dynamic_mask(
820
+ attention_mask=attention_mask,
821
+ sequence_length=sequence_length,
822
+ target_length=target_length,
823
+ dtype=dtype,
824
+ device=device,
825
+ cache_position=cache_position,
826
+ batch_size=input_tensor.shape[0],
827
+ )
828
+
829
+ return causal_mask
830
+
831
+ @staticmethod
832
+ def _prepare_4d_causal_attention_mask_with_cache_position_and_dynamic_mask(
833
+ attention_mask: torch.Tensor = None,
834
+ sequence_length: int = None,
835
+ target_length: int = None,
836
+ dtype: torch.dtype = None,
837
+ device: torch.device = None,
838
+ cache_position: torch.Tensor = None,
839
+ batch_size: int = None,
840
+ **kwargs,
841
+ ):
842
+ """
843
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
844
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
845
+
846
+ Args:
847
+ attention_mask (`torch.Tensor`):
848
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
849
+ `(batch_size, 1, query_length, key_value_length)`.
850
+ sequence_length (`int`):
851
+ The sequence length being processed.
852
+ target_length (`int`):
853
+ The target length: when generating with static cache, the mask should be as long as the static cache,
854
+ to account for the 0 padding, the part of the cache that is not filled yet.
855
+ dtype (`torch.dtype`):
856
+ The dtype to use for the 4D attention mask.
857
+ device (`torch.device`):
858
+ The device to plcae the 4D attention mask on.
859
+ cache_position (`torch.Tensor`):
860
+ Indices depicting the position of the input sequence tokens in the sequence.
861
+ batch_size (`torch.Tensor`):
862
+ Batch size.
863
+ """
864
+ if attention_mask is not None and attention_mask.dim() == 4:
865
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
866
+ causal_mask = attention_mask
867
+ else:
868
+ min_dtype = torch.finfo(dtype).min
869
+ causal_mask = torch.full(
870
+ (sequence_length, target_length),
871
+ fill_value=min_dtype, dtype=dtype, device=device,
872
+ )
873
+ if sequence_length != 1:
874
+ causal_mask = torch.triu(causal_mask, diagonal=1)
875
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
876
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
877
+ if attention_mask is not None:
878
+ # print(f"attention_mask: {attention_mask.shape}")
879
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
880
+ mask_length = attention_mask.shape[-1]
881
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
882
+ padding_mask = padding_mask == 0
883
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
884
+ padding_mask, min_dtype
885
+ )
886
+
887
+ return causal_mask
888
+
889
+
890
+ class DogeForCausalLM(DogePreTrainedModel, GenerationMixin):
891
+ _tied_weights_keys = ["lm_head.weight"]
892
+
893
+ def __init__(self, config: DogeConfig):
894
+ super().__init__(config)
895
+ self.config = config
896
+ self.model = DogeModel(config)
897
+ self.vocab_size = config.vocab_size
898
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
899
+
900
+ # Initialize weights and apply final processing
901
+ self.post_init()
902
+
903
+ def get_input_embeddings(self):
904
+ return self.model.word_embed
905
+
906
+ def set_input_embeddings(self, value):
907
+ self.model.word_embed = value
908
+
909
+ def get_output_embeddings(self):
910
+ return self.lm_head
911
+
912
+ def set_output_embeddings(self, new_embeddings):
913
+ self.lm_head = new_embeddings
914
+
915
+ def set_decoder(self, decoder):
916
+ self.model = decoder
917
+
918
+ def get_decoder(self):
919
+ return self.model
920
+
921
+ @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING)
922
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
923
+ def forward(
924
+ self,
925
+ input_ids: torch.LongTensor = None,
926
+ attention_mask: Optional[torch.Tensor] = None,
927
+ position_ids: Optional[torch.LongTensor] = None,
928
+ past_key_values: Optional[torch.Tensor] = None,
929
+ inputs_embeds: Optional[torch.FloatTensor] = None,
930
+ labels: Optional[torch.LongTensor] = None,
931
+ use_cache: Optional[bool] = None,
932
+ output_attentions: Optional[bool] = None,
933
+ output_hidden_states: Optional[bool] = None,
934
+ return_dict: Optional[bool] = None,
935
+ cache_position: Optional[torch.LongTensor] = None,
936
+ num_logits_to_keep: int = 0,
937
+ **loss_kwargs,
938
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
939
+ r"""
940
+ Args:
941
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
942
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
943
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
944
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
945
+
946
+ num_logits_to_keep (`int`, *optional*):
947
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
948
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
949
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
950
+
951
+ Returns:
952
+ """
953
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
954
+ output_hidden_states = (
955
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
956
+ )
957
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
958
+
959
+ # decoder output consists of (dec_features, layer_state, dec_hidden, dec_attn)
960
+ outputs = self.model(
961
+ input_ids=input_ids,
962
+ attention_mask=attention_mask,
963
+ position_ids=position_ids,
964
+ past_key_values=past_key_values,
965
+ inputs_embeds=inputs_embeds,
966
+ use_cache=use_cache,
967
+ output_attentions=output_attentions,
968
+ output_hidden_states=output_hidden_states,
969
+ return_dict=return_dict,
970
+ cache_position=cache_position,
971
+ )
972
+
973
+ hidden_states = outputs[0]
974
+
975
+ # only compute necessary logits, and do not upcast them to float if we are not computing the loss
976
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
977
+
978
+ loss = None
979
+ if labels is not None:
980
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.vocab_size, **loss_kwargs)
981
+
982
+ if not return_dict:
983
+ output = (logits,) + outputs[1:]
984
+ return (loss,) + output if loss is not None else output
985
+
986
+ return CausalLMOutputWithPast(
987
+ loss=loss,
988
+ logits=logits,
989
+ past_key_values=outputs.past_key_values,
990
+ hidden_states=outputs.hidden_states,
991
+ attentions=outputs.attentions,
992
+ )
993
+
994
+
995
+ @add_start_docstrings(
996
+ """
997
+ The Doge Model transformer with a sequence classification head on top (linear layer).
998
+
999
+ [`DogeForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1000
+ (e.g. GPT-2) do.
1001
+
1002
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1003
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1004
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1005
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1006
+ each row of the batch).
1007
+ """
1008
+ )
1009
+ class DogeForSequenceClassification(DogePreTrainedModel):
1010
+ def __init__(self, config: DogeConfig):
1011
+ super().__init__(config)
1012
+ self.config = config
1013
+ self.num_labels = config.num_labels
1014
+
1015
+ self.model = DogeModel(config)
1016
+ self.classifier = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1017
+
1018
+ # Initialize weights and apply final processing
1019
+ self.init_weights()
1020
+
1021
+ def get_input_embeddings(self):
1022
+ return self.model.word_embed
1023
+
1024
+ def set_input_embeddings(self, value):
1025
+ self.model.word_embed = value
1026
+
1027
+ @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING)
1028
+ def forward(
1029
+ self,
1030
+ input_ids: Optional[torch.LongTensor] = None,
1031
+ attention_mask: Optional[torch.Tensor] = None,
1032
+ position_ids: Optional[torch.LongTensor] = None,
1033
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1034
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1035
+ labels: Optional[torch.LongTensor] = None,
1036
+ use_cache: Optional[bool] = None,
1037
+ output_attentions: Optional[bool] = None,
1038
+ output_hidden_states: Optional[bool] = None,
1039
+ return_dict: Optional[bool] = None,
1040
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1041
+ r"""
1042
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1043
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1044
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1045
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1046
+ """
1047
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1048
+
1049
+ outputs = self.model(
1050
+ input_ids=input_ids,
1051
+ attention_mask=attention_mask,
1052
+ position_ids=position_ids,
1053
+ past_key_values=past_key_values,
1054
+ inputs_embeds=inputs_embeds,
1055
+ use_cache=use_cache,
1056
+ output_attentions=output_attentions,
1057
+ output_hidden_states=output_hidden_states,
1058
+ return_dict=return_dict,
1059
+ )
1060
+ hidden_states = outputs[0]
1061
+ logits = self.classifier(hidden_states)
1062
+
1063
+ if input_ids is not None:
1064
+ batch_size = input_ids.shape[0]
1065
+ else:
1066
+ batch_size = inputs_embeds.shape[0]
1067
+
1068
+ if self.config.pad_token_id is None and batch_size != 1:
1069
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1070
+ if self.config.pad_token_id is None:
1071
+ sequence_lengths = -1
1072
+ else:
1073
+ if input_ids is not None:
1074
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1075
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1076
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1077
+ sequence_lengths = sequence_lengths.to(logits.device)
1078
+ else:
1079
+ sequence_lengths = -1
1080
+
1081
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1082
+
1083
+ loss = None
1084
+ if labels is not None:
1085
+ loss = self.loss_function(
1086
+ logits=logits,
1087
+ labels=labels,
1088
+ pooled_logits=pooled_logits,
1089
+ config=self.config,
1090
+ )
1091
+
1092
+ if not return_dict:
1093
+ output = (pooled_logits,) + outputs[1:]
1094
+ return ((loss,) + output) if loss is not None else output
1095
+
1096
+ return SequenceClassifierOutputWithPast(
1097
+ loss=loss,
1098
+ logits=pooled_logits,
1099
+ past_key_values=outputs.past_key_values,
1100
+ hidden_states=outputs.hidden_states,
1101
+ attentions=outputs.attentions,
1102
+ )