rulixiang commited on
Commit
e14e154
·
1 Parent(s): 81578a2

first commit

Browse files
README.md ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cense: apache-2.0
2
+ tags:
3
+ - diffusion
4
+ - dllm
5
+ ---
6
+ # LLaDA-MoE
7
+
8
+ **LLaDA-MoE** is a new and upgraded series of the LLaDA diffusion language model. This pre-release includes two cutting-edge models:
9
+
10
+ - `LLaDA-MoE-7B-A1B-Base`: A base pre-trained model designed for research and secondary development.
11
+ - `LLaDA-MoE-7B-A1B-Instruct`: An instruction-tuned model optimized for practical applications.
12
+
13
+ ---
14
+ <div align="center">
15
+ <img src="https://raw.githubusercontent.com/Ulov888/LLaDA_Assets/main/benchmarks_grouped_bar.png" width="800" />
16
+ <img src="https://raw.githubusercontent.com/Ulov888/LLaDA_Assets/main/benchmarks_details_table.png" width="800" />
17
+ </div>
18
+
19
+
20
+
21
+
22
+ ## 🚀 Performance Highlights
23
+
24
+ - **Leading MoE Architecture**:
25
+ The first open-source **Mixture-of-Experts (MoE) diffusion large language model**, pre-trained from scratch on approximately **20 trillion tokens**.
26
+
27
+ - **Efficient Inference**:
28
+ With **7 billion total parameters**, only **1.4 billion** are activated during inference. LLaDA-MoE significantly reduces computational costs while outperforming open-source dense models of similar scale.
29
+
30
+ - **Impressive Performance on Code & Complex Reasoning**:
31
+ Excels in tasks such as **code generation** and **advanced mathematical reasoning**, demonstrating strong reasoning capabilities.
32
+
33
+ - **Tool Use**:
34
+ Supports **tool calling** and achieves excellent performance in complex agent-based tasks.
35
+
36
+ - **Open & Extensible**:
37
+ Fully open-source with commitment to transparency. We plan to release a **leading inference framework** in the future and continue investing in cutting-edge areas like **diffusion LLMs (dLLM)** to drive disruptive innovation.
38
+
39
+ ---
40
+
41
+ ## 📦 Model Variants
42
+
43
+ | Model ID | Description | Hugging Face Link |
44
+ |--------|-------------|-------------------|
45
+ | [`inclusionAI/LLaDA-MoE-7B-A1B-Base`](https://huggingface.co/inclusionAI/LLaDA-MoE-7B-A1B-Base) | Base pre-trained model for research and fine-tuning. | [🤗 Model Card](https://huggingface.co/inclusionAI/LLaDA-MoE-7B-A1B-Base) |
46
+ | [`inclusionAI/LLaDA-MoE-7B-A1B-Instruct`](https://huggingface.co/inclusionAI/LLaDA-MoE-7B-A1B-Instruct) | Instruction-tuned model, ready for downstream applications. | [🤗 Model Card](https://huggingface.co/inclusionAI/LLaDA-MoE-7B-A1B-Instruct) |
47
+
48
+ ---
49
+
50
+ ## 🔍 Model Overview
51
+
52
+ **LLaDA-MoE-7B-A1B** has the following specifications:
53
+
54
+ - **Type**: Mixture-of-Experts (MoE) Diffusion Language Model
55
+ - **Total Parameters (Non-Embedding)**: 7.03B
56
+ - **Number of Layers**: 16
57
+ - **Attention Heads**: 16
58
+ - **Context Length**: 4,096 tokens
59
+ - **Position Embedding**: Rotary (RoPE)
60
+ - **Vocabulary Size**: 157,184
61
+
62
+ ---
63
+
64
+ ## ⚡ Quickstart
65
+
66
+ Make sure you have `transformers` and its dependencies installed:
67
+
68
+ ```bash
69
+ pip install transformers torch
70
+ ```
71
+
72
+ You can then load the model using the AutoModelForCausalLM and AutoTokenizer classes:
73
+
74
+ ```python
75
+ import torch
76
+ import numpy as np
77
+ import torch.nn.functional as F
78
+
79
+ from transformers import AutoTokenizer, AutoModel
80
+
81
+
82
+ def add_gumbel_noise(logits, temperature):
83
+ if temperature == 0:
84
+ return logits
85
+ logits = logits.to(torch.float64)
86
+ noise = torch.rand_like(logits, dtype=torch.float64)
87
+ gumbel_noise = (- torch.log(noise)) ** temperature
88
+ return logits.exp() / gumbel_noise
89
+
90
+
91
+ def get_num_transfer_tokens(mask_index, steps):
92
+ mask_num = mask_index.sum(dim=1, keepdim=True)
93
+
94
+ base = mask_num // steps
95
+ remainder = mask_num % steps
96
+
97
+ num_transfer_tokens = torch.zeros(mask_num.size(0), steps, device=mask_index.device, dtype=torch.int64) + base
98
+
99
+ for i in range(mask_num.size(0)):
100
+ num_transfer_tokens[i, :remainder[i]] += 1
101
+
102
+ return num_transfer_tokens
103
+
104
+
105
+ @ torch.no_grad()
106
+ def generate(model, prompt, steps=128, gen_length=128, block_length=128, temperature=0.,
107
+ cfg_scale=0., remasking='low_confidence', mask_id=156895):
108
+ x = torch.full((1, prompt.shape[1] + gen_length), mask_id, dtype=torch.long).to(model.device)
109
+ x[:, :prompt.shape[1]] = prompt.clone()
110
+ prompt_index = (x != mask_id)
111
+
112
+ assert gen_length % block_length == 0
113
+ num_blocks = gen_length // block_length
114
+ assert steps % num_blocks == 0
115
+ steps = steps // num_blocks
116
+
117
+ for num_block in range(num_blocks):
118
+ block_mask_index = (x[:, prompt.shape[1] + num_block * block_length: prompt.shape[1] + (num_block + 1) * block_length:] == mask_id)
119
+ num_transfer_tokens = get_num_transfer_tokens(block_mask_index, steps)
120
+ for i in range(steps):
121
+ mask_index = (x == mask_id)
122
+ if cfg_scale > 0.:
123
+ un_x = x.clone()
124
+ un_x[prompt_index] = mask_id
125
+ x_ = torch.cat([x, un_x], dim=0)
126
+ logits = model(x_).logits
127
+ logits, un_logits = torch.chunk(logits, 2, dim=0)
128
+ logits = un_logits + (cfg_scale + 1) * (logits - un_logits)
129
+ else:
130
+ logits = model(x).logits
131
+
132
+ logits_with_noise = add_gumbel_noise(logits, temperature=temperature)
133
+ x0 = torch.argmax(logits_with_noise, dim=-1) # b, l
134
+
135
+ if remasking == 'low_confidence':
136
+ p = F.softmax(logits, dim=-1)
137
+ x0_p = torch.squeeze(
138
+ torch.gather(p, dim=-1, index=torch.unsqueeze(x0, -1)), -1) # b, l
139
+ elif remasking == 'random':
140
+ x0_p = torch.rand((x0.shape[0], x0.shape[1]), device=x0.device)
141
+ else:
142
+ raise NotImplementedError(remasking)
143
+
144
+ x0_p[:, prompt.shape[1] + (num_block + 1) * block_length:] = -np.inf
145
+
146
+ x0 = torch.where(mask_index, x0, x)
147
+ confidence = torch.where(mask_index, x0_p, -np.inf)
148
+
149
+ transfer_index = torch.zeros_like(x0, dtype=torch.bool, device=x0.device)
150
+ for j in range(confidence.shape[0]):
151
+ _, select_index = torch.topk(confidence[j], k=num_transfer_tokens[j, i])
152
+ transfer_index[j, select_index] = True
153
+ x[transfer_index] = x0[transfer_index]
154
+
155
+ return x
156
+
157
+
158
+ device = 'cuda'
159
+ model = AutoModel.from_pretrained('inclusionAI/LLaDA-MoE-7B-A1B-Instruct', trust_remote_code=True, torch_dtype=torch.bfloat16).to(device).eval()
160
+ tokenizer = AutoTokenizer.from_pretrained('inclusionAI/LLaDA-MoE-7B-A1B-Instruct', trust_remote_code=True)
161
+
162
+ prompt = "Lily can run 12 kilometers per hour for 4 hours. After that, she runs 6 kilometers per hour. How many kilometers can she run in 8 hours?"
163
+ m = [
164
+ {"role": "system", "content": "You are a helpful AI assistant."},
165
+ {"role": "user", "content": prompt}
166
+ ]
167
+ prompt = tokenizer.apply_chat_template(m, add_generation_prompt=True, tokenize=False)
168
+
169
+ input_ids = tokenizer(prompt)['input_ids']
170
+ input_ids = torch.tensor(input_ids).to(device).unsqueeze(0)
171
+
172
+ text = generate(model, input_ids, steps=128, gen_length=128, block_length=32, temperature=0., cfg_scale=0., remasking='low_confidence')
173
+ print(tokenizer.batch_decode(text[:, input_ids.shape[1]:], skip_special_tokens=False)[0])
174
+
175
+
176
+
177
+
178
+ ```
179
+
180
+
181
+ ## 📚 Citation (Coming Soon)
182
+
183
+ We are preparing the technical report and citation information.
184
+ Stay tuned — citation details will be available soon.
185
+
186
+ ---
187
+
188
+ ## 🌐 License
189
+
190
+ This project is licensed under the terms of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0).
191
+
192
+ ---
193
+
194
+ ## 🤝 Contact & Collaboration
195
+
196
+ For questions, collaborations, or feedback, please reach out via [Hugging Face](https://huggingface.co/inclusionAI/LLaDA-MoE-7B-A1B-Base) or open an issue in the [repository](https://github.com/inclusionAI).
197
+
198
+ 👉 Join us in advancing open, efficient, and intelligent language models!
config.json ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "LLaDAMoEModel"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "clip_qkv": null,
8
+ "dense_intermediate_size": 8192,
9
+ "eos_token_id": 156892,
10
+ "expert_intermediate_size": 1024,
11
+ "hidden_act": "silu",
12
+ "hidden_size": 2048,
13
+ "initializer_range": 0.02,
14
+ "max_position_embeddings": 8192,
15
+ "model_type": "llada",
16
+ "moe_layer_freq": [
17
+ 1,
18
+ 1,
19
+ 1,
20
+ 1,
21
+ 1,
22
+ 1,
23
+ 1,
24
+ 1,
25
+ 1,
26
+ 1,
27
+ 1,
28
+ 1,
29
+ 1,
30
+ 1,
31
+ 1,
32
+ 1
33
+ ],
34
+ "moe_router_enable_expert_bias": false,
35
+ "moe_router_score_function": "softmax",
36
+ "norm_topk_prob": null,
37
+ "num_attention_heads": 16,
38
+ "num_experts": 64,
39
+ "num_experts_per_tok": 8,
40
+ "num_hidden_layers": 16,
41
+ "num_key_value_heads": 16,
42
+ "output_router_logits": false,
43
+ "pad_token_id": 156892,
44
+ "partial_rotary_factor": 1,
45
+ "qk_layernorm": true,
46
+ "rms_norm_eps": 1e-05,
47
+ "rope_scaling": null,
48
+ "rope_theta": 50000,
49
+ "routed_scaling_factor": 1,
50
+ "router_aux_loss_coef": 0.01,
51
+ "router_num_group": null,
52
+ "router_topk_group": null,
53
+ "shared_expert_intermediate_size": null,
54
+ "tie_word_embeddings": false,
55
+ "torch_dtype": "bfloat16",
56
+ "transformers_version": "4.53.2",
57
+ "use_cache": false,
58
+ "vocab_size": 157184,
59
+ "auto_map": {
60
+ "AutoConfig": "configuration_lladamoe.LLaDAConfig",
61
+ "AutoModel": "modeling_lladamoe.LLaDAMoEModelLM",
62
+ "AutoModelForCausalLM": "modeling_lladamoe.LLaDAMoEModelLM"
63
+ }
64
+ }
configuration_lladamoe.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LLaDA MoE configuration
3
+ """
4
+
5
+ from transformers.configuration_utils import PretrainedConfig
6
+ from transformers.modeling_rope_utils import rope_config_validation
7
+
8
+
9
+ class LLaDAConfig(PretrainedConfig):
10
+ model_type = "llada"
11
+ keys_to_ignore_at_inference = ["past_key_values"]
12
+
13
+ def __init__(
14
+ self,
15
+ vocab_size=-1,
16
+ hidden_size=-1,
17
+ dense_intermediate_size=-1,
18
+ expert_intermediate_size=-1,
19
+ shared_expert_intermediate_size=-1,
20
+ num_hidden_layers=-1,
21
+ num_attention_heads=-1,
22
+ num_key_value_heads=None,
23
+ hidden_act="silu",
24
+ max_position_embeddings=4096,
25
+ initializer_range=0.02,
26
+ rms_norm_eps=1e-05,
27
+ use_cache=False,
28
+ pad_token_id=1,
29
+ bos_token_id=None,
30
+ eos_token_id=50279,
31
+ tie_word_embeddings=False,
32
+ rope_theta=-1,
33
+ partial_rotary_factor=-1,
34
+ rope_scaling=None,
35
+ attention_bias=False,
36
+ attention_dropout=0.0,
37
+ clip_qkv=None,
38
+ num_experts_per_tok=-1,
39
+ num_experts=-1,
40
+ output_router_logits=False,
41
+ router_aux_loss_coef=0.01,
42
+ norm_topk_prob=None,
43
+ qk_layernorm=None,
44
+ moe_layer_freq=[],
45
+ moe_router_enable_expert_bias=None,
46
+ moe_router_score_function=None,
47
+ routed_scaling_factor=1,
48
+ router_num_group=-2,
49
+ router_topk_group=-2,
50
+ **kwargs,
51
+ ):
52
+ self.vocab_size = vocab_size
53
+ self.max_position_embeddings = max_position_embeddings
54
+ self.hidden_size = hidden_size
55
+ self.expert_intermediate_size = expert_intermediate_size
56
+ self.dense_intermediate_size = dense_intermediate_size
57
+ self.shared_expert_intermediate_size = shared_expert_intermediate_size
58
+ self.num_hidden_layers = num_hidden_layers
59
+ self.num_attention_heads = num_attention_heads
60
+ if num_key_value_heads is None:
61
+ num_key_value_heads = num_attention_heads
62
+ self.num_key_value_heads = num_key_value_heads
63
+
64
+ self.hidden_act = hidden_act
65
+ self.initializer_range = initializer_range
66
+ self.rms_norm_eps = rms_norm_eps
67
+ self.use_cache = use_cache
68
+ self.rope_theta = rope_theta
69
+ self.rope_scaling = rope_scaling
70
+ self.attention_bias = attention_bias
71
+ self.attention_dropout = attention_dropout
72
+ self.clip_qkv = clip_qkv
73
+ self.num_experts_per_tok = num_experts_per_tok
74
+ self.num_experts = num_experts
75
+ self.output_router_logits = output_router_logits
76
+ self.router_aux_loss_coef = router_aux_loss_coef
77
+ self.norm_topk_prob = norm_topk_prob
78
+ self.qk_layernorm = qk_layernorm
79
+ self.moe_layer_freq = moe_layer_freq
80
+ self.moe_router_enable_expert_bias = moe_router_enable_expert_bias
81
+ self.moe_router_score_function = moe_router_score_function
82
+ self.partial_rotary_factor = partial_rotary_factor
83
+ self.routed_scaling_factor = routed_scaling_factor
84
+ self.router_num_group = router_num_group
85
+ self.router_topk_group = router_topk_group
86
+
87
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
88
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
89
+ rope_config_validation(self)
90
+
91
+ super().__init__(
92
+ pad_token_id=pad_token_id,
93
+ bos_token_id=bos_token_id,
94
+ eos_token_id=eos_token_id,
95
+ tie_word_embeddings=tie_word_embeddings,
96
+ **kwargs,
97
+ )
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "eos_token_id": 156892,
4
+ "pad_token_id": 156892,
5
+ "transformers_version": "4.46.3",
6
+ "use_cache": false
7
+ }
model-00001-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:84a7f34af2f3f14d767b0106b8fa7f0d7f9b95a0eeac74f2ab3f21bd69a03908
3
+ size 4999258928
model-00002-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2ddb9174a03003263250c789942372382e2ce97f115377e28cb749c082f0b2d7
3
+ size 4997188984
model-00003-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b1998424a021938681487ece097838f7131324eb4f776b8b0ce0c515526b31f4
3
+ size 4717712520
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_lladamoe.py ADDED
@@ -0,0 +1,1186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LLaDA MoE model pytorch implementation"""
2
+
3
+ import math
4
+ from typing import List, Optional, Tuple, Union
5
+
6
+ import torch
7
+ import torch.nn.functional as F
8
+ import torch.utils.checkpoint
9
+ from torch import nn
10
+ from torch.nn import CrossEntropyLoss
11
+
12
+ from transformers.activations import ACT2FN
13
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
14
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
15
+ from transformers.modeling_outputs import (
16
+ MoeCausalLMOutputWithPast,
17
+ MoeModelOutputWithPast,
18
+ )
19
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
20
+ from transformers.modeling_utils import PreTrainedModel
21
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
22
+ from transformers.utils import (
23
+ add_start_docstrings,
24
+ add_start_docstrings_to_model_forward,
25
+ is_flash_attn_2_available,
26
+ is_flash_attn_greater_or_equal_2_10,
27
+ logging,
28
+ replace_return_docstrings,
29
+ )
30
+
31
+ from .configuration_lladamoe import LLaDAConfig
32
+
33
+
34
+ if is_flash_attn_2_available():
35
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+ _CONFIG_FOR_DOC = "LLaDAConfig"
41
+
42
+
43
+ # Copied from transformers.models.mixtral.modeling_mixtral.load_balancing_loss_func
44
+ def load_balancing_loss_func(
45
+ gate_logits: torch.Tensor, num_experts: torch.Tensor = None, top_k=2, attention_mask: Optional[torch.Tensor] = None
46
+ ) -> float:
47
+ r"""
48
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
49
+
50
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
51
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
52
+ experts is too unbalanced.
53
+
54
+ Args:
55
+ gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor]):
56
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
57
+ shape [batch_size X sequence_length, num_experts].
58
+ attention_mask (`torch.Tensor`, *optional*):
59
+ For diffusion language model, attention_mask is set to None by default.
60
+ If you pass an attention mask and expect the model to use it for computing other attention mechanisms,
61
+ it may lead to logits and aux_loss returned by the model being inconsistent with your expectations.
62
+ num_experts (`int`, *optional*):
63
+ Number of experts
64
+
65
+ Returns:
66
+ The auxiliary loss.
67
+ """
68
+ if gate_logits is None or not isinstance(gate_logits, tuple):
69
+ return 0
70
+
71
+ if isinstance(gate_logits, tuple):
72
+ compute_device = gate_logits[0].device
73
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
74
+
75
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
76
+
77
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
78
+
79
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
80
+
81
+ if attention_mask is None:
82
+ # Compute the percentage of tokens routed to each experts
83
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
84
+
85
+ # Compute the average probability of routing to these experts
86
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
87
+ else:
88
+ batch_size, sequence_length = attention_mask.shape
89
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
90
+
91
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
92
+ expert_attention_mask = (
93
+ attention_mask[None, :, :, None, None]
94
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
95
+ .reshape(-1, top_k, num_experts)
96
+ .to(compute_device)
97
+ )
98
+
99
+ # Compute the percentage of tokens routed to each experts
100
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
101
+ expert_attention_mask, dim=0
102
+ )
103
+
104
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
105
+ router_per_expert_attention_mask = (
106
+ attention_mask[None, :, :, None]
107
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
108
+ .reshape(-1, num_experts)
109
+ .to(compute_device)
110
+ )
111
+
112
+ # Compute the average probability of routing to these experts
113
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
114
+ router_per_expert_attention_mask, dim=0
115
+ )
116
+
117
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
118
+ return overall_loss * num_experts
119
+
120
+ # copied from transformers.models.olmoe.modeling_olmoe.OlmoeRMSNorm -> LLaDAMoERMSNorm
121
+ class LLaDAMoERMSNorm(nn.Module):
122
+ def __init__(self, hidden_size, eps=1e-5):
123
+ """
124
+ LLaDAMoERMSNorm is equivalent to T5LayerNorm
125
+ """
126
+ super().__init__()
127
+ self.weight = nn.Parameter(torch.ones(hidden_size))
128
+ self.variance_epsilon = eps
129
+
130
+ def forward(self, hidden_states):
131
+ input_dtype = hidden_states.dtype
132
+ hidden_states = hidden_states.to(torch.float32)
133
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
134
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
135
+ return self.weight * hidden_states.to(input_dtype)
136
+
137
+ def extra_repr(self):
138
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
139
+
140
+
141
+ ALL_LAYERNORM_LAYERS.append(LLaDAMoERMSNorm)
142
+
143
+ # copied from transformers.models.olmoe.modeling_olmoe.OlmoeRotaryEmbedding -> LLaDAMoERotaryEmbedding
144
+ class LLaDAMoERotaryEmbedding(nn.Module):
145
+ def __init__(
146
+ self,
147
+ dim=None,
148
+ max_position_embeddings=2048,
149
+ base=10000,
150
+ device=None,
151
+ scaling_factor=1.0,
152
+ rope_type="default",
153
+ config: Optional[LLaDAConfig] = None,
154
+ ):
155
+ super().__init__()
156
+ # TODO (joao): remove the `if` below, only used for BC
157
+ self.rope_kwargs = {}
158
+ if config is None:
159
+ logger.warning_once(
160
+ "`LLaDAMoERotaryEmbedding` can now be fully parameterized by passing the model config through the "
161
+ "`config` argument. All other arguments will be removed in v4.46"
162
+ )
163
+ self.rope_kwargs = {
164
+ "rope_type": rope_type,
165
+ "factor": scaling_factor,
166
+ "dim": dim,
167
+ "base": base,
168
+ "max_position_embeddings": max_position_embeddings,
169
+ }
170
+ self.rope_type = rope_type
171
+ self.max_seq_len_cached = max_position_embeddings
172
+ self.original_max_seq_len = max_position_embeddings
173
+ else:
174
+ # BC: "rope_type" was originally "type"
175
+ if config.rope_scaling is not None:
176
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
177
+ else:
178
+ self.rope_type = "default"
179
+ self.max_seq_len_cached = config.max_position_embeddings
180
+ self.original_max_seq_len = config.max_position_embeddings
181
+
182
+ self.config = config
183
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
184
+
185
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
186
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
187
+ self.original_inv_freq = self.inv_freq
188
+
189
+ def _dynamic_frequency_update(self, position_ids, device):
190
+ """
191
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
192
+ 1 - growing beyond the cached sequence length (allow scaling)
193
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
194
+ """
195
+ seq_len = torch.max(position_ids) + 1
196
+ if seq_len > self.max_seq_len_cached: # growth
197
+ inv_freq, self.attention_scaling = self.rope_init_fn(
198
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
199
+ )
200
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
201
+ self.max_seq_len_cached = seq_len
202
+
203
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
204
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
205
+ self.max_seq_len_cached = self.original_max_seq_len
206
+
207
+ @torch.no_grad()
208
+ def forward(self, x, position_ids):
209
+ if "dynamic" in self.rope_type:
210
+ self._dynamic_frequency_update(position_ids, device=x.device)
211
+
212
+ # Core RoPE block
213
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
214
+ position_ids_expanded = position_ids[:, None, :].float()
215
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
216
+ device_type = x.device.type
217
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
218
+ with torch.autocast(device_type=device_type, enabled=False):
219
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
220
+ emb = torch.cat((freqs, freqs), dim=-1)
221
+ cos = emb.cos()
222
+ sin = emb.sin()
223
+
224
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
225
+ cos = cos * self.attention_scaling
226
+ sin = sin * self.attention_scaling
227
+
228
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
229
+
230
+
231
+ # copied from transformers.models.olmoe.modeling_olmoe.rotate_half
232
+ def rotate_half(x):
233
+ """Rotates half the hidden dims of the input."""
234
+ x1 = x[..., : x.shape[-1] // 2]
235
+ x2 = x[..., x.shape[-1] // 2 :]
236
+ return torch.cat((-x2, x1), dim=-1)
237
+
238
+
239
+ # copied from transformers.models.olmoe.modeling_olmoe.apply_rotary_pos_emb
240
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
241
+ """Applies Rotary Position Embedding to the query and key tensors.
242
+
243
+ Args:
244
+ q (`torch.Tensor`): The query tensor.
245
+ k (`torch.Tensor`): The key tensor.
246
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
247
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
248
+ position_ids (`torch.Tensor`, *optional*):
249
+ Deprecated and unused.
250
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
251
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
252
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
253
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
254
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
255
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
256
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
257
+ Returns:
258
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
259
+ """
260
+ rotary_dim = cos.shape[-1]
261
+
262
+ cos = cos.unsqueeze(unsqueeze_dim)
263
+ sin = sin.unsqueeze(unsqueeze_dim)
264
+
265
+ q_rot = q[..., :rotary_dim]
266
+ q_pass = q[..., rotary_dim:]
267
+
268
+ k_rot = k[..., :rotary_dim]
269
+ k_pass = k[..., rotary_dim:]
270
+
271
+ q_rotated = (q_rot * cos) + (rotate_half(q_rot) * sin)
272
+ k_rotated = (k_rot * cos) + (rotate_half(k_rot) * sin)
273
+
274
+ q_final = torch.cat((q_rotated, q_pass), dim=-1)
275
+ k_final = torch.cat((k_rotated, k_pass), dim=-1)
276
+
277
+ return q_final, k_final
278
+
279
+
280
+ # copied from transformers.models.olmoe.modeling_olmoe.OlmoeMLP with OlmoeMLP->LLaDAMoEMLP
281
+ class LLaDAMoEMLP(nn.Module):
282
+ def __init__(self, config, mlp_type):
283
+ super().__init__()
284
+ self.config = config
285
+ self.hidden_size = config.hidden_size
286
+ if mlp_type == 'dense':
287
+ self.intermediate_size = config.dense_intermediate_size
288
+ elif mlp_type == 'expert':
289
+ self.intermediate_size = config.expert_intermediate_size
290
+ elif mlp_type == 'shared_expert':
291
+ self.intermediate_size = config.shared_expert_intermediate_size
292
+ else:
293
+ assert False, "unknown mlp type"
294
+
295
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
296
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
297
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
298
+ self.act_fn = ACT2FN[config.hidden_act]
299
+
300
+ def forward(self, x):
301
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
302
+
303
+
304
+ # copied from transformers.models.olmoe.modeling_olmoe.repeat_kv
305
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
306
+ """
307
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
308
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
309
+ """
310
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
311
+ if n_rep == 1:
312
+ return hidden_states
313
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
314
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
315
+
316
+
317
+ # copied from transformers.models.olmoe.modeling_olmoe.OlmoeAttention with OlmoeAttention->LLaDAMoEAttention
318
+ class LLaDAMoEAttention(nn.Module):
319
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
320
+
321
+ def __init__(self, config: LLaDAConfig, layer_idx: Optional[int] = None):
322
+ super().__init__()
323
+ self.config = config
324
+ self.layer_idx = layer_idx
325
+ if layer_idx is None:
326
+ logger.warning_once(
327
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
328
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
329
+ "when creating this class."
330
+ )
331
+
332
+ self.attention_dropout = config.attention_dropout
333
+ self.hidden_size = config.hidden_size
334
+ self.num_heads = config.num_attention_heads
335
+ self.head_dim = self.hidden_size // self.num_heads
336
+ self.num_key_value_heads = config.num_key_value_heads
337
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
338
+ self.max_position_embeddings = config.max_position_embeddings
339
+ self.rope_theta = config.rope_theta
340
+
341
+ # **For diffusion language model, we set is_causal to False by default.**
342
+ self.is_causal = False
343
+
344
+ if (self.head_dim * self.num_heads) != self.hidden_size:
345
+ raise ValueError(
346
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
347
+ f" and `num_heads`: {self.num_heads})."
348
+ )
349
+
350
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
351
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
352
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
353
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
354
+ if config.qk_layernorm:
355
+ self.q_norm = LLaDAMoERMSNorm(self.head_dim, eps=config.rms_norm_eps)
356
+ self.k_norm = LLaDAMoERMSNorm(
357
+ self.head_dim, eps=config.rms_norm_eps
358
+ )
359
+
360
+ def forward(
361
+ self,
362
+ hidden_states: torch.Tensor,
363
+ attention_mask: Optional[torch.Tensor] = None,
364
+ position_ids: Optional[torch.LongTensor] = None,
365
+ past_key_value: Optional[Cache] = None,
366
+ output_attentions: bool = False,
367
+ use_cache: bool = False,
368
+ cache_position: Optional[torch.LongTensor] = None,
369
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
370
+ **kwargs,
371
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
372
+ bsz, q_len, _ = hidden_states.size()
373
+
374
+ query_states = self.q_proj(hidden_states)
375
+ key_states = self.k_proj(hidden_states)
376
+ if 'q_norm' in dir(self):
377
+ query_states = self.q_norm(query_states.reshape(-1, self.head_dim)).reshape(bsz, q_len, -1)
378
+ key_states = self.k_norm(key_states.reshape(-1, self.head_dim)).reshape(bsz, q_len, -1)
379
+ value_states = self.v_proj(hidden_states)
380
+
381
+ if self.config.clip_qkv is not None:
382
+ query_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
383
+ key_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
384
+ value_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
385
+
386
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
387
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
388
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
389
+
390
+ cos, sin = position_embeddings
391
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
392
+
393
+ if past_key_value is not None:
394
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
395
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
396
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
397
+
398
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
399
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
400
+
401
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
402
+
403
+ # **For diffusion language model, attention_mask is set to None(full attention) by default.**
404
+ attention_mask = None
405
+
406
+ if attention_mask is not None: # no matter the length, we just slice it
407
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
408
+ attn_weights = attn_weights + causal_mask
409
+
410
+ # upcast attention to fp32
411
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
412
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
413
+ attn_output = torch.matmul(attn_weights, value_states)
414
+
415
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
416
+ raise ValueError(
417
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
418
+ f" {attn_output.size()}"
419
+ )
420
+
421
+ attn_output = attn_output.transpose(1, 2).contiguous()
422
+
423
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
424
+
425
+ attn_output = self.o_proj(attn_output)
426
+
427
+ if not output_attentions:
428
+ attn_weights = None
429
+
430
+ return attn_output, attn_weights, past_key_value
431
+
432
+
433
+ # copied from transformers.models.olmoe.modeling_olmoe.FlashAttention2 with OlmoeFlashAttention2->LLaDAMoEFlashAttention2
434
+ class LLaDAMoEFlashAttention2(LLaDAMoEAttention):
435
+ """
436
+ LLaDAMoE flash attention module. This module inherits from `LLaDAMoEAttention` as the weights of the module stays
437
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
438
+ flash attention and deal with padding tokens in case the input contains any of them.
439
+ """
440
+
441
+ # copied from transformers.models.olmoe.modeling_olmoe.OlmoeFlashAttention2.__init__
442
+ def __init__(self, *args, **kwargs):
443
+ super().__init__(*args, **kwargs)
444
+
445
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
446
+ # 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.
447
+ # 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).
448
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
449
+
450
+ def forward(
451
+ self,
452
+ hidden_states: torch.Tensor,
453
+ attention_mask: Optional[torch.LongTensor] = None,
454
+ position_ids: Optional[torch.LongTensor] = None,
455
+ past_key_value: Optional[Cache] = None,
456
+ output_attentions: bool = False,
457
+ use_cache: bool = False,
458
+ cache_position: Optional[torch.LongTensor] = None,
459
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
460
+ **kwargs,
461
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
462
+ output_attentions = False
463
+
464
+ bsz, q_len, _ = hidden_states.size()
465
+
466
+ query_states = self.q_proj(hidden_states)
467
+ key_states = self.k_proj(hidden_states)
468
+ if 'q_norm' in dir(self):
469
+ query_states = self.q_norm(query_states.reshape(-1, self.head_dim)).reshape(bsz, q_len, -1)
470
+ key_states = self.k_norm(key_states.reshape(-1, self.head_dim)).reshape(bsz, q_len, -1)
471
+ value_states = self.v_proj(hidden_states)
472
+ if self.config.clip_qkv is not None:
473
+ query_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
474
+ key_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
475
+ value_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
476
+
477
+ # Flash attention requires the input to have the shape
478
+ # batch_size x seq_length x head_dim x hidden_dim
479
+ # therefore we just need to keep the original shape
480
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
481
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
482
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
483
+
484
+ cos, sin = position_embeddings
485
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
486
+
487
+ if past_key_value is not None:
488
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
489
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
490
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
491
+
492
+ # 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
493
+ # to be able to avoid many of these transpose/reshape/view.
494
+ query_states = query_states.transpose(1, 2)
495
+ key_states = key_states.transpose(1, 2)
496
+ value_states = value_states.transpose(1, 2)
497
+
498
+ dropout_rate = self.attention_dropout if self.training else 0.0
499
+
500
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
501
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
502
+ # cast them back in the correct dtype just to be sure everything works as expected.
503
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
504
+ # in fp32. (LLaDAMoERMSNorm handles it correctly)
505
+
506
+ input_dtype = query_states.dtype
507
+ if input_dtype == torch.float32:
508
+ if torch.is_autocast_enabled():
509
+ target_dtype = torch.get_autocast_gpu_dtype()
510
+ # Handle the case where the model is quantized
511
+ elif hasattr(self.config, "_pre_quantization_dtype"):
512
+ target_dtype = self.config._pre_quantization_dtype
513
+ else:
514
+ target_dtype = self.q_proj.weight.dtype
515
+
516
+ logger.warning_once(
517
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
518
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
519
+ f" {target_dtype}."
520
+ )
521
+
522
+ query_states = query_states.to(target_dtype)
523
+ key_states = key_states.to(target_dtype)
524
+ value_states = value_states.to(target_dtype)
525
+
526
+ # **For diffusion language model, attention_mask is set to None(full attention) by default.**
527
+ attention_mask = None
528
+ self.is_causal = False
529
+
530
+ attn_output = _flash_attention_forward(
531
+ query_states,
532
+ key_states,
533
+ value_states,
534
+ attention_mask,
535
+ q_len,
536
+ dropout=dropout_rate,
537
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
538
+ is_causal=self.is_causal,
539
+ )
540
+
541
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
542
+ attn_output = self.o_proj(attn_output)
543
+
544
+ if not output_attentions:
545
+ attn_weights = None
546
+
547
+ return attn_output, attn_weights, past_key_value
548
+
549
+
550
+ # copied from transformers.models.olmoe.modeling_olmoe.OlmoeSdpaAttention with OlmoeSdpaAttention->LLaDAMoESdpaAttention
551
+ class LLaDAMoESdpaAttention(LLaDAMoEAttention):
552
+ """
553
+ LLaDAMoE attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
554
+ `LLaDAMoEAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
555
+ SDPA API.
556
+ """
557
+ def forward(
558
+ self,
559
+ hidden_states: torch.Tensor,
560
+ attention_mask: Optional[torch.Tensor] = None,
561
+ position_ids: Optional[torch.LongTensor] = None,
562
+ past_key_value: Optional[Cache] = None,
563
+ output_attentions: bool = False,
564
+ use_cache: bool = False,
565
+ cache_position: Optional[torch.LongTensor] = None,
566
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
567
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
568
+ if output_attentions:
569
+ logger.warning_once(
570
+ "LLaDAModel is using LLaDAMoESdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
571
+ '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.'
572
+ )
573
+ return super().forward(
574
+ hidden_states=hidden_states,
575
+ attention_mask=attention_mask,
576
+ position_ids=position_ids,
577
+ past_key_value=past_key_value,
578
+ output_attentions=output_attentions,
579
+ use_cache=use_cache,
580
+ cache_position=cache_position,
581
+ position_embeddings=position_embeddings,
582
+ )
583
+
584
+ bsz, q_len, _ = hidden_states.size()
585
+
586
+ query_states = self.q_proj(hidden_states)
587
+ key_states = self.k_proj(hidden_states)
588
+ if 'q_norm' in dir(self):
589
+ query_states = self.q_norm(query_states.reshape(-1, self.head_dim)).reshape(bsz, q_len, -1)
590
+ key_states = self.k_norm(key_states.reshape(-1, self.head_dim)).reshape(bsz, q_len, -1)
591
+ value_states = self.v_proj(hidden_states)
592
+
593
+ if self.config.clip_qkv is not None:
594
+ query_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
595
+ key_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
596
+ value_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
597
+
598
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
599
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
600
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
601
+
602
+ cos, sin = position_embeddings
603
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
604
+
605
+ if past_key_value is not None:
606
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
607
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
608
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
609
+
610
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
611
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
612
+
613
+ causal_mask = attention_mask
614
+ # if attention_mask is not None and cache_position is not None:
615
+ if attention_mask is not None:
616
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
617
+
618
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
619
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
620
+ if query_states.device.type == "cuda" and causal_mask is not None:
621
+ query_states = query_states.contiguous()
622
+ key_states = key_states.contiguous()
623
+ value_states = value_states.contiguous()
624
+
625
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
626
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
627
+ is_causal = True if causal_mask is None and q_len > 1 else False
628
+
629
+ # **For diffusion language model, attention_mask is set to None(full attention) by default.**
630
+ is_causal = False
631
+ causal_mask = None
632
+
633
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
634
+ query_states,
635
+ key_states,
636
+ value_states,
637
+ attn_mask=causal_mask,
638
+ dropout_p=self.attention_dropout if self.training else 0.0,
639
+ is_causal=is_causal,
640
+ )
641
+
642
+ attn_output = attn_output.transpose(1, 2).contiguous()
643
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
644
+
645
+ attn_output = self.o_proj(attn_output)
646
+
647
+ return attn_output, None, past_key_value
648
+
649
+
650
+ LLADAMOE_ATTENTION_CLASSES = {
651
+ "eager": LLaDAMoEAttention,
652
+ "flash_attention_2": LLaDAMoEFlashAttention2,
653
+ "sdpa": LLaDAMoESdpaAttention,
654
+ }
655
+
656
+
657
+ # copied from transformers.models.olmoe.modeling_olmoe.OlmoeSparseMoeBlock with OlmoeSparseMoeBlock->LLaDAMoESparseMoeBlock
658
+ class LLaDAMoESparseMoeBlock(nn.Module):
659
+ def __init__(self, config):
660
+ super().__init__()
661
+ self.num_experts = config.num_experts
662
+ self.top_k = config.num_experts_per_tok
663
+ self.norm_topk_prob = False
664
+ self.gate = nn.Linear(config.hidden_size, self.num_experts, bias=False)
665
+ self.experts = nn.ModuleList([LLaDAMoEMLP(config, 'expert') for _ in range(self.num_experts)])
666
+ self.score_func = config.moe_router_score_function
667
+ if config.moe_router_enable_expert_bias:
668
+ self.register_buffer("expert_bias", torch.zeros(self.num_experts))
669
+ else:
670
+ self.expert_bias = None
671
+
672
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
673
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
674
+ hidden_states = hidden_states.view(-1, hidden_dim)
675
+ # router_logits: (batch * sequence_length, n_experts)
676
+ router_logits = self.gate(hidden_states)
677
+
678
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
679
+
680
+ if self.expert_bias is not None:
681
+ routing_weights += self.expert_bias
682
+
683
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
684
+ if self.norm_topk_prob:
685
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
686
+ # we cast back to the input dtype
687
+ routing_weights = routing_weights.to(hidden_states.dtype)
688
+
689
+ final_hidden_states = torch.zeros(
690
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
691
+ )
692
+
693
+ # One hot encode the selected experts to create an expert mask
694
+ # this will be used to easily index which expert is going to be selected
695
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
696
+
697
+ # Loop over all available experts in the model and perform the computation on each expert
698
+ for expert_idx in range(self.num_experts):
699
+ expert_layer = self.experts[expert_idx]
700
+ idx, top_x = torch.where(expert_mask[expert_idx])
701
+
702
+ # Index the correct hidden states and compute the expert hidden state for
703
+ # the current expert. We need to make sure to multiply the output hidden
704
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
705
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
706
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
707
+
708
+ # However `index_add_` only support torch tensors for indexing so we'll use
709
+ # the `top_x` tensor here.
710
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
711
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
712
+ return final_hidden_states
713
+
714
+
715
+ class LLaDAMoEDecoderLayer(nn.Module):
716
+ def __init__(self, config: LLaDAConfig, layer_idx: int):
717
+ super().__init__()
718
+ self.hidden_size = config.hidden_size
719
+ self.mlp_type = 'dense' if config.moe_layer_freq[layer_idx] == 0 else 'moe'
720
+
721
+ self.self_attn = LLADAMOE_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
722
+
723
+ self.mlp = LLaDAMoESparseMoeBlock(config) if self.mlp_type == 'moe' else LLaDAMoEMLP(config, 'dense')
724
+ self.input_layernorm = LLaDAMoERMSNorm(config.hidden_size, eps=config.rms_norm_eps)
725
+ self.post_attention_layernorm = LLaDAMoERMSNorm(config.hidden_size, eps=config.rms_norm_eps)
726
+ if config.shared_expert_intermediate_size is not None and self.mlp_type == 'moe':
727
+ self.shared_expert = LLaDAMoEMLP(config, 'shared_expert')
728
+
729
+ def forward(
730
+ self,
731
+ hidden_states: torch.Tensor,
732
+ attention_mask: Optional[torch.Tensor] = None,
733
+ position_ids: Optional[torch.LongTensor] = None,
734
+ past_key_value: Optional[Cache] = None,
735
+ output_attentions: Optional[bool] = False,
736
+ output_router_logits: Optional[bool] = False,
737
+ use_cache: Optional[bool] = False,
738
+ cache_position: Optional[torch.LongTensor] = None,
739
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
740
+ **kwargs,
741
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
742
+ """
743
+ Args:
744
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
745
+ attention_mask (`torch.FloatTensor`, *optional*):
746
+ For diffusion language model, attention_mask is set to None(full attention).
747
+ output_attentions (`bool`, *optional*):
748
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
749
+ returned tensors for more detail.
750
+ output_router_logits (`bool`, *optional*):
751
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
752
+ and should not be returned during inference.
753
+ use_cache (`bool`, *optional*):
754
+ For diffusion language model, use_cache is set to False by default.
755
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*):
756
+ For diffusion language model, past_key_value is set to None by default.
757
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
758
+ For diffusion language model, cache_position is set to None by default.
759
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
760
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
761
+ with `head_dim` being the embedding dimension of each attention head.
762
+ kwargs (`dict`, *optional*):
763
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
764
+ into the model
765
+ """
766
+ residual = hidden_states
767
+
768
+ hidden_states = self.input_layernorm(hidden_states)
769
+
770
+ # **For diffusion language model, attention_mask is set to None(full attention) by default.**
771
+ use_cache = False
772
+ attention_mask = None
773
+
774
+ # Self Attention
775
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
776
+ hidden_states=hidden_states,
777
+ attention_mask=attention_mask,
778
+ position_ids=position_ids,
779
+ past_key_value=past_key_value,
780
+ output_attentions=output_attentions,
781
+ use_cache=use_cache,
782
+ cache_position=cache_position,
783
+ position_embeddings=position_embeddings,
784
+ **kwargs,
785
+ )
786
+ hidden_states = residual + hidden_states
787
+
788
+ # Fully Connected
789
+ residual = hidden_states
790
+ hidden_states = self.post_attention_layernorm(hidden_states)
791
+ shared_expert_states = hidden_states
792
+
793
+ hidden_states = self.mlp(hidden_states)
794
+
795
+ if hasattr(self, "shared_expert"):
796
+ hidden_states = hidden_states + self.shared_expert(shared_expert_states)
797
+ hidden_states = residual + hidden_states
798
+
799
+ outputs = (hidden_states,)
800
+
801
+ if output_attentions:
802
+ outputs += (self_attn_weights,)
803
+
804
+ if use_cache:
805
+ outputs += (present_key_value,)
806
+
807
+ return outputs
808
+
809
+
810
+ LLADAMOE_START_DOCSTRING = r"""
811
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
812
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
813
+ etc.)
814
+
815
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
816
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
817
+ and behavior.
818
+
819
+ Parameters:
820
+ config ([`LLaDAConfig`]):
821
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
822
+ load the weights associated with the model, only the configuration. Check out the
823
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
824
+ """
825
+
826
+
827
+ @add_start_docstrings(
828
+ "The bare LLaDAMoE Model outputting raw hidden-states without any specific head on top.",
829
+ LLADAMOE_START_DOCSTRING,
830
+ )
831
+ # copied from transformers.models.olmoe.modeling_olmoe.OlmoeModel with OlmoePreTrainedModel->LLaDAMoEPreTrainedModel
832
+ class LLaDAMoEPreTrainedModel(PreTrainedModel):
833
+ config_class = LLaDAConfig
834
+ base_model_prefix = "model"
835
+ supports_gradient_checkpointing = True
836
+ _no_split_modules = ["LLaDAMoEDecoderLayer"]
837
+ _skip_keys_device_placement = ["past_key_values"]
838
+ _supports_flash_attn_2 = True
839
+ _supports_sdpa = True
840
+ _supports_cache_class = True
841
+ _supports_quantized_cache = True
842
+ _supports_static_cache = True
843
+
844
+ def _init_weights(self, module):
845
+ std = self.config.initializer_range
846
+ if isinstance(module, nn.Linear):
847
+ module.weight.data.normal_(mean=0.0, std=std)
848
+ if module.bias is not None:
849
+ module.bias.data.zero_()
850
+ elif isinstance(module, nn.Embedding):
851
+ module.weight.data.normal_(mean=0.0, std=std)
852
+ if module.padding_idx is not None:
853
+ module.weight.data[module.padding_idx].zero_()
854
+
855
+
856
+ LLADAMOE_INPUTS_DOCSTRING = r"""
857
+ Args:
858
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
859
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
860
+ it.
861
+
862
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
863
+ [`PreTrainedTokenizer.__call__`] for details.
864
+
865
+ [What are input IDs?](../glossary#input-ids)
866
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
867
+ Mask to avoid performing attention on padding token indices.
868
+ **For diffusion language model, attention_mask is set to None(full attention) by default.**
869
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
870
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
871
+ config.n_positions - 1]`.
872
+
873
+ [What are position IDs?](../glossary#position-ids)
874
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
875
+ **For diffusion language model, past_key_values can not be applied by default.**
876
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
877
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
878
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
879
+ model's internal embedding lookup matrix.
880
+ use_cache (`bool`, *optional*):
881
+ For diffusion languagem model, the use_cache and past_key_values can not be enabled for default setting.
882
+ output_attentions (`bool`, *optional*):
883
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
884
+ tensors for more detail.
885
+ output_hidden_states (`bool`, *optional*):
886
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
887
+ more detail.
888
+ output_router_logits (`bool`, *optional*):
889
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
890
+ should not be returned during inference.
891
+ return_dict (`bool`, *optional*):
892
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
893
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
894
+ **For diffusion language model, cache_position can not be applied by default.**
895
+ """
896
+
897
+
898
+ @add_start_docstrings(
899
+ "The bare LLaDAMoE Model outputting raw hidden-states without any specific head on top.",
900
+ LLADAMOE_START_DOCSTRING,
901
+ )
902
+ # copied from transformers.models.olmoe.modeling_olmoe.OlmoeModel with OlmoeModel->LLaDAMoEModel
903
+ class LLaDAMoEModel(LLaDAMoEPreTrainedModel):
904
+ """
905
+ Transformer encoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LLaDAMoEDecoderLayer`]
906
+
907
+ Args:
908
+ config: LLaDAConfig
909
+ """
910
+
911
+ def __init__(self, config: LLaDAConfig):
912
+ super().__init__(config)
913
+ self.padding_idx = config.pad_token_id
914
+ self.vocab_size = config.vocab_size
915
+
916
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
917
+ self.layers = nn.ModuleList(
918
+ [LLaDAMoEDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
919
+ )
920
+ self.norm = LLaDAMoERMSNorm(config.hidden_size, eps=config.rms_norm_eps)
921
+ self.rotary_emb = LLaDAMoERotaryEmbedding(config=config)
922
+ self.gradient_checkpointing = False
923
+
924
+ # Initialize weights and apply final processing
925
+ self.post_init()
926
+
927
+ def get_input_embeddings(self):
928
+ return self.embed_tokens
929
+
930
+ def set_input_embeddings(self, value):
931
+ self.embed_tokens = value
932
+
933
+ @add_start_docstrings_to_model_forward(LLADAMOE_INPUTS_DOCSTRING)
934
+ def forward(
935
+ self,
936
+ input_ids: torch.LongTensor = None,
937
+ attention_mask: Optional[torch.Tensor] = None,
938
+ position_ids: Optional[torch.LongTensor] = None,
939
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
940
+ inputs_embeds: Optional[torch.FloatTensor] = None,
941
+ use_cache: Optional[bool] = None,
942
+ output_attentions: Optional[bool] = None,
943
+ output_hidden_states: Optional[bool] = None,
944
+ output_router_logits: Optional[bool] = None,
945
+ return_dict: Optional[bool] = None,
946
+ cache_position: Optional[torch.LongTensor] = None,
947
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
948
+ assert (not use_cache and past_key_values is None and cache_position is None), "The cache mechanism is not suppotred for LLaDA MoE by default."
949
+
950
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
951
+ output_router_logits = (
952
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
953
+ )
954
+ output_hidden_states = (
955
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
956
+ )
957
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
958
+
959
+ if (input_ids is None) ^ (inputs_embeds is not None):
960
+ raise ValueError(
961
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
962
+ )
963
+
964
+ if inputs_embeds is None:
965
+ inputs_embeds = self.embed_tokens(input_ids)
966
+
967
+ return_legacy_cache = False
968
+ if cache_position is None:
969
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
970
+ cache_position = torch.arange(
971
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
972
+ )
973
+ if position_ids is None:
974
+ position_ids = cache_position.unsqueeze(0)
975
+
976
+ causal_mask = None
977
+ logger.warning_once(
978
+ f"Please note that, unlike autoregressive models, LLaDA MoE employs a bidirectional attention mechanism. "
979
+ f"In the forward code in modeling_lladamoe.py, we set both attention_mask and causal_mask to None, "
980
+ f"which affects the default causal attention and causes the input attention_mask parameter to become ineffective. "
981
+ f"If you pass an attention mask and expect the model to use it for computing other attention mechanisms, "
982
+ f"it may lead to logits and aux_loss returned by the model being inconsistent with your expectations. "
983
+ )
984
+
985
+ # embed positions
986
+ hidden_states = inputs_embeds
987
+
988
+ # create position embeddings to be shared across the decoder layers
989
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
990
+
991
+ # decoder layers
992
+ all_hidden_states = () if output_hidden_states else None
993
+ all_self_attns = () if output_attentions else None
994
+ all_router_logits = () if output_router_logits else None
995
+ next_decoder_cache = None
996
+
997
+ for decoder_layer in self.layers:
998
+ if output_hidden_states:
999
+ all_hidden_states += (hidden_states,)
1000
+
1001
+ if self.gradient_checkpointing and self.training:
1002
+ layer_outputs = self._gradient_checkpointing_func(
1003
+ decoder_layer.__call__,
1004
+ hidden_states,
1005
+ causal_mask,
1006
+ position_ids,
1007
+ past_key_values,
1008
+ output_attentions,
1009
+ output_router_logits,
1010
+ use_cache,
1011
+ cache_position,
1012
+ position_embeddings,
1013
+ )
1014
+ else:
1015
+ layer_outputs = decoder_layer(
1016
+ hidden_states,
1017
+ attention_mask=causal_mask,
1018
+ position_ids=position_ids,
1019
+ past_key_value=past_key_values,
1020
+ output_attentions=output_attentions,
1021
+ output_router_logits=output_router_logits,
1022
+ use_cache=use_cache,
1023
+ cache_position=cache_position,
1024
+ position_embeddings=position_embeddings,
1025
+ )
1026
+
1027
+ hidden_states = layer_outputs[0]
1028
+
1029
+ if use_cache:
1030
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1031
+
1032
+ if output_attentions:
1033
+ all_self_attns += (layer_outputs[1],)
1034
+
1035
+ if output_router_logits and layer_outputs[-1] is not None:
1036
+ all_router_logits += (layer_outputs[-1],)
1037
+
1038
+ hidden_states = self.norm(hidden_states)
1039
+
1040
+ # add hidden states from the last layer
1041
+ if output_hidden_states:
1042
+ all_hidden_states += (hidden_states,)
1043
+
1044
+ next_cache = next_decoder_cache if use_cache else None
1045
+ if return_legacy_cache:
1046
+ next_cache = next_cache.to_legacy_cache()
1047
+
1048
+ if not return_dict:
1049
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1050
+ return MoeModelOutputWithPast(
1051
+ last_hidden_state=hidden_states,
1052
+ past_key_values=next_cache,
1053
+ hidden_states=all_hidden_states,
1054
+ attentions=all_self_attns,
1055
+ router_logits=all_router_logits,
1056
+ )
1057
+
1058
+
1059
+ class LLaDAMoEModelLM(LLaDAMoEPreTrainedModel):
1060
+ _tied_weights_keys = ["lm_head.weight"]
1061
+
1062
+ def __init__(self, config):
1063
+ super().__init__(config)
1064
+ self.model = LLaDAMoEModel(config)
1065
+ self.vocab_size = config.vocab_size
1066
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1067
+
1068
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1069
+ self.num_experts = config.num_experts
1070
+ self.num_experts_per_tok = config.num_experts_per_tok
1071
+ # Initialize weights and apply final processing
1072
+ self.post_init()
1073
+
1074
+ def get_input_embeddings(self):
1075
+ return self.model.embed_tokens
1076
+
1077
+ def set_input_embeddings(self, value):
1078
+ self.model.embed_tokens = value
1079
+
1080
+ def get_output_embeddings(self):
1081
+ return self.lm_head
1082
+
1083
+ def set_output_embeddings(self, new_embeddings):
1084
+ self.lm_head = new_embeddings
1085
+
1086
+ def set_decoder(self, decoder):
1087
+ self.model = decoder
1088
+
1089
+ def get_decoder(self):
1090
+ return self.model
1091
+
1092
+ @add_start_docstrings_to_model_forward(LLADAMOE_INPUTS_DOCSTRING)
1093
+ @replace_return_docstrings(output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1094
+ def forward(
1095
+ self,
1096
+ input_ids: torch.LongTensor = None,
1097
+ attention_mask: Optional[torch.Tensor] = None,
1098
+ position_ids: Optional[torch.LongTensor] = None,
1099
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1100
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1101
+ labels: Optional[torch.LongTensor] = None,
1102
+ use_cache: Optional[bool] = None,
1103
+ output_attentions: Optional[bool] = None,
1104
+ output_hidden_states: Optional[bool] = None,
1105
+ output_router_logits: Optional[bool] = None,
1106
+ return_dict: Optional[bool] = None,
1107
+ cache_position: Optional[torch.LongTensor] = None,
1108
+ num_logits_to_keep: int = 0,
1109
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
1110
+ r"""
1111
+ For the current inference code of the diffusion language model, passing the parameters `labels` and `num_logits_to_keep` to compute loss is not supported.
1112
+ Please note that for the diffusion language model, you cannot use model.generate() to generate responses. Please use the provided sampling code to generate model outputs.
1113
+
1114
+ Returns:
1115
+
1116
+ Example:
1117
+
1118
+ ```python
1119
+ >>> from transformers import AutoTokenizer, AutoModel
1120
+
1121
+ >>> model = AutoModel.from_pretrained("path/to/LLaDAMoE")
1122
+ >>> tokenizer = AutoTokenizer.from_pretrained("path/to/LLaDAMoE")
1123
+
1124
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1125
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1126
+
1127
+ >>> # Generate
1128
+ >>> generate_ids = generate() # Please use the customized generate method instead of model.generate().
1129
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1130
+ 'Hey, are you conscious? Can you talk to me?\nI’m not sure if you’re conscious of this, but I’m'
1131
+ ```
1132
+ """
1133
+ assert (labels is None and num_logits_to_keep == 0), "LLaDAMoE model does not support calculate loss in the forward pass."
1134
+
1135
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1136
+ output_router_logits = (
1137
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1138
+ )
1139
+ output_hidden_states = (
1140
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1141
+ )
1142
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1143
+
1144
+ outputs = self.model(
1145
+ input_ids=input_ids,
1146
+ attention_mask=attention_mask,
1147
+ position_ids=position_ids,
1148
+ past_key_values=past_key_values,
1149
+ inputs_embeds=inputs_embeds,
1150
+ use_cache=use_cache,
1151
+ output_attentions=output_attentions,
1152
+ output_hidden_states=output_hidden_states,
1153
+ output_router_logits=output_router_logits,
1154
+ return_dict=return_dict,
1155
+ cache_position=cache_position,
1156
+ )
1157
+
1158
+ hidden_states = outputs[0]
1159
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1160
+
1161
+ loss = None
1162
+
1163
+ aux_loss = None
1164
+ if output_router_logits:
1165
+ aux_loss = load_balancing_loss_func(
1166
+ outputs.router_logits if return_dict else outputs[-1],
1167
+ self.num_experts,
1168
+ self.num_experts_per_tok,
1169
+ attention_mask,
1170
+ )
1171
+
1172
+ if not return_dict:
1173
+ output = (logits,) + outputs[1:]
1174
+ if output_router_logits:
1175
+ output = (aux_loss,) + output
1176
+ return (loss,) + output if loss is not None else output
1177
+
1178
+ return MoeCausalLMOutputWithPast(
1179
+ loss=loss,
1180
+ aux_loss=aux_loss,
1181
+ logits=logits,
1182
+ past_key_values=outputs.past_key_values,
1183
+ hidden_states=outputs.hidden_states,
1184
+ attentions=outputs.attentions,
1185
+ router_logits=outputs.router_logits,
1186
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|startoftext|>",
3
+ "cls_token": "[CLS]",
4
+ "eos_token": "<|endoftext|>",
5
+ "gmask_token": "[gMASK]",
6
+ "pad_token": "<|endoftext|>"
7
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "fast_tokenizer": true,
10
+ "gmask_token": "[gMASK]",
11
+ "merges_file": null,
12
+ "model_max_length": 1000000000000000019884624838656,
13
+ "pad_token": "<|endoftext|>",
14
+ "tokenizer_class": "PreTrainedTokenizerFast",
15
+ "trust_remote_code": true,
16
+ "vocab_file": null
17
+ }