liyadong commited on
Commit
3ffc3b7
·
1 Parent(s): 59bc3ad

fix model file and script

Browse files
chat_template.jinja ADDED
@@ -0,0 +1 @@
 
 
1
+ {% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|role_start|>system<|role_end|>你是megrez-3x7b-a3b-instruct<|turn_end|>' }}{% endif %}{{ '<|role_start|>' + message['role'] + '<|role_end|>' + message['content'] + '<|turn_end|>' }}{% endfor %}{% if add_generation_prompt %}{{ '<|role_start|>assistant<|role_end|>' }}{% endif %}
config.json CHANGED
@@ -29,7 +29,7 @@
29
  "norm_topk_prob": true,
30
  "num_attention_heads": 16,
31
  "num_experts_per_tok": 6,
32
- "num_hidden_layers": 11,
33
  "num_key_value_heads": 4,
34
  "pad_token_id": 120002,
35
  "pre_gate": true,
 
29
  "norm_topk_prob": true,
30
  "num_attention_heads": 16,
31
  "num_experts_per_tok": 6,
32
+ "num_hidden_layers": 31,
33
  "num_key_value_heads": 4,
34
  "pad_token_id": 120002,
35
  "pre_gate": true,
model-00001-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1a7d2425fd5f1de10e9dfef4107cd5a23e077adb5dbf72e3650b1cbfcba991d0
3
+ size 4994539224
model-00002-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:510db202ee9e0172fdd3ab71fd7ed3ade9b78f9dae68f576a8712394e1eedf39
3
+ size 4995331096
model-00003-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c2bca00397338a1e77781693e9afa93625845c316f0930cb6499cfb4be60719c
3
+ size 4958908880
model.safetensors.index.json CHANGED
The diff for this file is too large to render. See raw diff
 
modeling_megrez_moe.py CHANGED
@@ -1,5 +1,5 @@
1
  # coding=utf-8
2
- # Copyright 2023 DeepSeek-AI and The HuggingFace Inc. team. All rights reserved.
3
  #
4
  # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
  # and OPT implementations in this library. It has been modified from its
@@ -17,53 +17,30 @@
17
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
  # See the License for the specific language governing permissions and
19
  # limitations under the License.
20
- """ PyTorch DeepSeek model."""
21
  import math
22
  import warnings
23
  from typing import List, Optional, Tuple, Union
24
 
 
25
  import torch
 
26
  import torch.nn.functional as F
27
- import torch.utils.checkpoint
28
  from torch import nn
29
  from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
-
31
  from transformers.activations import ACT2FN
32
  from transformers.cache_utils import Cache, DynamicCache
33
- from transformers.modeling_attn_mask_utils import (
34
- AttentionMaskConverter,
35
- _prepare_4d_attention_mask,
36
- _prepare_4d_causal_attention_mask,
37
- )
38
- from transformers.modeling_outputs import (
39
- BaseModelOutputWithPast,
40
- CausalLMOutputWithPast,
41
- SequenceClassifierOutputWithPast,
42
- )
43
  from transformers.modeling_utils import PreTrainedModel
44
- from transformers.pytorch_utils import (
45
- ALL_LAYERNORM_LAYERS,
46
- is_torch_greater_or_equal_than_1_13,
47
- )
48
- from transformers.utils import (
49
- add_start_docstrings,
50
- add_start_docstrings_to_model_forward,
51
- is_flash_attn_2_available,
52
- is_flash_attn_greater_or_equal_2_10,
53
- logging,
54
- replace_return_docstrings,
55
- )
56
- from transformers.utils.import_utils import is_torch_fx_available
57
- from .configuration_megrez_moe import MegrezMoeConfig
58
- import torch.distributed as dist
59
- import numpy as np
60
-
61
  from transformers.models.llama.modeling_llama import LlamaAttention, LlamaRotaryEmbedding
 
 
 
 
62
 
63
- if is_flash_attn_2_available():
64
- from flash_attn import flash_attn_func, flash_attn_varlen_func
65
- from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
66
-
67
 
68
  # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
69
  # It means that the function will not be traced through and simply appear as a node in the graph.
@@ -79,18 +56,6 @@ logger = logging.get_logger(__name__)
79
  _CONFIG_FOR_DOC = "MegrezMoeConfig"
80
 
81
 
82
- def _get_unpad_data(attention_mask):
83
- seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
84
- indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
85
- max_seqlen_in_batch = seqlens_in_batch.max().item()
86
- cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
87
- return (
88
- indices,
89
- cu_seqlens,
90
- max_seqlen_in_batch,
91
- )
92
-
93
-
94
  class MegrezMoeRMSNorm(nn.Module):
95
  def __init__(self, hidden_size, eps=1e-6):
96
  """
@@ -214,8 +179,9 @@ class MegrezMoeMoE(nn.Module):
214
  A mixed expert module containing shared experts.
215
  """
216
 
217
- def __init__(self, config, init_experts: bool = True):
218
  super().__init__()
 
219
  self.config = config
220
  self.num_experts_per_tok = config.num_experts_per_tok
221
 
@@ -267,7 +233,6 @@ class MegrezMoeMoE(nn.Module):
267
  topk_idx, topk_weight = self.gate(pre_gate_hidden_states)
268
  else:
269
  topk_idx, topk_weight = self.gate(hidden_states)
270
-
271
  hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
272
  flat_topk_idx = topk_idx.view(-1)
273
  if self.training:
@@ -280,7 +245,9 @@ class MegrezMoeMoE(nn.Module):
280
  else:
281
  y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
282
  if self.config.n_shared_experts is not None:
283
- y = y + self.shared_experts(identity)
 
 
284
  return y
285
 
286
  @torch.no_grad()
@@ -369,7 +336,9 @@ class MegrezMoeDecoderLayer(nn.Module):
369
  self.config = config
370
  self.layer_number = layer_idx
371
 
372
- self.experts_shared = config.experts_shared_frequency is not None and layer_idx >= self.config.first_k_dense_replace
 
 
373
 
374
  self.pre_gate = config.pre_gate
375
 
@@ -381,43 +350,11 @@ class MegrezMoeDecoderLayer(nn.Module):
381
  and layer_idx % config.moe_layer_freq == 0
382
  )
