Pinaster commited on
Commit
922c2db
·
verified ·
1 Parent(s): 1c53d2d

Restore official GLM-5 4-layer checkpoint layout

Browse files
chat_template.jinja CHANGED
@@ -32,10 +32,10 @@ For each function call, output the function name and arguments within the follow
32
  {%- set ns = namespace(last_user_index=-1) %}
33
  {%- for m in messages %}
34
  {%- if m.role == 'user' %}
35
- {% set ns.last_user_index = loop.index0 -%}
36
  {%- endif %}
37
  {%- endfor %}
38
- {% for m in messages %}
39
  {%- if m.role == 'user' -%}<|user|>{{ visible_text(m.content) }}
40
  {%- elif m.role == 'assistant' -%}
41
  <|assistant|>
 
32
  {%- set ns = namespace(last_user_index=-1) %}
33
  {%- for m in messages %}
34
  {%- if m.role == 'user' %}
35
+ {%- set ns.last_user_index = loop.index0 -%}
36
  {%- endif %}
37
  {%- endfor %}
38
+ {%- for m in messages -%}
39
  {%- if m.role == 'user' -%}<|user|>{{ visible_text(m.content) }}
40
  {%- elif m.role == 'assistant' -%}
41
  <|assistant|>
config.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "architectures": [
3
- "DeepseekV32ForCausalLM"
4
  ],
5
  "attention_bias": false,
6
  "attention_dropout": 0.0,
@@ -25,7 +25,7 @@
25
  "max_position_embeddings": 202752,
26
  "moe_intermediate_size": 2048,
27
  "moe_layer_freq": 1,
28
- "model_type": "deepseek_v32",
29
  "n_group": 1,
30
  "n_routed_experts": 256,
31
  "n_shared_experts": 1,
@@ -34,7 +34,7 @@
34
  "num_experts_per_tok": 8,
35
  "num_hidden_layers": 4,
36
  "num_key_value_heads": 64,
37
- "num_nextn_predict_layers": 1,
38
  "pad_token_id": 154820,
39
  "pretraining_tp": 1,
40
  "q_lora_rank": 2048,
@@ -55,9 +55,5 @@
55
  "transformers_version": "5.0.2.dev0",
56
  "use_cache": true,
57
  "v_head_dim": 256,
58
- "vocab_size": 154880,
59
- "auto_map": {
60
- "AutoConfig": "configuration_deepseek_v32.DeepseekV32Config",
61
- "AutoModelForCausalLM": "modeling_deepseek_v32.DeepseekV32ForCausalLM"
62
- }
63
  }
 
1
  {
2
  "architectures": [
3
+ "GlmMoeDsaForCausalLM"
4
  ],
5
  "attention_bias": false,
6
  "attention_dropout": 0.0,
 
25
  "max_position_embeddings": 202752,
26
  "moe_intermediate_size": 2048,
27
  "moe_layer_freq": 1,
28
+ "model_type": "glm_moe_dsa",
29
  "n_group": 1,
30
  "n_routed_experts": 256,
31
  "n_shared_experts": 1,
 
34
  "num_experts_per_tok": 8,
35
  "num_hidden_layers": 4,
36
  "num_key_value_heads": 64,
37
+ "num_nextn_predict_layers": 0,
38
  "pad_token_id": 154820,
39
  "pretraining_tp": 1,
40
  "q_lora_rank": 2048,
 
55
  "transformers_version": "5.0.2.dev0",
56
  "use_cache": true,
57
  "v_head_dim": 256,
58
+ "vocab_size": 154880
 
 
 
 
59
  }
