Text Generation
Transformers
Safetensors
English
doge
conversational
custom_code
JingzeShi commited on
Commit
3c40c20
·
verified ·
1 Parent(s): d8cf920

Upload DogeForCausalLM

Browse files
Files changed (2) hide show
  1. config.json +2 -2
  2. modeling_old_doge.py +1245 -0
config.json CHANGED
@@ -1,12 +1,12 @@
1
  {
2
- "_name_or_path": "SmallDoge/Doge-160M",
3
  "architectures": [
4
  "DogeForCausalLM"
5
  ],
6
  "attention_dropout": 0.0,
7
  "auto_map": {
8
  "AutoConfig": "configuration_doge.DogeConfig",
9
- "AutoModelForCausalLM": "modeling_doge.DogeForCausalLM"
10
  },
11
  "bos_token_id": 0,
12
  "dynamic_mask_ratio": 0.0,
 
1
  {
2
+ "_name_or_path": "./Doge-160M-new",
3
  "architectures": [
4
  "DogeForCausalLM"
5
  ],
6
  "attention_dropout": 0.0,
7
  "auto_map": {
8
  "AutoConfig": "configuration_doge.DogeConfig",
9
+ "AutoModelForCausalLM": "modeling_old_doge.DogeForCausalLM"
10
  },
11
  "bos_token_id": 0,
12
  "dynamic_mask_ratio": 0.0,
modeling_old_doge.py ADDED
@@ -0,0 +1,1245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/2412.11834
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 Callable, 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.processing_utils import Unpack
40
+ from transformers.utils import (
41
+ LossKwargs,
42
+ add_start_docstrings,
43
+ add_start_docstrings_to_model_forward,
44
+ is_torch_greater_or_equal,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from .configuration_doge import DogeConfig
49
+
50
+ try:
51
+ from einx import add as einx_add
52
+ except ImportError:
53
+ einx_add = None
54
+
55
+ if is_torch_greater_or_equal("2.5"):
56
+ from torch.nn.attention.flex_attention import flex_attention
57
+
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+ _CONFIG_FOR_DOC = "DogeConfig"
62
+
63
+
64
+ class RMSNorm(nn.Module):
65
+ def __init__(self, hidden_size, eps=1e-6):
66
+ """
67
+ RMSNorm is equivalent to T5LayerNorm
68
+ """
69
+ super().__init__()
70
+ self.weight = nn.Parameter(torch.ones(hidden_size))
71
+ self.variance_epsilon = eps
72
+
73
+ def forward(self, hidden_states):
74
+ input_dtype = hidden_states.dtype
75
+ hidden_states = hidden_states.to(torch.float32)
76
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
77
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
78
+ return self.weight * hidden_states.to(input_dtype)
79
+
80
+ def extra_repr(self):
81
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
82
+
83
+
84
+ class Residual(nn.Module):
85
+ def __init__(self, hidden_size):
86
+ super().__init__()
87
+ self.weight = nn.Parameter(torch.ones(hidden_size))
88
+
89
+ def forward(self, residual_states, hidden_states):
90
+ return self.weight * residual_states + hidden_states
91
+
92
+ def extra_repr(self):
93
+ return f"{tuple(self.weight.shape)}"
94
+
95
+
96
+ class RotaryEmbedding(nn.Module):
97
+ def __init__(self, config: Optional[DogeConfig] = None):
98
+ super().__init__()
99
+ self.rope_kwargs = {}
100
+
101
+ if config.rope_scaling is not None:
102
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
103
+ else:
104
+ self.rope_type = "default"
105
+ self.max_seq_len_cached = config.max_position_embeddings
106
+ self.original_max_seq_len = config.max_position_embeddings
107
+ self.base = config.rope_theta
108
+
109
+ self.config = config
110
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
111
+
112
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, **self.rope_kwargs)
113
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
114
+ self.original_inv_freq = self.inv_freq
115
+
116
+ def _dynamic_frequency_update(self, position_ids, device):
117
+ """
118
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
119
+ 1 - growing beyond the cached sequence length (allow scaling)
120
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
121
+ """
122
+ seq_len = torch.max(position_ids) + 1
123
+ if seq_len > self.max_seq_len_cached: # growth
124
+ inv_freq, self.attention_scaling = self.rope_init_fn(
125
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
126
+ )
127
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
128
+ self.max_seq_len_cached = seq_len
129
+
130
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
131
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
132
+ self.max_seq_len_cached = self.original_max_seq_len
133
+
134
+ @torch.no_grad()
135
+ def forward(self, x, position_ids):
136
+ if "dynamic" in self.rope_type:
137
+ self._dynamic_frequency_update(position_ids, device=x.device)
138
+
139
+ # core RoPE block
140
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
141
+ position_ids_expanded = position_ids[:, None, :].float()
142
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
143
+ device_type = x.device.type
144
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
145
+ with torch.autocast(device_type=device_type, enabled=False):
146
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
147
+ emb = torch.cat((freqs, freqs), dim=-1)
148
+ cos = emb.cos()
149
+ sin = emb.sin()
150
+
151
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
152
+ cos = cos * self.attention_scaling
153
+ sin = sin * self.attention_scaling
154
+
155
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
156
+
157
+
158
+ def rotate_half(x):
159
+ """
160
+ Rotates half the hidden dims of the input.
161
+ """
162
+ x1 = x[..., : x.shape[-1] // 2]
163
+ x2 = x[..., x.shape[-1] // 2 :]
164
+ return torch.cat((-x2, x1), dim=-1)
165
+
166
+
167
+ def apply_QK_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
168
+ """Applies Rotary Position Embedding to the query and key tensors.
169
+
170
+ Args:
171
+ q (`torch.Tensor`): The query tensor.
172
+ k (`torch.Tensor`): The key tensor.
173
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
174
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
175
+ position_ids (`torch.Tensor`, *optional*):
176
+ Deprecated and unused.
177
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
178
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
179
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k.
180
+ For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim].
181
+ Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k.
182
+ Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
183
+ Returns:
184
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
185
+ """
186
+ cos = cos.unsqueeze(unsqueeze_dim)
187
+ sin = sin.unsqueeze(unsqueeze_dim)
188
+ q_embed = (q * cos) + (rotate_half(q) * sin)
189
+ k_embed = (k * cos) + (rotate_half(k) * sin)
190
+ return q_embed, k_embed
191
+
192
+
193
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
194
+ """
195
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep).
196
+ The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
197
+ """
198
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
199
+ if n_rep == 1:
200
+ return hidden_states
201
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
202
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
203
+
204
+
205
+ class DogeDynamicMaskAttention(nn.Module):
206
+ """Dynamic Mask Attention from 'Wonderful Matrices' paper."""
207
+
208
+ def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None):
209
+ super().__init__()
210
+ self.config = config
211
+ self.layer_idx = layer_idx
212
+ self.head_dim = config.hidden_size // config.num_attention_heads
213
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
214
+ self.scaling = self.head_dim ** -0.5
215
+ self.attention_dropout = config.attention_dropout
216
+ self.dynamic_mask_ratio = config.dynamic_mask_ratio
217
+
218
+ self.ALL_ATTENTION_FUNCTIONS = {
219
+ "eager": self.eager_attention_forward,
220
+ "flex_attention": self.flex_attention_forward,
221
+ "sdpa": self.sdpa_attention_forward,
222
+ }
223
+
224
+ # Q K V O projections
225
+ self.q_proj = nn.Linear(
226
+ config.hidden_size,
227
+ config.num_attention_heads * self.head_dim,
228
+ bias=config.hidden_bias
229
+ )
230
+ self.k_proj = nn.Linear(
231
+ config.hidden_size,
232
+ config.num_key_value_heads * self.head_dim,
233
+ bias=config.hidden_bias
234
+ )
235
+ self.v_proj = nn.Linear(
236
+ config.hidden_size,
237
+ config.num_key_value_heads * self.head_dim,
238
+ bias=config.hidden_bias
239
+ )
240
+ # dynamic mask for the QK^T attention score matrix
241
+ self.A = nn.Parameter(
242
+ torch.zeros(config.num_attention_heads)
243
+ )
244
+ self.dt_proj = nn.Linear(
245
+ config.num_key_value_heads * self.head_dim,
246
+ config.num_attention_heads,
247
+ bias=config.hidden_bias
248
+ )
249
+ self.o_proj = nn.Linear(
250
+ config.num_attention_heads * self.head_dim,
251
+ config.hidden_size,
252
+ bias=config.hidden_bias
253
+ )
254
+
255
+ def forward(
256
+ self,
257
+ hidden_states: torch.Tensor,
258
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
259
+ attention_mask: Optional[torch.Tensor] = None,
260
+ past_key_value: Optional[Cache] = None,
261
+ cache_position: Optional[torch.LongTensor] = None,
262
+ **kwargs,
263
+ ) -> Tuple[torch.Tensor, Optional[Cache]]:
264
+ input_shape = hidden_states.shape[:-1]
265
+ hidden_shape = (*input_shape, -1, self.head_dim)
266
+
267
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
268
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
269
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
270
+
271
+ cos, sin = position_embeddings
272
+ query_states, key_states = apply_QK_rotary_pos_emb(query_states, key_states, cos, sin)
273
+
274
+ if past_key_value is not None:
275
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
276
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
277
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
278
+
279
+ # calculate dynamic mask from value_states
280
+ # NOTE: If these weights are not trained in causal mode, a mask of all ones will be returned, which will not affect the training results of causal mode
281
+ # TODO: The main reason for setting causal mode is that the Flex Attention kernel does not yet support score_mod functions with learnable parameters. However, we can continue training from the causal checkpoint later.
282
+ dt_states = self.dt_proj(value_states.transpose(1, 2).reshape(value_states.shape[0], value_states.shape[-2], -1))
283
+ dynamic_mask = torch.exp(self.A * F.softplus(dt_states)).transpose(-1, -2)
284
+ attn_mask = self.prepare_dynamic_mask(
285
+ hidden_states=hidden_states,
286
+ dynamic_mask=dynamic_mask,
287
+ dynamic_mask_ratio=self.dynamic_mask_ratio,
288
+ attention_mask=attention_mask,
289
+ )
290
+
291
+ attention_interface: Callable = self.eager_attention_forward
292
+ if self.config._attn_implementation != "eager":
293
+ attention_interface = self.ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
294
+
295
+ attn_output = attention_interface(
296
+ query_states,
297
+ key_states,
298
+ value_states,
299
+ attention_mask=attn_mask,
300
+ dropout=0.0 if not self.training else self.attention_dropout,
301
+ scaling=self.scaling,
302
+ **kwargs,
303
+ )
304
+
305
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
306
+ attn_output = self.o_proj(attn_output)
307
+ return attn_output
308
+
309
+ def prepare_dynamic_mask(
310
+ self,
311
+ hidden_states: torch.Tensor,
312
+ dynamic_mask: torch.Tensor,
313
+ dynamic_mask_ratio: float = 0.0,
314
+ attention_mask: Optional[torch.Tensor] = None,
315
+ ):
316
+ """
317
+ Combine `dynamic_mask` with `attention_mask` to generate the final `attn_mask`.
318
+
319
+ Args:
320
+ hidden_states (`torch.Tensor`): The input hidden_states, used to determine the minimum value of the current input precision.
321
+ dynamic_mask (`torch.Tensor`): dynamic mask of shape `(batch_size, num_heads, key_sequence_length)`.
322
+ dynamic_mask_ratio (`float`, *optional*): Ratio from 0.0 to 1.0 used to control the proportion of the dynamic mask filled with the minimum value.
323
+ attention_mask (`torch.Tensor`, *optional*): attention mask of shape `(batch_size, 1, query_sequence_length, key_sequence_length)`.
324
+ """
325
+ attn_mask = None
326
+ if dynamic_mask is not None:
327
+ attn_mask = dynamic_mask[:, :, None, :]
328
+ if 0.0 < dynamic_mask_ratio < 1.0:
329
+ min_type = torch.finfo(hidden_states.dtype).min
330
+ num_dynamic_mask = int(attn_mask.shape[-1] * dynamic_mask_ratio)
331
+ if num_dynamic_mask > 0:
332
+ rate_value = torch.kthvalue(attn_mask, num_dynamic_mask, dim=-1, keepdim=True).values
333
+ attn_mask = attn_mask.masked_fill(attn_mask < rate_value, min_type)
334
+ if attention_mask is not None:
335
+ attn_mask = attn_mask + attention_mask[:, :, :, : attn_mask.shape[-1]]
336
+ else:
337
+ attn_mask = attention_mask
338
+
339
+ return attn_mask
340
+
341
+ def eager_attention_forward(
342
+ self,
343
+ query: torch.Tensor,
344
+ key: torch.Tensor,
345
+ value: torch.Tensor,
346
+ attention_mask: Optional[torch.Tensor],
347
+ scaling: float,
348
+ dropout: float = 0.0,
349
+ **kwargs,
350
+ ) -> torch.Tensor:
351
+ key_states = repeat_kv(key, self.num_key_value_groups)
352
+ value_states = repeat_kv(value, self.num_key_value_groups)
353
+
354
+ # compute attention scores matrix
355
+ attn_weights = torch.matmul(query, key_states.transpose(-1, -2)) * scaling
356
+ if attention_mask is not None:
357
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
358
+ attn_weights = attn_weights + causal_mask
359
+
360
+ # upcast attention scores to fp32
361
+ attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
362
+ attn_weights = F.dropout(attn_weights, p=dropout, training=self.training)
363
+
364
+ # apply attention scores to value states
365
+ attn_output = torch.matmul(attn_weights, value_states)
366
+ attn_output = attn_output.transpose(1, 2).contiguous()
367
+ return attn_output
368
+
369
+ def sdpa_attention_forward(
370
+ self,
371
+ query: torch.Tensor,
372
+ key: torch.Tensor,
373
+ value: torch.Tensor,
374
+ attention_mask: Optional[torch.Tensor],
375
+ scaling: float,
376
+ dropout: float = 0.0,
377
+ **kwargs,
378
+ ) -> torch.Tensor:
379
+ causal_mask = attention_mask
380
+ if attention_mask is not None:
381
+ causal_mask = causal_mask[:, :, :, : key.shape[-2]]
382
+
383
+ # SDPA with memory-efficient backend is bugged with non-contiguous inputs and custom attn_mask for some torch versions
384
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
385
+ query = query.contiguous()
386
+ key = key.contiguous()
387
+ value = value.contiguous()
388
+
389
+ # NOTE: As of pytorch 2.5.1, cuDNN's SDPA backward pass is still incorrect, so we disable cuDNN SDPA (see https://github.com/pytorch/pytorch/issues/138581)
390
+ torch.backends.cuda.enable_cudnn_sdp(False)
391
+ attn_output = F.scaled_dot_product_attention(
392
+ query,
393
+ key,
394
+ value,
395
+ attn_mask=causal_mask,
396
+ dropout_p=dropout,
397
+ scale=scaling,
398
+ enable_gqa=True,
399
+ )
400
+ attn_output = attn_output.transpose(1, 2).contiguous()
401
+ return attn_output
402
+
403
+ def flex_attention_forward(
404
+ self,
405
+ query: torch.Tensor,
406
+ key: torch.Tensor,
407
+ value: torch.Tensor,
408
+ attention_mask: Optional[torch.Tensor],
409
+ scaling: float,
410
+ dropout: float = 0.0,
411
+ **kwargs,
412
+ ) -> torch.Tensor:
413
+ causal_mask = attention_mask
414
+ if attention_mask is not None:
415
+ causal_mask = causal_mask[:, :, :, : key.shape[-2]]
416
+
417
+ # TODO: flex_attention: As of pytorch 2.5.1, captured buffers that require grad are not yet supported.
418
+ # NOTE: So we only use flex_attention in inference mode.
419
+
420
+ def causal_mod(score, batch, head, q_idx, kv_idx):
421
+ score = score + causal_mask[batch][0][q_idx][kv_idx]
422
+ return score
423
+
424
+ def dynamic_mod(score, batch, head, q_idx, kv_idx):
425
+ score = score + causal_mask[batch][head][q_idx][kv_idx]
426
+ return score
427
+
428
+ mask_mod = causal_mod if self.is_causal else dynamic_mod
429
+
430
+ attn_output = flex_attention(
431
+ query,
432
+ key,
433
+ value,
434
+ score_mod=mask_mod,
435
+ scale=scaling,
436
+ enable_gqa=True,
437
+ )
438
+ attn_output = attn_output.transpose(1, 2).contiguous()
439
+ return attn_output
440
+
441
+
442
+ class DogeMLP(nn.Module):
443
+
444
+ def __init__(self, config: DogeConfig):
445
+ super().__init__()
446
+ self.hidden_dim = config.hidden_size
447
+ self.intermediate_dim = config.intermediate_size
448
+ self.act_fn = ACT2FN[config.hidden_act]
449
+
450
+ self.gate_proj = nn.Linear(self.hidden_dim, self.intermediate_dim, bias=config.hidden_bias)
451
+ self.up_proj = nn.Linear(self.hidden_dim, self.intermediate_dim, bias=config.hidden_bias)
452
+ self.down_proj = nn.Linear(self.intermediate_dim, self.hidden_dim, bias=config.hidden_bias)
453
+
454
+ def forward(
455
+ self,
456
+ hidden_states: torch.Tensor,
457
+ **kwargs,
458
+ ) -> torch.Tensor:
459
+ hidden_states = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))
460
+ return hidden_states
461
+
462
+
463
+ class DogeCDMoE(DogeMLP):
464
+ """Cross Domain Mixture of Experts from 'Wonderful Matrices' paper."""
465
+
466
+ def __init__(self, config: DogeConfig):
467
+ super().__init__(config)
468
+ self.hidden_dim = config.hidden_size
469
+ self.act_fn = ACT2FN[config.hidden_act]
470
+
471
+ self.expert_retrieval_dim = config.expert_retrieval_size
472
+ self.num_cdmoe_experts = config.num_cdmoe_experts
473
+ self.num_cdmoe_heads = config.num_cdmoe_heads
474
+ self.num_cdmoe_experts_per_head = config.num_cdmoe_experts_per_head
475
+ self.num_keys = int(math.sqrt(self.num_cdmoe_experts))
476
+
477
+ # queries and keys for retrieval experts
478
+ self.queries = nn.Linear(self.hidden_dim, self.num_cdmoe_heads * self.expert_retrieval_dim, bias=False)
479
+ self.keys = nn.Parameter(torch.zeros(self.num_cdmoe_heads, self.num_keys, 2, self.expert_retrieval_dim // 2))
480
+
481
+ # experts
482
+ self.down_embed = nn.Embedding(self.num_cdmoe_experts, self.hidden_dim)
483
+ self.up_embed = nn.Embedding(self.num_cdmoe_experts, self.hidden_dim)
484
+
485
+ def forward(
486
+ self,
487
+ hidden_states: torch.Tensor,
488
+ **kwargs,
489
+ ) -> torch.Tensor:
490
+ bsz, seq_len, _ = hidden_states.shape
491
+
492
+ # get similarity with queries and keys
493
+ queries = self.queries(hidden_states)
494
+ queries = queries.view(bsz, seq_len, 2, self.num_cdmoe_heads, -1).permute(2, 0, 1, 3, 4)
495
+ sim = torch.einsum("p b t h n, h k p n -> p b t h k", queries, self.keys)
496
+
497
+ # get experts with the highest similarity
498
+ (scores_x, scores_y), (indices_x, indices_y) = sim.topk(self.num_cdmoe_experts_per_head, dim=-1)
499
+ if einx_add is not None:
500
+ all_scores = einx_add("... i, ... j -> ... (i j)", scores_x, scores_y)
501
+ all_indices = einx_add("... i, ... j -> ... (i j)", indices_x * self.num_keys, indices_y)
502
+ else:
503
+ all_scores = scores_x.unsqueeze(-1) + scores_y.unsqueeze(-2)
504
+ all_scores = all_scores.view(*scores_x.shape[:-1], -1)
505
+ all_indices = (indices_x.unsqueeze(-1) * self.num_keys) + indices_y.unsqueeze(-2)
506
+ all_indices = all_indices.view(*indices_x.shape[:-1], -1)
507
+ scores, pk_indices = all_scores.topk(self.num_cdmoe_experts_per_head, dim=-1)
508
+ indices = all_indices.gather(-1, pk_indices)
509
+ down_embed = self.down_embed(indices)
510
+ up_embed = self.up_embed(indices)
511
+
512
+ # mix experts states with cross domain states
513
+ experts_weights = torch.einsum("b t d, b t h k d -> b t h k", hidden_states, down_embed)
514
+ experts_weights = self.act_fn(experts_weights) * scores.softmax(dim=-1)
515
+ experts_states = torch.einsum("b t h k, b t h k d -> b t d", experts_weights, up_embed)
516
+ hidden_states = self.down_proj(self.act_fn(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))
517
+ hidden_states = hidden_states + experts_states
518
+ return hidden_states
519
+
520
+
521
+ class DogeDecoderLayer(nn.Module):
522
+ def __init__(self, config: DogeConfig, layer_idx: Optional[int] = None):
523
+ super().__init__()
524
+ self.hidden_dropout = config.hidden_dropout
525
+
526
+ self.pre_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
527
+ self.self_attn = DogeDynamicMaskAttention(config=config, layer_idx=layer_idx)
528
+ self.pre_residual = Residual(config.hidden_size)
529
+
530
+ self.post_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
531
+ self.feed_forward = DogeMLP(config) if config.is_moe == False else DogeCDMoE(config)
532
+ self.post_residual = Residual(config.hidden_size)
533
+
534
+ def forward(
535
+ self,
536
+ hidden_states: torch.Tensor,
537
+ attention_mask: Optional[torch.Tensor] = None,
538
+ position_ids: Optional[torch.LongTensor] = None,
539
+ past_key_value: Optional[Cache] = None,
540
+ output_attentions: Optional[bool] = False,
541
+ use_cache: Optional[bool] = False,
542
+ cache_position: Optional[torch.LongTensor] = None,
543
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
544
+ **kwargs,
545
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
546
+
547
+ # sequence transformation
548
+ residual = hidden_states
549
+ hidden_states = self.pre_layernorm(hidden_states)
550
+ hidden_states = self.self_attn(
551
+ hidden_states=hidden_states,
552
+ attention_mask=attention_mask,
553
+ position_ids=position_ids,
554
+ past_key_value=past_key_value,
555
+ cache_position=cache_position,
556
+ position_embeddings=position_embeddings,
557
+ **kwargs,
558
+ )
559
+ self_attn_weights = None
560
+ hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training)
561
+ hidden_states = self.pre_residual(residual, hidden_states)
562
+
563
+ # state transformation
564
+ residual = hidden_states
565
+ hidden_states = self.post_layernorm(hidden_states)
566
+ hidden_states = self.feed_forward(hidden_states)
567
+ hidden_states = F.dropout(hidden_states, p=self.hidden_dropout, training=self.training)
568
+ hidden_states = self.post_residual(residual, hidden_states)
569
+
570
+ outputs = (hidden_states,)
571
+ if output_attentions:
572
+ outputs += (self_attn_weights,)
573
+
574
+ return outputs
575
+
576
+
577
+ DOGE_START_DOCSTRING = r"""
578
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
579
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
580
+ etc.)
581
+
582
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
583
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
584
+ and behavior.
585
+
586
+ Parameters:
587
+ config ([`DogeConfig`]):
588
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
589
+ load the weights associated with the model, only the configuration. Check out the
590
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
591
+ """
592
+ @add_start_docstrings(
593
+ "The bare Doge Model outputting raw hidden-states without any specific head on top.",
594
+ DOGE_START_DOCSTRING,
595
+ )
596
+ class DogePreTrainedModel(PreTrainedModel):
597
+ config_class = DogeConfig
598
+ base_model_prefix = "model"
599
+ supports_gradient_checkpointing = True
600
+ _no_split_modules = ["DogeDecoderLayer"]
601
+ _skip_keys_device_placement = ["past_key_values"]
602
+ _supports_sdpa = True
603
+ # _supports_flex_attn = True
604
+ _supports_cache_class = True
605
+ _supports_quantized_cache = True
606
+ _supports_static_cache = True
607
+
608
+ def _init_weights(self, module):
609
+ std = self.config.initializer_range
610
+ if isinstance(module, (nn.Linear)):
611
+ module.weight.data.normal_(mean=0.0, std=std)
612
+ if module.bias is not None:
613
+ module.bias.data.zero_()
614
+ elif isinstance(module, nn.Embedding):
615
+ module.weight.data.normal_(mean=0.0, std=std)
616
+ if module.padding_idx is not None:
617
+ module.weight.data[module.padding_idx].zero_()
618
+
619
+
620
+ DOGE_INPUTS_DOCSTRING = r"""
621
+ Args:
622
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
623
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
624
+ it.
625
+
626
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
627
+ [`PreTrainedTokenizer.__call__`] for details.
628
+
629
+ [What are input IDs?](../glossary#input-ids)
630
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
631
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
632
+
633
+ - 1 for tokens that are **not masked**,
634
+ - 0 for tokens that are **masked**.
635
+
636
+ [What are attention masks?](../glossary#attention-mask)
637
+
638
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
639
+ [`PreTrainedTokenizer.__call__`] for details.
640
+
641
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
642
+ `past_key_values`).
643
+
644
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
645
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
646
+ information on the default strategy.
647
+
648
+ - 1 indicates the head is **not masked**,
649
+ - 0 indicates the head is **masked**.
650
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
651
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
652
+ config.n_positions - 1]`.
653
+
654
+ [What are position IDs?](../glossary#position-ids)
655
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
656
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
657
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
658
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
659
+
660
+ Two formats are allowed:
661
+ - a [`~cache_utils.Cache`] instance, see our
662
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
663
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
664
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
665
+ cache format.
666
+
667
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
668
+ legacy cache format will be returned.
669
+
670
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
671
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
672
+ of shape `(batch_size, sequence_length)`.
673
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
674
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
675
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
676
+ model's internal embedding lookup matrix.
677
+ use_cache (`bool`, *optional*):
678
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
679
+ `past_key_values`).
680
+ output_attentions (`bool`, *optional*):
681
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
682
+ tensors for more detail.
683
+ output_hidden_states (`bool`, *optional*):
684
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
685
+ more detail.
686
+ return_dict (`bool`, *optional*):
687
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
688
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
689
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
690
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
691
+ the complete sequence length.
692
+ """
693
+
694
+
695
+ @add_start_docstrings(
696
+ "The bare Doge Model outputting raw hidden-states without any specific head on top.",
697
+ DOGE_START_DOCSTRING,
698
+ )
699
+ class DogeModel(DogePreTrainedModel):
700
+ """
701
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DogeDecoderLayer`]
702
+
703
+ Args:
704
+ config: DogeConfig
705
+ """
706
+
707
+ def __init__(self, config: DogeConfig):
708
+ super().__init__(config)
709
+ self.config = config
710
+ self.padding_idx = config.pad_token_id
711
+ self.vocab_size = config.vocab_size
712
+
713
+ self.word_embed = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
714
+ self.rotary_emb = RotaryEmbedding(config)
715
+ self.layers = nn.ModuleList(
716
+ [DogeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
717
+ )
718
+ self.final_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
719
+ self.gradient_checkpointing = False
720
+
721
+ # Initialize weights and apply final processing
722
+ self.post_init()
723
+
724
+ def get_input_embeddings(self):
725
+ return self.word_embed
726
+
727
+ def set_input_embeddings(self, value):
728
+ self.word_embed = value
729
+
730
+ @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING)
731
+ def forward(
732
+ self,
733
+ input_ids: torch.LongTensor = None,
734
+ attention_mask: Optional[torch.Tensor] = None,
735
+ position_ids: Optional[torch.LongTensor] = None,
736
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
737
+ inputs_embeds: Optional[torch.FloatTensor] = None,
738
+ use_cache: Optional[bool] = None,
739
+ output_attentions: Optional[bool] = None,
740
+ output_hidden_states: Optional[bool] = None,
741
+ return_dict: Optional[bool] = None,
742
+ cache_position: Optional[torch.LongTensor] = None,
743
+ **kwargs,
744
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
745
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
746
+ output_hidden_states = (
747
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
748
+ )
749
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
750
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
751
+
752
+ if (input_ids is None) ^ (inputs_embeds is not None):
753
+ raise ValueError("You cannot specify both input_ids and inputs_embeds")
754
+
755
+ if self.gradient_checkpointing and self.training and use_cache:
756
+ logger.warning_once(
757
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
758
+ )
759
+ use_cache = False
760
+
761
+ if inputs_embeds is None:
762
+ inputs_embeds = self.word_embed(input_ids)
763
+
764
+ if use_cache and past_key_values is None:
765
+ past_key_values = DynamicCache()
766
+
767
+ if cache_position is None:
768
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
769
+ cache_position = torch.arange(
770
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
771
+ )
772
+
773
+ if position_ids is None:
774
+ position_ids = cache_position.unsqueeze(0)
775
+
776
+ causal_mask = self._update_causal_mask(
777
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
778
+ )
779
+
780
+ hidden_states = inputs_embeds
781
+
782
+ # create position embeddings to be shared across the decoder layers
783
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
784
+
785
+ # decoder layers
786
+ all_hidden_states = () if output_hidden_states else None
787
+ all_self_attns = () if output_attentions else None
788
+
789
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
790
+ if output_hidden_states:
791
+ all_hidden_states += (hidden_states,)
792
+
793
+ if self.gradient_checkpointing and self.training:
794
+ layer_outputs = self._gradient_checkpointing_func(
795
+ decoder_layer.__call__,
796
+ hidden_states,
797
+ causal_mask,
798
+ position_ids,
799
+ past_key_values,
800
+ output_attentions,
801
+ use_cache,
802
+ cache_position,
803
+ position_embeddings,
804
+ )
805
+ else:
806
+ layer_outputs = decoder_layer(
807
+ hidden_states,
808
+ attention_mask=causal_mask,
809
+ position_ids=position_ids,
810
+ past_key_value=past_key_values,
811
+ output_attentions=output_attentions,
812
+ use_cache=use_cache,
813
+ cache_position=cache_position,
814
+ position_embeddings=position_embeddings,
815
+ **kwargs,
816
+ )
817
+
818
+ hidden_states = layer_outputs[0]
819
+
820
+ if output_attentions:
821
+ all_self_attns += (layer_outputs[1],)
822
+
823
+ hidden_states = self.final_layernorm(hidden_states)
824
+
825
+ # add hidden states from the last decoder layer
826
+ if output_hidden_states:
827
+ all_hidden_states += (hidden_states,)
828
+
829
+ output = BaseModelOutputWithPast(
830
+ last_hidden_state=hidden_states,
831
+ past_key_values=past_key_values if use_cache else None,
832
+ hidden_states=all_hidden_states,
833
+ attentions=all_self_attns,
834
+ )
835
+ return output if return_dict else output.to_tuple()
836
+
837
+ def _update_causal_mask(
838
+ self,
839
+ attention_mask: torch.Tensor,
840
+ input_tensor: torch.Tensor,
841
+ cache_position: torch.Tensor,
842
+ past_key_values: Cache,
843
+ output_attentions: bool,
844
+ ):
845
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
846
+ using_static_cache = isinstance(past_key_values, StaticCache)
847
+
848
+ dtype, device = input_tensor.dtype, input_tensor.device
849
+ sequence_length = input_tensor.shape[1]
850
+ if using_static_cache:
851
+ target_length = past_key_values.get_max_cache_shape()
852
+ else:
853
+ target_length = (
854
+ attention_mask.shape[-1]
855
+ if isinstance(attention_mask, torch.Tensor)
856
+ else past_seen_tokens + sequence_length + 1
857
+ )
858
+
859
+ # in case the provided `attention` mask is 2D, we generate a causal mask here (4D).
860
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
861
+ attention_mask=attention_mask,
862
+ sequence_length=sequence_length,
863
+ target_length=target_length,
864
+ dtype=dtype,
865
+ device=device,
866
+ cache_position=cache_position,
867
+ batch_size=input_tensor.shape[0],
868
+ )
869
+
870
+ return causal_mask
871
+
872
+ @staticmethod
873
+ def _prepare_4d_causal_attention_mask_with_cache_position(
874
+ attention_mask: torch.Tensor = None,
875
+ sequence_length: int = None,
876
+ target_length: int = None,
877
+ dtype: torch.dtype = None,
878
+ device: torch.device = None,
879
+ cache_position: torch.Tensor = None,
880
+ batch_size: int = None,
881
+ **kwargs,
882
+ ):
883
+ """
884
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
885
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
886
+
887
+ Args:
888
+ attention_mask (`torch.Tensor`):
889
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
890
+ `(batch_size, 1, query_length, key_value_length)`.
891
+ sequence_length (`int`):
892
+ The sequence length being processed.
893
+ target_length (`int`):
894
+ The target length: when generating with static cache, the mask should be as long as the static cache,
895
+ to account for the 0 padding, the part of the cache that is not filled yet.
896
+ dtype (`torch.dtype`):
897
+ The dtype to use for the 4D attention mask.
898
+ device (`torch.device`):
899
+ The device to plcae the 4D attention mask on.
900
+ cache_position (`torch.Tensor`):
901
+ Indices depicting the position of the input sequence tokens in the sequence.
902
+ batch_size (`torch.Tensor`):
903
+ Batch size.
904
+ """
905
+ if attention_mask is not None and attention_mask.dim() == 4:
906
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
907
+ causal_mask = attention_mask
908
+ else:
909
+ min_dtype = torch.finfo(dtype).min
910
+ causal_mask = torch.full(
911
+ (sequence_length, target_length),
912
+ fill_value=min_dtype, dtype=dtype, device=device,
913
+ )
914
+ if sequence_length != 1:
915
+ causal_mask = torch.triu(causal_mask, diagonal=1)
916
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
917
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
918
+ if attention_mask is not None:
919
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
920
+ mask_length = attention_mask.shape[-1]
921
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
922
+ padding_mask = padding_mask == 0
923
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
924
+ padding_mask, min_dtype
925
+ )
926
+
927
+ return causal_mask
928
+
929
+
930
+ class KwargsForCausalLM(LossKwargs): ...
931
+
932
+
933
+ class DogeForCausalLM(DogePreTrainedModel, GenerationMixin):
934
+ _tied_weights_keys = ["lm_head.weight"]
935
+ _tp_plan = {"lm_head": "colwise_rep"}
936
+
937
+ def __init__(self, config: DogeConfig):
938
+ super().__init__(config)
939
+ self.config = config
940
+ self.model = DogeModel(config)
941
+ self.vocab_size = config.vocab_size
942
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
943
+
944
+ # Initialize weights and apply final processing
945
+ self.post_init()
946
+
947
+ def get_input_embeddings(self):
948
+ return self.model.word_embed
949
+
950
+ def set_input_embeddings(self, value):
951
+ self.model.word_embed = value
952
+
953
+ def get_output_embeddings(self):
954
+ return self.lm_head
955
+
956
+ def set_output_embeddings(self, new_embeddings):
957
+ self.lm_head = new_embeddings
958
+
959
+ def get_decoder(self):
960
+ return self.model
961
+
962
+ def set_decoder(self, decoder):
963
+ self.model = decoder
964
+
965
+ @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING)
966
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
967
+ def forward(
968
+ self,
969
+ input_ids: torch.LongTensor = None,
970
+ attention_mask: Optional[torch.Tensor] = None,
971
+ position_ids: Optional[torch.LongTensor] = None,
972
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
973
+ inputs_embeds: Optional[torch.FloatTensor] = None,
974
+ labels: Optional[torch.LongTensor] = None,
975
+ use_cache: Optional[bool] = None,
976
+ output_attentions: Optional[bool] = None,
977
+ output_hidden_states: Optional[bool] = None,
978
+ return_dict: Optional[bool] = None,
979
+ cache_position: Optional[torch.LongTensor] = None,
980
+ num_logits_to_keep: int = 0,
981
+ **kwargs: Unpack[KwargsForCausalLM],
982
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
983
+ r"""
984
+ Args:
985
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
986
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
987
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
988
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
989
+
990
+ num_logits_to_keep (`int`, *optional*):
991
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
992
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
993
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
994
+
995
+ Returns:
996
+
997
+ Example:
998
+
999
+ ```python
1000
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
1001
+
1002
+ >>> model = AutoModelForCausalLM.from_pretrained("JingzeShi/Doge-20M-Instruct")
1003
+ >>> tokenizer = AutoTokenizer.from_pretrained("JingzeShi/Doge-20M-Instruct")
1004
+
1005
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1006
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1007
+
1008
+ >>> # Generate
1009
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1010
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1011
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1012
+ ```"""
1013
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1014
+ output_hidden_states = (
1015
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1016
+ )
1017
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1018
+
1019
+ # decoder output consists of (dec_features, layer_state, dec_hidden, dec_attn)
1020
+ outputs = self.model(
1021
+ input_ids=input_ids,
1022
+ attention_mask=attention_mask,
1023
+ position_ids=position_ids,
1024
+ past_key_values=past_key_values,
1025
+ inputs_embeds=inputs_embeds,
1026
+ use_cache=use_cache,
1027
+ output_attentions=output_attentions,
1028
+ output_hidden_states=output_hidden_states,
1029
+ return_dict=return_dict,
1030
+ cache_position=cache_position,
1031
+ **kwargs,
1032
+ )
1033
+
1034
+ hidden_states = outputs[0]
1035
+
1036
+ # only compute necessary logits, and do not upcast them to float if we are not computing the loss
1037
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1038
+
1039
+ loss = None
1040
+ if labels is not None:
1041
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.vocab_size, **kwargs)
1042
+
1043
+ if not return_dict:
1044
+ output = (logits,) + outputs[1:]
1045
+ return (loss,) + output if loss is not None else output
1046
+
1047
+ return CausalLMOutputWithPast(
1048
+ loss=loss,
1049
+ logits=logits,
1050
+ past_key_values=outputs.past_key_values,
1051
+ hidden_states=outputs.hidden_states,
1052
+ attentions=outputs.attentions,
1053
+ )
1054
+
1055
+
1056
+ class DogePatchEmbedding(nn.Module):
1057
+ """
1058
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial `hidden_states` of shape `(batch_size, seq_len, hidden_size)` to be consumed by a Transformer.
1059
+ """
1060
+
1061
+ def __init__(self, config: DogeConfig):
1062
+ super().__init__()
1063
+
1064
+ self.num_channels = config.num_channels
1065
+ self.patch_size = config.patch_size
1066
+ self.hidden_dim = config.hidden_size
1067
+
1068
+ self.sequence_proj = nn.Conv2d(self.num_channels, self.hidden_dim, kernel_size=self.patch_size, stride=self.patch_size)
1069
+ self.state_proj = nn.Linear(self.hidden_dim, self.hidden_dim, bias=config.hidden_bias)
1070
+
1071
+ def forward(
1072
+ self,
1073
+ pixel_values: torch.Tensor,
1074
+ ) -> torch.Tensor:
1075
+ image_embedding = self.sequence_proj(pixel_values).flatten(2).transpose(1, 2)
1076
+ image_embedding = self.state_proj(image_embedding)
1077
+ return image_embedding
1078
+
1079
+
1080
+ class DogeForCausalVLM(DogeForCausalLM):
1081
+ _tied_weights_keys = ["lm_head.weight"]
1082
+
1083
+ def __init__(self, config: DogeConfig):
1084
+ super().__init__(config)
1085
+ self.config = config
1086
+ self.pixel_embed = DogePatchEmbedding(config)
1087
+
1088
+ # Initialize weights and apply final processing
1089
+ self.post_init()
1090
+
1091
+ def forward(
1092
+ self,
1093
+ input_ids: torch.LongTensor = None,
1094
+ pixel_values: torch.FloatTensor = None,
1095
+ attention_mask: Optional[torch.Tensor] = None,
1096
+ position_ids: Optional[torch.LongTensor] = None,
1097
+ past_key_values: Optional[torch.Tensor] = None,
1098
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1099
+ labels: Optional[torch.LongTensor] = None,
1100
+ use_cache: Optional[bool] = None,
1101
+ output_attentions: Optional[bool] = None,
1102
+ output_hidden_states: Optional[bool] = None,
1103
+ return_dict: Optional[bool] = None,
1104
+ cache_position: Optional[torch.LongTensor] = None,
1105
+ num_logits_to_keep: int = 0,
1106
+ **loss_kwargs,
1107
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1108
+ # TODO: @wubingheng111: refer to Llava for implementating the forward method
1109
+ ...
1110
+
1111
+ def prepare_inputs_for_generation(
1112
+ self,
1113
+ input_ids=None,
1114
+ pixel_values=None,
1115
+ past_key_values=None,
1116
+ input_embeds=None,
1117
+ attention_mask=None,
1118
+ cache_position=None,
1119
+ num_logits_to_keep=None,
1120
+ **kwargs,
1121
+ ):
1122
+ model_inputs = self.model.prepare_inputs_for_generation(
1123
+ input_ids,
1124
+ past_key_values=past_key_values,
1125
+ inputs_embeds=input_embeds,
1126
+ attention_mask=attention_mask,
1127
+ cache_position=cache_position,
1128
+ num_logits_to_keep=num_logits_to_keep,
1129
+ **kwargs,
1130
+ )
1131
+
1132
+ if cache_position[0] == 0:
1133
+ model_inputs["pixel_values"] = pixel_values
1134
+
1135
+ return model_inputs
1136
+
1137
+
1138
+ @add_start_docstrings(
1139
+ """
1140
+ The Doge Model transformer with a sequence classification head on top (linear layer).
1141
+
1142
+ [`DogeForSequenceClassification`] uses the last token in order to do the classification, as other causal models (e.g. GPT-2) do.
1143
+
1144
+ Since it does classification on the last token, it requires to know the position of the last token.
1145
+ If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row.
1146
+ If no `pad_token_id` is defined, it simply takes the last value in each row of the batch.
1147
+ Since it cannot guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in each row of the batch).
1148
+ """
1149
+ )
1150
+ class DogeForSequenceClassification(DogePreTrainedModel):
1151
+ def __init__(self, config: DogeConfig):
1152
+ super().__init__(config)
1153
+ self.config = config
1154
+ self.num_labels = config.num_labels
1155
+
1156
+ self.model = DogeModel(config)
1157
+ self.classifier = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1158
+
1159
+ # Initialize weights and apply final processing
1160
+ self.init_weights()
1161
+
1162
+ def get_input_embeddings(self):
1163
+ return self.model.word_embed
1164
+
1165
+ def set_input_embeddings(self, value):
1166
+ self.model.word_embed = value
1167
+
1168
+ @add_start_docstrings_to_model_forward(DOGE_INPUTS_DOCSTRING)
1169
+ def forward(
1170
+ self,
1171
+ input_ids: Optional[torch.LongTensor] = None,
1172
+ attention_mask: Optional[torch.Tensor] = None,
1173
+ position_ids: Optional[torch.LongTensor] = None,
1174
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1175
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1176
+ labels: Optional[torch.LongTensor] = None,
1177
+ use_cache: Optional[bool] = None,
1178
+ output_attentions: Optional[bool] = None,
1179
+ output_hidden_states: Optional[bool] = None,
1180
+ return_dict: Optional[bool] = None,
1181
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1182
+ r"""
1183
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1184
+ Labels for computing the sequence classification/regression loss.
1185
+ Indices should be in `[0, ..., config.num_labels - 1]`.
1186
+ If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1187
+ """
1188
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1189
+
1190
+ outputs = self.model(
1191
+ input_ids=input_ids,
1192
+ attention_mask=attention_mask,
1193
+ position_ids=position_ids,
1194
+ past_key_values=past_key_values,
1195
+ inputs_embeds=inputs_embeds,
1196
+ use_cache=use_cache,
1197
+ output_attentions=output_attentions,
1198
+ output_hidden_states=output_hidden_states,
1199
+ return_dict=return_dict,
1200
+ )
1201
+ hidden_states = outputs[0]
1202
+ logits = self.classifier(hidden_states)
1203
+
1204
+ if input_ids is not None:
1205
+ batch_size = input_ids.shape[0]
1206
+ else:
1207
+ batch_size = inputs_embeds.shape[0]
1208
+
1209
+ if self.config.pad_token_id is None and batch_size != 1:
1210
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1211
+ if self.config.pad_token_id is None:
1212
+ sequence_lengths = -1
1213
+ else:
1214
+ if input_ids is not None:
1215
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1216
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1217
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1218
+ sequence_lengths = sequence_lengths.to(logits.device)
1219
+ else:
1220
+ sequence_lengths = -1
1221
+
1222
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1223
+
1224
+ loss = None
1225
+ if labels is not None:
1226
+ loss = self.loss_function(
1227
+ logits=logits,
1228
+ labels=labels,
1229
+ pooled_logits=pooled_logits,
1230
+ config=self.config,
1231
+ )
1232
+
1233
+ if not return_dict:
1234
+ output = (pooled_logits,) + outputs[1:]
1235
+ return ((loss,) + output) if loss is not None else output
1236
+
1237
+ return SequenceClassifierOutputWithPast(
1238
+ loss=loss,
1239
+ logits=pooled_logits,
1240
+ past_key_values=outputs.past_key_values,
1241
+ hidden_states=outputs.hidden_states,
1242
+ attentions=outputs.attentions,
1243
+ )
1244
+
1245
+ __all__ = ["DogeForCausalLM", "DogeModel", "DogePreTrainedModel", "DogeForSequenceClassification"]