383
 
384
- if self.experts_shared:
385
- assert config.moe_layer_freq == 1
386
- self.self_attn = torch.nn.ModuleList(
387
- [LlamaAttention(config=config, layer_idx=layer_idx) for _ in range(config.experts_shared_frequency)]
388
- )
389
- for idx in range(config.experts_shared_frequency):
390
- attn_layer_idx = (
391
- layer_idx - self.config.first_k_dense_replace
392
- ) * self.config.experts_shared_frequency + self.config.first_k_dense_replace + idx
393
- self.self_attn[idx].layer_idx = attn_layer_idx
394
- self.input_layernorm = torch.nn.ModuleList(
395
- [
396
- MegrezMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
397
- for _ in range(config.experts_shared_frequency)
398
- ]
399
- )
400
- self.post_attention_layernorm = torch.nn.ModuleList(
401
- [
402
- MegrezMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
403
- for _ in range(config.experts_shared_frequency)
404
- ]
405
- )
406
-
407
- mlp = [MegrezMoeMoE(config, init_experts=True)]
408
- for _ in range(1, config.experts_shared_frequency):
409
- layer = MegrezMoeMoE(config, init_experts=False)
410
- # layer.set_experts(mlp[0].experts)
411
- mlp.append(layer)
412
- self.mlp = torch.nn.ModuleList(mlp)
413
-
414
- else:
415
-
416
- self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx)
417
-
418
- self.mlp = MegrezMoeMoE(config) if is_moe else MegrezMoeMLP(config)
419
- self.input_layernorm = MegrezMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
420
- self.post_attention_layernorm = MegrezMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
421
 
422
  def forward(
423
  self,
@@ -457,63 +394,32 @@ class MegrezMoeDecoderLayer(nn.Module):
457
  "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
458
  )
459
 
460
- if self.experts_shared:
461
-
462
- for idx in range(self.config.experts_shared_frequency):
463
- residual = hidden_states
464
-
465
- hidden_states = self.input_layernorm[idx](hidden_states)
466
-
467
- # Self Attention
468
- hidden_states, self_attn_weights = self.self_attn[idx](
469
- hidden_states=hidden_states,
470
- attention_mask=attention_mask,
471
- position_ids=position_ids,
472
- past_key_value=past_key_value,
473
- output_attentions=output_attentions,
474
- use_cache=use_cache,
475
- position_embeddings=position_embeddings,
476
- **kwargs,
477
- )
478
- hidden_states = residual + hidden_states
479
-
480
- # Fully Connected
481
- residual = hidden_states
482
- hidden_states = self.post_attention_layernorm[idx](hidden_states)
483
- post_attention_layernorm_hidden_states = hidden_states
484
- if idx > 0:
485
- self.mlp[idx].set_experts(self.mlp[0].experts)
486
- hidden_states = self.mlp[idx](hidden_states, pre_gate_hidden_states=pre_gate_hidden_states)
487
- if idx > 0:
488
- self.mlp[idx].set_experts(None)
489
- hidden_states = residual + hidden_states
490
- pre_gate_hidden_states = post_attention_layernorm_hidden_states
491
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
492
  else:
493
- residual = hidden_states
494
-
495
- hidden_states = self.input_layernorm(hidden_states)
496
-
497
- # Self Attention
498
- hidden_states, self_attn_weights = self.self_attn(
499
- hidden_states=hidden_states,
500
- attention_mask=attention_mask,
501
- position_ids=position_ids,
502
- past_key_value=past_key_value,
503
- output_attentions=output_attentions,
504
- use_cache=use_cache,
505
- position_embeddings=position_embeddings,
506
- **kwargs,
507
- )
508
- hidden_states = residual + hidden_states
509
-
510
- # Fully Connected
511
- residual = hidden_states
512
- hidden_states = self.post_attention_layernorm(hidden_states)
513
- post_attention_layernorm_hidden_states = hidden_states
514
  hidden_states = self.mlp(hidden_states)
515
- hidden_states = residual + hidden_states
516
- pre_gate_hidden_states = post_attention_layernorm_hidden_states
517
 
518
  if self.pre_gate and self.layer_number < self.config.num_hidden_layers - 1:
519
  hidden_states = torch.cat([pre_gate_hidden_states, hidden_states], dim=0)
@@ -728,7 +634,6 @@ class MegrezMoeModel(MegrezMoePreTrainedModel):
728
 
729
  if inputs_embeds is None:
730
  inputs_embeds = self.embed_tokens(input_ids)
731
-
732
  if self._use_flash_attention_2:
733
  # 2d mask is passed through the layers
734
  attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
@@ -750,11 +655,19 @@ class MegrezMoeModel(MegrezMoePreTrainedModel):
750
  next_decoder_cache = None
751
 
752
  position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
753
-
754
- for decoder_layer in self.layers:
755
  if output_hidden_states:
756
  all_hidden_states += (hidden_states,)
757
 
 
 
 
 
 
 
 
 
 
758
  if self.gradient_checkpointing and self.training:
759
  layer_outputs = self._gradient_checkpointing_func(
760
  decoder_layer.__call__,
@@ -778,14 +691,14 @@ class MegrezMoeModel(MegrezMoePreTrainedModel):
778
  position_embeddings=position_embeddings,
779
  **flash_attn_kwargs,
780
  )
781
-
 
782
  hidden_states = layer_outputs[0]
783
 
784
  if output_attentions:
785
  all_self_attns += (layer_outputs[1],)
786
 
787
  hidden_states = self.norm(hidden_states)
788
-
789
  # add hidden states from the last decoder layer
790
  if output_hidden_states:
791
  all_hidden_states += (hidden_states,)
 
1
  # coding=utf-8
2
+ # Copyright 2025 Infini-AI and The HuggingFace Inc. team. All rights reserved.
3
  #
4
  # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
  # and OPT implementations in this library. It has been modified from its
 
17
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
  # See the License for the specific language governing permissions and
19
  # limitations under the License.
20
+ """PyTorch Megrez model."""
21
  import math
22
  import warnings
23
  from typing import List, Optional, Tuple, Union
24
 
25
+ import numpy as np
26
  import torch
27
+ import torch.distributed as dist
28
  import torch.nn.functional as F
 
29
  from torch import nn
30
  from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
 
31
  from transformers.activations import ACT2FN
32
  from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
34
+ from transformers.modeling_outputs import (BaseModelOutputWithPast, CausalLMOutputWithPast,
35
+ SequenceClassifierOutputWithPast)
 
 
 
 
 
 
 
36
  from transformers.modeling_utils import PreTrainedModel
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  from transformers.models.llama.modeling_llama import LlamaAttention, LlamaRotaryEmbedding
38
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
39
+ from transformers.utils import (add_start_docstrings, add_start_docstrings_to_model_forward, logging,
40
+ replace_return_docstrings)
41
+ from transformers.utils.import_utils import is_torch_fx_available
42
 
43
+ from .configuration_megrez_moe import MegrezMoeConfig
 
 
 
44
 
45
  # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
46
  # It means that the function will not be traced through and simply appear as a node in the graph.
 
56
  _CONFIG_FOR_DOC = "MegrezMoeConfig"
57
 
58
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  class MegrezMoeRMSNorm(nn.Module):
60
  def __init__(self, hidden_size, eps=1e-6):
61
  """
 
179
  A mixed expert module containing shared experts.
180
  """
181
 
182
+ def __init__(self, config, layer_number, init_experts: bool = True):
183
  super().__init__()