configuration_deepseek_v32.py DELETED
@@ -1,61 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2025 bzantium and the HuggingFace Inc. team. All rights reserved.
3
- #
4
- # This code is based on the DeepSeekV3 implementations from the DeepSeek AI team. (https://huggingface.co/deepseek-ai/DeepSeek-V3)
5
-
6
- # Licensed under the Apache License, Version 2.0 (the "License");
7
- # you may not use this file except in compliance with the License.
8
- # You may obtain a copy of the License at
9
- #
10
- # http://www.apache.org/licenses/LICENSE-2.0
11
- #
12
- # Unless required by applicable law or agreed to in writing, software
13
- # distributed under the License is distributed on an "AS IS" BASIS,
14
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
- # See the License for the specific language governing permissions and
16
- # limitations under the License.
17
- """DeepSeekV3.2 model configuration"""
18
-
19
- from typing import Optional
20
-
21
- from transformers.models.deepseek_v3.configuration_deepseek_v3 import DeepseekV3Config
22
-
23
-
24
- DEEPSEEK_V32_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
25
-
26
-
27
- class DeepseekV32Config(DeepseekV3Config):
28
- r"""
29
- This is the configuration class to store the configuration of a [`DeepseekV32Model`]. It is used to instantiate a DeepSeek
30
- V3.2 model according to the specified arguments, defining the model architecture.
31
-
32
- DeepSeek V3.2 extends DeepSeek V3 with native sparse attention mechanism using an indexer for efficient
33
- attention computation on long sequences.
34
- Configuration objects inherit from [`DeepseekV3Config`] and can be used to control the model outputs. Read the
35
- documentation from [`PreTrainedConfig`] for more information.
36
- Args:
37
- index_topk (`int`, *optional*, defaults to 2048):
38
- Number of top-k tokens to select for sparse attention. This enables the native sparse attention
39
- mechanism in DeepSeek V3.2.
40
- **kwargs:
41
- All other arguments from DeepseekV3Config.
42
- ```python
43
- >>> from transformers import DeepseekV32Model, DeepseekV32Config
44
- >>> # Initializing a Deepseek-V3.2 style configuration
45
- >>> configuration = DeepseekV32Config()
46
- >>> # Accessing the model configuration
47
- >>> configuration = model.config
48
- ```"""
49
-
50
- model_type = "deepseek_v32"
51
-
52
- def __init__(
53
- self,
54
- index_topk: Optional[int] = 2048,
55
- **kwargs,
56
- ):
57
- super().__init__(**kwargs)
58
- self.index_topk = index_topk
59
-
60
-
61
- __all__ = ["DeepseekV32Config"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
modeling_deepseek_v32.py DELETED
@@ -1,339 +0,0 @@
1
- import math
2
- import warnings
3
- from collections.abc import Callable
4
- from typing import Optional
5
-
6
- import torch
7
- import torch.nn.functional as F
8
- from torch import nn
9
-
10
- from transformers import initialization as init
11
- from transformers.cache_utils import Cache
12
- from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
13
- from transformers.modeling_layers import GenericForSequenceClassification, GenericForTokenClassification
14
- from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
15
- from transformers.processing_utils import Unpack
16
- from transformers.utils import logging
17
- from transformers.models.deepseek_v3.modeling_deepseek_v3 import (
18
- DeepseekV3Attention,
19
- DeepseekV3DecoderLayer,
20
- DeepseekV3ForCausalLM,
21
- DeepseekV3MLP,
22
- DeepseekV3Model,
23
- DeepseekV3MoE,
24
- DeepseekV3PreTrainedModel,
25
- DeepseekV3RMSNorm,
26
- DeepseekV3RotaryEmbedding,
27
- apply_rotary_pos_emb_interleave,
28
- yarn_get_mscale,
29
- )
30
- from transformers.models.llama.modeling_llama import (
31
- apply_rotary_pos_emb,
32
- eager_attention_forward,
33
- )
34
- from configuration_deepseek_v32 import DeepseekV32Config
35
-
36
-
37
- logger = logging.get_logger(__name__)
38
-
39
-
40
- class DeepseekV32RMSNorm(DeepseekV3RMSNorm):
41
- pass
42
-
43
-
44
- class DeepseekV32RotaryEmbedding(DeepseekV3RotaryEmbedding):
45
- pass
46
-
47
-
48
- class DeepseekV32MLP(DeepseekV3MLP):
49
- pass
50
-
51
-
52
- class DeepseekV32MoE(DeepseekV3MoE):
53
- pass
54
-
55
-
56
- class DeepseekV32SparseAttention(nn.Module):
57
- """
58
- DeepSeek V3.2 sparse attention mechanism with indexer.
59
-
60
- This implements the native sparse attention from DeepSeek V3.2 which uses
61
- an indexer to select top-k tokens for attention computation, making it
62
- more efficient for long sequences.
63
- """
64
-
65
- def __init__(self, config: DeepseekV32Config, layer_idx: int):
66
- super().__init__()
67
- self.config = config
68
- self.layer_idx = layer_idx
69
- self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
70
- self.attention_dropout = config.attention_dropout
71
- self.num_heads = config.num_attention_heads
72
-
73
- self.q_lora_rank = config.q_lora_rank
74
- self.qk_rope_head_dim = config.qk_rope_head_dim
75
- self.kv_lora_rank = config.kv_lora_rank
76
- self.v_head_dim = config.v_head_dim
77
- self.qk_nope_head_dim = config.qk_nope_head_dim
78
- self.qk_head_dim = config.qk_head_dim
79
- self.index_topk = config.index_topk
80
-
81
- self.is_causal = True
82
-
83
- # Query projection
84
- if self.q_lora_rank is None:
85
- self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.qk_head_dim, bias=False)
86
- else:
87
- self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=config.attention_bias)
88
- self.q_a_layernorm = DeepseekV32RMSNorm(config.q_lora_rank)
89
- self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
90
-
91
- # Key-Value projections
92
- self.kv_a_proj_with_mqa = nn.Linear(
93
- config.hidden_size,
94
- self.kv_lora_rank + self.qk_rope_head_dim,
95
- bias=config.attention_bias,
96
- )
97
- self.kv_a_layernorm = DeepseekV32RMSNorm(self.kv_lora_rank)
98
- self.kv_b_proj = nn.Linear(
99
- self.kv_lora_rank,
100
- self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
101
- bias=False,
102
- )
103
-
104
- # Output projection
105
- self.o_proj = nn.Linear(
106
- self.num_heads * self.v_head_dim,
107
- config.hidden_size,
108
- bias=config.attention_bias,
109
- )
110
-
111
- # Indexer components for sparse attention
112
- self.wq_b = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
113
- self.wk = nn.Linear(config.hidden_size, self.qk_head_dim, bias=config.attention_bias)
114
- self.k_norm = DeepseekV32RMSNorm(self.qk_head_dim)
115
- self.weights_proj = nn.Linear(config.hidden_size, self.num_heads, bias=False)
116
-
117
- self.scaling = self.qk_head_dim ** (-0.5)
118
- if self.config.rope_parameters.get("rope_type", "default") != "default":
119
- mscale_all_dim = self.config.rope_parameters.get("mscale_all_dim", 0)
120
- scaling_factor = self.config.rope_parameters["factor"]
121
- if mscale_all_dim:
122
- mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
123
- self.scaling = self.scaling * mscale * mscale
124
-
125
- def forward(
126
- self,
127
- hidden_states: torch.Tensor,
128
- position_embeddings: tuple[torch.Tensor, torch.Tensor],
129
- attention_mask: Optional[torch.Tensor],
130
- past_key_values: Optional[Cache] = None,
131
- cache_position: Optional[torch.LongTensor] = None,
132
- **kwargs: Unpack[FlashAttentionKwargs],
133
- ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
134
- batch_size, seq_length = hidden_states.shape[:-1]
135
-
136
- # For training or when index_topk is not effective, fall back to standard attention
137
- # This is a simplified implementation - in practice, you'd implement the full sparse indexer
138
- if self.training or seq_length <= self.index_topk:
139
- warnings.warn(
140
- "DeepSeek V3.2 sparse attention is not fully implemented in this version. "
141
- "Falling back to standard attention. For production use, please use vLLM or "
142
- "other optimized inference engines.",
143
- UserWarning,
144
- )
145
- return self._standard_attention(
146
- hidden_states, position_embeddings, attention_mask, past_key_values, cache_position, **kwargs
147
- )
148
-
149
- # Sparse attention implementation would go here
150
- # This requires custom CUDA kernels for efficient top-k selection and indexing
151
- return self._standard_attention(
152
- hidden_states, position_embeddings, attention_mask, past_key_values, cache_position, **kwargs
153
- )
154
-
155
- def _standard_attention(
156
- self,
157
- hidden_states: torch.Tensor,
158
- position_embeddings: tuple[torch.Tensor, torch.Tensor],
159
- attention_mask: Optional[torch.Tensor],
160
- past_key_values: Optional[Cache] = None,
161
- cache_position: Optional[torch.LongTensor] = None,
162
- **kwargs: Unpack[FlashAttentionKwargs],
163
- ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
164
- """Standard attention fallback (same as DeepSeek V3)"""
165
- batch_size, seq_length = hidden_states.shape[:-1]
166
- query_shape = (batch_size, seq_length, -1, self.qk_head_dim)
167
- key_shape = (batch_size, seq_length, -1, self.qk_nope_head_dim + self.v_head_dim)
168
-
169
- if self.q_lora_rank is None:
170
- q_states = self.q_proj(hidden_states)
171
- else:
172
- q_states = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
173
- q_states = q_states.view(query_shape).transpose(1, 2)
174
- q_pass, q_rot = torch.split(q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
175
-
176
- compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
177
- k_pass, k_rot = torch.split(compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
178
-
179
- k_pass = self.kv_b_proj(self.kv_a_layernorm(k_pass)).view(key_shape).transpose(1, 2)
180
- k_pass, value_states = torch.split(k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
181
-
182
- k_rot = k_rot.view(batch_size, 1, seq_length, self.qk_rope_head_dim)
183
-
184
- cos, sin = position_embeddings
185
- if self.config.rope_interleave:
186
- q_rot, k_rot = apply_rotary_pos_emb_interleave(q_rot, k_rot, cos, sin)
187
- else:
188
- q_rot, k_rot = apply_rotary_pos_emb(q_rot, k_rot, cos, sin)
189
- k_rot = k_rot.expand(*k_pass.shape[:-1], -1)
190
-
191
- query_states = torch.cat((q_pass, q_rot), dim=-1)
192
- key_states = torch.cat((k_pass, k_rot), dim=-1)
193
-
194
- if past_key_values is not None:
195
- cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
196
- key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
197
-
198
- if self.config._attn_implementation == "flash_attention_2" and self.qk_head_dim != self.v_head_dim:
199
- value_states = F.pad(value_states, [0, self.qk_head_dim - self.v_head_dim])
200
-
201
- attention_interface: Callable = eager_attention_forward
202
- if self.config._attn_implementation != "eager":
203
- attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
204
-
205
- attn_output, attn_weights = attention_interface(
206
- self,
207
- query_states,
208
- key_states,
209
- value_states,
210
- attention_mask,
211
- dropout=0.0 if not self.training else self.attention_dropout,
212
- scaling=self.scaling,
213
- **kwargs,
214
- )
215
-
216
- if self.config._attn_implementation == "flash_attention_2" and self.qk_head_dim != self.v_head_dim:
217
- attn_output = attn_output[:, :, :, : self.v_head_dim]
218
-
219
- attn_output = attn_output.reshape(batch_size, seq_length, -1).contiguous()
220
- attn_output = self.o_proj(attn_output)
221
- return attn_output, attn_weights
222
-
223
-
224
- class DeepseekV32DecoderLayer(nn.Module):
225
- def __init__(self, config: DeepseekV32Config, layer_idx: int):
226
- super().__init__()
227
- self.hidden_size = config.hidden_size
228
-
229
- # Use sparse attention for V3.2
230
- self.self_attn = DeepseekV32SparseAttention(config=config, layer_idx=layer_idx)
231
-
232
- if layer_idx >= config.first_k_dense_replace:
233
- self.mlp = DeepseekV32MoE(config)
234
- else:
235
- self.mlp = DeepseekV32MLP(config)
236
-
237
- self.input_layernorm = DeepseekV32RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
238
- self.post_attention_layernorm = DeepseekV32RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
239
-
240
- def forward(
241
- self,
242
- hidden_states: torch.Tensor,
243
- position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
244
- attention_mask: Optional[torch.Tensor] = None,
245
- past_key_values: Optional[Cache] = None,
246
- cache_position: Optional[torch.LongTensor] = None,
247
- **kwargs: Unpack[FlashAttentionKwargs],
248
- ) -> torch.Tensor:
249
- residual = hidden_states
250
-
251
- hidden_states = self.input_layernorm(hidden_states)
252
-
253
- # Self Attention
254
- hidden_states, self_attn_weights = self.self_attn(
255
- hidden_states=hidden_states,
256
- position_embeddings=position_embeddings,
257
- attention_mask=attention_mask,
258
- past_key_values=past_key_values,
259
- cache_position=cache_position,
260
- **kwargs,
261
- )
262
- hidden_states = residual + hidden_states
263
-
264
- # Fully Connected
265
- residual = hidden_states
266
- hidden_states = self.post_attention_layernorm(hidden_states)
267
- hidden_states = self.mlp(hidden_states)
268
- hidden_states = residual + hidden_states
269
-
270
- return hidden_states
271
-
272
-
273
- class DeepseekV32PreTrainedModel(DeepseekV3PreTrainedModel):
274
- config_class = DeepseekV32Config
275
- _can_compile_fullgraph = False
276
- _keep_in_fp32_modules_strict = ["e_score_correction_bias"]
277
-
278
-
279
- class DeepseekV32Model(DeepseekV3Model):
280
- """
281
- DeepSeek V3.2 Model with native sparse attention.
282
-
283
- This model extends DeepSeek V3 with an efficient sparse attention mechanism
284
- that uses an indexer to select top-k tokens for attention computation.
285
- """
286
- config_class = DeepseekV32Config
287
- _keys_to_ignore_on_load_unexpected = [r"model\.layers\.61.*"]
288
-
289
- def __init__(self, config: DeepseekV32Config):
290
- # Skip DeepseekV3Model.__init__ and go directly to PreTrainedModel
291
- DeepseekV3PreTrainedModel.__init__(self, config)
292
- self.padding_idx = config.pad_token_id
293
- self.vocab_size = config.vocab_size
294
-
295
- self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
296
- # Use V3.2-specific decoder layers
297
- self.layers = nn.ModuleList(
298
- [DeepseekV32DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
299
- )
300
- self.norm = DeepseekV32RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
301
- self.rotary_emb = DeepseekV32RotaryEmbedding(config=config)
302
- self.gradient_checkpointing = False
303
-
304
- # Initialize weights and apply final processing
305
- self.post_init()
306
-
307
-
308
- class DeepseekV32ForCausalLM(DeepseekV3ForCausalLM):
309
- """
310
- DeepSeek V3.2 Model for causal language modeling with sparse attention.
311
- """
312
- config_class = DeepseekV32Config
313
- _tied_weights_keys = ["lm_head.weight"]
314
-
315
- def __init__(self, config):
316
- super(DeepseekV3ForCausalLM, self).__init__(config)
317
- self.model = DeepseekV32Model(config)
318
- self.vocab_size = config.vocab_size
319
- self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
320
-
321
- # Initialize weights and apply final processing
322
- self.post_init()
323
-
324
-
325
- class DeepseekV32ForSequenceClassification(GenericForSequenceClassification, DeepseekV32PreTrainedModel):
326
- pass
327
-
328
-
329
- class DeepseekV32ForTokenClassification(GenericForTokenClassification, DeepseekV32PreTrainedModel):
330
- pass
331
-
332
-
333
- __all__ = [
334
- "DeepseekV32PreTrainedModel",
335
- "DeepseekV32Model",
336
- "DeepseekV32ForCausalLM",
337
- "DeepseekV32ForSequenceClassification",
338
- "DeepseekV32ForTokenClassification",
339
- ]