luguoshan commited on
Commit
9d2babf
·
1 Parent(s): cf04c33

First model version

Browse files
Files changed (50) hide show
  1. README.md +141 -3
  2. config.json +56 -0
  3. configuration_llada2_moe.py +87 -0
  4. model-00001-of-00042.safetensors +3 -0
  5. model-00002-of-00042.safetensors +3 -0
  6. model-00003-of-00042.safetensors +3 -0
  7. model-00004-of-00042.safetensors +3 -0
  8. model-00005-of-00042.safetensors +3 -0
  9. model-00006-of-00042.safetensors +3 -0
  10. model-00007-of-00042.safetensors +3 -0
  11. model-00008-of-00042.safetensors +3 -0
  12. model-00009-of-00042.safetensors +3 -0
  13. model-00010-of-00042.safetensors +3 -0
  14. model-00011-of-00042.safetensors +3 -0
  15. model-00012-of-00042.safetensors +3 -0
  16. model-00013-of-00042.safetensors +3 -0
  17. model-00014-of-00042.safetensors +3 -0
  18. model-00015-of-00042.safetensors +3 -0
  19. model-00016-of-00042.safetensors +3 -0
  20. model-00017-of-00042.safetensors +3 -0
  21. model-00018-of-00042.safetensors +3 -0
  22. model-00019-of-00042.safetensors +3 -0
  23. model-00020-of-00042.safetensors +3 -0
  24. model-00021-of-00042.safetensors +3 -0
  25. model-00022-of-00042.safetensors +3 -0
  26. model-00023-of-00042.safetensors +3 -0
  27. model-00024-of-00042.safetensors +3 -0
  28. model-00025-of-00042.safetensors +3 -0
  29. model-00026-of-00042.safetensors +3 -0
  30. model-00027-of-00042.safetensors +3 -0
  31. model-00028-of-00042.safetensors +3 -0
  32. model-00029-of-00042.safetensors +3 -0
  33. model-00030-of-00042.safetensors +3 -0
  34. model-00031-of-00042.safetensors +3 -0
  35. model-00032-of-00042.safetensors +3 -0
  36. model-00033-of-00042.safetensors +3 -0
  37. model-00034-of-00042.safetensors +3 -0
  38. model-00035-of-00042.safetensors +3 -0
  39. model-00036-of-00042.safetensors +3 -0
  40. model-00037-of-00042.safetensors +3 -0
  41. model-00038-of-00042.safetensors +3 -0
  42. model-00039-of-00042.safetensors +3 -0
  43. model-00040-of-00042.safetensors +3 -0
  44. model-00041-of-00042.safetensors +3 -0
  45. model-00042-of-00042.safetensors +3 -0
  46. model.safetensors.index.json +0 -0
  47. modeling_llada2_moe.py +1804 -0
  48. special_tokens_map.json +8 -0
  49. tokenizer.json +0 -0
  50. tokenizer_config.json +18 -0
