Text Generation
Transformers
Safetensors
llada2_moe
diffusion
dllm
mmd
math
custom_code
conversational
Eval Results
Instructions to use yresearch/DMax-Math-MMD with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use yresearch/DMax-Math-MMD with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="yresearch/DMax-Math-MMD", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("yresearch/DMax-Math-MMD", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use yresearch/DMax-Math-MMD with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "yresearch/DMax-Math-MMD" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "yresearch/DMax-Math-MMD", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/yresearch/DMax-Math-MMD
- SGLang
How to use yresearch/DMax-Math-MMD with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "yresearch/DMax-Math-MMD" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "yresearch/DMax-Math-MMD", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "yresearch/DMax-Math-MMD" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "yresearch/DMax-Math-MMD", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use yresearch/DMax-Math-MMD with Docker Model Runner:
docker model run hf.co/yresearch/DMax-Math-MMD
Add files using upload-large-folder tool
Browse files- .gitattributes +1 -0
- chat_template.jinja +86 -0
- config.json +61 -0
- configuration_llada2_moe.py +88 -0
- model-00001-of-00009.safetensors +3 -0
- model-00002-of-00009.safetensors +3 -0
- model-00003-of-00009.safetensors +3 -0
- model-00004-of-00009.safetensors +3 -0
- model-00005-of-00009.safetensors +3 -0
- model-00006-of-00009.safetensors +3 -0
- model-00007-of-00009.safetensors +3 -0
- model-00008-of-00009.safetensors +3 -0
- model-00009-of-00009.safetensors +3 -0
- model.safetensors.index.json +0 -0
- modeling_llada2_moe.py +370 -0
- tokenizer.json +3 -0
- tokenizer_config.json +23 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% set thinking_option = 'off' %}
|
| 2 |
+
{{- '<role>SYSTEM</role>' }}
|
| 3 |
+
{%- if messages[0].role == 'system' %}
|
| 4 |
+
{{- messages[0].content + '\n' }}
|
| 5 |
+
{%- endif %}
|
| 6 |
+
{%- if tools %}
|
| 7 |
+
{{- "# 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>" }}
|
| 8 |
+
{%- for tool in tools %}
|
| 9 |
+
{{- "\n" }}
|
| 10 |
+
{{- tool | tojson }}
|
| 11 |
+
{%- endfor %}
|
| 12 |
+
{{- "\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" }}
|
| 13 |
+
{%- endif %}
|
| 14 |
+
{{- 'detailed thinking ' + thinking_option + '<|role_end|>' }}
|
| 15 |
+
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
|
| 16 |
+
{%- for message in messages[::-1] %}
|
| 17 |
+
{%- set index = (messages|length - 1) - loop.index0 %}
|
| 18 |
+
{%- 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>')) %}
|
| 19 |
+
{%- set ns.multi_step_tool = false %}
|
| 20 |
+
{%- set ns.last_query_index = index %}
|
| 21 |
+
{%- endif %}
|
| 22 |
+
{%- endfor %}
|
| 23 |
+
{%- for message in messages %}
|
| 24 |
+
{%- if message.content is string %}
|
| 25 |
+
{%- set content = message.content %}
|
| 26 |
+
{%- else %}
|
| 27 |
+
{%- set content = '' %}
|
| 28 |
+
{%- endif %}
|
| 29 |
+
{%- if message.role == "user" %}
|
| 30 |
+
{{- '<role>HUMAN</role>' + message.content + '<|role_end|>' }}
|
| 31 |
+
{%- elif message.role == "system" and not loop.first %}
|
| 32 |
+
{{- '<role>SYSTEM</role>' + message.content + '<|role_end|>' }}
|
| 33 |
+
{%- elif message.role == "assistant" %}
|
| 34 |
+
{%- set reasoning_content = '' %}
|
| 35 |
+
{%- if message.reasoning_content is string %}
|
| 36 |
+
{%- set reasoning_content = message.reasoning_content %}
|
| 37 |
+
{%- else %}
|
| 38 |
+
{%- if '</think>' in content %}
|
| 39 |
+
{%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
|
| 40 |
+
{%- set content = content.split('</think>')[-1].lstrip('\n') %}
|
| 41 |
+
{%- endif %}
|
| 42 |
+
{%- endif %}
|
| 43 |
+
{%- if loop.index0 > ns.last_query_index %}
|
| 44 |
+
{%- if reasoning_content %}
|
| 45 |
+
{{- '<role>ASSISTANT</role>' + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
|
| 46 |
+
{%- else %}
|
| 47 |
+
{{- '<role>ASSISTANT</role>' + content }}
|
| 48 |
+
{%- endif %}
|
| 49 |
+
{%- else %}
|
| 50 |
+
{{- '<role>ASSISTANT</role>' + content }}
|
| 51 |
+
{%- endif %}
|
| 52 |
+
{%- if message.tool_calls %}
|
| 53 |
+
{%- for tool_call in message.tool_calls %}
|
| 54 |
+
{%- if (loop.first and content) or (not loop.first) %}
|
| 55 |
+
{{- '\n' }}
|
| 56 |
+
{%- endif %}
|
| 57 |
+
{%- if tool_call.function %}
|
| 58 |
+
{%- set tool_call = tool_call.function %}
|
| 59 |
+
{%- endif %}
|
| 60 |
+
{{- '<tool_call>\n{"name": "' }}
|
| 61 |
+
{{- tool_call.name }}
|
| 62 |
+
{{- '", "arguments": ' }}
|
| 63 |
+
{%- if tool_call.arguments is string %}
|
| 64 |
+
{{- tool_call.arguments }}
|
| 65 |
+
{%- else %}
|
| 66 |
+
{{- tool_call.arguments | tojson }}
|
| 67 |
+
{%- endif %}
|
| 68 |
+
{{- '}\n</tool_call>' }}
|
| 69 |
+
{%- endfor %}
|
| 70 |
+
{%- endif %}
|
| 71 |
+
{{- '<|role_end|>' }}
|
| 72 |
+
{%- elif message.role == "tool" %}
|
| 73 |
+
{%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
|
| 74 |
+
{{- '<role>OBSERVATION</role>' }}
|
| 75 |
+
{%- endif %}
|
| 76 |
+
{{- '\n<tool_response>\n' }}
|
| 77 |
+
{{- content }}
|
| 78 |
+
{{- '\n</tool_response>' }}
|
| 79 |
+
{%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
|
| 80 |
+
{{- '<|role_end|>' }}
|
| 81 |
+
{%- endif %}
|
| 82 |
+
{%- endif %}
|
| 83 |
+
{%- endfor %}
|
| 84 |
+
{%- if add_generation_prompt %}
|
| 85 |
+
{{- '<role>ASSISTANT</role>' }}
|
| 86 |
+
{%- endif %}
|
config.json
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_moe_implementation": "fused",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"LLaDA2MoeModelLM"
|
| 5 |
+
],
|
| 6 |
+
"attention_dropout": 0.0,
|
| 7 |
+
"auto_map": {
|
| 8 |
+
"AutoConfig": "configuration_llada2_moe.LLaDA2MoeConfig",
|
| 9 |
+
"AutoModelForCausalLM": "modeling_llada2_moe.LLaDA2MoeModelLM"
|
| 10 |
+
},
|
| 11 |
+
"dtype": "float32",
|
| 12 |
+
"embedding_dropout": 0.0,
|
| 13 |
+
"first_k_dense_replace": 1,
|
| 14 |
+
"fuse_cross_entropy": false,
|
| 15 |
+
"head_dim": 128,
|
| 16 |
+
"hidden_act": "silu",
|
| 17 |
+
"hidden_size": 2048,
|
| 18 |
+
"initializer_range": 0.02,
|
| 19 |
+
"intermediate_size": 5120,
|
| 20 |
+
"max_position_embeddings": 16384,
|
| 21 |
+
"max_window_layers": 28,
|
| 22 |
+
"model_type": "llada2_moe",
|
| 23 |
+
"moe_intermediate_size": 512,
|
| 24 |
+
"moe_router_enable_expert_bias": true,
|
| 25 |
+
"n_group": 8,
|
| 26 |
+
"norm_head": false,
|
| 27 |
+
"norm_softmax": false,
|
| 28 |
+
"norm_topk_prob": true,
|
| 29 |
+
"num_attention_heads": 16,
|
| 30 |
+
"num_experts": 256,
|
| 31 |
+
"num_experts_per_tok": 8,
|
| 32 |
+
"num_hidden_layers": 20,
|
| 33 |
+
"num_key_value_heads": 4,
|
| 34 |
+
"num_shared_experts": 1,
|
| 35 |
+
"output_dropout": 0.0,
|
| 36 |
+
"output_router_logits": false,
|
| 37 |
+
"pad_token_id": 156892,
|
| 38 |
+
"partial_rotary_factor": 0.5,
|
| 39 |
+
"rms_norm_eps": 1e-06,
|
| 40 |
+
"rope_parameters": {
|
| 41 |
+
"partial_rotary_factor": 0.5,
|
| 42 |
+
"rope_theta": 600000,
|
| 43 |
+
"rope_type": "default"
|
| 44 |
+
},
|
| 45 |
+
"rope_theta": 600000,
|
| 46 |
+
"rotary_dim": 64,
|
| 47 |
+
"routed_scaling_factor": 2.5,
|
| 48 |
+
"router_dtype": "fp32",
|
| 49 |
+
"score_function": "sigmoid",
|
| 50 |
+
"sliding_window": 4096,
|
| 51 |
+
"tie_word_embeddings": false,
|
| 52 |
+
"topk_group": 4,
|
| 53 |
+
"transformers_version": "5.9.0",
|
| 54 |
+
"use_bias": false,
|
| 55 |
+
"use_cache": false,
|
| 56 |
+
"use_qkv_bias": false,
|
| 57 |
+
"use_rmsnorm": true,
|
| 58 |
+
"use_sliding_window": false,
|
| 59 |
+
"using_split_qkv_in_self_attention": false,
|
| 60 |
+
"vocab_size": 157184
|
| 61 |
+
}
|
configuration_llada2_moe.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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=None,
|
| 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__(pad_token_id=pad_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
__all__ = ["LLaDA2MoeConfig"]
|
model-00001-of-00009.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c4776026726cd89a292fab7431fe8924be2d42cc06d47575c51631b59d2ac59f
|
| 3 |
+
size 3999486248
|
model-00002-of-00009.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d7f6442de6cd3e0f1bd312f8ab33fae1b6141ddab64a3a6467f27d4c0ef1e0c3
|
| 3 |
+
size 3999530848
|
model-00003-of-00009.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3a871cc17484d8824c8c9d980fec5c5e71f2a3b9bc6f6d8dd0d3bc11b3c0b058
|
| 3 |
+
size 3999522984
|
model-00004-of-00009.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3b26fbb592d980652baecc98797b94d9519503786a038f5ed25ddb1c1262a15e
|
| 3 |
+
size 3998483688
|
model-00005-of-00009.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0ac4a6102533711068a5e3881d2541b1b39b5e049ddef6408c4c2aa8ba673d76
|
| 3 |
+
size 3999524816
|
model-00006-of-00009.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:53eb3b76783026fcf2a45b68dccc83b8ac1dd35cac18521a8f684cba7a96972b
|
| 3 |
+
size 3998485416
|
model-00007-of-00009.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7e0005cdb808fe7c884838d10f8fa597ecafc9087af5748962c24bb2fbe9e33b
|
| 3 |
+
size 3999524720
|
model-00008-of-00009.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f576f4d7b06c5c37fceb4f3ae090dac44248a4c84035adce34d3274b33ef4f91
|
| 3 |
+
size 3874746464
|
model-00009-of-00009.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9bc83c02783109a1136c23972b1555fd9d6cca00ba797c30cfd759eaa108f371
|
| 3 |
+
size 643825808
|
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,370 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 Antgroup and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 5 |
+
# and OPT implementations in this library. It has been modified from its
|
| 6 |
+
# original forms to accommodate minor architectural differences compared
|
| 7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
"""DMax LLaDA2 training layers; see NOTICE.md for upstream revision and adaptations.
|
| 21 |
+
|
| 22 |
+
Explicit 4D attention masks are passed unchanged to SDPA (True means attend).
|
| 23 |
+
"""
|
| 24 |
+
import math
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn.functional as F
|
| 27 |
+
from torch import nn
|
| 28 |
+
from torch.utils.checkpoint import checkpoint
|
| 29 |
+
from transformers.activations import ACT2FN
|
| 30 |
+
from transformers.modeling_outputs import MoeCausalLMOutputWithPast
|
| 31 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 32 |
+
from .configuration_llada2_moe import LLaDA2MoeConfig
|
| 33 |
+
|
| 34 |
+
class LLaDA2MoeRMSNorm(nn.Module):
|
| 35 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 36 |
+
"""
|
| 37 |
+
LLaDA2MoeRMSNorm is equivalent to T5LayerNorm
|
| 38 |
+
"""
|
| 39 |
+
super().__init__()
|
| 40 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 41 |
+
self.variance_epsilon = eps
|
| 42 |
+
|
| 43 |
+
def forward(self, hidden_states):
|
| 44 |
+
input_dtype = hidden_states.dtype
|
| 45 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 46 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 47 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 48 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def rotate_half(x):
|
| 52 |
+
"""Rotates half the hidden dims of the input."""
|
| 53 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 54 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 55 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
|
| 59 |
+
def apply_rotary_pos_emb(q, k, cos, sin):
|
| 60 |
+
"""Rotate the configured head dimensions at the supplied logical positions."""
|
| 61 |
+
# RoPE values are [batch, token, rotary_dim]; broadcast over attention heads.
|
| 62 |
+
cos = cos.unsqueeze(1)
|
| 63 |
+
sin = sin.unsqueeze(1)
|
| 64 |
+
|
| 65 |
+
# Keep half or full tensor for later concatenation
|
| 66 |
+
rotary_dim = cos.shape[-1]
|
| 67 |
+
q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
|
| 68 |
+
k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
|
| 69 |
+
|
| 70 |
+
# Apply rotary embeddings on the first half or full tensor
|
| 71 |
+
q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
|
| 72 |
+
k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
|
| 73 |
+
|
| 74 |
+
# Concatenate back to full shape
|
| 75 |
+
q_embed = torch.cat([q_embed, q_pass], dim=-1)
|
| 76 |
+
k_embed = torch.cat([k_embed, k_pass], dim=-1)
|
| 77 |
+
return q_embed, k_embed
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class LLaDA2MoeMLP(nn.Module):
|
| 81 |
+
def __init__(self, config: LLaDA2MoeConfig, intermediate_size: int):
|
| 82 |
+
super().__init__()
|
| 83 |
+
self.config = config
|
| 84 |
+
self.hidden_size = config.hidden_size
|
| 85 |
+
self.intermediate_size = intermediate_size
|
| 86 |
+
|
| 87 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 88 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 89 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 90 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 91 |
+
|
| 92 |
+
def forward(self, x):
|
| 93 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class LLaDA2MoeGate(nn.Module):
|
| 97 |
+
def __init__(self, config):
|
| 98 |
+
super().__init__()
|
| 99 |
+
self.config = config
|
| 100 |
+
self.top_k = config.num_experts_per_tok
|
| 101 |
+
self.num_experts = config.num_experts
|
| 102 |
+
|
| 103 |
+
self.n_group = config.n_group
|
| 104 |
+
self.topk_group = config.topk_group
|
| 105 |
+
|
| 106 |
+
# topk selection algorithm
|
| 107 |
+
self.gating_dim = config.hidden_size
|
| 108 |
+
self.weight = nn.Parameter(torch.empty((self.num_experts, self.gating_dim)))
|
| 109 |
+
self.routed_scaling_factor = config.routed_scaling_factor
|
| 110 |
+
|
| 111 |
+
self.register_buffer("expert_bias", torch.zeros((self.num_experts)))
|
| 112 |
+
self.reset_parameters()
|
| 113 |
+
|
| 114 |
+
def reset_parameters(self) -> None:
|
| 115 |
+
import torch.nn.init as init
|
| 116 |
+
|
| 117 |
+
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
|
| 118 |
+
|
| 119 |
+
def group_limited_topk(
|
| 120 |
+
self,
|
| 121 |
+
scores: torch.Tensor,
|
| 122 |
+
):
|
| 123 |
+
num_tokens, _ = scores.size()
|
| 124 |
+
# Organize the experts into groups
|
| 125 |
+
group_scores = scores.view(num_tokens, self.n_group, -1).topk(2, dim=-1)[0].sum(dim=-1)
|
| 126 |
+
group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
|
| 127 |
+
group_mask = torch.zeros_like(group_scores)
|
| 128 |
+
group_mask.scatter_(1, group_idx, 1)
|
| 129 |
+
|
| 130 |
+
# Mask the experts based on selection groups
|
| 131 |
+
score_mask = (
|
| 132 |
+
group_mask.unsqueeze(-1)
|
| 133 |
+
.expand(num_tokens, self.n_group, self.num_experts // self.n_group)
|
| 134 |
+
.reshape(num_tokens, -1)
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
masked_scores = scores.masked_fill(~score_mask.bool(), float('-inf'))
|
| 138 |
+
probs, top_indices = torch.topk(masked_scores, k=self.top_k, dim=-1)
|
| 139 |
+
|
| 140 |
+
return probs, top_indices
|
| 141 |
+
|
| 142 |
+
def forward(self, hidden_states):
|
| 143 |
+
# compute gating score
|
| 144 |
+
hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
|
| 145 |
+
logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
|
| 146 |
+
|
| 147 |
+
scores = torch.sigmoid(logits.float()).type_as(logits)
|
| 148 |
+
|
| 149 |
+
scores_for_routing = scores + self.expert_bias
|
| 150 |
+
_, topk_idx = self.group_limited_topk(scores_for_routing)
|
| 151 |
+
|
| 152 |
+
scores = torch.gather(scores, dim=1, index=topk_idx).type_as(logits)
|
| 153 |
+
|
| 154 |
+
topk_weight = scores / (scores.sum(dim=-1, keepdim=True) + 1e-20) if self.top_k > 1 else scores
|
| 155 |
+
topk_weight = topk_weight * self.routed_scaling_factor
|
| 156 |
+
|
| 157 |
+
return topk_idx, topk_weight, logits
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class LLaDA2MoeRotaryEmbedding(nn.Module):
|
| 161 |
+
def __init__(self, config):
|
| 162 |
+
super().__init__()
|
| 163 |
+
self.config = config
|
| 164 |
+
scaling = config.rope_scaling or {}
|
| 165 |
+
if scaling.get("rope_type", scaling.get("type", "default")) != "default":
|
| 166 |
+
raise ValueError("yrDMax supports the released LLaDA2 default RoPE only")
|
| 167 |
+
self.rebuild(torch.device("cpu"))
|
| 168 |
+
|
| 169 |
+
def rebuild(self, device):
|
| 170 |
+
dim = int(self.config.head_dim * self.config.partial_rotary_factor)
|
| 171 |
+
inv_freq = 1.0 / (self.config.rope_theta ** (
|
| 172 |
+
torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim))
|
| 173 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 174 |
+
|
| 175 |
+
@torch.no_grad()
|
| 176 |
+
def forward(self, x, position_ids):
|
| 177 |
+
inv = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
| 178 |
+
with torch.autocast(device_type=x.device.type, enabled=False):
|
| 179 |
+
freqs = (inv @ position_ids[:, None, :].float()).transpose(1, 2)
|
| 180 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 181 |
+
return emb.cos().to(x.dtype), emb.sin().to(x.dtype)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class LLaDA2MoeSparseMoeBlock(nn.Module):
|
| 185 |
+
def __init__(self, config):
|
| 186 |
+
super().__init__()
|
| 187 |
+
self.config = config
|
| 188 |
+
self.num_experts_per_tok = config.num_experts_per_tok
|
| 189 |
+
self.experts = nn.ModuleList([
|
| 190 |
+
LLaDA2MoeMLP(config, config.moe_intermediate_size)
|
| 191 |
+
for _ in range(config.num_experts)])
|
| 192 |
+
self.gate = LLaDA2MoeGate(config)
|
| 193 |
+
self.shared_experts = (LLaDA2MoeMLP(
|
| 194 |
+
config, config.moe_intermediate_size * config.num_shared_experts)
|
| 195 |
+
if config.num_shared_experts else None)
|
| 196 |
+
|
| 197 |
+
def forward(self, hidden_states):
|
| 198 |
+
# Same expert and combine equations as upstream _forward; autograd also
|
| 199 |
+
# works in eval mode, so temporary mode changes cannot freeze experts.
|
| 200 |
+
shape = hidden_states.shape
|
| 201 |
+
indices, weights, router_logits = self.gate(hidden_states)
|
| 202 |
+
flat = hidden_states.reshape(-1, shape[-1])
|
| 203 |
+
expanded = flat.repeat_interleave(self.num_experts_per_tok, dim=0)
|
| 204 |
+
result = torch.empty_like(expanded)
|
| 205 |
+
for i, expert in enumerate(self.experts):
|
| 206 |
+
selected = indices.reshape(-1) == i
|
| 207 |
+
# Unwrapped/DDP FP32 masters may produce BF16 expert activations
|
| 208 |
+
# under autocast. Indexed assignment does not promote dtypes.
|
| 209 |
+
result[selected] = expert(expanded[selected]).to(result.dtype)
|
| 210 |
+
result = (result.view(*weights.shape, -1) * weights.unsqueeze(-1)).sum(1)
|
| 211 |
+
result = result.to(hidden_states.dtype).view(shape)
|
| 212 |
+
if self.shared_experts is not None:
|
| 213 |
+
result = result + self.shared_experts(hidden_states)
|
| 214 |
+
return result
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 218 |
+
"""
|
| 219 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 220 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 221 |
+
"""
|
| 222 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 223 |
+
if n_rep == 1:
|
| 224 |
+
return hidden_states
|
| 225 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 226 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
# Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->LLaDA2Moe
|
| 230 |
+
class LLaDA2MoeAttention(nn.Module):
|
| 231 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 232 |
+
|
| 233 |
+
def __init__(self, config: LLaDA2MoeConfig, layer_idx=None):
|
| 234 |
+
super().__init__()
|
| 235 |
+
self.config = config
|
| 236 |
+
self.layer_idx = layer_idx
|
| 237 |
+
|
| 238 |
+
self.attention_dropout = config.attention_dropout
|
| 239 |
+
self.hidden_size = config.hidden_size
|
| 240 |
+
self.num_heads = config.num_attention_heads
|
| 241 |
+
self.head_dim = config.head_dim or self.hidden_size // self.num_heads
|
| 242 |
+
partial_rotary_factor = config.partial_rotary_factor if hasattr(config, "partial_rotary_factor") else 1.0
|
| 243 |
+
self.rope_dim = int(self.head_dim * partial_rotary_factor)
|
| 244 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 245 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 246 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 247 |
+
self.rope_theta = config.rope_theta
|
| 248 |
+
self.is_causal = False
|
| 249 |
+
|
| 250 |
+
self.query_key_value = nn.Linear(
|
| 251 |
+
self.hidden_size,
|
| 252 |
+
(self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
|
| 253 |
+
bias=config.use_qkv_bias,
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
self.query_layernorm = LLaDA2MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 257 |
+
self.key_layernorm = LLaDA2MoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 258 |
+
self.dense = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.use_bias)
|
| 259 |
+
|
| 260 |
+
def forward(self, hidden_states, attention_mask, position_embeddings):
|
| 261 |
+
bsz, q_len, _ = hidden_states.shape
|
| 262 |
+
qkv = self.query_key_value(hidden_states).view(
|
| 263 |
+
bsz, q_len, self.num_heads + 2 * self.num_key_value_heads, self.head_dim)
|
| 264 |
+
query, key, value = qkv.split(
|
| 265 |
+
[self.num_heads, self.num_key_value_heads, self.num_key_value_heads], dim=-2)
|
| 266 |
+
query = self.query_layernorm(query.transpose(1, 2))
|
| 267 |
+
key = self.key_layernorm(key.transpose(1, 2))
|
| 268 |
+
value = value.transpose(1, 2)
|
| 269 |
+
query, key = apply_rotary_pos_emb(query, key, *position_embeddings)
|
| 270 |
+
key, value = repeat_kv(key, self.num_key_value_groups), repeat_kv(value, self.num_key_value_groups)
|
| 271 |
+
out = F.scaled_dot_product_attention(
|
| 272 |
+
query.contiguous(), key.contiguous(), value.contiguous(),
|
| 273 |
+
attn_mask=attention_mask,
|
| 274 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
| 275 |
+
is_causal=False)
|
| 276 |
+
out = self.dense(out.transpose(1, 2).contiguous().reshape(bsz, q_len, -1))
|
| 277 |
+
return out
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
class LLaDA2MoeDecoderLayer(nn.Module):
|
| 281 |
+
def __init__(self, config, layer_idx):
|
| 282 |
+
super().__init__()
|
| 283 |
+
self.attention = LLaDA2MoeAttention(config, layer_idx)
|
| 284 |
+
self.mlp = (LLaDA2MoeSparseMoeBlock(config)
|
| 285 |
+
if config.num_experts is not None and layer_idx >= config.first_k_dense_replace
|
| 286 |
+
else LLaDA2MoeMLP(config, config.intermediate_size))
|
| 287 |
+
self.input_layernorm = LLaDA2MoeRMSNorm(config.hidden_size, config.rms_norm_eps)
|
| 288 |
+
self.post_attention_layernorm = LLaDA2MoeRMSNorm(config.hidden_size, config.rms_norm_eps)
|
| 289 |
+
|
| 290 |
+
def forward(self, hidden_states, attention_mask, position_embeddings):
|
| 291 |
+
attention_output = self.attention(self.input_layernorm(hidden_states), attention_mask,
|
| 292 |
+
position_embeddings)
|
| 293 |
+
hidden_states = hidden_states + attention_output
|
| 294 |
+
hidden_states = hidden_states + self.mlp(self.post_attention_layernorm(hidden_states))
|
| 295 |
+
return hidden_states
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
class LLaDA2MoeModel(nn.Module):
|
| 299 |
+
def __init__(self, config):
|
| 300 |
+
super().__init__()
|
| 301 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
|
| 302 |
+
self.layers = nn.ModuleList([LLaDA2MoeDecoderLayer(config, i) for i in range(config.num_hidden_layers)])
|
| 303 |
+
self.norm = LLaDA2MoeRMSNorm(config.hidden_size, config.rms_norm_eps)
|
| 304 |
+
self.rotary_emb = LLaDA2MoeRotaryEmbedding(config)
|
| 305 |
+
self.gradient_checkpointing = False
|
| 306 |
+
|
| 307 |
+
def forward(self, input_ids, attention_mask, position_ids, inputs_embeds=None):
|
| 308 |
+
hidden = self.word_embeddings(input_ids) if inputs_embeds is None else inputs_embeds
|
| 309 |
+
positions = self.rotary_emb(hidden, position_ids)
|
| 310 |
+
for layer in self.layers:
|
| 311 |
+
if self.gradient_checkpointing and self.training:
|
| 312 |
+
hidden = checkpoint(layer, hidden, attention_mask, positions, use_reentrant=False)
|
| 313 |
+
else:
|
| 314 |
+
hidden = layer(hidden, attention_mask, positions)
|
| 315 |
+
return self.norm(hidden)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
class LLaDA2MoeModelLM(PreTrainedModel):
|
| 319 |
+
config_class = LLaDA2MoeConfig
|
| 320 |
+
base_model_prefix = "model"
|
| 321 |
+
_no_split_modules = ["LLaDA2MoeDecoderLayer"]
|
| 322 |
+
_supports_sdpa = True
|
| 323 |
+
supports_gradient_checkpointing = True
|
| 324 |
+
_tied_weights_keys = {"lm_head.weight": "model.word_embeddings.weight"}
|
| 325 |
+
|
| 326 |
+
def __init__(self, config):
|
| 327 |
+
super().__init__(config)
|
| 328 |
+
self.model = LLaDA2MoeModel(config)
|
| 329 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 330 |
+
self.post_init()
|
| 331 |
+
|
| 332 |
+
def _init_weights(self, module):
|
| 333 |
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
| 334 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
| 335 |
+
if getattr(module, "bias", None) is not None:
|
| 336 |
+
module.bias.data.zero_()
|
| 337 |
+
if getattr(module, "padding_idx", None) is not None:
|
| 338 |
+
module.weight.data[module.padding_idx].zero_()
|
| 339 |
+
elif isinstance(module, LLaDA2MoeGate):
|
| 340 |
+
module.reset_parameters()
|
| 341 |
+
elif isinstance(module, LLaDA2MoeRMSNorm):
|
| 342 |
+
module.weight.data.fill_(1.0)
|
| 343 |
+
|
| 344 |
+
def get_input_embeddings(self):
|
| 345 |
+
return self.model.word_embeddings
|
| 346 |
+
|
| 347 |
+
def get_output_embeddings(self):
|
| 348 |
+
return self.lm_head
|
| 349 |
+
|
| 350 |
+
def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None):
|
| 351 |
+
self.model.gradient_checkpointing = True
|
| 352 |
+
|
| 353 |
+
def forward(self, input_ids=None, attention_mask=None, position_ids=None,
|
| 354 |
+
inputs_embeds=None, logits_to_keep=None):
|
| 355 |
+
"""Apply the explicit OPUT grid and project only the requested loss positions."""
|
| 356 |
+
if (input_ids is None) == (inputs_embeds is None):
|
| 357 |
+
raise ValueError("Supply exactly one of input_ids and inputs_embeds")
|
| 358 |
+
shape = input_ids.shape if input_ids is not None else inputs_embeds.shape[:2]
|
| 359 |
+
if attention_mask is None or attention_mask.ndim != 4:
|
| 360 |
+
raise ValueError("Supply an explicit 4D block attention mask")
|
| 361 |
+
if attention_mask.shape[-2:] != (shape[1], shape[1]):
|
| 362 |
+
raise ValueError("Attention mask does not match the input grid")
|
| 363 |
+
if position_ids is None:
|
| 364 |
+
raise ValueError("Supply original DMax position_ids explicitly")
|
| 365 |
+
hidden = self.model(input_ids, attention_mask, position_ids, inputs_embeds)
|
| 366 |
+
if logits_to_keep is not None:
|
| 367 |
+
# The student needs only candidate logits; the frozen teacher needs
|
| 368 |
+
# no vocabulary projection when its decoder hook collects features.
|
| 369 |
+
hidden = hidden[:, logits_to_keep if isinstance(logits_to_keep, slice) else slice(*logits_to_keep)]
|
| 370 |
+
return MoeCausalLMOutputWithPast(logits=self.lm_head(hidden))
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:878eb900ea4a42da7e54bc18ad38352bec005bbfd81bdf76a5ecf1aad1093a6c
|
| 3 |
+
size 12205801
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": "<|startoftext|>",
|
| 4 |
+
"clean_up_tokenization_spaces": false,
|
| 5 |
+
"cls_token": "[CLS]",
|
| 6 |
+
"eos_token": "<|endoftext|>",
|
| 7 |
+
"fast_tokenizer": true,
|
| 8 |
+
"gmask_token": "[gMASK]",
|
| 9 |
+
"is_local": false,
|
| 10 |
+
"local_files_only": true,
|
| 11 |
+
"mask_token": "<|mask|>",
|
| 12 |
+
"merges_file": null,
|
| 13 |
+
"model_max_length": 32768,
|
| 14 |
+
"model_specific_special_tokens": {
|
| 15 |
+
"gmask_token": "[gMASK]"
|
| 16 |
+
},
|
| 17 |
+
"pad_token": "<|endoftext|>",
|
| 18 |
+
"padding_side": "right",
|
| 19 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
| 20 |
+
"extra_special_tokens": {
|
| 21 |
+
"gmask_token": "[gMASK]"
|
| 22 |
+
}
|
| 23 |
+
}
|