184
+ self.layer_number = layer_number
185
  self.config = config
186
  self.num_experts_per_tok = config.num_experts_per_tok
187
 
 
233
  topk_idx, topk_weight = self.gate(pre_gate_hidden_states)
234
  else:
235
  topk_idx, topk_weight = self.gate(hidden_states)
 
236
  hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
237
  flat_topk_idx = topk_idx.view(-1)
238
  if self.training:
 
245
  else:
246
  y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
247
  if self.config.n_shared_experts is not None:
248
+ shared_out = self.shared_experts(identity)
249
+ y = y + shared_out
250
+ # y = y + self.shared_experts(identity)
251
  return y
252
 
253
  @torch.no_grad()
 
336
  self.config = config
337
  self.layer_number = layer_idx
338
 
339
+ self.experts_shared = (
340
+ config.experts_shared_frequency is not None and layer_idx >= self.config.first_k_dense_replace
341
+ )
342
 
343
  self.pre_gate = config.pre_gate
344
 
 
350
  and layer_idx % config.moe_layer_freq == 0
351
  )
352
 
353
+ init_experts = (layer_idx - config.first_k_dense_replace) % config.experts_shared_frequency == 0
354
+ self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx)
355
+ self.mlp = MegrezMoeMoE(config, layer_idx, init_experts) if is_moe else MegrezMoeMLP(config)
356
+ self.input_layernorm = MegrezMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
357
+ self.post_attention_layernorm = MegrezMoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358
 
359
  def forward(
360
  self,
 
394
  "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
395
  )
396
 
397
+ residual = hidden_states
398
+ hidden_states = self.input_layernorm(hidden_states)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
399
 
400
+ # Self Attention
401
+ hidden_states, self_attn_weights = self.self_attn(
402
+ hidden_states=hidden_states,
403
+ attention_mask=attention_mask,
404
+ position_ids=position_ids,
405
+ past_key_value=past_key_value,
406
+ output_attentions=output_attentions,
407
+ use_cache=use_cache,
408
+ position_embeddings=position_embeddings,
409
+ **kwargs,
410
+ )
411
+ hidden_states = residual + hidden_states
412
+
413
+ # Fully Connected
414
+ residual = hidden_states
415
+ hidden_states = self.post_attention_layernorm(hidden_states)
416
+ post_attention_layernorm_hidden_states = hidden_states
417
+ if isinstance(self.mlp, MegrezMoeMoE):
418
+ hidden_states = self.mlp(hidden_states, pre_gate_hidden_states=pre_gate_hidden_states)
419
  else:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420
  hidden_states = self.mlp(hidden_states)
421
+ hidden_states = residual + hidden_states
422
+ pre_gate_hidden_states = post_attention_layernorm_hidden_states
423
 
424
  if self.pre_gate and self.layer_number < self.config.num_hidden_layers - 1:
425
  hidden_states = torch.cat([pre_gate_hidden_states, hidden_states], dim=0)
 
634
 
635
  if inputs_embeds is None:
636
  inputs_embeds = self.embed_tokens(input_ids)
 
637
  if self._use_flash_attention_2:
638
  # 2d mask is passed through the layers
639
  attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
 
655
  next_decoder_cache = None
656
 
657
  position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
658
+ for layer_idx, decoder_layer in enumerate(self.layers):
 
659
  if output_hidden_states:
660
  all_hidden_states += (hidden_states,)
661
 
662
+ shared_layer_idx = (
663
+ (layer_idx - self.config.first_k_dense_replace)
664
+ // self.config.experts_shared_frequency
665
+ * self.config.experts_shared_frequency
666
+ + self.config.first_k_dense_replace
667
+ )
668
+ if layer_idx >= self.config.first_k_dense_replace and shared_layer_idx != layer_idx:
669
+ decoder_layer.mlp.set_experts(self.layers[shared_layer_idx].mlp.experts)
670
+
671
  if self.gradient_checkpointing and self.training:
672
  layer_outputs = self._gradient_checkpointing_func(
673
  decoder_layer.__call__,
 
691
  position_embeddings=position_embeddings,
692
  **flash_attn_kwargs,
693
  )
694
+ if layer_idx >= self.config.first_k_dense_replace and shared_layer_idx != layer_idx:
695
+ decoder_layer.mlp.set_experts(None)
696
  hidden_states = layer_outputs[0]
697
 
698
  if output_attentions:
699
  all_self_attns += (layer_outputs[1],)
700
 
701
  hidden_states = self.norm(hidden_states)
 
702
  # add hidden states from the last decoder layer
703
  if output_hidden_states:
704
  all_hidden_states += (hidden_states,)