README.md CHANGED
@@ -1,3 +1,141 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ library_name: transformers
4
+ tags:
5
+ - dllm
6
+ - diffusion
7
+ - llm
8
+ - text_generation
9
+ ---
10
+ # LLaDA2.0-flash-CAP
11
+
12
+ **LLaDA2.0-flash-CAP** is an enhanced version of LLaDA2.0-flash that incorporates **Confidence-Aware Parallel (CAP) Training** for significantly improved inference efficiency. Built upon the 100B-A6B Mixture-of-Experts (MoE) diffusion architecture, this model achieves faster parallel decoding while maintaining strong performance across diverse benchmarks.
13
+
14
+ ---
15
+
16
+ ## 📊 Performance Comparison
17
+ ### Efficiency vs. Quality Trade-off
18
+ | Model | Average Score | Tokens/Forward (TPF) | Speedup |
19
+ | :---: | :---: | :---: | :---: |
20
+ | LLaDA2.0-flash | 78.57 | 3.19 | 1.0× |
21
+ | **LLaDA2.0-flash-CAP** | **76.85** | **4.65** | **1.46×** |
22
+
23
+
24
+ _Evaluated on 12 diverse benchmarks covering knowledge, reasoning, coding, and mathematics._
25
+
26
+ ### Key Insights
27
+ + **1.46× faster generation** with only a 1.72% performance trade-off
28
+ + Ideal for latency-sensitive applications requiring real-time responses
29
+ + Maintains competitive accuracy across all task categories
30
+
31
+ ---
32
+
33
+ ## 🔬 What is CAP Training?
34
+ **Confidence-Aware Parallel (CAP) Training** is a novel training technique designed to enhance parallel decoding efficiency in diffusion language models.
35
+
36
+ ### Technical Overview
37
+ The training objective combines two complementary losses:
38
+
39
+ ```math
40
+ L(θ) = L_SFT(θ) + λL_conf(θ)
41
+ ```
42
+
43
+ Where:
44
+
45
+ + **L_SFT**: Supervised fine-tuning loss ensuring prediction correctness
46
+ + **L_conf**: Confidence loss that minimizes entropy only for correctly predicted tokens
47
+ + **λ**: Hyperparameter balancing the two objectives
48
+
49
+ ### Why CAP Works
50
+ 1. **Sharpens Correct Predictions**: While standard training ensures correctness, it provides diminishing incentive to increase confidence on already-correct tokens. CAP explicitly optimizes for high-confidence predictions.
51
+ 2. **Enables Aggressive Parallelism**: Higher confidence allows the model to decode multiple tokens simultaneously with greater reliability, reducing the total number of forward passes needed.
52
+ 3. **Selective Optimization**: By focusing only on correct predictions, CAP avoids penalizing the model's exploration of uncertain outputs.
53
+
54
+ ---
55
+
56
+ ## 📦 Model Variants
57
+ | Model ID | Description | Hugging Face Link |
58
+ | --- | --- | --- |
59
+ | `inclusionAI/LLaDA2.0-flash-CAP` | CAP-enhanced model optimized for fast inference | [🤗 Model Card](https://huggingface.co/inclusionAI/LLaDA2.0-flash-CAP) |
60
+ | `inclusionAI/LLaDA2.0-flash` | Base instruction-tuned model | [🤗 Model Card](https://huggingface.co/inclusionAI/LLaDA2.0-flash) |
61
+
62
+
63
+ ---
64
+
65
+ ## 🔍 Model Overview
66
+ **LLaDA2.0-flash-CAP** inherits the architecture of LLaDA2.0-flash:
67
+
68
+ + **Type**: Mixture-of-Experts (MoE) Diffusion Language Model
69
+ + **Total Parameters (Non-Embedding)**: 100B
70
+ + **Number of Layers**: 32
71
+ + **Attention Heads**: 32
72
+ + **Context Length**: 32,768 tokens
73
+ + **Position Embedding**: Rotary (RoPE)
74
+ + **Vocabulary Size**: 157,184
75
+ + **Training Enhancement**: Confidence-Aware Parallel (CAP) Training
76
+
77
+ ---
78
+
79
+ ## 💻 Usage
80
+ ### 🤗 Hugging Face Transformers
81
+ ```python
82
+ import torch
83
+ import torch.nn.functional as F
84
+ from transformers import AutoModelForCausalLM
85
+ from transformers import AutoTokenizer
86
+
87
+ model_path = "/path/to/LLaDA2.0-flash-CAP"
88
+ device = "cuda:0"
89
+ model = AutoModelForCausalLM.from_pretrained(
90
+ model_path, trust_remote_code=True, device_map=device
91
+ )
92
+ model = model.to(torch.bfloat16)
93
+ model.eval()
94
+ tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
95
+
96
+ prompt = "Why does Camus think that Sisyphus is happy?"
97
+ input_ids = tokenizer.apply_chat_template(
98
+ [{"role": "user", "content": prompt}],
99
+ add_generation_prompt=True,
100
+ tokenize=True,
101
+ return_tensors="pt",
102
+ )
103
+ generated_tokens = model.generate(
104
+ inputs=input_ids,
105
+ eos_early_stop=True,
106
+ gen_length=512,
107
+ block_length=32,
108
+ steps=32,
109
+ temperature=0.0,
110
+ )
111
+ generated_answer = tokenizer.decode(
112
+ generated_tokens[0],
113
+ skip_special_tokens=True,
114
+ )
115
+ print(generated_answer)
116
+ ```
117
+
118
+
119
+
120
+ ### Best Practices
121
+ To achieve optimal performance, we recommend the following settings:
122
+
123
+ 1. **Sampling Parameters**:
124
+ We suggest using `Temperature=0.0`, `block_length=32`, and `steps=32`. Using a higher temperature value may occasionally result in language mixing and a slight decrease in model performance.
125
+ 2. **Adequate Output Length**:
126
+ We recommend using an output length of 32768 tokens for most queries.
127
+
128
+ ---
129
+
130
+ ## 🌐 License
131
+ This project is licensed under the terms of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0).
132
+
133
+ ---
134
+
135
+ ## 🤝 Contact & Collaboration
136
+ For questions, collaborations, or feedback, please reach out via [Hugging Face](https://huggingface.co/inclusionAI/LLaDA2.0-flash-CAP) or open an issue in the [repository](https://github.com/inclusionAI).
137
+
138
+ 👉 Join us in advancing open, efficient, and intelligent language models!
139
+
140
+ ---
141
+
config.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "LLaDA2MoeModelLM"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_llada2_moe.LLaDA2MoeConfig",
8
+ "AutoModel": "modeling_llada2_moe.LLaDA2MoeModel",
9
+ "AutoModelForCausalLM": "modeling_llada2_moe.LLaDA2MoeModelLM"
10
+ },
11
+ "embedding_dropout": 0.0,
12
+ "first_k_dense_replace": 1,
13
+ "head_dim": 128,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 4096,
16
+ "initializer_range": 0.02,
17
+ "intermediate_size": 9216,
18
+ "max_position_embeddings": 32768,
19
+ "max_window_layers": 28,
20
+ "model_type": "llada2_moe",
21
+ "moe_intermediate_size": 1024,
22
+ "moe_router_enable_expert_bias": true,
23
+ "n_group": 8,
24
+ "norm_head": false,
25
+ "norm_softmax": false,
26
+ "norm_topk_prob": true,
27
+ "num_attention_heads": 32,
28
+ "num_experts": 256,
29
+ "num_experts_per_tok": 8,
30
+ "num_hidden_layers": 32,
31
+ "num_key_value_heads": 4,
32
+ "num_shared_experts": 1,
33
+ "output_dropout": 0.0,
34
+ "output_router_logits": false,
35
+ "pad_token_id": 156892,
36
+ "partial_rotary_factor": 0.5,
37
+ "rms_norm_eps": 1e-06,
38
+ "rope_scaling": null,
39
+ "rope_theta": 600000,
40
+ "rotary_dim": 64,
41
+ "routed_scaling_factor": 2.5,
42
+ "router_dtype": "fp32",
43
+ "score_function": "sigmoid",
44
+ "sliding_window": 4096,
45
+ "tie_word_embeddings": false,
46
+ "topk_group": 4,
47
+ "torch_dtype": "bfloat16",
48
+ "transformers_version": "4.51.0",
49
+ "use_bias": false,
50
+ "use_cache": false,
51
+ "use_qkv_bias": false,
52
+ "use_rmsnorm": true,
53
+ "use_sliding_window": false,
54
+ "using_split_qkv_in_self_attention": false,
55
+ "vocab_size": 157184
56
+ }
configuration_llada2_moe.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LLaDA2 MoE model configuration"""
2
+
3
+ from transformers.configuration_utils import PretrainedConfig
4
+
5
+
6
+ class LLaDA2MoeConfig(PretrainedConfig):
7
+ model_type = "llada2_moe"
8
+
9
+ def __init__(
10
+ self,
11
+ vocab_size=30592,
12
+ hidden_size=1024,
13
+ intermediate_size=None,
14
+ num_hidden_layers=24,
15
+ num_attention_heads=16,
16
+ num_key_value_heads=0,
17
+ hidden_act="silu",
18
+ use_qkv_bias=False, # llada2 only
19
+ use_qk_norm=False,
20
+ use_bias=True, # llada2 only
21
+ rms_norm_eps=1e-05,
22
+ norm_head=False, # llada2 only
23
+ tie_word_embeddings=False, # PretrainedConfig key, here change default value.
24
+ embedding_dropout=0.1,
25
+ attention_dropout=0.1,
26
+ output_dropout=0.1,
27
+ initializer_range=0.02,
28
+ max_position_embeddings=16384,
29
+ rope_theta=10000.0,
30
+ use_cache=True,
31
+ use_sliding_window=False,
32
+ sliding_window=4096,
33
+ max_window_layers=28,
34
+ rope_scaling=None,
35
+ pad_token_id=126081,
36
+ num_experts=16,
37
+ num_shared_experts=0,
38
+ num_experts_per_tok=2,
39
+ n_group=8,
40
+ topk_group=4,
41
+ routed_scaling_factor=2.5,
42
+ moe_intermediate_size=None,
43
+ first_k_dense_replace=0,
44
+ head_dim=None,
45
+ output_router_logits=False,
46
+ partial_rotary_factor=0.5,
47
+ **kwargs,
48
+ ):
49
+ self.num_hidden_layers = num_hidden_layers
50
+ self.vocab_size = vocab_size
51
+ self.hidden_size = hidden_size
52
+ self.intermediate_size = intermediate_size
53
+ self.num_attention_heads = num_attention_heads
54
+ self.num_key_value_heads = num_key_value_heads
55
+ self.hidden_act = hidden_act
56
+ self.use_qkv_bias = use_qkv_bias
57
+ self.use_bias = use_bias
58
+ self.norm_head = norm_head
59
+ self.rms_norm_eps = rms_norm_eps
60
+ self.embedding_dropout = embedding_dropout
61
+ self.attention_dropout = attention_dropout
62
+ self.output_dropout = output_dropout
63
+ self.initializer_range = initializer_range
64
+ self.max_position_embeddings = max_position_embeddings
65
+ self.rope_theta = rope_theta
66
+ self.use_cache = use_cache
67
+ self.use_sliding_window = use_sliding_window
68
+ self.sliding_window = sliding_window
69
+ self.max_window_layers = max_window_layers
70
+ self.head_dim = head_dim or self.hidden_size // self.num_attention_heads
71
+ self.rope_scaling = rope_scaling
72
+
73
+ # MoE configs
74
+ self.num_experts = num_experts
75
+ self.num_shared_experts = num_shared_experts
76
+ self.num_experts_per_tok = num_experts_per_tok
77
+ self.n_group = n_group
78
+ self.topk_group = topk_group
79
+ self.moe_intermediate_size = moe_intermediate_size
80
+ self.first_k_dense_replace = first_k_dense_replace
81
+ self.output_router_logits = output_router_logits
82
+ self.routed_scaling_factor = routed_scaling_factor
83
+ self.partial_rotary_factor = partial_rotary_factor
84
+
85
+ super().__init__(
86
+ pad_token_id=pad_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs
87
+ )
model-00001-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f9a69b721654eb565d97d87b89ad7795338d23f6778658012528092774cedd3e
3
+ size 4995484480
model-00002-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2383dc18cd853afe26d35eaa04823df41e091d064e25b30c5c9a361e43b5f044
3
+ size 4993409784
model-00003-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36795163f3e7a7272e8b99b2d7ae168e5d07015cfa7dbd9d4536017ca6297596
3
+ size 4993409464
model-00004-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d453ecf6ba690b46cb5d67a42053b80b020e8befb2fafb24f175986e6ed24145
3
+ size 4999684432
model-00005-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1ff3526a3b9ccee49147448539175b2fd07d6ab5a6c3baa284bc821ff254391e
3
+ size 4993409648
model-00006-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:04cd3ac2a284af7b29212fd27d9bbec5f306e6298a12cc2cbea4daa2bfc372cc
3
+ size 4993409864
model-00007-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:67d32d6a5d8685f368657323fe52f0b4281e05f8e0d87e86e8549f8a3f6b7da1
3
+ size 4993409424
model-00008-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:61f4df4da00fcc8be046d53d8e36d40c99ac8c830bf419373c39353961b553cc
3
+ size 4999684472
model-00009-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d3dd7933cd4d2560cad02d069af99c9d59212e48c75ee2a0364f7202a50232cd
3
+ size 4993409576
model-00010-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b6cf0d073bc68e70edaaac58e85e3349336e1d0d82801720c75a37976e9b6d2b
3
+ size 4993409824
model-00011-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2edf764d30fe4de9d15e640418a4a87f32fe9ed1f4d2585d261cc401e58df907
3
+ size 4993409512
model-00012-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:345de49ff058831f927ac611607e1278045d3bfd694d5f4f1daf467f60d2b7b5
3
+ size 4999684504
model-00013-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8a1cbc4d3b694186024588857cfd6917d14a92d7575a53ae4cab2bf844dfd4dc
3
+ size 4993410040
model-00014-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a704b28f8b7b1227e8bc62b860e53d1813beece7db563998c6f9e0d9e1f4f6b9
3
+ size 4993410376
model-00015-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c2fe0a734958f744a2d7b5a2c3faa11f899fff475fb0701260fff18d36d0fe4b
3
+ size 4993410232
model-00016-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:59c84495781bfab04c73558091aefebfc95727d9b7fcfd210dc7bb0164927177
3
+ size 4999685104
model-00017-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b8dacf8af93a32160685dea1b20e7499bd23b2a0d370a99ad1b896d09c1b02f2
3
+ size 4993410040
model-00018-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8740773e62a31401e1bd29a4a635bc5ce35b4ea924ade07073a45e8069d9f392
3
+ size 4993410312
model-00019-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a405f2fbd957855c94ae6b2303c9e7c6fb634cfa3df5333d9a2a638dfd0a50dc
3
+ size 4993410328
model-00020-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e1b10d2a846b634b1ad4a854f0fcf21cef44d3ce0b0fb0acac77cd32953b5855
3
+ size 4993410080
model-00021-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d2c43057a1658cf9d65c1a7895ccee505fca7c163c54e9319a1da348fc737b77
3
+ size 4999685016
model-00022-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:08fbd68f6e439629354c4838b9fc047c3139878b553b47bd68278bdf5ad7e0e2
3
+ size 4993410272
model-00023-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ad41131311ee87fa0b638759333d9ee60d66ef027b4695e6add9e41baaffa9a6
3
+ size 4993410416
model-00024-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7851edcf9ea6a5bc833fe4301513154c053eefea2efecafaa9edf5563ea6f219
3
+ size 4993410032
model-00025-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:931bba910813da3e18f30c9647ad27d1fce891ce83b02f9db24c104208947060
3
+ size 4999685048
model-00026-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:71895f3407434d64c85008014dcc9507f19ea71a51822221a6aa9750f3cf41ea
3
+ size 4993410200
model-00027-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1bfb3e4bc12458fa4ba5aa570170cbd051b94801a405046205c2bc71441a08e2
3
+ size 4993410432
model-00028-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0ef90ef0e57ba2389d3046fc7aa4e8fde9c3843a41639949a6bb8785b269d7ce
3
+ size 4993410056
model-00029-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7bdc968de461947117519cdfd6896e6690f0d7ca8733d30b2a642e254eead8dc
3
+ size 4999685088
model-00030-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cbbf061a8a63ffe3e4d0c2d20ec3d72a475d1721db7123ac9ade0676504ac0d3
3
+ size 4993410128
model-00031-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:68501a88c3cbb8616a951f6cd17c67ba9eeccc640f515d4297ad6324f0dc6b6d
3
+ size 4993410392
model-00032-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:505b26ead99b47f2be748e3f1febae299c54d46f78c614b93203366cffe0d61f
3
+ size 4993410168
model-00033-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4dc2530db28c60078b8578532193f9d81b29ac1544e659200419023b69c6631e
3
+ size 4999685104
model-00034-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9fbc289edaaa517a2a7e730e19a4f66abfa74a1d1d7e0fd243b9c0012395edab
3
+ size 4993410064
model-00035-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4312862c80a9ffbcddf6e3a5ea4cc61da97edd30ff57e48788ab0b085f186e61
3
+ size 4993410336
model-00036-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc721a1a7cccc79d437180c840cf9f511ca877003d98837b2cfa038c18957547
3
+ size 4993410288
model-00037-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1e32be857d2bf35d0b94d249c409462bd9a64d0592016054d5c0db992ba1d783
3
+ size 4999685104
model-00038-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fa00f7cb3dda9422d61a2950e2f73bf1e3aa5126ece721029994fe6ca3c43953
3
+ size 4993410024
model-00039-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58a80b2cc4a612cb87761d0dbbae74853349a758b8a75043733a24a3ca6f21f6
3
+ size 4993410296
model-00040-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8655edc8ae867a805933e2636f694a2d7843a0e411adba813585d4d68c648820
3
+ size 4993410368
model-00041-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b6111dd16362a80b1df3e8e70715b965a366f959bd8f5a1f12bcfe9998ccc82b
3
+ size 4699812800
model-00042-of-00042.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f55d21f4f9523b17cd9e3402f83741f9b08fa94ddfe65c72f9c802f3afe4e58
3
+ size 1287670696
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_llada2_moe.py ADDED
@@ -0,0 +1,1804 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Antgroup and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
4
+ # and OPT implementations in this library. It has been modified from its
5
+ # original forms to accommodate minor architectural differences compared
6
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
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 LLaDA2MoE model."""
20
+
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 CrossEntropyLoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import (
34
+ _prepare_4d_causal_attention_mask,
35
+ _prepare_4d_causal_attention_mask_for_sdpa,
36
+ )
37
+ from transformers.modeling_outputs import (
38
+ MoeModelOutputWithPast,
39
+ MoeCausalLMOutputWithPast,
40
+ )
41
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
42
+ from transformers.modeling_utils import PreTrainedModel
43
+ from transformers.pytorch_utils import (
44
+ ALL_LAYERNORM_LAYERS,
45
+ is_torch_greater_or_equal_than_1_13,
46
+ )
47
+ from transformers.utils import (
48
+ add_start_docstrings,
49
+ add_start_docstrings_to_model_forward,
50
+ is_flash_attn_2_available,
51
+ is_flash_attn_greater_or_equal_2_10,
52
+ logging,
53
+ replace_return_docstrings,
54
+ )
55
+ from transformers.utils.import_utils import is_torch_fx_available
56
+ from .configuration_llada2_moe import LLaDA2MoeConfig
57
+ from transformers.generation.utils import GenerationMixin
58
+
59
+
60
+ if is_flash_attn_2_available():
61
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
62
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
63
+
64
+
65
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
66
+ # It means that the function will not be traced through and simply appear as a node in the graph.
67
+ if is_torch_fx_available():
68
+ if not is_torch_greater_or_equal_than_1_13:
69
+ import torch.fx
70
+
71
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
72
+
73
+
74
+ logger = logging.get_logger(__name__)
75
+
76
+ _CONFIG_FOR_DOC = "LLaDA2MoeConfig"
77
+
78
+
79
+ def _get_unpad_data(attention_mask):
80
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
81
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
82
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
83
+ cu_seqlens = F.pad(
84
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
85
+ )
86
+ return (
87
+ indices,
88
+ cu_seqlens,
89
+ max_seqlen_in_batch,
90
+ )
91
+
92
+
93
+ class LLaDA2MoeRMSNorm(nn.Module):
94
+ def __init__(self, hidden_size, eps=1e-6):
95
+ """
96
+ LLaDA2MoeRMSNorm is equivalent to T5LayerNorm
97
+ """
98
+ super().__init__()
99
+ self.weight = nn.Parameter(torch.ones(hidden_size))
100
+ self.variance_epsilon = eps
101
+
102
+ def forward(self, hidden_states):
103
+ input_dtype = hidden_states.dtype
104
+ hidden_states = hidden_states.to(torch.float32)
105
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
106
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
107
+ return self.weight * hidden_states.to(input_dtype)
108
+
109
+
110
+ ALL_LAYERNORM_LAYERS.append(LLaDA2MoeRMSNorm)
111
+
112
+
113
+ class LLaDA2MoeRotaryEmbedding(nn.Module):
114
+ def __init__(self, config: LLaDA2MoeConfig, device=None):
115
+ super().__init__()
116
+ # BC: "rope_type" was originally "type"
117
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
118
+ self.rope_type = config.rope_scaling.get(
119
+ "rope_type", config.rope_scaling.get("type")
120
+ )
121
+ else:
122
+ self.rope_type = "default"
123
+ self.max_seq_len_cached = config.max_position_embeddings
124
+ self.original_max_seq_len = config.max_position_embeddings
125
+
126
+ self.config = config
127
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
128
+
129
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
130
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
131
+ self.original_inv_freq = self.inv_freq
132
+
133
+ @torch.no_grad()
134
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
135
+ def forward(self, x, position_ids):
136
+ inv_freq_expanded = (
137
+ self.inv_freq[None, :, None]
138
+ .float()
139
+ .expand(position_ids.shape[0], -1, 1)
140
+ .to(x.device)
141
+ )
142
+ position_ids_expanded = position_ids[:, None, :].float()
143
+
144
+ device_type = (
145
+ x.device.type
146
+ if isinstance(x.device.type, str) and x.device.type != "mps"
147
+ else "cpu"
148
+ )
149
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
150
+ freqs = (
151
+ inv_freq_expanded.float() @ position_ids_expanded.float()
152
+ ).transpose(1, 2)
153
+ emb = torch.cat((freqs, freqs), dim=-1)
154
+ cos = emb.cos() * self.attention_scaling
155
+ sin = emb.sin() * self.attention_scaling
156
+
157
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
158
+
159
+
160
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
161
+ def rotate_half(x):
162
+ """Rotates half the hidden dims of the input."""
163
+ x1 = x[..., : x.shape[-1] // 2]
164
+ x2 = x[..., x.shape[-1] // 2 :]
165
+ return torch.cat((-x2, x1), dim=-1)
166
+
167
+
168
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
169
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
170
+ """Applies Rotary Position Embedding to the query and key tensors.
171
+
172
+ Args:
173
+ q (`torch.Tensor`): The query tensor.
174
+ k (`torch.Tensor`): The key tensor.
175
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
176
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
177
+ position_ids (`torch.Tensor`):
178
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
179
+ used to pass offsetted position ids when working with a KV-cache.
180
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
181
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
182
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
183
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
184
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
185
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
186
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
187
+ Returns:
188
+ `tuple(torch.Tensor)` comprising the query and key tensors rotated using the Rotary Position Embedding.
189
+ """
190
+ cos = cos.unsqueeze(unsqueeze_dim)
191
+ sin = sin.unsqueeze(unsqueeze_dim)
192
+
193
+ # Keep half or full tensor for later concatenation
194
+ rotary_dim = cos.shape[-1]
195
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
196
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
197
+
198
+ # Apply rotary embeddings on the first half or full tensor
199
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
200
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
201
+
202
+ # Concatenate back to full shape
203
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
204
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
205
+ return q_embed, k_embed
206
+
207
+
208
+ class LLaDA2MoeMLP(nn.Module):
209
+ def __init__(self, config: LLaDA2MoeConfig, intermediate_size: int):
210
+ super().__init__()
211
+ self.config = config
212
+ self.hidden_size = config.hidden_size
213
+ self.intermediate_size = intermediate_size
214
+
215
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
216
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
217
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
218
+ self.act_fn = ACT2FN[config.hidden_act]
219
+
220
+ def forward(self, x):
221
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
222
+
223
+
224
+ class LLaDA2MoeGate(nn.Module):
225
+ def __init__(self, config):
226
+ super().__init__()
227
+ self.config = config
228
+ self.top_k = config.num_experts_per_tok
229
+ self.num_experts = config.num_experts
230
+
231
+ self.n_group = config.n_group
232
+ self.topk_group = config.topk_group
233
+
234
+ # topk selection algorithm
235
+ self.gating_dim = config.hidden_size
236
+ self.weight = nn.Parameter(torch.empty((self.num_experts, self.gating_dim)))
237
+ self.routed_scaling_factor = config.routed_scaling_factor
238
+
239
+ self.register_buffer("expert_bias", torch.zeros(self.num_experts))
240
+ self.reset_parameters()
241
+
242
+ def reset_parameters(self) -> None:
243
+ import torch.nn.init as init
244
+
245
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
246
+
247
+ def group_limited_topk(
248
+ self,
249
+ scores: torch.Tensor,
250
+ ):
251
+ num_tokens, _ = scores.size()
252
+ # Organize the experts into groups
253
+ group_scores = (
254
+ scores.view(num_tokens, self.n_group, -1).topk(2, dim=-1)[0].sum(dim=-1)
255
+ )
256
+ group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
257
+ group_mask = torch.zeros_like(group_scores)
258
+ group_mask.scatter_(1, group_idx, 1)
259
+
260
+ # Mask the experts based on selection groups
261
+ score_mask = (
262
+ group_mask.unsqueeze(-1)
263
+ .expand(num_tokens, self.n_group, self.num_experts // self.n_group)
264
+ .reshape(num_tokens, -1)
265
+ )
266
+
267
+ masked_scores = scores.masked_fill(~score_mask.bool(), float("-inf"))
268
+ probs, top_indices = torch.topk(masked_scores, k=self.top_k, dim=-1)
269
+
270
+ return probs, top_indices
271
+
272
+ def forward(self, hidden_states):
273
+ # compute gating score
274
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
275
+ logits = F.linear(
276
+ hidden_states.type(torch.float32), self.weight.type(torch.float32)
277
+ )
278
+
279
+ scores = torch.sigmoid(logits.float()).type_as(logits)
280
+
281
+ scores_for_routing = scores + self.expert_bias
282
+ _, topk_idx = self.group_limited_topk(scores_for_routing)
283
+
284
+ scores = torch.gather(scores, dim=1, index=topk_idx).type_as(logits)
285
+
286
+ topk_weight = (
287
+ scores / (scores.sum(dim=-1, keepdim=True) + 1e-20)
288
+ if self.top_k > 1
289
+ else scores
290
+ )
291
+ topk_weight = topk_weight * self.routed_scaling_factor
292
+
293
+ return topk_idx, topk_weight, logits
294
+
295
+
296
+ class LLaDA2MoeSparseMoeBlock(nn.Module):
297
+ """
298
+ A mixed expert module containing shared experts.
299
+ """
300
+
301
+ def __init__(self, config: LLaDA2MoeConfig):
302
+ super().__init__()
303
+ self.config = config
304
+ self.num_experts_per_tok = config.num_experts_per_tok
305
+ self._setup_experts()
306
+ self.gate = LLaDA2MoeGate(config)
307
+ if config.num_shared_experts is not None:
308
+ self.shared_experts = LLaDA2MoeMLP(
309
+ config=config,
310
+ intermediate_size=config.moe_intermediate_size
311
+ * config.num_shared_experts,
312
+ )
313
+
314
+ def _setup_experts(self):
315
+ self.experts = nn.ModuleList(
316
+ [
317
+ LLaDA2MoeMLP(
318
+ config=self.config,
319
+ intermediate_size=self.config.moe_intermediate_size,
320
+ )
321
+ for _ in range(self.config.num_experts)
322
+ ]
323
+ )
324
+
325
+ def forward(self, hidden_states):
326
+ identity = hidden_states
327
+ bsz, seq_len, h = hidden_states.shape
328
+ topk_idx, topk_weight, router_logits = self.gate(hidden_states)
329
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
330
+ flat_topk_idx = topk_idx.view(-1)
331
+ if self.training:
332
+ hidden_states = hidden_states.repeat_interleave(
333
+ self.num_experts_per_tok, dim=0
334
+ )
335
+ y = torch.empty_like(hidden_states)
336
+ for i, expert in enumerate(self.experts):
337
+ y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
338
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
339
+ y = y.to(hidden_states.dtype).view(bsz, seq_len, h)
340
+ else:
341
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(
342
+ bsz, seq_len, h
343
+ )
344
+ if self.config.num_shared_experts is not None:
345
+ y = y + self.shared_experts(identity)
346
+ return y, (
347
+ router_logits.view(bsz, seq_len, -1),
348
+ topk_idx.view(bsz, seq_len, -1),
349
+ )
350
+
351
+ @torch.no_grad()
352
+ def moe_infer(self, x, topk_ids, topk_weight):
353
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
354
+ cnts.scatter_(1, topk_ids, 1)
355
+ tokens_per_expert = cnts.sum(dim=0)
356
+ idxs = topk_ids.view(-1).argsort()
357
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
358
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
359
+ outputs = []
360
+ start_idx = 0
361
+ for i, num_tokens in enumerate(tokens_per_expert):
362
+ end_idx = start_idx + num_tokens
363
+ if num_tokens == 0:
364
+ continue
365
+ expert = self.experts[i]
366
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
367
+ expert_out = expert(tokens_for_this_expert)
368
+ outputs.append(expert_out.to(x.device))
369
+ start_idx = end_idx
370
+
371
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
372
+ new_x = torch.empty_like(outs)
373
+ new_x[idxs] = outs
374
+ final_out = (
375
+ new_x.view(*topk_ids.shape, -1)
376
+ .type(topk_weight.dtype)
377
+ .mul_(topk_weight.unsqueeze(dim=-1))
378
+ .sum(dim=1)
379
+ .type(new_x.dtype)
380
+ )
381
+ return final_out
382
+
383
+
384
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
385
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
386
+ """
387
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
388
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
389
+ """
390
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
391
+ if n_rep == 1:
392
+ return hidden_states
393
+ hidden_states = hidden_states[:, :, None, :, :].expand(
394
+ batch, num_key_value_heads, n_rep, slen, head_dim
395
+ )
396
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
397
+
398
+
399
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->LLaDA2Moe
400
+ class LLaDA2MoeAttention(nn.Module):
401
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
402
+
403
+ def __init__(self, config: LLaDA2MoeConfig, layer_idx: Optional[int] = None):
404
+ super().__init__()
405
+ self.config = config
406
+ self.layer_idx = layer_idx
407
+ if layer_idx is None:
408
+ logger.warning_once(
409
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
410
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
411
+ "when creating this class."
412
+ )
413
+
414
+ self.attention_dropout = config.attention_dropout
415
+ self.hidden_size = config.hidden_size
416
+ self.num_heads = config.num_attention_heads
417
+ self.head_dim = config.head_dim or self.hidden_size // self.num_heads
418
+ partial_rotary_factor = (
419
+ config.partial_rotary_factor
420
+ if hasattr(config, "partial_rotary_factor")
421
+ else 1.0
422
+ )
423
+ self.rope_dim = int(self.head_dim * partial_rotary_factor)
424
+ self.num_key_value_heads = config.num_key_value_heads
425
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
426
+ self.max_position_embeddings = config.max_position_embeddings
427
+ self.rope_theta = config.rope_theta
428
+ self.is_causal = False
429
+
430
+ self.query_key_value = nn.Linear(
431
+ self.hidden_size,
432
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
433
+ bias=config.use_qkv_bias,
434
+ )
435
+
436
+ self.query_layernorm = LLaDA2MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
437
+ self.key_layernorm = LLaDA2MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
438
+ self.dense = nn.Linear(
439
+ self.num_heads * self.head_dim, self.hidden_size, bias=config.use_bias
440
+ )
441
+
442
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
443
+ return (
444
+ tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
445
+ .transpose(1, 2)
446
+ .contiguous()
447
+ )
448
+
449
+ def forward(
450
+ self,
451
+ hidden_states: torch.Tensor,
452
+ attention_mask: Optional[torch.Tensor] = None,
453
+ position_ids: Optional[torch.LongTensor] = None,
454
+ past_key_value: Optional[Cache] = None,
455
+ output_attentions: bool = False,
456
+ use_cache: bool = False,
457
+ position_embeddings: Optional[
458
+ Tuple[torch.Tensor, torch.Tensor]
459
+ ] = None, # necessary, but kept here for BC
460
+ **kwargs,
461
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
462
+ if "padding_mask" in kwargs:
463
+ warnings.warn(
464
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
465
+ )
466
+
467
+ bsz, q_len, _ = hidden_states.size()
468
+
469
+ qkv = self.query_key_value(hidden_states)
470
+ qkv = qkv.view(
471
+ bsz, q_len, self.num_heads + 2 * self.num_key_value_heads, self.head_dim
472
+ )
473
+
474
+ query_states, key_states, value_states = qkv.split(
475
+ [self.num_heads, self.num_key_value_heads, self.num_key_value_heads], dim=-2
476
+ )
477
+ query_states = query_states.transpose(1, 2)
478
+ key_states = key_states.transpose(1, 2)
479
+ value_states = value_states.transpose(1, 2)
480
+
481
+ query_states = self.query_layernorm(query_states)
482
+ key_states = self.key_layernorm(key_states)
483
+
484
+ kv_seq_len = key_states.shape[-2]
485
+ if past_key_value is not None:
486
+ if self.layer_idx is None:
487
+ raise ValueError(
488
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
489
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
490
+ "with a layer index."
491
+ )
492
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
493
+ cos, sin = position_embeddings
494
+ query_states, key_states = apply_rotary_pos_emb(
495
+ query_states, key_states, cos, sin, position_ids
496
+ )
497
+
498
+ if past_key_value is not None:
499
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
500
+ key_states, value_states = past_key_value.update(
501
+ key_states, value_states, self.layer_idx, cache_kwargs
502
+ )
503
+
504
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
505
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
506
+
507
+ attn_weights = torch.matmul(
508
+ query_states, key_states.transpose(2, 3)
509
+ ) / math.sqrt(self.head_dim)
510
+
511
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
512
+ raise ValueError(
513
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
514
+ f" {attn_weights.size()}"
515
+ )
516
+ # attention_mask = None
517
+ if attention_mask is not None:
518
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
519
+ raise ValueError(
520
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
521
+ )
522
+ attn_weights = attn_weights + attention_mask
523
+
524
+ # upcast attention to fp32
525
+ attn_weights = nn.functional.softmax(
526
+ attn_weights, dim=-1, dtype=torch.float32
527
+ ).to(query_states.dtype)
528
+ attn_weights = nn.functional.dropout(
529
+ attn_weights, p=self.attention_dropout, training=self.training
530
+ )
531
+ attn_output = torch.matmul(attn_weights, value_states)
532
+
533
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
534
+ raise ValueError(
535
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
536
+ f" {attn_output.size()}"
537
+ )
538
+
539
+ attn_output = attn_output.transpose(1, 2).contiguous()
540
+
541
+ attn_output = attn_output.reshape(bsz, q_len, -1)
542
+
543
+ attn_output = self.dense(attn_output)
544
+
545
+ if not output_attentions:
546
+ attn_weights = None
547
+
548
+ return attn_output, attn_weights, past_key_value
549
+
550
+
551
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->LLaDA2Moe
552
+ class LLaDA2MoeFlashAttention2(LLaDA2MoeAttention):
553
+ """
554
+ LLaDA2Moe flash attention module. This module inherits from `LLaDA2MoeAttention` as the weights of the module stays
555
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
556
+ flash attention and deal with padding tokens in case the input contains any of them.
557
+ """
558
+
559
+ def __init__(self, *args, **kwargs):
560
+ super().__init__(*args, **kwargs)
561
+
562
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
563
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
564
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
565
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
566
+
567
+ def forward(
568
+ self,
569
+ hidden_states: torch.Tensor,
570
+ attention_mask: Optional[torch.LongTensor] = None,
571
+ position_ids: Optional[torch.LongTensor] = None,
572
+ past_key_value: Optional[Cache] = None,
573
+ output_attentions: bool = False,
574
+ use_cache: bool = False,
575
+ position_embeddings: Optional[
576
+ Tuple[torch.Tensor, torch.Tensor]
577
+ ] = None, # necessary, but kept here for BC
578
+ **kwargs,
579
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
580
+ # LLaDA2MoeFlashAttention2 attention does not support output_attentions
581
+ if "padding_mask" in kwargs:
582
+ warnings.warn(
583
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
584
+ )
585
+
586
+ # overwrite attention_mask with padding_mask
587
+ attention_mask = kwargs.pop("padding_mask")
588
+
589
+ output_attentions = False
590
+
591
+ bsz, q_len, _ = hidden_states.size()
592
+
593
+ # Flash attention requires the input to have the shape
594
+ # batch_size x seq_length x head_dim x hidden_dim
595
+ # therefore we just need to keep the original shape
596
+
597
+ qkv = self.query_key_value(hidden_states)
598
+ qkv = qkv.view(
599
+ bsz, q_len, self.num_heads + 2 * self.num_key_value_heads, self.head_dim
600
+ )
601
+
602
+ query_states, key_states, value_states = qkv.split(
603
+ [self.num_heads, self.num_key_value_heads, self.num_key_value_heads], dim=-2
604
+ )
605
+ query_states = query_states.transpose(1, 2)
606
+ key_states = key_states.transpose(1, 2)
607
+ value_states = value_states.transpose(1, 2)
608
+
609
+ query_states = self.query_layernorm(query_states)
610
+ key_states = self.key_layernorm(key_states)
611
+
612
+ kv_seq_len = key_states.shape[-2]
613
+ if past_key_value is not None:
614
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
615
+ cos, sin = position_embeddings
616
+ query_states, key_states = apply_rotary_pos_emb(
617
+ query_states, key_states, cos, sin, position_ids
618
+ )
619
+
620
+ if past_key_value is not None:
621
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
622
+ key_states, value_states = past_key_value.update(
623
+ key_states, value_states, self.layer_idx, cache_kwargs
624
+ )
625
+
626
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
627
+ # to be able to avoid many of these transpose/reshape/view.
628
+ query_states = query_states.transpose(1, 2)
629
+ key_states = key_states.transpose(1, 2)
630
+ value_states = value_states.transpose(1, 2)
631
+
632
+ dropout_rate = self.attention_dropout if self.training else 0.0
633
+
634
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
635
+ # therefore the input hidden states gets silently cast in float32. Hence, we need
636
+ # cast them back in the correct dtype just to be sure everything works as expected.
637
+ # This might slow down training & inference so it is recommended to not cast the LayerNorms
638
+ # in fp32. (LLaDA2MoeRMSNorm handles it correctly)
639
+
640
+ input_dtype = query_states.dtype
641
+ if input_dtype == torch.float32:
642
+ # Handle the case where the model is quantized
643
+ if hasattr(self.config, "_pre_quantization_dtype"):
644
+ target_dtype = self.config._pre_quantization_dtype
645
+ elif torch.is_autocast_enabled():
646
+ target_dtype = torch.get_autocast_gpu_dtype()
647
+ else:
648
+ target_dtype = self.query_key_value.weight.dtype
649
+
650
+ logger.warning_once(
651
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
652
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
653
+ f" {target_dtype}."
654
+ )
655
+
656
+ query_states = query_states.to(target_dtype)
657
+ key_states = key_states.to(target_dtype)
658
+ value_states = value_states.to(target_dtype)
659
+
660
+ attn_output = self._flash_attention_forward(
661
+ query_states,
662
+ key_states,
663
+ value_states,
664
+ attention_mask,
665
+ q_len,
666
+ dropout=dropout_rate,
667
+ )
668
+
669
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
670
+ attn_output = self.dense(attn_output)
671
+
672
+ if not output_attentions:
673
+ attn_weights = None
674
+
675
+ return attn_output, attn_weights, past_key_value
676
+
677
+ def _flash_attention_forward(
678
+ self,
679
+ query_states,
680
+ key_states,
681
+ value_states,
682
+ attention_mask,
683
+ query_length,
684
+ dropout=0.0,
685
+ softmax_scale=None,
686
+ ):
687
+ """
688
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
689
+ first unpad the input, then computes the attention scores and pad the final attention scores.
690
+
691
+ Args:
692
+ query_states (`torch.Tensor`):
693
+ Input query states to be passed to Flash Attention API
694
+ key_states (`torch.Tensor`):
695
+ Input key states to be passed to Flash Attention API
696
+ value_states (`torch.Tensor`):
697
+ Input value states to be passed to Flash Attention API
698
+ attention_mask (`torch.Tensor`):
699
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
700
+ position of padding tokens and 1 for the position of non-padding tokens.
701
+ dropout (`int`, *optional*):
702
+ Attention dropout
703
+ softmax_scale (`float`, *optional*):
704
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
705
+ query_length (`int`):
706
+ The length of the query sequence in terms of tokens. This represents the number of tokens in the
707
+ `query_states` tensor along the sequence dimension. It is used to determine the effective sequence
708
+ length for attention computations.
709
+ """
710
+ if not self._flash_attn_uses_top_left_mask:
711
+ causal = self.is_causal
712
+ else:
713
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LLaDA2MoeFlashAttention2 __init__.
714
+ causal = self.is_causal and query_length != 1
715
+
716
+ # attention_mask = None
717
+ # Contains at least one padding token in the sequence
718
+ if attention_mask is not None:
719
+ batch_size = query_states.shape[0]
720
+ (
721
+ query_states,
722
+ key_states,
723
+ value_states,
724
+ indices_q,
725
+ cu_seq_lens,
726
+ max_seq_lens,
727
+ ) = self._upad_input(
728
+ query_states, key_states, value_states, attention_mask, query_length
729
+ )
730
+
731
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
732
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
733
+
734
+ attn_output_unpad = flash_attn_varlen_func(
735
+ query_states,
736
+ key_states,
737
+ value_states,
738
+ cu_seqlens_q=cu_seqlens_q,
739
+ cu_seqlens_k=cu_seqlens_k,
740
+ max_seqlen_q=max_seqlen_in_batch_q,
741
+ max_seqlen_k=max_seqlen_in_batch_k,
742
+ dropout_p=dropout,
743
+ softmax_scale=softmax_scale,
744
+ causal=causal,
745
+ )
746
+
747
+ attn_output = pad_input(
748
+ attn_output_unpad, indices_q, batch_size, query_length
749
+ )
750
+ else:
751
+ attn_output = flash_attn_func(
752
+ query_states,
753
+ key_states,
754
+ value_states,
755
+ dropout,
756
+ softmax_scale=softmax_scale,
757
+ causal=causal,
758
+ )
759
+
760
+ return attn_output
761
+
762
+ def _upad_input(
763
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
764
+ ):
765
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
766
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
767
+
768
+ key_layer = index_first_axis(
769
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
770
+ indices_k,
771
+ )
772
+ value_layer = index_first_axis(
773
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
774
+ indices_k,
775
+ )
776
+ if query_length == kv_seq_len:
777
+ query_layer = index_first_axis(
778
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
779
+ indices_k,
780
+ )
781
+ cu_seqlens_q = cu_seqlens_k
782
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
783
+ indices_q = indices_k
784
+ elif query_length == 1:
785
+ max_seqlen_in_batch_q = 1
786
+ cu_seqlens_q = torch.arange(
787
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
788
+ ) # There is a memcpy here, that is very bad.
789
+ indices_q = cu_seqlens_q[:-1]
790
+ query_layer = query_layer.squeeze(1)
791
+ else:
792
+ # The -q_len: slice assumes left padding.
793
+ attention_mask = attention_mask[:, -query_length:]
794
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
795
+ query_layer, attention_mask
796
+ )
797
+
798
+ return (
799
+ query_layer,
800
+ key_layer,
801
+ value_layer,
802
+ indices_q,
803
+ (cu_seqlens_q, cu_seqlens_k),
804
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
805
+ )
806
+
807
+
808
+ # Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->LLaDA2Moe
809
+ class LLaDA2MoeSdpaAttention(LLaDA2MoeAttention):
810
+ """
811
+ LLaDA2Moe attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
812
+ `LLaDA2MoeAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
813
+ SDPA API.
814
+ """
815
+
816
+ # Adapted from LLaDA2MoeAttention.forward
817
+ def forward(
818
+ self,
819
+ hidden_states: torch.Tensor,
820
+ attention_mask: Optional[torch.Tensor] = None,
821
+ position_ids: Optional[torch.LongTensor] = None,
822
+ past_key_value: Optional[Cache] = None,
823
+ output_attentions: bool = False,
824
+ use_cache: bool = False,
825
+ position_embeddings: Optional[
826
+ Tuple[torch.Tensor, torch.Tensor]
827
+ ] = None, # necessary, but kept here for BC
828
+ **kwargs,
829
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
830
+ if output_attentions:
831
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
832
+ logger.warning_once(
833
+ "LLaDA2MoeModel is using LLaDA2MoeSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
834
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
835
+ )
836
+ return super().forward(
837
+ hidden_states=hidden_states,
838
+ attention_mask=attention_mask,
839
+ position_ids=position_ids,
840
+ past_key_value=past_key_value,
841
+ output_attentions=output_attentions,
842
+ use_cache=use_cache,
843
+ )
844
+
845
+ bsz, q_len, _ = hidden_states.size()
846
+
847
+ qkv = self.query_key_value(hidden_states)
848
+ qkv = qkv.view(
849
+ bsz, q_len, self.num_heads + 2 * self.num_key_value_heads, self.head_dim
850
+ )
851
+
852
+ query_states, key_states, value_states = qkv.split(
853
+ [self.num_heads, self.num_key_value_heads, self.num_key_value_heads], dim=-2
854
+ )
855
+ query_states = query_states.transpose(1, 2)
856
+ key_states = key_states.transpose(1, 2)
857
+ value_states = value_states.transpose(1, 2)
858
+
859
+ query_states = self.query_layernorm(query_states)
860
+ key_states = self.key_layernorm(key_states)
861
+
862
+ kv_seq_len = key_states.shape[-2]
863
+ if past_key_value is not None:
864
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
865
+ cos, sin = position_embeddings
866
+
867
+ query_states, key_states = apply_rotary_pos_emb(
868
+ query_states, key_states, cos, sin, position_ids
869
+ )
870
+
871
+ if past_key_value is not None:
872
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
873
+ key_states, value_states = past_key_value.update(
874
+ key_states, value_states, self.layer_idx, cache_kwargs
875
+ )
876
+
877
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
878
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
879
+
880
+ # attention_mask = None
881
+ if attention_mask is not None:
882
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
883
+ raise ValueError(
884
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
885
+ )
886
+
887
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
888
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
889
+ if query_states.device.type == "cuda" and attention_mask is not None:
890
+ query_states = query_states.contiguous()
891
+ key_states = key_states.contiguous()
892
+ value_states = value_states.contiguous()
893
+
894
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
895
+ query_states,
896
+ key_states,
897
+ value_states,
898
+ attn_mask=attention_mask,
899
+ dropout_p=self.attention_dropout if self.training else 0.0,
900
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
901
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
902
+ )
903
+
904
+ attn_output = attn_output.transpose(1, 2).contiguous()
905
+ attn_output = attn_output.reshape(bsz, q_len, -1)
906
+
907
+ attn_output = self.dense(attn_output)
908
+
909
+ return attn_output, None, past_key_value
910
+
911
+
912
+ ATTENTION_CLASSES = {
913
+ "eager": LLaDA2MoeAttention,
914
+ "flash_attention_2": LLaDA2MoeFlashAttention2,
915
+ "sdpa": LLaDA2MoeSdpaAttention,
916
+ }
917
+
918
+
919
+ class LLaDA2MoeDecoderLayer(nn.Module):
920
+ def __init__(self, config: LLaDA2MoeConfig, layer_idx: int):
921
+ super().__init__()
922
+ self.hidden_size = config.hidden_size
923
+
924
+ self.attention = ATTENTION_CLASSES[config._attn_implementation](
925
+ config=config, layer_idx=layer_idx
926
+ )
927
+
928
+ self.mlp = (
929
+ LLaDA2MoeSparseMoeBlock(config)
930
+ if (
931
+ config.num_experts is not None
932
+ and layer_idx >= config.first_k_dense_replace
933
+ )
934
+ else LLaDA2MoeMLP(config=config, intermediate_size=config.intermediate_size)
935
+ )
936
+ self.input_layernorm = LLaDA2MoeRMSNorm(
937
+ config.hidden_size, eps=config.rms_norm_eps
938
+ )
939
+ self.post_attention_layernorm = LLaDA2MoeRMSNorm(
940
+ config.hidden_size, eps=config.rms_norm_eps
941
+ )
942
+
943
+ def forward(
944
+ self,
945
+ hidden_states: torch.Tensor,
946
+ attention_mask: Optional[torch.Tensor] = None,
947
+ position_ids: Optional[torch.LongTensor] = None,
948
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
949
+ output_attentions: Optional[bool] = False,
950
+ output_router_logits: Optional[bool] = False,
951
+ use_cache: Optional[bool] = False,
952
+ position_embeddings: Optional[
953
+ Tuple[torch.Tensor, torch.Tensor]
954
+ ] = None, # necessary, but kept here for BC
955
+ **kwargs,
956
+ ) -> Tuple[
957
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
958
+ ]:
959
+ """
960
+ Args:
961
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
962
+ attention_mask (`torch.FloatTensor`, *optional*):
963
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
964
+ query_sequence_length, key_sequence_length)` if default attention is used.
965
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
966
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
967
+ config.n_positions - 1]`.
968
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*):
969
+ cached past key and value projection states
970
+ output_attentions (`bool`, *optional*):
971
+ Whether to return the attentions tensors of all attention layers. See `attentions` under
972
+ returned tensors for more detail.
973
+ output_router_logits (`bool`, *optional*):
974
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
975
+ and should not be returned during inference.
976
+ use_cache (`bool`, *optional*):
977
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
978
+ (see `past_key_values`).
979
+ """
980
+ if "padding_mask" in kwargs:
981
+ warnings.warn(
982
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
983
+ )
984
+ residual = hidden_states
985
+
986
+ hidden_states = self.input_layernorm(hidden_states)
987
+
988
+ # Self Attention
989
+ hidden_states, self_attn_weights, present_key_value = self.attention(
990
+ hidden_states=hidden_states,
991
+ attention_mask=attention_mask,
992
+ position_ids=position_ids,
993
+ past_key_value=past_key_value,
994
+ output_attentions=output_attentions,
995
+ position_embeddings=position_embeddings,
996
+ use_cache=use_cache,
997
+ )
998
+ hidden_states = residual + hidden_states
999
+
1000
+ # Fully Connected
1001
+ residual = hidden_states
1002
+ hidden_states = self.post_attention_layernorm(hidden_states)
1003
+ hidden_states = self.mlp(hidden_states)
1004
+ if isinstance(hidden_states, tuple):
1005
+ hidden_states, router_logits = hidden_states
1006
+ else:
1007
+ router_logits = None
1008
+ hidden_states = residual + hidden_states.to(residual.device)
1009
+
1010
+ outputs = (hidden_states,)
1011
+
1012
+ if output_attentions:
1013
+ outputs += (self_attn_weights,)
1014
+
1015
+ if use_cache:
1016
+ outputs += (present_key_value,)
1017
+
1018
+ if output_router_logits:
1019
+ outputs += (router_logits,)
1020
+
1021
+ return outputs
1022
+
1023
+
1024
+ LLADA2MOE_START_DOCSTRING = r"""
1025
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1026
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1027
+ etc.)
1028
+
1029
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1030
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1031
+ and behavior.
1032
+
1033
+ Parameters:
1034
+ config ([`LLaDA2MoeConfig`]):
1035
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1036
+ load the weights associated with the model, only the configuration. Check out the
1037
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1038
+ """
1039
+
1040
+
1041
+ @add_start_docstrings(
1042
+ "The bare LLaDA2Moe Model outputting raw hidden-states without any specific head on top.",
1043
+ LLADA2MOE_START_DOCSTRING,
1044
+ )
1045
+ class LLaDA2MoePreTrainedModel(PreTrainedModel):
1046
+ config_class = LLaDA2MoeConfig
1047
+ base_model_prefix = "model"
1048
+ supports_gradient_checkpointing = True
1049
+ _no_split_modules = ["LLaDA2MoeDecoderLayer"]
1050
+ _skip_keys_device_placement = "past_key_values"
1051
+ _supports_flash_attn_2 = True
1052
+ _supports_sdpa = True
1053
+ _supports_cache_class = True
1054
+
1055
+ def _init_weights(self, module):
1056
+ std = self.config.initializer_range
1057
+ if isinstance(module, nn.Linear):
1058
+ module.weight.data.normal_(mean=0.0, std=std)
1059
+ if module.bias is not None:
1060
+ module.bias.data.zero_()
1061
+ elif isinstance(module, nn.Embedding):
1062
+ module.weight.data.normal_(mean=0.0, std=std)
1063
+ if module.padding_idx is not None:
1064
+ module.weight.data[module.padding_idx].zero_()
1065
+
1066
+
1067
+ LLADA2MOE_INPUTS_DOCSTRING = r"""
1068
+ Args:
1069
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1070
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1071
+ it.
1072
+
1073
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1074
+ [`PreTrainedTokenizer.__call__`] for details.
1075
+
1076
+ [What are input IDs?](../glossary#input-ids)
1077
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1078
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1079
+
1080
+ - 1 for tokens that are **not masked**,
1081
+ - 0 for tokens that are **masked**.
1082
+
1083
+ [What are attention masks?](../glossary#attention-mask)
1084
+
1085
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1086
+ [`PreTrainedTokenizer.__call__`] for details.
1087
+
1088
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1089
+ `past_key_values`).
1090
+
1091
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1092
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1093
+ information on the default strategy.
1094
+
1095
+ - 1 indicates the head is **not masked**,
1096
+ - 0 indicates the head is **masked**.
1097
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1098
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1099
+ config.n_positions - 1]`.
1100
+
1101
+ [What are position IDs?](../glossary#position-ids)
1102
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1103
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1104
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1105
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1106
+
1107
+ Two formats are allowed:
1108
+ - a [`~cache_utils.Cache`] instance;
1109
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1110
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1111
+ cache format.
1112
+
1113
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1114
+ legacy cache format will be returned.
1115
+
1116
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1117
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1118
+ of shape `(batch_size, sequence_length)`.
1119
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1120
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1121
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1122
+ model's internal embedding lookup matrix.
1123
+ use_cache (`bool`, *optional*):
1124
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1125
+ `past_key_values`).
1126
+ output_attentions (`bool`, *optional*):
1127
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1128
+ tensors for more detail.
1129
+ output_hidden_states (`bool`, *optional*):
1130
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1131
+ more detail.
1132
+ return_dict (`bool`, *optional*):
1133
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1134
+ """
1135
+
1136
+
1137
+ @add_start_docstrings(
1138
+ "The bare LLaDA2Moe Model outputting raw hidden-states without any specific head on top.",
1139
+ LLADA2MOE_START_DOCSTRING,
1140
+ )
1141
+ class LLaDA2MoeModel(LLaDA2MoePreTrainedModel):
1142
+ """
1143
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LLaDA2MoeDecoderLayer`]
1144
+
1145
+ Args:
1146
+ config: LLaDA2MoeConfig
1147
+ """
1148
+
1149
+ def __init__(self, config: LLaDA2MoeConfig):
1150
+ super().__init__(config)
1151
+ self.padding_idx = config.pad_token_id
1152
+ self.vocab_size = config.vocab_size
1153
+
1154
+ self.word_embeddings = nn.Embedding(
1155
+ config.vocab_size, config.hidden_size, self.padding_idx
1156
+ )
1157
+ self.layers = nn.ModuleList(
1158
+ [
1159
+ LLaDA2MoeDecoderLayer(config, layer_idx)
1160
+ for layer_idx in range(config.num_hidden_layers)
1161
+ ]
1162
+ )
1163
+ self._use_sdpa = config._attn_implementation == "sdpa"
1164
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1165
+ self.norm = LLaDA2MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1166
+ self.rotary_emb = LLaDA2MoeRotaryEmbedding(config=config)
1167
+ self.gradient_checkpointing = False
1168
+ # Initialize weights and apply final processing
1169
+ self.post_init()
1170
+
1171
+ def get_input_embeddings(self):
1172
+ return self.word_embeddings
1173
+
1174
+ def set_input_embeddings(self, value):
1175
+ self.word_embeddings = value
1176
+
1177
+ @add_start_docstrings_to_model_forward(LLADA2MOE_INPUTS_DOCSTRING)
1178
+ def forward(
1179
+ self,
1180
+ input_ids: torch.LongTensor = None,
1181
+ attention_mask: Optional[torch.Tensor] = None,
1182
+ position_ids: Optional[torch.LongTensor] = None,
1183
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1184
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1185
+ use_cache: Optional[bool] = None,
1186
+ output_attentions: Optional[bool] = None,
1187
+ output_hidden_states: Optional[bool] = None,
1188
+ output_router_logits: Optional[bool] = None,
1189
+ return_dict: Optional[bool] = None,
1190
+ **kwargs,
1191
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
1192
+ output_attentions = (
1193
+ output_attentions
1194
+ if output_attentions is not None
1195
+ else self.config.output_attentions
1196
+ )
1197
+ output_hidden_states = (
1198
+ output_hidden_states
1199
+ if output_hidden_states is not None
1200
+ else self.config.output_hidden_states
1201
+ )
1202
+ output_router_logits = (
1203
+ output_router_logits
1204
+ if output_router_logits is not None
1205
+ else self.config.output_router_logits
1206
+ )
1207
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1208
+
1209
+ return_dict = (
1210
+ return_dict if return_dict is not None else self.config.use_return_dict
1211
+ )
1212
+
1213
+ # retrieve input_ids and inputs_embeds
1214
+ if input_ids is not None and inputs_embeds is not None:
1215
+ raise ValueError(
1216
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1217
+ )
1218
+ elif input_ids is not None:
1219
+ batch_size, seq_length = input_ids.shape[:2]
1220
+ elif inputs_embeds is not None:
1221
+ batch_size, seq_length = inputs_embeds.shape[:2]
1222
+ else:
1223
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1224
+
1225
+ if self.gradient_checkpointing and self.training:
1226
+ if use_cache:
1227
+ logger.warning_once(
1228
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`transformers."
1229
+ )
1230
+ use_cache = False
1231
+
1232
+ past_key_values_length = 0
1233
+ if use_cache:
1234
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1235
+ if use_legacy_cache:
1236
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1237
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1238
+
1239
+ if position_ids is None:
1240
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1241
+ position_ids = torch.arange(
1242
+ past_key_values_length,
1243
+ seq_length + past_key_values_length,
1244
+ dtype=torch.long,
1245
+ device=device,
1246
+ )
1247
+ position_ids = position_ids.unsqueeze(0)
1248
+
1249
+ if inputs_embeds is None:
1250
+ inputs_embeds = self.word_embeddings(input_ids)
1251
+
1252
+ # TODO flash attention 2 can not support custom attention mask
1253
+ # if self._use_flash_attention_2:
1254
+ # # 2d mask is passed through the layers
1255
+ # attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1256
+ if self._use_sdpa and not output_attentions:
1257
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1258
+ # the manual implementation that requires a 4D causal mask in all cases.
1259
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1260
+ attention_mask,
1261
+ (batch_size, seq_length),
1262
+ inputs_embeds,
1263
+ past_key_values_length,
1264
+ )
1265
+ else:
1266
+ # 4d mask is passed through the layers
1267
+ attention_mask = _prepare_4d_causal_attention_mask(
1268
+ attention_mask,
1269
+ (batch_size, seq_length),
1270
+ inputs_embeds,
1271
+ past_key_values_length,
1272
+ )
1273
+
1274
+ # embed positions
1275
+ hidden_states = inputs_embeds
1276
+
1277
+ # create position embeddings to be shared across the decoder layers
1278
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1279
+
1280
+ # decoder layers
1281
+ all_hidden_states = () if output_hidden_states else None
1282
+ all_self_attns = () if output_attentions else None
1283
+ all_router_logits = () if output_router_logits else None
1284
+ next_decoder_cache = None
1285
+
1286
+ for decoder_layer in self.layers:
1287
+ if output_hidden_states:
1288
+ all_hidden_states += (hidden_states,)
1289
+
1290
+ if self.gradient_checkpointing and self.training:
1291
+ layer_outputs = self._gradient_checkpointing_func(
1292
+ decoder_layer.__call__,
1293
+ hidden_states,
1294
+ attention_mask,
1295
+ position_ids,
1296
+ past_key_values,
1297
+ output_attentions,
1298
+ output_router_logits,
1299
+ use_cache,
1300
+ position_embeddings,
1301
+ )
1302
+ else:
1303
+ layer_outputs = decoder_layer(
1304
+ hidden_states,
1305
+ attention_mask=attention_mask,
1306
+ position_ids=position_ids,
1307
+ past_key_value=past_key_values,
1308
+ output_attentions=output_attentions,
1309
+ output_router_logits=output_router_logits,
1310
+ use_cache=use_cache,
1311
+ position_embeddings=position_embeddings,
1312
+ )
1313
+ hidden_states = layer_outputs[0]
1314
+
1315
+ if use_cache:
1316
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1317
+
1318
+ if output_attentions:
1319
+ all_self_attns += (layer_outputs[1],)
1320
+
1321
+ if output_router_logits and layer_outputs[-1] is not None:
1322
+ all_router_logits += (layer_outputs[-1],)
1323
+
1324
+ hidden_states = self.norm(hidden_states)
1325
+
1326
+ # add hidden states from the last decoder layer
1327
+ if output_hidden_states:
1328
+ all_hidden_states += (hidden_states,)
1329
+
1330
+ next_cache = None
1331
+ if use_cache:
1332
+ next_cache = (
1333
+ next_decoder_cache.to_legacy_cache()
1334
+ if use_legacy_cache
1335
+ else next_decoder_cache
1336
+ )
1337
+ if not return_dict:
1338
+ return tuple(
1339
+ v
1340
+ for v in [
1341
+ hidden_states,
1342
+ next_cache,
1343
+ all_hidden_states,
1344
+ all_self_attns,
1345
+ all_router_logits,
1346
+ ]
1347
+ if v is not None
1348
+ )
1349
+ return MoeModelOutputWithPast(
1350
+ last_hidden_state=hidden_states,
1351
+ past_key_values=next_cache,
1352
+ hidden_states=all_hidden_states,
1353
+ attentions=all_self_attns,
1354
+ router_logits=all_router_logits,
1355
+ )
1356
+
1357
+
1358
+ class LLaDA2MoeModelLM(LLaDA2MoePreTrainedModel, GenerationMixin):
1359
+ _tied_weights_keys = ["lm_head.weight"]
1360
+
1361
+ def __init__(self, config: LLaDA2MoeConfig):
1362
+ super().__init__(config)
1363
+ self.model = LLaDA2MoeModel(config)
1364
+ self.vocab_size = config.vocab_size
1365
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1366
+
1367
+ # Initialize weights and apply final processing
1368
+ self.post_init()
1369
+
1370
+ def get_input_embeddings(self):
1371
+ return self.model.word_embeddings
1372
+
1373
+ def set_input_embeddings(self, value):
1374
+ self.model.word_embeddings = value
1375
+
1376
+ def get_output_embeddings(self):
1377
+ return self.lm_head
1378
+
1379
+ def set_output_embeddings(self, new_embeddings):
1380
+ self.lm_head = new_embeddings
1381
+
1382
+ def set_decoder(self, decoder):
1383
+ self.model = decoder
1384
+
1385
+ def get_decoder(self):
1386
+ return self.model
1387
+
1388
+ @add_start_docstrings_to_model_forward(LLADA2MOE_INPUTS_DOCSTRING)
1389
+ @replace_return_docstrings(
1390
+ output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1391
+ )
1392
+ def forward(
1393
+ self,
1394
+ input_ids: torch.LongTensor = None,
1395
+ attention_mask: Optional[torch.Tensor] = None,
1396
+ position_ids: Optional[torch.LongTensor] = None,
1397
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1398
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1399
+ labels: Optional[torch.LongTensor] = None,
1400
+ use_cache: Optional[bool] = None,
1401
+ output_attentions: Optional[bool] = None,
1402
+ output_hidden_states: Optional[bool] = None,
1403
+ output_router_logits: Optional[bool] = None,
1404
+ return_dict: Optional[bool] = None,
1405
+ **kwargs,
1406
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
1407
+ r"""
1408
+ Args:
1409
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1410
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1411
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1412
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1413
+
1414
+ Returns:
1415
+
1416
+ Example:
1417
+
1418
+ ```python
1419
+ >>> from transformers import AutoTokenizer
1420
+
1421
+ >>> model = LLaDA2MoeForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1422
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1423
+
1424
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1425
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1426
+
1427
+ >>> # Generate
1428
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1429
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1430
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1431
+ ```"""
1432
+ output_attentions = (
1433
+ output_attentions
1434
+ if output_attentions is not None
1435
+ else self.config.output_attentions
1436
+ )
1437
+ output_hidden_states = (
1438
+ output_hidden_states
1439
+ if output_hidden_states is not None
1440
+ else self.config.output_hidden_states
1441
+ )
1442
+ output_router_logits = (
1443
+ output_router_logits
1444
+ if output_router_logits is not None
1445
+ else self.config.output_router_logits
1446
+ )
1447
+ return_dict = (
1448
+ return_dict if return_dict is not None else self.config.use_return_dict
1449
+ )
1450
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1451
+ outputs = self.model(
1452
+ input_ids=input_ids,
1453
+ attention_mask=attention_mask,
1454
+ position_ids=position_ids,
1455
+ past_key_values=past_key_values,
1456
+ inputs_embeds=inputs_embeds,
1457
+ use_cache=use_cache,
1458
+ output_attentions=output_attentions,
1459
+ output_hidden_states=output_hidden_states,
1460
+ output_router_logits=output_router_logits,
1461
+ return_dict=return_dict,
1462
+ **kwargs,
1463
+ )
1464
+
1465
+ hidden_states = outputs[0]
1466
+
1467
+ logits = self.lm_head(hidden_states)
1468
+ logits = logits.float()
1469
+
1470
+ loss = None
1471
+ aux_loss = None
1472
+
1473
+ if labels is not None:
1474
+ # Shift so that tokens < n predict n
1475
+ shift_logits = logits[..., :-1, :].contiguous()
1476
+ shift_labels = labels[..., 1:].contiguous()
1477
+ # Flatten the tokens
1478
+ loss_fct = CrossEntropyLoss()
1479
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1480
+ shift_labels = shift_labels.view(-1)
1481
+ # Enable model parallelism
1482
+ shift_labels = shift_labels.to(shift_logits.device)
1483
+ loss = loss_fct(shift_logits, shift_labels)
1484
+
1485
+ if not return_dict:
1486
+ output = (logits,) + outputs[1:]
1487
+ if output_router_logits:
1488
+ output = (aux_loss,) + output
1489
+ return (loss,) + output if loss is not None else output
1490
+
1491
+ return MoeCausalLMOutputWithPast(
1492
+ loss=loss,
1493
+ aux_loss=aux_loss,
1494
+ logits=logits,
1495
+ past_key_values=outputs.past_key_values,
1496
+ hidden_states=outputs.hidden_states,
1497
+ attentions=outputs.attentions,
1498
+ router_logits=outputs.router_logits,
1499
+ )
1500
+
1501
+ def prepare_inputs_for_generation(
1502
+ self,
1503
+ input_ids,
1504
+ past_key_values=None,
1505
+ attention_mask=None,
1506
+ inputs_embeds=None,
1507
+ token_type_ids=None,
1508
+ **kwargs,
1509
+ ):
1510
+ if past_key_values is not None:
1511
+ if isinstance(past_key_values, Cache):
1512
+ cache_length = past_key_values.get_seq_length()
1513
+ past_length = past_key_values.seen_tokens
1514
+ max_cache_length = (
1515
+ past_key_values.get_max_length()
1516
+ if hasattr(past_key_values, "get_max_length")
1517
+ else past_key_values.get_max_cache_shape()
1518
+ )
1519
+ else:
1520
+ cache_length = past_length = past_key_values[0][0].shape[2]
1521
+ max_cache_length = None
1522
+
1523
+ # Keep only the unprocessed tokens:
1524
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1525
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as input)
1526
+ if (
1527
+ attention_mask is not None
1528
+ and attention_mask.shape[1] > input_ids.shape[1]
1529
+ ):
1530
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1531
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1532
+ # input_ids based on the past_length.
1533
+ elif past_length < input_ids.shape[1]:
1534
+ input_ids = input_ids[:, past_length:]
1535
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1536
+
1537
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1538
+ if (
1539
+ max_cache_length is not None
1540
+ and attention_mask is not None
1541
+ and cache_length + input_ids.shape[1] > max_cache_length
1542
+ ):
1543
+ attention_mask = attention_mask[:, -max_cache_length:]
1544
+
1545
+ position_ids = kwargs.get("position_ids", None)
1546
+ if attention_mask is not None and position_ids is None:
1547
+ # create position_ids on the fly for batch generation
1548
+ position_ids = attention_mask.long().cumsum(-1) - 1
1549
+ position_ids.masked_fill_(attention_mask == 0, 1)
1550
+ if past_key_values:
1551
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1552
+
1553
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1554
+ if inputs_embeds is not None and past_key_values is None:
1555
+ model_inputs = {"inputs_embeds": inputs_embeds}
1556
+ else:
1557
+ model_inputs = {"input_ids": input_ids}
1558
+
1559
+ model_inputs.update(
1560
+ {
1561
+ "position_ids": position_ids,
1562
+ "past_key_values": past_key_values,
1563
+ "use_cache": kwargs.get("use_cache"),
1564
+ "attention_mask": attention_mask,
1565
+ }
1566
+ )
1567
+ return model_inputs
1568
+
1569
+ @staticmethod
1570
+ def _reorder_cache(past_key_values, beam_idx):
1571
+ reordered_past = ()
1572
+ for layer_past in past_key_values:
1573
+ reordered_past += (
1574
+ tuple(
1575
+ past_state.index_select(0, beam_idx.to(past_state.device))
1576
+ for past_state in layer_past
1577
+ ),
1578
+ )
1579
+ return reordered_past
1580
+
1581
+ @staticmethod
1582
+ def _top_k_logits(logits, k):
1583
+ if k is None or k <= 0:
1584
+ return logits
1585
+ else:
1586
+ values, _ = torch.topk(logits, k)
1587
+ min_values = values[..., -1, None]
1588
+ return torch.where(
1589
+ logits < min_values, torch.full_like(logits, float("-inf")), logits
1590
+ )
1591
+
1592
+ @staticmethod
1593
+ def _top_p_logits(logits, p):
1594
+ if p is None or p >= 1.0:
1595
+ return logits
1596
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
1597
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
1598
+ sorted_mask = cumulative_probs > p
1599
+ sorted_mask[..., 1:] = sorted_mask[..., :-1].clone()
1600
+ sorted_mask[..., 0] = False
1601
+ mask_indices = torch.scatter(
1602
+ torch.full_like(logits, False, dtype=torch.bool),
1603
+ -1,
1604
+ sorted_indices,
1605
+ sorted_mask,
1606
+ )
1607
+ return logits.masked_fill(mask_indices, float("-inf"))
1608
+
1609
+ def _sample_with_temperature_topk_topp(
1610
+ self, logits, temperature=1.0, top_k=0, top_p=1.0
1611
+ ):
1612
+ orig_shape = logits.shape[:-1]
1613
+ vocab_size = logits.shape[-1]
1614
+ logits = logits.reshape(-1, vocab_size)
1615
+ if temperature > 0 and temperature != 1.0:
1616
+ logits = logits / temperature
1617
+ logits = self._top_k_logits(logits, top_k)
1618
+ logits = self._top_p_logits(logits, top_p)
1619
+ probs = F.softmax(logits, dim=-1)
1620
+ token = torch.multinomial(probs, num_samples=1)
1621
+ token_prob = torch.gather(probs, -1, token)
1622
+ return token.view(*orig_shape), token_prob.view(*orig_shape)
1623
+
1624
+ @staticmethod
1625
+ def _get_num_transfer_tokens(block_length, steps):
1626
+ if steps == 0:
1627
+ return torch.tensor([], dtype=torch.int64)
1628
+ base = block_length // steps
1629
+ remainder = block_length % steps
1630
+ num_transfer_tokens = torch.full((steps,), base, dtype=torch.int64)
1631
+ num_transfer_tokens[:remainder] += 1
1632
+ return num_transfer_tokens
1633
+
1634
+ @torch.no_grad()
1635
+ def generate(
1636
+ self,
1637
+ inputs: Optional[torch.Tensor] = None,
1638
+ temperature: int = 0.0,
1639
+ block_length: int = 32,
1640
+ steps: int = 32,
1641
+ gen_length: int = 2048,
1642
+ top_p: Optional[int] = None,
1643
+ top_k: Optional[int] = None,
1644
+ eos_early_stop: bool = False,
1645
+ minimal_topk: int = 1,
1646
+ threshold: float = 0.95,
1647
+ eos_id: int = 156892,
1648
+ mask_id: int = 156895,
1649
+ ):
1650
+ r"""
1651
+ Generates tokens using a block-wise, iterative refinement strategy.
1652
+
1653
+ This method operates differently from standard autoregressive generation. It first creates a template of the
1654
+ full desired length, filled with a special `mask_id`. It then processes this template in segments (`blocks`)
1655
+ and iteratively "denoises" or "refines" the `mask_id` tokens into actual tokens over a series of `steps` for
1656
+ each block. A custom block-diagonal causal attention mask ensures that generation within a block can attend to
1657
+ all previous blocks but not future ones.
1658
+
1659
+ <Tip warning={true}>
1660
+
1661
+ This is a specialized generation method. The quality and speed of the output are highly dependent on the interplay
1662
+ between `block_length`, `steps`, and `threshold`. It aims to achieve faster generation through parallel
1663
+ decoding within blocks, which is a departure from the token-by-token generation of standard `.generate()` methods.
1664
+
1665
+ </Tip>
1666
+
1667
+ Parameters:
1668
+ inputs (`torch.Tensor`):
1669
+ The token sequence used as a prompt for the generation.
1670
+ temperature (`float`, *optional*, defaults to 0.0):
1671
+ The value used to module the next token probabilities. A value of 0.0 corresponds to greedy decoding.
1672
+ block_length (`int`, *optional*, defaults to 32):
1673
+ The size of each generation block. The model generates text in parallel within these blocks. This is a
1674
+ key parameter for controlling the granularity of the generation process.
1675
+ steps (`int`, *optional*, defaults to 32):
1676
+ The number of iterative refinement (or "denoising") steps to perform for each block. Within each block,
1677
+ the model will try to replace `mask_id` tokens with real tokens for this many iterations.
1678
+ gen_length (`int`, *optional*, defaults to 2048):
1679
+ The maximum number of tokens to generate, excluding the prompt.
1680
+ top_p (`float`, *optional*):
1681
+ If set to a float value between 0 and 1, only the most probable tokens with probabilities that add up to
1682
+ `top_p` or higher are kept for generation (nucleus sampling).
1683
+ top_k (`int`, *optional*):
1684
+ The number of highest probability vocabulary tokens to keep for top-k-filtering.
1685
+ eos_early_stop (`bool`, *optional*, defaults to `False`):
1686
+ If `True`, generation will stop as soon as a valid End-Of-Sequence token is generated and confirmed,
1687
+ even if `gen_length` has not been reached.
1688
+ minimal_topk (`int`, *optional*, defaults to 1):
1689
+ A parameter used to dynamically adjust the number of refinement `steps`. The effective number of steps
1690
+ is capped at `gen_length // minimal_topk`.
1691
+ threshold (`float`, *optional*, defaults to 0.95):
1692
+ The confidence probability threshold for accepting a sampled token. During each refinement step, a
1693
+ sampled token is only kept if its probability is above this threshold. If not enough tokens meet the
1694
+ threshold, the ones with the highest confidence are chosen.
1695
+ eos_id (`int`, *optional*, defaults to 156892):
1696
+ The token ID for the end-of-sequence token. Used for `eos_early_stop`.
1697
+ mask_id (`int`, *optional*, defaults to 156895):
1698
+ The token ID used as a placeholder for tokens that are yet to be generated. This is central to the
1699
+ iterative refinement algorithm.
1700
+
1701
+ Return:
1702
+ `torch.Tensor`: A string containing the generated token IDs, starting
1703
+ after the prompt and stopping at the first `eos_id` or `gen_length`.
1704
+ """
1705
+ steps = min(steps, gen_length // minimal_topk)
1706
+ input_ids = inputs.to(self.device)
1707
+
1708
+ prompt_length = input_ids.shape[1]
1709
+ num_blocks = (prompt_length + gen_length + block_length - 1) // block_length
1710
+ total_length = num_blocks * block_length
1711
+
1712
+ block_mask = torch.tril(torch.ones(num_blocks, num_blocks, device=self.device))
1713
+ block_diffusion_attention_mask = (
1714
+ block_mask.repeat_interleave(block_length, dim=0)
1715
+ .repeat_interleave(block_length, dim=1)
1716
+ .unsqueeze(0)
1717
+ .unsqueeze(0)
1718
+ ).bool()
1719
+ block_diffusion_attention_mask = torch.where(
1720
+ block_diffusion_attention_mask, 0.0, float("-inf")
1721
+ ).to(torch.bfloat16)
1722
+
1723
+ position_ids = torch.arange(total_length, device=self.device).unsqueeze(0)
1724
+ x = torch.full((1, total_length), mask_id, dtype=torch.long, device=self.device)
1725
+ x[:, :prompt_length] = input_ids.clone()
1726
+
1727
+ prompt_index_full = torch.zeros_like(x, dtype=torch.bool)
1728
+ prompt_index_full[:, :prompt_length] = True
1729
+
1730
+ prefill_blocks = prompt_length // block_length
1731
+
1732
+ denoising_steps_per_block = steps
1733
+ num_transfer_tokens_schedule = self._get_num_transfer_tokens(
1734
+ block_length, denoising_steps_per_block
1735
+ )
1736
+ for num_block in range(prefill_blocks, num_blocks):
1737
+ current_window_end = (num_block + 1) * block_length
1738
+ cur_x = x[:, :current_window_end]
1739
+ cur_attn_mask = block_diffusion_attention_mask[
1740
+ :, :, :current_window_end, :current_window_end
1741
+ ]
1742
+ cur_position_ids = position_ids[:, :current_window_end]
1743
+
1744
+ for step in range(denoising_steps_per_block):
1745
+ active_block_mask = cur_x[:, -block_length:] == mask_id
1746
+ if active_block_mask.sum() == 0:
1747
+ break
1748
+
1749
+ logits = self.forward(
1750
+ cur_x,
1751
+ attention_mask=cur_attn_mask,
1752
+ position_ids=cur_position_ids,
1753
+ ).logits
1754
+
1755
+ active_logits = logits[:, -block_length:, :]
1756
+ x0, x0_p = self._sample_with_temperature_topk_topp(
1757
+ active_logits, temperature=temperature, top_k=top_k, top_p=top_p
1758
+ )
1759
+
1760
+ num_to_transfer = num_transfer_tokens_schedule[step].item()
1761
+ transfer_index = torch.zeros_like(x0, dtype=torch.bool)
1762
+
1763
+ confidence = torch.where(active_block_mask, x0_p, -torch.inf)
1764
+ high_conf_mask = confidence[0] > threshold
1765
+ num_high_confidence = high_conf_mask.sum().item()
1766
+
1767
+ if num_high_confidence >= num_to_transfer:
1768
+ transfer_index[0] = high_conf_mask
1769
+ else:
1770
+ _, idx = torch.topk(
1771
+ confidence[0],
1772
+ k=min(num_to_transfer, active_block_mask.sum().item()),
1773
+ )
1774
+ transfer_index[0, idx] = True
1775
+
1776
+ if transfer_index.any():
1777
+ cur_x[:, -block_length:][transfer_index] = x0[transfer_index]
1778
+ if eos_early_stop and (x0[transfer_index] == eos_id).any():
1779
+ eos_pos_in_x = (cur_x[0] == eos_id).nonzero(as_tuple=True)
1780
+ if len(eos_pos_in_x[0]) > 0:
1781
+ eos_pos = eos_pos_in_x[0][0].item()
1782
+ if (cur_x[0, prompt_length:eos_pos] != mask_id).all():
1783
+ final_x = x[:, :total_length][:, : eos_pos + 1]
1784
+ return final_x
1785
+
1786
+ x[:, :current_window_end] = cur_x
1787
+ if (
1788
+ eos_id is not None
1789
+ and (x[0, prompt_length:current_window_end] == eos_id).any()
1790
+ ):
1791
+ break
1792
+
1793
+ generated_answer = x[:, : prompt_length + gen_length]
1794
+
1795
+ mask_positions = (generated_answer[0][input_ids.shape[1] :] == eos_id).nonzero(
1796
+ as_tuple=True
1797
+ )[0]
1798
+ if len(mask_positions) > 0:
1799
+ first_mask_position = mask_positions[0].item()
1800
+ else:
1801
+ first_mask_position = gen_length
1802
+ return generated_answer[
1803
+ :, input_ids.shape[1] : input_ids.shape[1] + first_mask_position + 1
1804
+ ]
special_tokens_map.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|startoftext|>",
3
+ "cls_token": "[CLS]",
4
+ "eos_token": "<|endoftext|>",
5
+ "gmask_token": "[gMASK]",
6
+ "pad_token": "<|endoftext|>",
7
+ "mask_token": "<|mask|>"
8
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "bos_token": "<|startoftext|>",
5
+ "chat_template": "{% set thinking_option = 'off' %}\n{{- '<role>SYSTEM</role>' }}\n{%- if messages[0].role == 'system' %}\n {{- messages[0].content + '\\n' }}\n{%- endif %}\n{%- if tools %}\n {{- \"# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call>\\n\" }}\n{%- endif %}\n{{- 'detailed thinking ' + thinking_option + '<|role_end|>' }}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if message.content is string %}\n {%- set content = message.content %}\n {%- else %}\n {%- set content = '' %}\n {%- endif %}\n {%- if message.role == \"user\" %}\n {{- '<role>HUMAN</role>' + message.content + '<|role_end|>' }}\n {%- elif message.role == \"system\" and not loop.first %}\n {{- '<role>SYSTEM</role>' + message.content + '<|role_end|>' }}\n {%- elif message.role == \"assistant\" %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is string %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- else %}\n {%- if '</think>' in content %}\n {%- set reasoning_content = content.split('</think>')[0].rstrip('\\n').split('<think>')[-1].lstrip('\\n') %}\n {%- set content = content.split('</think>')[-1].lstrip('\\n') %}\n {%- endif %}\n {%- endif %}\n {%- if loop.index0 > ns.last_query_index %}\n {%- if reasoning_content %}\n {{- '<role>ASSISTANT</role>' + '\\n<think>\\n' + reasoning_content.strip('\\n') + '\\n</think>\\n\\n' + content.lstrip('\\n') }}\n {%- else %}\n {{- '<role>ASSISTANT</role>' + content }}\n {%- endif %}\n {%- else %}\n {{- '<role>ASSISTANT</role>' + content }}\n {%- endif %}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {%- if tool_call.arguments is string %}\n {{- tool_call.arguments }}\n {%- else %}\n {{- tool_call.arguments | tojson }}\n {%- endif %}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|role_end|>' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<role>OBSERVATION</role>' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|role_end|>' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<role>ASSISTANT</role>' }}\n{%- endif %}",
6
+ "clean_up_tokenization_spaces": false,
7
+ "cls_token": "[CLS]",
8
+ "eos_token": "<|endoftext|>",
9
+ "mask_token": "<|mask|>",
10
+ "fast_tokenizer": true,
11
+ "gmask_token": "[gMASK]",
12
+ "merges_file": null,
13
+ "model_max_length": 32768,
14
+ "pad_token": "<|endoftext|>",
15
+ "tokenizer_class": "PreTrainedTokenizerFast",
16
+ "trust_remote_code": true,
17
+ "vocab_file": null
18
+ }