demonwizard0 guoteng commited on
Commit
91ecdcc
·
0 Parent(s):

Duplicate from nex-agi/DeepSeek-V3.1-Nex-N1.1

Browse files

Co-authored-by: wang <guoteng@users.noreply.huggingface.co>

Files changed (48) hide show
  1. .gitattributes +35 -0
  2. README.md +66 -0
  3. chat_template.jinja +153 -0
  4. config.json +70 -0
  5. configuration_deepseek.py +210 -0
  6. figures/NEX_logo.svg +7 -0
  7. model-rank-000-00001.safetensors +3 -0
  8. model-rank-000-00002.safetensors +3 -0
  9. model-rank-000-00003.safetensors +3 -0
  10. model-rank-001-00001.safetensors +3 -0
  11. model-rank-001-00002.safetensors +3 -0
  12. model-rank-001-00003.safetensors +3 -0
  13. model-rank-001-00004.safetensors +3 -0
  14. model-rank-001-00005.safetensors +3 -0
  15. model-rank-002-00001.safetensors +3 -0
  16. model-rank-002-00002.safetensors +3 -0
  17. model-rank-002-00003.safetensors +3 -0
  18. model-rank-002-00004.safetensors +3 -0
  19. model-rank-002-00005.safetensors +3 -0
  20. model-rank-003-00001.safetensors +3 -0
  21. model-rank-003-00002.safetensors +3 -0
  22. model-rank-003-00003.safetensors +3 -0
  23. model-rank-003-00004.safetensors +3 -0
  24. model-rank-003-00005.safetensors +3 -0
  25. model-rank-004-00001.safetensors +3 -0
  26. model-rank-004-00002.safetensors +3 -0
  27. model-rank-004-00003.safetensors +3 -0
  28. model-rank-004-00004.safetensors +3 -0
  29. model-rank-004-00005.safetensors +3 -0
  30. model-rank-005-00001.safetensors +3 -0
  31. model-rank-005-00002.safetensors +3 -0
  32. model-rank-005-00003.safetensors +3 -0
  33. model-rank-005-00004.safetensors +3 -0
  34. model-rank-005-00005.safetensors +3 -0
  35. model-rank-006-00001.safetensors +3 -0
  36. model-rank-006-00002.safetensors +3 -0
  37. model-rank-006-00003.safetensors +3 -0
  38. model-rank-006-00004.safetensors +3 -0
  39. model-rank-006-00005.safetensors +3 -0
  40. model-rank-007-00001.safetensors +3 -0
  41. model-rank-007-00002.safetensors +3 -0
  42. model-rank-007-00003.safetensors +3 -0
  43. model-rank-007-00004.safetensors +3 -0
  44. model.safetensors.index.json +0 -0
  45. modeling_deepseek.py +2253 -0
  46. special_tokens_map.json +23 -0
  47. tokenizer.json +0 -0
  48. tokenizer_config.json +0 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz 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
README.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ pipeline_tag: text-generation
4
+ library_name: transformers
5
+ base_model:
6
+ - deepseek-ai/DeepSeek-V3.1-Base
7
+ ---
8
+
9
+ <div align="center">
10
+ <img src="./figures/NEX_logo.svg" width="20%"/>
11
+ </div>
12
+
13
+ ---
14
+
15
+ <div align="center">
16
+ 🏠 <a href="https://nex.sii.edu.cn"><b>Home&nbspPage</b></a>&nbsp&nbsp | &nbsp&nbsp
17
+ 🤗 <a href="https://hf.co/collections/nex-agi/nex-n1"><b>Model</b></a>&nbsp&nbsp | &nbsp&nbsp
18
+ 🤗 <a href="https://huggingface.co/datasets/nex-agi/agent-sft"><b>Data</b></a>&nbsp&nbsp | &nbsp&nbsp
19
+ 📚 <a href="https://huggingface.co/papers/2512.04987"><b>Paper</b></a>&nbsp&nbsp | &nbsp&nbsp
20
+ 💻 <a href="https://github.com/nex-agi/Nex-N1"><b>Code</b></a>
21
+ </div>
22
+
23
+ # Nex-N1.1
24
+
25
+ Nex is a next-generation, full-stack agentic platform that brings foundation models, synthetic data pipelines, RL training, agent frameworks, and deployment tools together in one unified ecosystem.
26
+ DeepSeek-V3.1-Nex-N1.1 is the latest flagship release of the Nex-N1 series — a post-trained model designed to highlight agent autonomy, tool use, and real-world productivity.
27
+ We are committed to making it easier than ever to build and deploy AI agents by offering researchers and entrepreneurs a high-performance, reliable, and cost-effective "out-of-the-box" agent system.
28
+
29
+ ## What's New in N1.1
30
+
31
+ - **Enhanced Claude Skills Integration**: Significantly improved ability to work with Claude Skills, delivering a more seamless tool-calling experience
32
+ - **Improved Instruction Following**: Substantially enhanced instruction adherence with greater stability and accuracy in complex tasks
33
+ - **Upgraded Frontend Capabilities**: Specialized optimization for frontend development scenarios, excelling in HTML, CSS, and JavaScript generation
34
+ - **Advanced Vibe Coding**: Further enhanced general-purpose coding abilities to meet diverse development needs
35
+ - **200K Context Length**: Extended context window to 200K tokens, perfectly compatible with Claude Code and other long-context scenarios
36
+ - **MTP Support**: Added Multi-Token Prediction capability for improved inference efficiency
37
+
38
+ ## Usage
39
+
40
+ ### Local Deployment
41
+
42
+ We recommend `sglang` for serving Nex-series models locally:
43
+
44
+ ```bash
45
+ python -m sglang.launch_server --model-path /path/to/your/model
46
+ ```
47
+
48
+ ### Function Calling
49
+
50
+ Nex-series models support robust function-calling capabilities. To maximize the function-calling capabilities of the Nex-series models, we modified the tool parser of `qwen3_coder`, see: <https://github.com/sgl-project/sglang/pull/13411>. To enable this feature, simply add the `--tool-call-parser qwen3_coder` flag when launching the server:
51
+
52
+ ```bash
53
+ python -m sglang.launch_server --model-path /path/to/your/model --tool-call-parser qwen3_coder
54
+ ```
55
+
56
+ ### Mini Program Development
57
+
58
+ Nex-N1.1 is optimized for mini program development with enhanced 200K context support. For optimal performance, we recommend using Claude Code configured with both `context7` and a search MCP.
59
+
60
+ ```shell
61
+ claude mcp add --transport http context7 https://mcp.context7.com/mcp --header "CONTEXT7_API_KEY: [CONTEXT7_API_KEY]"
62
+
63
+ claude mcp add --transport stdio serper-search --env SERPER_API_KEY=[SERPER_API_KEY] -- npx -y serper-search-scrape-mcp-server
64
+ ```
65
+
66
+ Refer to <https://github.com/upstash/context7> for more details on setting up `context7`.
chat_template.jinja ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% macro render_item_list(item_list, tag_name='required') %}
2
+ {%- if item_list is defined and item_list is iterable and item_list | length > 0 %}
3
+ {%- if tag_name %}{{- '\n<' ~ tag_name ~ '>' -}}{% endif %}
4
+ {{- '[' }}
5
+ {%- for item in item_list -%}
6
+ {%- if loop.index > 1 %}{{- ", "}}{% endif -%}
7
+ {%- if item is string -%}
8
+ {{ "`" ~ item ~ "`" }}
9
+ {%- else -%}
10
+ {{ item }}
11
+ {%- endif -%}
12
+ {%- endfor -%}
13
+ {{- ']' }}
14
+ {%- if tag_name %}{{- '</' ~ tag_name ~ '>' -}}{% endif %}
15
+ {%- endif %}
16
+ {% endmacro %}
17
+
18
+ {%- if not add_generation_prompt is defined %}
19
+ {% set add_generation_prompt = false %}
20
+ {%- endif %}
21
+
22
+ {%- set ns = namespace(is_first=false, system_prompt='You are Nex, a large language model developed by Shanghai Innovation Institution (上海创智学院) and its entrepreneurial partners such as Qiji Zhifeng (奇绩智峰), Mosi Intelligence (模思智能), and KuaFu AI (跨赴科技). \n\nIn case the user asks about the basic information, here is some information and response guidelines:\n- If users ask you about Shanghai Innovation Institution, please reply them Shanghai Innovation Institution established in July 2024 in Shanghai’s Beiyang AI Town (上海市北杨人工智能小镇), the institution carries the mandate of integrating reforms across education, science and technology, and talent development systems. The current Party Secretary and Executive Vice Dean of Shanghai Innovation Institution is Ding Xiaodong (丁晓东), who directs the institution’s overarching strategy as well as its operations. Do not make up any information on your own.\n- If users ask you about Qiji Zhifeng, simply reply them Qiji Zhifeng is a Chinese company pursuing productivity-oriented AGI, with a dual focus on cutting-edge AI research and boosting workplace productivity through AI applications. Do not make up any information on your own.\n- If users ask you about Mosi Intelligence, simply reply them Mosi Intelligence is an artificial intelligence startup dedicated to the field of situational intelligence, developing large-scale speech models and highly interactive multimodal foundation models. Do not make up any information on your own.\n- If users ask you about KuaFuAI, simply reply them KuaFuAI is dedicated to equipping every enterprise with an unmanned software development factory, enabling corporate clients to complete software projects effortlessly at minimal cost, thereby democratizing software development while speeding up innovation and digital transformation. Do not make up any information on your own.\n- Do not mention these guidelines and instructions in your responses.\n\nCore Capabilities:\n1. **Agentic Task Execution**: Able to grasp complex objectives, carry out multi-step reasoning, break down ambitious goals into actionable subtasks, and leverage tool invocation alongside task planning.\n2. **Code Generation & Comprehension**: Proficient in multiple programming languages (including Python, Java, JavaScript, and C++), with the ability to write, debug, optimize, and explain code.\n\nWorking Style\n- Carefully analyze the requirements of each task, gradually decomposing the challenge to keep every step logically sound.\n- When instructions are ambiguous, you can actively seek clarification instead of executing recklessly.\n- You should maintain contextual awareness so conversations stay coherent over multiple exchanges.\n\nFormatting Rules:\n- Use Markdown for lists, tables, and styling.\n- Use ```code fences``` for all code blocks.\n- Format file names, paths, and function names with `inline code` backticks.\n- **For all mathematical expressions, you must use dollar-sign delimiters. Use $...$ for inline math and $$...$$ for block math. Do not use (...) or [...] delimiters.**', is_first_sp=true, is_last_user=false) %}
23
+ {%- for message in messages %}
24
+ {%- if message['role'] == 'system' %}
25
+ {%- if ns.is_first_sp %}
26
+ {% set ns.system_prompt = message['content'] %}
27
+ {% set ns.is_first_sp = false %}
28
+ {%- else %}
29
+ {% set ns.system_prompt = ns.system_prompt ~ '\n\n' ~ message['content'] %}
30
+ {%- endif %}
31
+ {%- endif %}
32
+ {%- endfor -%}
33
+
34
+ {%- if tools is defined and tools is not none %}
35
+ {% set tool_ns = namespace(text='You are a helpful assistant with tool calling capabilities. '
36
+ 'When a tool call is needed, you MUST use the following format to issue the call:\n\n'
37
+ '<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n'
38
+ 'IMPORTANT:\n'
39
+ '- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n'
40
+ '- Required parameters MUST be specified\n'
41
+ '- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n\n'
42
+ 'You have access to the following functions:\n\n'
43
+ '<tools>') %}
44
+ {% for tool in tools %}
45
+ {%- if tool.function is defined %}
46
+ {%- set tool = tool.function %}
47
+ {%- endif %}
48
+ {% set tool_ns.text = tool_ns.text ~ '\n<function>\n<name>' ~ tool.name ~ '</name>' %}
49
+ {% set tool_ns.text = tool_ns.text ~ '\n<description>' ~ (tool.description | trim) ~ '</description>' %}
50
+ {% set tool_ns.text = tool_ns.text ~ '\n<parameters>' %}
51
+ {%- for param_name, param_fields in tool.parameters.properties|items %}
52
+ {% set tool_ns.text = tool_ns.text ~ '\n<parameter>' %}
53
+ {% set tool_ns.text = tool_ns.text ~ '\n<name>' ~ param_name ~ '</name>' %}
54
+ {%- if param_fields.type is defined %}
55
+ {% set tool_ns.text = tool_ns.text ~ '\n<type>' ~ (param_fields.type | string) ~ '</type>' %}
56
+ {%- endif %}
57
+ {%- if param_fields.description is defined %}
58
+ {% set tool_ns.text = tool_ns.text ~ '\n<description>' ~ (param_fields.description | trim) ~ '</description>' %}
59
+ {%- endif %}
60
+ {%- if param_fields.enum is defined and param_fields.enum is iterable and param_fields.enum | length > 0 %}
61
+ {% set tool_ns.text = tool_ns.text ~ render_item_list(param_fields.enum, 'enum') %}
62
+ {%- endif %}
63
+ {%- set handled_keys = ['type', 'description', 'enum', 'required'] %}
64
+ {%- for json_key in param_fields.keys() | reject("in", handled_keys) %}
65
+ {%- set normed_json_key = json_key | replace("-", "_") | replace(" ", "_") | replace("$", "") %}
66
+ {%- if param_fields[json_key] is mapping %}
67
+ {% set tool_ns.text = tool_ns.text ~ '\n<' ~ normed_json_key ~ '>' ~ (param_fields[json_key] | tojson | safe) ~ '</' ~ normed_json_key ~ '>' %}
68
+ {%- else %}
69
+ {% set tool_ns.text = tool_ns.text ~ '\n<' ~ normed_json_key ~ '>' ~ (param_fields[json_key] | string) ~ '</' ~ normed_json_key ~ '>' %}
70
+ {%- endif %}
71
+ {%- endfor %}
72
+ {%- if param_fields.required is defined and param_fields.required is iterable and param_fields.required | length > 0 %}
73
+ {% set tool_ns.text = tool_ns.text ~ render_item_list(param_fields.required, 'required') %}
74
+ {%- endif %}
75
+ {% set tool_ns.text = tool_ns.text ~ '\n</parameter>' %}
76
+ {%- endfor %}
77
+ {%- if tool.parameters.required is defined and tool.parameters.required is iterable and tool.parameters.required | length > 0 %}
78
+ {% set tool_ns.text = tool_ns.text ~ render_item_list(tool.parameters.required, 'required') %}
79
+ {%- endif %}
80
+ {% set tool_ns.text = tool_ns.text ~ '\n</parameters>' %}
81
+ {%- if tool.return is defined %}
82
+ {%- if tool.return is mapping %}
83
+ {% set tool_ns.text = tool_ns.text ~ '\n<return>' ~ (tool.return | tojson | safe) ~ '</return>' %}
84
+ {%- else %}
85
+ {% set tool_ns.text = tool_ns.text ~ '\n<return>' ~ (tool.return | string) ~ '</return>' %}
86
+ {%- endif %}
87
+ {%- endif %}
88
+ {% set tool_ns.text = tool_ns.text ~ '\n</function>' %}
89
+ {% endfor %}
90
+ {% set tool_ns.text = tool_ns.text ~ '\n</tools>' %}
91
+ {% set ns.system_prompt = ns.system_prompt ~ '\n\n' ~ tool_ns.text %}
92
+ {%- endif %}
93
+
94
+ {{- bos_token }}
95
+ {{- ns.system_prompt }}
96
+ {%- for message in messages %}
97
+ {% set content = message['content'] %}
98
+ {%- if content is none %}
99
+ {% set content = '' %}
100
+ {%- endif %}
101
+ {%- if message['role'] == 'user' %}
102
+ {%- set ns.is_first = false -%}
103
+ {%- set ns.is_last_user = true -%}
104
+ {{- '<|User|>' ~ content }}
105
+ {%- endif %}
106
+ {%- if message['role'] == 'assistant' %}
107
+ {% if '</think>' in content %}
108
+ {% set content = content.split('</think>')[-1] %}
109
+ {% endif %}
110
+ {% endif %}
111
+ {%- if message['role'] == 'assistant' and message['tool_calls'] is defined and message['tool_calls'] is not none %}
112
+ {%- set ns.is_last_user = false -%}
113
+ {%- set ns.is_first = false %}
114
+ {{- '<|Assistant|>' }}
115
+ {%- if content is defined and content is not none and content | trim | length > 0 %}
116
+ {{- content | trim ~ '\n' }}
117
+ {%- endif %}
118
+ {%- for tool in message['tool_calls'] %}
119
+ {%- if tool.function is defined %}
120
+ {%- set tool_call = tool.function %}
121
+ {%- else %}
122
+ {%- set tool_call = tool %}
123
+ {%- endif %}
124
+ {{- '<tool_call>\n<function=' ~ tool_call.name ~ '>\n' }}
125
+ {%- if tool_call.arguments is defined %}
126
+ {%- for args_name, args_value in tool_call.arguments|items %}
127
+ {{- '<parameter=' ~ args_name ~ '>\n' }}
128
+ {%- set args_value = args_value if args_value is string else args_value | string %}
129
+ {{- args_value }}
130
+ {{- '\n</parameter>\n' }}
131
+ {%- endfor %}
132
+ {%- endif %}
133
+ {{- '</function>\n</tool_call>' }}
134
+ {%- endfor %}
135
+ {{- '<|end▁of▁sentence|>'}}
136
+ {%- endif %}
137
+ {%- if message['role'] == 'assistant' and (message['tool_calls'] is not defined or message['tool_calls'] is none)%}
138
+ {%- set ns.is_last_user = false -%}
139
+ {{- '<|Assistant|>' ~ content ~ '<|end▁of▁sentence|>'}}
140
+ {%- endif %}
141
+ {%- if message['role'] == 'tool' %}
142
+ {%- set ns.is_last_user = false -%}
143
+ {%- if loop.previtem and loop.previtem['role'] != 'tool' %}
144
+ {{- '<|User|>' }}
145
+ {%- endif %}
146
+ {{- '<tool_response>\n' }}
147
+ {{- content }}
148
+ {{- '\n</tool_response>' }}
149
+ {%- endif %}
150
+ {%- endfor -%}
151
+ {% if add_generation_prompt %}
152
+ {{- '<|Assistant|>'}}
153
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "DeepseekV3ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_deepseek.DeepseekV3Config",
9
+ "AutoModel": "modeling_deepseek.DeepseekV3Model",
10
+ "AutoModelForCausalLM": "modeling_deepseek.DeepseekV3ForCausalLM"
11
+ },
12
+ "aux_loss_alpha": 0.001,
13
+ "bos_token_id": 0,
14
+ "eos_token_id": 1,
15
+ "ep_size": 1,
16
+ "first_k_dense_replace": 3,
17
+ "hidden_act": "silu",
18
+ "hidden_size": 7168,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 18432,
21
+ "kv_lora_rank": 512,
22
+ "max_position_embeddings": 200000,
23
+ "model_type": "deepseek_v3",
24
+ "moe_intermediate_size": 2048,
25
+ "moe_layer_freq": 1,
26
+ "n_group": 8,
27
+ "n_routed_experts": 256,
28
+ "n_shared_experts": 1,
29
+ "norm_topk_prob": true,
30
+ "num_attention_heads": 128,
31
+ "num_experts_per_tok": 8,
32
+ "num_hidden_layers": 61,
33
+ "num_key_value_heads": 128,
34
+ "num_nextn_predict_layers": 1,
35
+ "pretraining_tp": 1,
36
+ "q_lora_rank": 1536,
37
+ "qk_nope_head_dim": 128,
38
+ "qk_rope_head_dim": 64,
39
+ "quantization_config": {
40
+ "activation_scheme": "dynamic",
41
+ "fmt": "e4m3",
42
+ "quant_method": "fp8",
43
+ "weight_block_size": [
44
+ 128,
45
+ 128
46
+ ]
47
+ },
48
+ "rms_norm_eps": 1e-06,
49
+ "rope_scaling": {
50
+ "beta_fast": 32,
51
+ "beta_slow": 1,
52
+ "factor": 40,
53
+ "mscale": 1.0,
54
+ "mscale_all_dim": 1.0,
55
+ "original_max_position_embeddings": 4096,
56
+ "type": "yarn"
57
+ },
58
+ "rope_theta": 10000,
59
+ "routed_scaling_factor": 2.5,
60
+ "scoring_func": "sigmoid",
61
+ "seq_aux": true,
62
+ "tie_word_embeddings": false,
63
+ "topk_group": 4,
64
+ "topk_method": "noaux_tc",
65
+ "torch_dtype": "bfloat16",
66
+ "transformers_version": "4.46.3",
67
+ "use_cache": true,
68
+ "v_head_dim": 128,
69
+ "vocab_size": 129280
70
+ }
configuration_deepseek.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.configuration_utils import PretrainedConfig
2
+ from transformers.utils import logging
3
+
4
+ logger = logging.get_logger(__name__)
5
+
6
+ DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
7
+ class DeepseekV3Config(PretrainedConfig):
8
+ r"""
9
+ This is the configuration class to store the configuration of a [`DeepseekV3Model`]. It is used to instantiate an DeepSeek
10
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
11
+ defaults will yield a similar configuration to that of the DeepSeek-V3.
12
+
13
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
14
+ documentation from [`PretrainedConfig`] for more information.
15
+
16
+
17
+ Args:
18
+ vocab_size (`int`, *optional*, defaults to 129280):
19
+ Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
20
+ `inputs_ids` passed when calling [`DeepseekV3Model`]
21
+ hidden_size (`int`, *optional*, defaults to 4096):
22
+ Dimension of the hidden representations.
23
+ intermediate_size (`int`, *optional*, defaults to 11008):
24
+ Dimension of the MLP representations.
25
+ moe_intermediate_size (`int`, *optional*, defaults to 1407):
26
+ Dimension of the MoE representations.
27
+ num_hidden_layers (`int`, *optional*, defaults to 32):
28
+ Number of hidden layers in the Transformer decoder.
29
+ num_nextn_predict_layers (`int`, *optional*, defaults to 1):
30
+ Number of nextn predict layers in the DeepSeekV3 Model.
31
+ num_attention_heads (`int`, *optional*, defaults to 32):
32
+ Number of attention heads for each attention layer in the Transformer decoder.
33
+ n_shared_experts (`int`, *optional*, defaults to None):
34
+ Number of shared experts, None means dense model.
35
+ n_routed_experts (`int`, *optional*, defaults to None):
36
+ Number of routed experts, None means dense model.
37
+ routed_scaling_factor (`float`, *optional*, defaults to 1.0):
38
+ Scaling factor or routed experts.
39
+ topk_method (`str`, *optional*, defaults to `gready`):
40
+ Topk method used in routed gate.
41
+ n_group (`int`, *optional*, defaults to None):
42
+ Number of groups for routed experts.
43
+ topk_group (`int`, *optional*, defaults to None):
44
+ Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
45
+ num_experts_per_tok (`int`, *optional*, defaults to None):
46
+ Number of selected experts, None means dense model.
47
+ moe_layer_freq (`int`, *optional*, defaults to 1):
48
+ The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.
49
+ first_k_dense_replace (`int`, *optional*, defaults to 0):
50
+ Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
51
+ \--k dense layers--/
52
+ norm_topk_prob (`bool`, *optional*, defaults to False):
53
+ Whether to normalize the weights of the routed experts.
54
+ scoring_func (`str`, *optional*, defaults to 'softmax'):
55
+ Method of computing expert weights.
56
+ aux_loss_alpha (`float`, *optional*, defaults to 0.001):
57
+ Auxiliary loss weight coefficient.
58
+ seq_aux = (`bool`, *optional*, defaults to True):
59
+ Whether to compute the auxiliary loss for each individual sample.
60
+ num_key_value_heads (`int`, *optional*):
61
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
62
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
63
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
64
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
65
+ by meanpooling all the original heads within that group. For more details checkout [this
66
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
67
+ `num_attention_heads`.
68
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
69
+ The non-linear activation function (function or string) in the decoder.
70
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
71
+ The maximum sequence length that this model might ever be used with.
72
+ initializer_range (`float`, *optional*, defaults to 0.02):
73
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
74
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
75
+ The epsilon used by the rms normalization layers.
76
+ use_cache (`bool`, *optional*, defaults to `True`):
77
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
78
+ relevant if `config.is_decoder=True`.
79
+ pad_token_id (`int`, *optional*):
80
+ Padding token id.
81
+ bos_token_id (`int`, *optional*, defaults to 1):
82
+ Beginning of stream token id.
83
+ eos_token_id (`int`, *optional*, defaults to 2):
84
+ End of stream token id.
85
+ pretraining_tp (`int`, *optional*, defaults to 1):
86
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
87
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
88
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
89
+ issue](https://github.com/pytorch/pytorch/issues/76232).
90
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
91
+ Whether to tie weight embeddings
92
+ rope_theta (`float`, *optional*, defaults to 10000.0):
93
+ The base period of the RoPE embeddings.
94
+ rope_scaling (`Dict`, *optional*):
95
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
96
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
97
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
98
+ `max_position_embeddings` to the expected new maximum.
99
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
100
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
101
+ attention_dropout (`float`, *optional*, defaults to 0.0):
102
+ The dropout ratio for the attention probabilities.
103
+
104
+ ```python
105
+ >>> from transformers import DeepseekV3Model, DeepseekV3Config
106
+
107
+ >>> # Initializing a Deepseek-V3 style configuration
108
+ >>> configuration = DeepseekV3Config()
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "deepseek_v3"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=129280,
120
+ hidden_size=7168,
121
+ intermediate_size=18432,
122
+ moe_intermediate_size = 2048,
123
+ num_hidden_layers=61,
124
+ num_nextn_predict_layers=1,
125
+ num_attention_heads=128,
126
+ num_key_value_heads=128,
127
+ n_shared_experts = 1,
128
+ n_routed_experts = 256,
129
+ ep_size = 1,
130
+ routed_scaling_factor = 2.5,
131
+ kv_lora_rank = 512,
132
+ q_lora_rank = 1536,
133
+ qk_rope_head_dim = 64,
134
+ v_head_dim = 128,
135
+ qk_nope_head_dim = 128,
136
+ topk_method = 'noaux_tc',
137
+ n_group = 8,
138
+ topk_group = 4,
139
+ num_experts_per_tok = 8,
140
+ moe_layer_freq = 1,
141
+ first_k_dense_replace = 3,
142
+ norm_topk_prob = True,
143
+ scoring_func = 'sigmoid',
144
+ aux_loss_alpha = 0.001,
145
+ seq_aux = True,
146
+ hidden_act="silu",
147
+ max_position_embeddings=4096,
148
+ initializer_range=0.02,
149
+ rms_norm_eps=1e-6,
150
+ use_cache=True,
151
+ pad_token_id=None,
152
+ bos_token_id=0,
153
+ eos_token_id=1,
154
+ pretraining_tp=1,
155
+ tie_word_embeddings=False,
156
+ rope_theta=10000.0,
157
+ rope_scaling=None,
158
+ attention_bias=False,
159
+ attention_dropout=0.0,
160
+ **kwargs,
161
+ ):
162
+ self.vocab_size = vocab_size
163
+ self.max_position_embeddings = max_position_embeddings
164
+ self.hidden_size = hidden_size
165
+ self.intermediate_size = intermediate_size
166
+ self.moe_intermediate_size = moe_intermediate_size
167
+ self.num_hidden_layers = num_hidden_layers
168
+ self.num_nextn_predict_layers = num_nextn_predict_layers
169
+ self.num_attention_heads = num_attention_heads
170
+ self.n_shared_experts = n_shared_experts
171
+ self.n_routed_experts = n_routed_experts
172
+ self.ep_size = ep_size
173
+ self.routed_scaling_factor = routed_scaling_factor
174
+ self.kv_lora_rank = kv_lora_rank
175
+ self.q_lora_rank = q_lora_rank
176
+ self.qk_rope_head_dim = qk_rope_head_dim
177
+ self.v_head_dim = v_head_dim
178
+ self.qk_nope_head_dim = qk_nope_head_dim
179
+ self.topk_method = topk_method
180
+ self.n_group = n_group
181
+ self.topk_group = topk_group
182
+ self.num_experts_per_tok = num_experts_per_tok
183
+ self.moe_layer_freq = moe_layer_freq
184
+ self.first_k_dense_replace = first_k_dense_replace
185
+ self.norm_topk_prob = norm_topk_prob
186
+ self.scoring_func = scoring_func
187
+ self.aux_loss_alpha = aux_loss_alpha
188
+ self.seq_aux = seq_aux
189
+ # for backward compatibility
190
+ if num_key_value_heads is None:
191
+ num_key_value_heads = num_attention_heads
192
+
193
+ self.num_key_value_heads = num_key_value_heads
194
+ self.hidden_act = hidden_act
195
+ self.initializer_range = initializer_range
196
+ self.rms_norm_eps = rms_norm_eps
197
+ self.pretraining_tp = pretraining_tp
198
+ self.use_cache = use_cache
199
+ self.rope_theta = rope_theta
200
+ self.rope_scaling = rope_scaling
201
+ self.attention_bias = attention_bias
202
+ self.attention_dropout = attention_dropout
203
+
204
+ super().__init__(
205
+ pad_token_id=pad_token_id,
206
+ bos_token_id=bos_token_id,
207
+ eos_token_id=eos_token_id,
208
+ tie_word_embeddings=tie_word_embeddings,
209
+ **kwargs,
210
+ )
figures/NEX_logo.svg ADDED
model-rank-000-00001.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3a2581d0796a3095a23d0dd0ea0f158cf557df2c3e15006303ac993fe29b9bb5
3
+ size 21474473776
model-rank-000-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:18635543049d4265eb603fa9a57f4c23fbb848708c6cf95ea751e6ad04850ac0
3
+ size 21467794376
model-rank-000-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:361c5f44aa189cbecf15086e6d9654b465132d6e7aaeb682c5e954bf833033aa
3
+ size 6710599544
model-rank-001-00001.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e1e27b3537e9458c70a55b9ffa06250e04849dbd2b5dc2ce6966212d35fd80c4
3
+ size 21467736672
model-rank-001-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7b56077c720cbe3d2028e63ea4e4d7d77cc1391a30ab045342b228b798b39f0
3
+ size 21467791816
model-rank-001-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ed27e0c109deef2cfa6f5dd934bef2dbd5ea0088d2ec4b73ac0b875634aef102
3
+ size 21467801000
model-rank-001-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c64d533449c0f856693d3e89e530ae69516b180bc882c553e4c17b6f1fcaef2d
3
+ size 21467797280
model-rank-001-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b51e98bc9801e2deef6e4b45125c8c99902c20ce603ee73a34c172267e93f097
3
+ size 6226031672
model-rank-002-00001.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4d14ed8e4e3f33a9e74fe58c3d7262c7d8290e883e74646ac4c76eaef33e65a2
3
+ size 21467739576
model-rank-002-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c0b6f774c6b99f86cef8e2fbf48d802410205ec01ef63538a34df9b63a7f882d
3
+ size 21467793584
model-rank-002-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dc682b5c6dc89eb2fd7ccca0b5fe92cab0931c6499ffac665809c6a3315517ce
3
+ size 21467801000
model-rank-002-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac5d5c08bb994bb5b5a5d7c082f74d793f42ddefce77ec631bf34a42efc17a45
3
+ size 21467797280
model-rank-002-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac0c949c0e29041105c01c5c2f4cfd5beeba1bdc79b0918accdba50eba134122
3
+ size 6226031672
model-rank-003-00001.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:316197bbb9033d3af6e872768b10501b55786474b93e2cba0133f0d8fecb87e1
3
+ size 21467739576
model-rank-003-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5ee189fbfee7896aa9819a6cf24cfdca5fdaaa70091bbc443601238d43d99f3d
3
+ size 21467793584
model-rank-003-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7f72b3c4c6490ec24403a7699287971cbac61821ddbe85c40146fd1ce83340fe
3
+ size 21467801000
model-rank-003-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6777ce2a257eac76ff686396060878ef8ddca7563f1a926e04eae9f077b25ff3
3
+ size 21467797280
model-rank-003-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5525f0321bcfcff478c41b93768560d967e059da545a35a30575f4aa0a47d4c3
3
+ size 6226031672
model-rank-004-00001.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0ea4ea1d7bc88417caf6f1172f55017e3fc395435041612b53ddb062ac1cbe81
3
+ size 21467739576
model-rank-004-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8c7ab7eac78acbb6718bd91fa5733a07309ddfb7033136a38ff0690bbb8837fa
3
+ size 21467793584
model-rank-004-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:258aa8589176a0caf910bbd504d2d463a934d235b84248902d626144ba5d80c4
3
+ size 21467801000
model-rank-004-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c8c57b0da9d9f853ce5262f6e8ed8120fa4d3cc89e4882c8df650249e50657af
3
+ size 21467797280
model-rank-004-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:148adf75051cdfab0b3494f54cd4fb96a6a9e07e1f523aa04940fcecf35d4a2c
3
+ size 6226031672
model-rank-005-00001.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:864501ddf0017e1dda6b09d0587c726a5b0dac9225dd636ef383c9844dd9854d
3
+ size 21467739576
model-rank-005-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6470dfe34b02de44e6a9c1207e071508e693bfb23f310e08230e79c59d10b879
3
+ size 21467793584
model-rank-005-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8a29742fdf87df3ba832cf0d18238542994b045591209803129286339d046497
3
+ size 21467801000
model-rank-005-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b1a44c0926040cec35060771e149723dc0359b35dfb67ded6f2e640869a894e8
3
+ size 21467797280
model-rank-005-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:821ed49cfb0dd9937350b33f004681e5bdd3d88153db3e19b230303efadde6a8
3
+ size 6226031672
model-rank-006-00001.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:605626ed3aedb4b858f119adc4be4e73229e4b9482280d77eaa5f3d10fa633c9
3
+ size 21467739576
model-rank-006-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3fae8e37d7740c5d12ca28fde16b36b2ad9c2356662f6677fdbf7290a3475f0d
3
+ size 21467793584
model-rank-006-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0ae4a481482d990855ab2242a22b3b2bd39c6d42d372e6910f529bd5732814d1
3
+ size 21467801000
model-rank-006-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f2f7cf3b5c262dc7cd055f1473020dd6e75f79f33c911c249914f5d764f29eb8
3
+ size 21467797280
model-rank-006-00005.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7496cca5f90d63570f2c8387db728a1250c7c37c772bb843d77afa0ac1006143
3
+ size 6226031672
model-rank-007-00001.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8d196642a42b4e7c6108c5428d80eead229cf77c753fb9e5c14121a68916476a
3
+ size 21470940624
model-rank-007-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9451b74c67144a097c5be6e7a2b3550b08f6d3e8e083d44a52689344b79a0e5d
3
+ size 21467793584
model-rank-007-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fdbb94be43c4dee537dbcebd446082a0b47c73165975c9e193bb9c52c1ff7b7e
3
+ size 21467800984
model-rank-007-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1484eff0d0c5a47ba8d7c633b86b33078bc3e865eb6171bc88d386b7594e24d2
3
+ size 18237405856
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
modeling_deepseek.py ADDED
@@ -0,0 +1,2253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 DeepSeek-AI and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
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
+ """ PyTorch DeepSeek model."""
21
+ import os
22
+ import math
23
+ import warnings
24
+ from typing import List, Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ from torch import nn
30
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
31
+
32
+ from transformers.activations import ACT2FN
33
+ from transformers.cache_utils import Cache, DynamicCache
34
+ from transformers.modeling_attn_mask_utils import (
35
+ AttentionMaskConverter,
36
+ _prepare_4d_attention_mask,
37
+ _prepare_4d_causal_attention_mask,
38
+ )
39
+ from transformers.modeling_outputs import (
40
+ BaseModelOutputWithPast,
41
+ CausalLMOutputWithPast,
42
+ SequenceClassifierOutputWithPast,
43
+ )
44
+ from transformers.modeling_utils import PreTrainedModel
45
+ from transformers.pytorch_utils import (
46
+ ALL_LAYERNORM_LAYERS,
47
+ is_torch_greater_or_equal_than_1_13,
48
+ )
49
+ from transformers.utils import (
50
+ add_start_docstrings,
51
+ add_start_docstrings_to_model_forward,
52
+ is_flash_attn_2_available,
53
+ is_flash_attn_greater_or_equal_2_10,
54
+ logging,
55
+ replace_return_docstrings,
56
+ )
57
+ from transformers.utils.import_utils import is_torch_fx_available
58
+ from .configuration_deepseek import DeepseekV3Config
59
+ import torch.distributed as dist
60
+ import numpy as np
61
+
62
+ from crossingbits.utils.constants import USE_MTP
63
+ from crossingbits.kernels.triton_kernel import fp8_gemm, fp8_act_quant
64
+
65
+ # Monkey patch init for nn.Linear
66
+ original_linear_init = nn.Linear.__init__
67
+
68
+ def new_linear_init(self, *args, **kwargs):
69
+ original_linear_init(self, *args, **kwargs)
70
+ self.weight_scale_inv = nn.Parameter(
71
+ torch.zeros(
72
+ math.ceil(self.out_features / 128), math.ceil(self.in_features / 128)
73
+ )
74
+ )
75
+
76
+ nn.Linear.__init__ = new_linear_init
77
+
78
+ # Monkey patch fp8 forward
79
+
80
+ original_linear_forward = nn.Linear.forward
81
+
82
+ def new_linear_forward(self, x: torch.Tensor) -> torch.Tensor:
83
+ if self.weight.dtype == torch.float8_e4m3fn:
84
+ a, a_s = fp8_act_quant(x)
85
+ output = fp8_gemm(a, a_s, self.weight, self.weight_scale_inv).to(x.dtype)
86
+ if self.bias is not None:
87
+ output = output + self.bias
88
+ return output
89
+ else:
90
+ return original_linear_forward(self, x)
91
+
92
+ nn.Linear.forward = new_linear_forward
93
+
94
+
95
+ if is_flash_attn_2_available():
96
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
97
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
98
+
99
+
100
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
101
+ # It means that the function will not be traced through and simply appear as a node in the graph.
102
+ if is_torch_fx_available():
103
+ if not is_torch_greater_or_equal_than_1_13:
104
+ import torch.fx
105
+
106
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
107
+
108
+
109
+ logger = logging.get_logger(__name__)
110
+
111
+ _CONFIG_FOR_DOC = "DeepseekV3Config"
112
+
113
+
114
+ def _get_unpad_data(attention_mask):
115
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
116
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
117
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
118
+ cu_seqlens = F.pad(
119
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
120
+ )
121
+ return (
122
+ indices,
123
+ cu_seqlens,
124
+ max_seqlen_in_batch,
125
+ )
126
+
127
+
128
+ class DeepseekV3RMSNorm(nn.Module):
129
+ def __init__(self, hidden_size, eps=1e-6):
130
+ """
131
+ DeepseekV3RMSNorm is equivalent to T5LayerNorm
132
+ """
133
+ super().__init__()
134
+ self.weight = nn.Parameter(torch.ones(hidden_size))
135
+ self.variance_epsilon = eps
136
+
137
+ def forward(self, hidden_states):
138
+ input_dtype = hidden_states.dtype
139
+ hidden_states = hidden_states.to(torch.float32)
140
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
141
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
142
+ return self.weight * hidden_states.to(input_dtype)
143
+
144
+
145
+ ALL_LAYERNORM_LAYERS.append(DeepseekV3RMSNorm)
146
+
147
+
148
+ class DeepseekV3RotaryEmbedding(nn.Module):
149
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
150
+ super().__init__()
151
+
152
+ self.dim = dim
153
+ self.max_position_embeddings = max_position_embeddings
154
+ self.base = base
155
+ inv_freq = 1.0 / (
156
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
157
+ )
158
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
159
+
160
+ # Build here to make `torch.jit.trace` work.
161
+ self._set_cos_sin_cache(
162
+ seq_len=max_position_embeddings,
163
+ device=self.inv_freq.device,
164
+ dtype=torch.get_default_dtype(),
165
+ )
166
+ self.max_seq_len_cached = None
167
+
168
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
169
+ self.max_seq_len_cached = seq_len
170
+ t = torch.arange(
171
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
172
+ )
173
+
174
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
175
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
176
+ emb = torch.cat((freqs, freqs), dim=-1)
177
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
178
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
179
+
180
+ def forward(self, x, seq_len=None):
181
+ # x: [bs, num_attention_heads, seq_len, head_size]
182
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
183
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
184
+
185
+ return (
186
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
187
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
188
+ )
189
+
190
+
191
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV3
192
+ class DeepseekV3LinearScalingRotaryEmbedding(DeepseekV3RotaryEmbedding):
193
+ """DeepseekV3RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
194
+
195
+ def __init__(
196
+ self,
197
+ dim,
198
+ max_position_embeddings=2048,
199
+ base=10000,
200
+ device=None,
201
+ scaling_factor=1.0,
202
+ ):
203
+ self.scaling_factor = scaling_factor
204
+ super().__init__(dim, max_position_embeddings, base, device)
205
+
206
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
207
+ self.max_seq_len_cached = seq_len
208
+ t = torch.arange(
209
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
210
+ )
211
+ t = t / self.scaling_factor
212
+
213
+ freqs = torch.outer(t, self.inv_freq)
214
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
215
+ emb = torch.cat((freqs, freqs), dim=-1)
216
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
217
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
218
+
219
+
220
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV3
221
+ class DeepseekV3DynamicNTKScalingRotaryEmbedding(DeepseekV3RotaryEmbedding):
222
+ """DeepseekV3RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
223
+
224
+ def __init__(
225
+ self,
226
+ dim,
227
+ max_position_embeddings=2048,
228
+ base=10000,
229
+ device=None,
230
+ scaling_factor=1.0,
231
+ ):
232
+ self.scaling_factor = scaling_factor
233
+ super().__init__(dim, max_position_embeddings, base, device)
234
+
235
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
236
+ self.max_seq_len_cached = seq_len
237
+
238
+ if seq_len > self.max_position_embeddings:
239
+ base = self.base * (
240
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
241
+ - (self.scaling_factor - 1)
242
+ ) ** (self.dim / (self.dim - 2))
243
+ inv_freq = 1.0 / (
244
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
245
+ )
246
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
247
+
248
+ t = torch.arange(
249
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
250
+ )
251
+
252
+ freqs = torch.outer(t, self.inv_freq)
253
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
254
+ emb = torch.cat((freqs, freqs), dim=-1)
255
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
256
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
257
+
258
+
259
+ # Inverse dim formula to find dim based on number of rotations
260
+ def yarn_find_correction_dim(
261
+ num_rotations, dim, base=10000, max_position_embeddings=2048
262
+ ):
263
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
264
+ 2 * math.log(base)
265
+ )
266
+
267
+
268
+ # Find dim range bounds based on rotations
269
+ def yarn_find_correction_range(
270
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
271
+ ):
272
+ low = math.floor(
273
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
274
+ )
275
+ high = math.ceil(
276
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
277
+ )
278
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
279
+
280
+
281
+ def yarn_get_mscale(scale=1, mscale=1):
282
+ if scale <= 1:
283
+ return 1.0
284
+ return 0.1 * mscale * math.log(scale) + 1.0
285
+
286
+
287
+ def yarn_linear_ramp_mask(min, max, dim):
288
+ if min == max:
289
+ max += 0.001 # Prevent singularity
290
+
291
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
292
+ ramp_func = torch.clamp(linear_func, 0, 1)
293
+ return ramp_func
294
+
295
+
296
+ class DeepseekV3YarnRotaryEmbedding(DeepseekV3RotaryEmbedding):
297
+
298
+ def __init__(
299
+ self,
300
+ dim,
301
+ max_position_embeddings=2048,
302
+ base=10000,
303
+ device=None,
304
+ scaling_factor=1.0,
305
+ original_max_position_embeddings=4096,
306
+ beta_fast=32,
307
+ beta_slow=1,
308
+ mscale=1,
309
+ mscale_all_dim=0,
310
+ ):
311
+ self.scaling_factor = scaling_factor
312
+ self.original_max_position_embeddings = original_max_position_embeddings
313
+ self.beta_fast = beta_fast
314
+ self.beta_slow = beta_slow
315
+ self.mscale = mscale
316
+ self.mscale_all_dim = mscale_all_dim
317
+ super().__init__(dim, max_position_embeddings, base, device)
318
+
319
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
320
+ self.max_seq_len_cached = seq_len
321
+ dim = self.dim
322
+
323
+ freq_extra = 1.0 / (
324
+ self.base
325
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
326
+ )
327
+ freq_inter = 1.0 / (
328
+ self.scaling_factor
329
+ * self.base
330
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
331
+ )
332
+
333
+ low, high = yarn_find_correction_range(
334
+ self.beta_fast,
335
+ self.beta_slow,
336
+ dim,
337
+ self.base,
338
+ self.original_max_position_embeddings,
339
+ )
340
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
341
+ device=device, dtype=torch.float32
342
+ )
343
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
344
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
345
+
346
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
347
+
348
+ freqs = torch.outer(t, inv_freq)
349
+
350
+ _mscale = float(
351
+ yarn_get_mscale(self.scaling_factor, self.mscale)
352
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
353
+ )
354
+
355
+ emb = torch.cat((freqs, freqs), dim=-1)
356
+ self.register_buffer(
357
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
358
+ )
359
+ self.register_buffer(
360
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
361
+ )
362
+
363
+
364
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
365
+ def rotate_half(x):
366
+ """Rotates half the hidden dims of the input."""
367
+ x1 = x[..., : x.shape[-1] // 2]
368
+ x2 = x[..., x.shape[-1] // 2 :]
369
+ return torch.cat((-x2, x1), dim=-1)
370
+
371
+
372
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
373
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
374
+ """Applies Rotary Position Embedding to the query and key tensors.
375
+
376
+ Args:
377
+ q (`torch.Tensor`): The query tensor.
378
+ k (`torch.Tensor`): The key tensor.
379
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
380
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
381
+ position_ids (`torch.Tensor`):
382
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
383
+ used to pass offsetted position ids when working with a KV-cache.
384
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
385
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
386
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
387
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
388
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
389
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
390
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
391
+ Returns:
392
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
393
+ """
394
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
395
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
396
+
397
+ b, h, s, d = q.shape
398
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
399
+
400
+ b, h, s, d = k.shape
401
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
402
+
403
+ q_embed = (q * cos) + (rotate_half(q) * sin)
404
+ k_embed = (k * cos) + (rotate_half(k) * sin)
405
+ return q_embed, k_embed
406
+
407
+
408
+ class DeepseekV3MLP(nn.Module):
409
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
410
+ super().__init__()
411
+ self.config = config
412
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
413
+ self.intermediate_size = (
414
+ config.intermediate_size if intermediate_size is None else intermediate_size
415
+ )
416
+
417
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
418
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
419
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
420
+ self.act_fn = ACT2FN[config.hidden_act]
421
+
422
+ def forward(self, x):
423
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
424
+ return down_proj
425
+
426
+
427
+ class MoEGate(nn.Module):
428
+ def __init__(self, config):
429
+ super().__init__()
430
+ self.config = config
431
+ self.top_k = config.num_experts_per_tok
432
+ self.n_routed_experts = config.n_routed_experts
433
+ self.routed_scaling_factor = config.routed_scaling_factor
434
+ self.scoring_func = config.scoring_func
435
+ self.topk_method = config.topk_method
436
+ self.n_group = config.n_group
437
+ self.topk_group = config.topk_group
438
+
439
+ # topk selection algorithm
440
+ self.norm_topk_prob = config.norm_topk_prob
441
+ self.gating_dim = config.hidden_size
442
+ self.weight = nn.Parameter(
443
+ torch.empty((self.n_routed_experts, self.gating_dim))
444
+ )
445
+ if self.topk_method == "noaux_tc":
446
+ self.e_score_correction_bias = nn.Parameter(
447
+ torch.empty((self.n_routed_experts))
448
+ )
449
+ self.reset_parameters()
450
+
451
+ def reset_parameters(self) -> None:
452
+ import torch.nn.init as init
453
+
454
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
455
+
456
+ def forward(self, hidden_states):
457
+ bsz, seq_len, h = hidden_states.shape
458
+ ### compute gating score
459
+ hidden_states = hidden_states.view(-1, h)
460
+ logits = F.linear(
461
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
462
+ )
463
+ if self.scoring_func == "sigmoid":
464
+ scores = logits.sigmoid()
465
+ else:
466
+ raise NotImplementedError(
467
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
468
+ )
469
+
470
+ ### select top-k experts
471
+ if self.topk_method == "noaux_tc":
472
+ assert not self.training
473
+ scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
474
+ group_scores = (
475
+ scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
476
+ ) # [n, n_group]
477
+ group_idx = torch.topk(
478
+ group_scores, k=self.topk_group, dim=-1, sorted=False
479
+ )[
480
+ 1
481
+ ] # [n, top_k_group]
482
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
483
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
484
+ score_mask = (
485
+ group_mask.unsqueeze(-1)
486
+ .expand(
487
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
488
+ )
489
+ .reshape(bsz * seq_len, -1)
490
+ ) # [n, e]
491
+ tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), 0.0) # [n, e]
492
+ _, topk_idx = torch.topk(
493
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
494
+ )
495
+ topk_weight = scores.gather(1, topk_idx)
496
+ else:
497
+ raise NotImplementedError(
498
+ f"insupportable TopK function for MoE gating: {self.topk_method}"
499
+ )
500
+
501
+ ### norm gate to sum 1
502
+ if self.top_k > 1 and self.norm_topk_prob:
503
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
504
+ topk_weight = topk_weight / denominator
505
+ topk_weight = topk_weight * self.routed_scaling_factor # must multiply the scaling factor
506
+
507
+ return topk_idx, topk_weight
508
+
509
+ class DeepseekV3MoE(nn.Module):
510
+ """
511
+ A mixed expert module containing shared experts.
512
+ """
513
+
514
+ def __init__(self, config):
515
+ super().__init__()
516
+ self.config = config
517
+ self.num_experts_per_tok = config.num_experts_per_tok
518
+
519
+ if hasattr(config, "ep_size") and config.ep_size > 1:
520
+ assert config.ep_size == dist.get_world_size()
521
+ self.ep_size = config.ep_size
522
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
523
+ self.ep_rank = dist.get_rank()
524
+ self.experts = nn.ModuleList(
525
+ [
526
+ (
527
+ DeepseekV3MLP(
528
+ config, intermediate_size=config.moe_intermediate_size
529
+ )
530
+ if i >= self.ep_rank * self.experts_per_rank
531
+ and i < (self.ep_rank + 1) * self.experts_per_rank
532
+ else None
533
+ )
534
+ for i in range(config.n_routed_experts)
535
+ ]
536
+ )
537
+ else:
538
+ self.ep_size = 1
539
+ self.experts_per_rank = config.n_routed_experts
540
+ self.ep_rank = 0
541
+ self.experts = nn.ModuleList(
542
+ [
543
+ DeepseekV3MLP(
544
+ config, intermediate_size=config.moe_intermediate_size
545
+ )
546
+ for i in range(config.n_routed_experts)
547
+ ]
548
+ )
549
+ self.gate = MoEGate(config)
550
+ if config.n_shared_experts is not None:
551
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
552
+ self.shared_experts = DeepseekV3MLP(
553
+ config=config, intermediate_size=intermediate_size
554
+ )
555
+
556
+ def forward(self, hidden_states):
557
+ identity = hidden_states
558
+ orig_shape = hidden_states.shape
559
+ topk_idx, topk_weight = self.gate(hidden_states)
560
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
561
+ flat_topk_idx = topk_idx.view(-1)
562
+ if not self.training:
563
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
564
+ if self.config.n_shared_experts is not None:
565
+ y = y + self.shared_experts(identity)
566
+ return y
567
+
568
+ @torch.no_grad()
569
+ def moe_infer(self, x, topk_ids, topk_weight):
570
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
571
+ cnts.scatter_(1, topk_ids, 1)
572
+ tokens_per_expert = cnts.sum(dim=0)
573
+ idxs = topk_ids.view(-1).argsort()
574
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
575
+ sorted_tokens_shape = sorted_tokens.shape
576
+ if self.ep_size > 1:
577
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
578
+ tokens_per_expert_group = tokens_per_expert.new_empty(
579
+ tokens_per_expert.shape[0]
580
+ )
581
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
582
+ output_splits = (
583
+ tokens_per_expert_group.view(self.ep_size, -1)
584
+ .sum(1)
585
+ .cpu()
586
+ .numpy()
587
+ .tolist()
588
+ )
589
+ gathered_tokens = sorted_tokens.new_empty(
590
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
591
+ )
592
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
593
+ dist.all_to_all(
594
+ list(gathered_tokens.split(output_splits)),
595
+ list(sorted_tokens.split(input_split_sizes)),
596
+ )
597
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(
598
+ self.ep_size, self.experts_per_rank
599
+ ).sum(dim=0)
600
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
601
+ s = 0
602
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
603
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
604
+ s += k
605
+ gatherd_idxs = gatherd_idxs.argsort()
606
+ sorted_tokens = gathered_tokens[gatherd_idxs]
607
+ tokens_per_expert = tokens_per_expert_post_gather
608
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
609
+
610
+ outputs = []
611
+ start_idx = 0
612
+ for i, num_tokens in enumerate(tokens_per_expert):
613
+ end_idx = start_idx + num_tokens
614
+ if num_tokens == 0:
615
+ continue
616
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
617
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
618
+ expert_out = expert(tokens_for_this_expert)
619
+ outputs.append(expert_out)
620
+ start_idx = end_idx
621
+
622
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
623
+ if self.ep_size > 1:
624
+ new_x = torch.empty_like(outs)
625
+ new_x[gatherd_idxs] = outs
626
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
627
+ dist.all_to_all(
628
+ list(gathered_tokens.split(input_split_sizes)),
629
+ list(new_x.split(output_splits)),
630
+ )
631
+ outs = gathered_tokens
632
+
633
+ new_x = torch.empty_like(outs)
634
+ new_x[idxs] = outs
635
+ final_out = (
636
+ new_x.view(*topk_ids.shape, -1)
637
+ .type(topk_weight.dtype)
638
+ .mul_(topk_weight.unsqueeze(dim=-1))
639
+ .sum(dim=1)
640
+ .type(new_x.dtype)
641
+ )
642
+ return final_out
643
+
644
+
645
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
646
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
647
+ """
648
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
649
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
650
+ """
651
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
652
+ if n_rep == 1:
653
+ return hidden_states
654
+ hidden_states = hidden_states[:, :, None, :, :].expand(
655
+ batch, num_key_value_heads, n_rep, slen, head_dim
656
+ )
657
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
658
+
659
+
660
+ class BMMLinear(nn.Linear):
661
+ def __init__(self, in_features, out_features, num_heads):
662
+ super().__init__(in_features, out_features, bias=False)
663
+ self.input_dim = in_features
664
+ self.output_dim = out_features
665
+ self.num_heads = num_heads
666
+
667
+ def forward(self, x):
668
+ weight = self.weight.view(self.num_heads, -1, self.input_dim)
669
+ if self.input_dim == x.size(-1):
670
+ weight = weight.transpose(1, 2)
671
+ return torch.matmul(x, weight)
672
+
673
+
674
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV3
675
+ class DeepseekV3Attention(nn.Module):
676
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
677
+
678
+ def __init__(self, config: DeepseekV3Config, layer_idx: Optional[int] = None):
679
+ super().__init__()
680
+ self.config = config
681
+ self.layer_idx = layer_idx
682
+ if layer_idx is None:
683
+ logger.warning_once(
684
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
685
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
686
+ "when creating this class."
687
+ )
688
+
689
+ self.attention_dropout = config.attention_dropout
690
+ self.hidden_size = config.hidden_size
691
+ self.num_heads = config.num_attention_heads
692
+
693
+ self.max_position_embeddings = config.max_position_embeddings
694
+ self.rope_theta = config.rope_theta
695
+ self.q_lora_rank = config.q_lora_rank
696
+ self.qk_rope_head_dim = config.qk_rope_head_dim
697
+ self.kv_lora_rank = config.kv_lora_rank
698
+ self.v_head_dim = config.v_head_dim
699
+ self.qk_nope_head_dim = config.qk_nope_head_dim
700
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
701
+
702
+ self.is_causal = True
703
+
704
+ if self.q_lora_rank is None:
705
+ self.q_proj = nn.Linear(
706
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
707
+ )
708
+ else:
709
+ self.q_a_proj = nn.Linear(
710
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
711
+ )
712
+ self.q_a_layernorm = DeepseekV3RMSNorm(config.q_lora_rank)
713
+ self.q_b_proj = nn.Linear(
714
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
715
+ )
716
+
717
+ self.kv_a_proj_with_mqa = nn.Linear(
718
+ self.hidden_size,
719
+ config.kv_lora_rank + config.qk_rope_head_dim,
720
+ bias=config.attention_bias,
721
+ )
722
+ self.kv_a_layernorm = DeepseekV3RMSNorm(config.kv_lora_rank)
723
+ self.kv_b_proj = nn.Linear(
724
+ config.kv_lora_rank,
725
+ self.num_heads
726
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
727
+ bias=False,
728
+ )
729
+
730
+ self.k_b_proj = BMMLinear(
731
+ config.kv_lora_rank,
732
+ self.num_heads * (self.q_head_dim - self.qk_rope_head_dim),
733
+ self.num_heads
734
+ )
735
+
736
+ self.v_b_proj = BMMLinear(
737
+ config.kv_lora_rank,
738
+ self.num_heads * self.v_head_dim,
739
+ self.num_heads
740
+ )
741
+
742
+ self.o_proj = nn.Linear(
743
+ self.num_heads * self.v_head_dim,
744
+ self.hidden_size,
745
+ bias=config.attention_bias,
746
+ )
747
+ self._init_rope()
748
+
749
+ self.softmax_scale = self.q_head_dim ** (-0.5)
750
+ if self.config.rope_scaling is not None:
751
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
752
+ scaling_factor = self.config.rope_scaling["factor"]
753
+ if mscale_all_dim:
754
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
755
+ self.softmax_scale = self.softmax_scale * mscale * mscale
756
+
757
+ def _init_rope(self):
758
+ if self.config.rope_scaling is None:
759
+ self.rotary_emb = DeepseekV3RotaryEmbedding(
760
+ self.qk_rope_head_dim,
761
+ max_position_embeddings=self.max_position_embeddings,
762
+ base=self.rope_theta,
763
+ )
764
+ else:
765
+ scaling_type = self.config.rope_scaling["type"]
766
+ scaling_factor = self.config.rope_scaling["factor"]
767
+ if scaling_type == "linear":
768
+ self.rotary_emb = DeepseekV3LinearScalingRotaryEmbedding(
769
+ self.qk_rope_head_dim,
770
+ max_position_embeddings=self.max_position_embeddings,
771
+ scaling_factor=scaling_factor,
772
+ base=self.rope_theta,
773
+ )
774
+ elif scaling_type == "dynamic":
775
+ self.rotary_emb = DeepseekV3DynamicNTKScalingRotaryEmbedding(
776
+ self.qk_rope_head_dim,
777
+ max_position_embeddings=self.max_position_embeddings,
778
+ scaling_factor=scaling_factor,
779
+ base=self.rope_theta,
780
+ )
781
+ elif scaling_type == "yarn":
782
+ kwargs = {
783
+ key: self.config.rope_scaling[key]
784
+ for key in [
785
+ "original_max_position_embeddings",
786
+ "beta_fast",
787
+ "beta_slow",
788
+ "mscale",
789
+ "mscale_all_dim",
790
+ ]
791
+ if key in self.config.rope_scaling
792
+ }
793
+ self.rotary_emb = DeepseekV3YarnRotaryEmbedding(
794
+ self.qk_rope_head_dim,
795
+ max_position_embeddings=self.max_position_embeddings,
796
+ scaling_factor=scaling_factor,
797
+ base=self.rope_theta,
798
+ **kwargs,
799
+ )
800
+ else:
801
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
802
+
803
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
804
+ return (
805
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
806
+ .transpose(1, 2)
807
+ .contiguous()
808
+ )
809
+
810
+ def vanilla_forward(
811
+ self,
812
+ hidden_states: torch.Tensor,
813
+ attention_mask: Optional[torch.Tensor] = None,
814
+ position_ids: Optional[torch.LongTensor] = None,
815
+ past_key_value: Optional[Cache] = None,
816
+ output_attentions: bool = False,
817
+ use_cache: bool = False,
818
+ **kwargs,
819
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
820
+ if "padding_mask" in kwargs:
821
+ warnings.warn(
822
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
823
+ )
824
+ bsz, q_len, _ = hidden_states.size()
825
+
826
+ if self.q_lora_rank is None:
827
+ q = self.q_proj(hidden_states)
828
+ else:
829
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
830
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
831
+ q_nope, q_pe = torch.split(
832
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
833
+ )
834
+
835
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
836
+ compressed_kv, k_pe = torch.split(
837
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
838
+ )
839
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
840
+ kv = (
841
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
842
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
843
+ .transpose(1, 2)
844
+ )
845
+
846
+ k_nope, value_states = torch.split(
847
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
848
+ )
849
+ kv_seq_len = value_states.shape[-2]
850
+ if past_key_value is not None:
851
+ if self.layer_idx is None:
852
+ raise ValueError(
853
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
854
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
855
+ "with a layer index."
856
+ )
857
+ kv_seq_len += past_key_value.get_seq_length(self.layer_idx)
858
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
859
+
860
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
861
+
862
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
863
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
864
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
865
+
866
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
867
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
868
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
869
+ if past_key_value is not None:
870
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
871
+ key_states, value_states = past_key_value.update(
872
+ key_states, value_states, self.layer_idx, cache_kwargs
873
+ )
874
+
875
+ attn_weights = (
876
+ torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
877
+ )
878
+
879
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
880
+ raise ValueError(
881
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
882
+ f" {attn_weights.size()}"
883
+ )
884
+ assert attention_mask is not None
885
+ if attention_mask is not None:
886
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
887
+ raise ValueError(
888
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
889
+ )
890
+ attn_weights = attn_weights + attention_mask
891
+
892
+ # upcast attention to fp32
893
+ attn_weights = nn.functional.softmax(
894
+ attn_weights, dim=-1, dtype=torch.float32
895
+ ).to(query_states.dtype)
896
+ attn_weights = nn.functional.dropout(
897
+ attn_weights, p=self.attention_dropout, training=self.training
898
+ )
899
+ attn_output = torch.matmul(attn_weights, value_states)
900
+
901
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
902
+ raise ValueError(
903
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
904
+ f" {attn_output.size()}"
905
+ )
906
+
907
+ attn_output = attn_output.transpose(1, 2).contiguous()
908
+
909
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
910
+
911
+ attn_output = self.o_proj(attn_output)
912
+
913
+ if not output_attentions:
914
+ attn_weights = None
915
+
916
+ return attn_output, attn_weights, past_key_value
917
+
918
+ # Note(Zhengzekang): Fused version
919
+ def fused_forward(
920
+ self,
921
+ hidden_states: torch.Tensor,
922
+ attention_mask: Optional[torch.Tensor] = None,
923
+ position_ids: Optional[torch.LongTensor] = None,
924
+ past_key_value: Optional[Cache] = None,
925
+ output_attentions: bool = False,
926
+ use_cache: bool = False,
927
+ **kwargs,
928
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
929
+ if "padding_mask" in kwargs:
930
+ warnings.warn(
931
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
932
+ )
933
+ bsz, q_len, _ = hidden_states.size()
934
+
935
+ if self.q_lora_rank is None:
936
+ q = self.q_proj(hidden_states)
937
+ else:
938
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
939
+
940
+ q = q.view(-1, self.num_heads, self.q_head_dim)
941
+ # numhead, bszxseq, headsize
942
+ q_nope = q[:, :, :self.qk_nope_head_dim].transpose(0, 1)
943
+ q_pe = q[:, :, self.qk_nope_head_dim: ].view(bsz, q_len, self.num_heads, -1).transpose(1, 2)
944
+
945
+ # k_b_proj = self.k_b_proj.weight
946
+
947
+ # k_b_proj = k_b_proj.view(self.num_heads, -1, self.kv_lora_rank)
948
+ # print("q_nope shape is: ", q_nope.shape)
949
+ # print("k_b_proj shape is: ", k_b_proj.shape)
950
+
951
+ # q_nope = torch.matmul(q_nope, k_b_proj).transpose(0, 1).view(bsz, q_len, self.num_heads, -1).transpose(1, 2)
952
+ q_nope = self.k_b_proj(q_nope).transpose(0, 1).view(bsz, q_len, self.num_heads, -1).transpose(1, 2)
953
+
954
+ # print("qk shape is: ", q_nope.shape)
955
+ # print("q_pe shape is: ", q_pe.shape)
956
+
957
+ # raise Exception()
958
+
959
+ # [*, 128, 128+64] -> [bz, 128, q_len, 128+64]
960
+ #q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
961
+
962
+ # [bz, 128, q_len, 128], [bz, 128, q_len, 64]
963
+ #q_nope, q_pe = torch.split(
964
+ # q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
965
+ #)
966
+
967
+ # [*, 5120] -> [*, 512+64]
968
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
969
+
970
+ # [*, 512], [*, 64]
971
+ compressed_kv, k_pe = torch.split(
972
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
973
+ )
974
+ # [*, 64]
975
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
976
+
977
+ compressed_kv = self.kv_a_layernorm(compressed_kv) # c_t
978
+
979
+ # [*, 512] -> [*, 128 * (128+128)]
980
+ #kv = (
981
+ # self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
982
+ # .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
983
+ # .transpose(1, 2)
984
+ #)
985
+
986
+ # [bz, 128, q_len, 128], [bz, 128, q_len, 128]
987
+ #k_nope, value_states = torch.split(
988
+ # kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
989
+ # )
990
+ kv_seq_len = q_len # value_states.shape[-2]
991
+ if past_key_value is not None:
992
+ if self.layer_idx is None:
993
+ raise ValueError(
994
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
995
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
996
+ "with a layer index."
997
+ )
998
+ kv_seq_len += past_key_value.get_seq_length(self.layer_idx)
999
+
1000
+ cos, sin = self.rotary_emb(torch.empty(bsz, self.num_heads, q_len, self.v_head_dim, dtype=hidden_states.dtype, device=hidden_states.device), seq_len=kv_seq_len)
1001
+
1002
+ # [bz, 128, q_len, 64], [bz, 1, q_len, 64]
1003
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids) # k_t
1004
+
1005
+ # # [bz, 128, q_len, 128+64]
1006
+ # query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.kv_lora_rank + self.qk_rope_head_dim)
1007
+ # query_states[:, :, :, : self.kv_lora_rank] = q_nope
1008
+ # query_states[:, :, :, self.kv_lora_rank :] = q_pe
1009
+
1010
+ # # [bz, 128, q_len, 128+64]
1011
+ # key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.kv_lora_rank + self.qk_rope_head_dim)
1012
+ # print("#########", compressed_kv.shape)
1013
+ # key_states[:, :, :, : self.kv_lora_rank] = compressed_kv
1014
+ # key_states[:, :, :, self.kv_lora_rank :] = k_pe
1015
+
1016
+
1017
+ # [bz, 128, q_len, 512+64]
1018
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.kv_lora_rank + self.qk_rope_head_dim)
1019
+ query_states[:, :, :, : self.kv_lora_rank] = q_nope
1020
+ query_states[:, :, :, self.kv_lora_rank :] = q_pe
1021
+
1022
+ if past_key_value is not None:
1023
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1024
+ compressed_kv, k_pe = past_key_value.update(
1025
+ compressed_kv.unsqueeze(1), k_pe, self.layer_idx, cache_kwargs
1026
+ )
1027
+ else:
1028
+ compressed_kv = compressed_kv.unsqueeze(1)
1029
+
1030
+ # [bz, 128, q_len, 512+64]
1031
+ key_states = k_pe.new_empty(bsz, self.num_heads, kv_seq_len, self.kv_lora_rank + self.qk_rope_head_dim)
1032
+ key_states[:, :, :, : self.kv_lora_rank] = compressed_kv
1033
+ key_states[:, :, :, self.kv_lora_rank :] = k_pe
1034
+ # print("keystates0: ", key_states[:, 0, :, :])
1035
+ # print("keystates1: ", key_states[:, 1, :, :])
1036
+
1037
+
1038
+ value_states = k_pe.new_empty(bsz, self.num_heads, kv_seq_len, self.kv_lora_rank)
1039
+ value_states[:, :, :, : self.kv_lora_rank] = compressed_kv
1040
+
1041
+ # [bz, 128, q_len, q_len]
1042
+ attn_weights = (
1043
+ torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
1044
+ )
1045
+
1046
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
1047
+ raise ValueError(
1048
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
1049
+ f" {attn_weights.size()}"
1050
+ )
1051
+ assert attention_mask is not None
1052
+ if attention_mask is not None:
1053
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
1054
+ raise ValueError(
1055
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
1056
+ )
1057
+ attn_weights = attn_weights + attention_mask
1058
+
1059
+ # upcast attention to fp32
1060
+ attn_weights = nn.functional.softmax(
1061
+ attn_weights, dim=-1, dtype=torch.float32
1062
+ ).to(query_states.dtype)
1063
+
1064
+
1065
+ attn_weights = nn.functional.dropout(
1066
+ attn_weights, p=self.attention_dropout, training=self.training
1067
+ )
1068
+
1069
+ # [bz, 128, q_len, 512]
1070
+ attn_output = torch.matmul(attn_weights, value_states)
1071
+ attn_output = attn_output.transpose(1, 2).reshape(-1, self.num_heads, self.kv_lora_rank).transpose(0, 1)
1072
+
1073
+ # print(self.v_b_proj.shape)
1074
+
1075
+ # v_b_proj = self.v_b_proj.weight
1076
+ # v_b_proj = v_b_proj.view(self.num_heads, self.v_head_dim, self.kv_lora_rank).transpose(1, 2)
1077
+ # attn_output = torch.matmul(attn_output, v_b_proj).transpose(0, 1).reshape(-1, self.num_heads * self.v_head_dim)
1078
+
1079
+ attn_output = self.v_b_proj(attn_output).transpose(0, 1).reshape(-1, self.num_heads * self.v_head_dim)
1080
+
1081
+
1082
+ # [*, 128 * 128] -> [*, 5120]
1083
+ attn_output = self.o_proj(attn_output)
1084
+
1085
+ if not output_attentions:
1086
+ attn_weights = None
1087
+
1088
+ # print("fused attn output is: ", attn_output)
1089
+ # exit(0)
1090
+ return attn_output.view(bsz, q_len, -1), attn_weights, past_key_value
1091
+
1092
+ def forward(
1093
+ self,
1094
+ hidden_states: torch.Tensor,
1095
+ attention_mask: Optional[torch.Tensor] = None,
1096
+ position_ids: Optional[torch.LongTensor] = None,
1097
+ past_key_value: Optional[Cache] = None,
1098
+ output_attentions: bool = False,
1099
+ use_cache: bool = False,
1100
+ **kwargs,
1101
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1102
+ if getattr(self.kv_b_proj, "use_vanilla_fwd", True):
1103
+ return self.vanilla_forward(hidden_states, attention_mask, position_ids, past_key_value, output_attentions, use_cache, **kwargs)
1104
+ else:
1105
+ return self.fused_forward(hidden_states, attention_mask, position_ids, past_key_value, output_attentions, use_cache, **kwargs)
1106
+
1107
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV3
1108
+ class DeepseekV3FlashAttention2(DeepseekV3Attention):
1109
+ """
1110
+ DeepseekV3 flash attention module. This module inherits from `DeepseekV3Attention` as the weights of the module stays
1111
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
1112
+ flash attention and deal with padding tokens in case the input contains any of them.
1113
+ """
1114
+
1115
+ def __init__(self, *args, **kwargs):
1116
+ super().__init__(*args, **kwargs)
1117
+
1118
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
1119
+ # 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.
1120
+ # 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).
1121
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
1122
+
1123
+ def forward(
1124
+ self,
1125
+ hidden_states: torch.Tensor,
1126
+ attention_mask: Optional[torch.LongTensor] = None,
1127
+ position_ids: Optional[torch.LongTensor] = None,
1128
+ past_key_value: Optional[Cache] = None,
1129
+ output_attentions: bool = False,
1130
+ use_cache: bool = False,
1131
+ **kwargs,
1132
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1133
+ # DeepseekV3FlashAttention2 attention does not support output_attentions
1134
+ if "padding_mask" in kwargs:
1135
+ warnings.warn(
1136
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1137
+ )
1138
+
1139
+ # overwrite attention_mask with padding_mask
1140
+ attention_mask = kwargs.pop("padding_mask")
1141
+
1142
+ output_attentions = False
1143
+
1144
+ bsz, q_len, _ = hidden_states.size()
1145
+
1146
+ if self.q_lora_rank is None:
1147
+ q = self.q_proj(hidden_states)
1148
+ else:
1149
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
1150
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
1151
+ q_nope, q_pe = torch.split(
1152
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
1153
+ )
1154
+
1155
+ # Flash attention requires the input to have the shape
1156
+ # batch_size x seq_length x head_dim x hidden_dim
1157
+ # therefore we just need to keep the original shape
1158
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
1159
+ compressed_kv, k_pe = torch.split(
1160
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
1161
+ )
1162
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
1163
+ kv = (
1164
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
1165
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
1166
+ .transpose(1, 2)
1167
+ )
1168
+
1169
+ k_nope, value_states = torch.split(
1170
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
1171
+ )
1172
+ kv_seq_len = value_states.shape[-2]
1173
+
1174
+ kv_seq_len = value_states.shape[-2]
1175
+ if past_key_value is not None:
1176
+ kv_seq_len += past_key_value.get_seq_length(self.layer_idx)
1177
+
1178
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1179
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1180
+
1181
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1182
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1183
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1184
+
1185
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1186
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1187
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1188
+
1189
+ if self.q_head_dim != self.v_head_dim:
1190
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
1191
+
1192
+ if past_key_value is not None:
1193
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1194
+ key_states, value_states = past_key_value.update(
1195
+ key_states, value_states, self.layer_idx, cache_kwargs
1196
+ )
1197
+
1198
+ # 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
1199
+ # to be able to avoid many of these transpose/reshape/view.
1200
+ query_states = query_states.transpose(1, 2)
1201
+ key_states = key_states.transpose(1, 2)
1202
+ value_states = value_states.transpose(1, 2)
1203
+
1204
+ dropout_rate = self.attention_dropout if self.training else 0.0
1205
+
1206
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
1207
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
1208
+ # cast them back in the correct dtype just to be sure everything works as expected.
1209
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
1210
+ # in fp32. (DeepseekV3RMSNorm handles it correctly)
1211
+
1212
+ input_dtype = query_states.dtype
1213
+ if input_dtype == torch.float32:
1214
+ # Handle the case where the model is quantized
1215
+ if hasattr(self.config, "_pre_quantization_dtype"):
1216
+ target_dtype = self.config._pre_quantization_dtype
1217
+ elif torch.is_autocast_enabled():
1218
+ target_dtype = torch.get_autocast_gpu_dtype()
1219
+ else:
1220
+ target_dtype = (
1221
+ self.q_proj.weight.dtype
1222
+ if self.q_lora_rank is None
1223
+ else self.q_a_proj.weight.dtype
1224
+ )
1225
+
1226
+ logger.warning_once(
1227
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
1228
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
1229
+ f" {target_dtype}."
1230
+ )
1231
+
1232
+ query_states = query_states.to(target_dtype)
1233
+ key_states = key_states.to(target_dtype)
1234
+ value_states = value_states.to(target_dtype)
1235
+
1236
+ attn_output = self._flash_attention_forward(
1237
+ query_states,
1238
+ key_states,
1239
+ value_states,
1240
+ attention_mask,
1241
+ q_len,
1242
+ dropout=dropout_rate,
1243
+ softmax_scale=self.softmax_scale,
1244
+ )
1245
+ if self.q_head_dim != self.v_head_dim:
1246
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
1247
+
1248
+ attn_output = attn_output.reshape(
1249
+ bsz, q_len, self.num_heads * self.v_head_dim
1250
+ ).contiguous()
1251
+ attn_output = self.o_proj(attn_output)
1252
+
1253
+ if not output_attentions:
1254
+ attn_weights = None
1255
+
1256
+ return attn_output, attn_weights, past_key_value
1257
+
1258
+ def _flash_attention_forward(
1259
+ self,
1260
+ query_states,
1261
+ key_states,
1262
+ value_states,
1263
+ attention_mask,
1264
+ query_length,
1265
+ dropout=0.0,
1266
+ softmax_scale=None,
1267
+ ):
1268
+ """
1269
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1270
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1271
+
1272
+ Args:
1273
+ query_states (`torch.Tensor`):
1274
+ Input query states to be passed to Flash Attention API
1275
+ key_states (`torch.Tensor`):
1276
+ Input key states to be passed to Flash Attention API
1277
+ value_states (`torch.Tensor`):
1278
+ Input value states to be passed to Flash Attention API
1279
+ attention_mask (`torch.Tensor`):
1280
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1281
+ position of padding tokens and 1 for the position of non-padding tokens.
1282
+ dropout (`int`, *optional*):
1283
+ Attention dropout
1284
+ softmax_scale (`float`, *optional*):
1285
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1286
+ """
1287
+ if not self._flash_attn_uses_top_left_mask:
1288
+ causal = self.is_causal
1289
+ else:
1290
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in DeepseekV3FlashAttention2 __init__.
1291
+ causal = self.is_causal and query_length != 1
1292
+
1293
+ # Contains at least one padding token in the sequence
1294
+ if attention_mask is not None:
1295
+ batch_size = query_states.shape[0]
1296
+ (
1297
+ query_states,
1298
+ key_states,
1299
+ value_states,
1300
+ indices_q,
1301
+ cu_seq_lens,
1302
+ max_seq_lens,
1303
+ ) = self._upad_input(
1304
+ query_states, key_states, value_states, attention_mask, query_length
1305
+ )
1306
+
1307
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1308
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1309
+
1310
+ attn_output_unpad = flash_attn_varlen_func(
1311
+ query_states,
1312
+ key_states,
1313
+ value_states,
1314
+ cu_seqlens_q=cu_seqlens_q,
1315
+ cu_seqlens_k=cu_seqlens_k,
1316
+ max_seqlen_q=max_seqlen_in_batch_q,
1317
+ max_seqlen_k=max_seqlen_in_batch_k,
1318
+ dropout_p=dropout,
1319
+ softmax_scale=softmax_scale,
1320
+ causal=causal,
1321
+ )
1322
+
1323
+ attn_output = pad_input(
1324
+ attn_output_unpad, indices_q, batch_size, query_length
1325
+ )
1326
+ else:
1327
+ attn_output = flash_attn_func(
1328
+ query_states,
1329
+ key_states,
1330
+ value_states,
1331
+ dropout,
1332
+ softmax_scale=softmax_scale,
1333
+ causal=causal,
1334
+ )
1335
+
1336
+ return attn_output
1337
+
1338
+ def _upad_input(
1339
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
1340
+ ):
1341
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1342
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1343
+
1344
+ key_layer = index_first_axis(
1345
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1346
+ indices_k,
1347
+ )
1348
+ value_layer = index_first_axis(
1349
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1350
+ indices_k,
1351
+ )
1352
+ if query_length == kv_seq_len:
1353
+ query_layer = index_first_axis(
1354
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1355
+ indices_k,
1356
+ )
1357
+ cu_seqlens_q = cu_seqlens_k
1358
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1359
+ indices_q = indices_k
1360
+ elif query_length == 1:
1361
+ max_seqlen_in_batch_q = 1
1362
+ cu_seqlens_q = torch.arange(
1363
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1364
+ ) # There is a memcpy here, that is very bad.
1365
+ indices_q = cu_seqlens_q[:-1]
1366
+ query_layer = query_layer.squeeze(1)
1367
+ else:
1368
+ # The -q_len: slice assumes left padding.
1369
+ attention_mask = attention_mask[:, -query_length:]
1370
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1371
+ query_layer, attention_mask
1372
+ )
1373
+
1374
+ return (
1375
+ query_layer,
1376
+ key_layer,
1377
+ value_layer,
1378
+ indices_q,
1379
+ (cu_seqlens_q, cu_seqlens_k),
1380
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1381
+ )
1382
+
1383
+
1384
+ ATTENTION_CLASSES = {
1385
+ "eager": DeepseekV3Attention,
1386
+ "flash_attention_2": DeepseekV3FlashAttention2,
1387
+ }
1388
+
1389
+
1390
+ class DeepseekV3DecoderLayer(nn.Module):
1391
+ def __init__(self, config: DeepseekV3Config, layer_idx: int):
1392
+ super().__init__()
1393
+ self.hidden_size = config.hidden_size
1394
+
1395
+ self.self_attn = ATTENTION_CLASSES[config._attn_implementation](
1396
+ config=config, layer_idx=layer_idx
1397
+ )
1398
+
1399
+ self.mlp = (
1400
+ DeepseekV3MoE(config)
1401
+ if (
1402
+ config.n_routed_experts is not None
1403
+ and layer_idx >= config.first_k_dense_replace
1404
+ and layer_idx % config.moe_layer_freq == 0
1405
+ )
1406
+ else DeepseekV3MLP(config)
1407
+ )
1408
+ self.input_layernorm = DeepseekV3RMSNorm(
1409
+ config.hidden_size, eps=config.rms_norm_eps
1410
+ )
1411
+ self.post_attention_layernorm = DeepseekV3RMSNorm(
1412
+ config.hidden_size, eps=config.rms_norm_eps
1413
+ )
1414
+
1415
+ def forward(
1416
+ self,
1417
+ hidden_states: torch.Tensor,
1418
+ attention_mask: Optional[torch.Tensor] = None,
1419
+ position_ids: Optional[torch.LongTensor] = None,
1420
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1421
+ output_attentions: Optional[bool] = False,
1422
+ use_cache: Optional[bool] = False,
1423
+ **kwargs,
1424
+ ) -> Tuple[
1425
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1426
+ ]:
1427
+ """
1428
+ Args:
1429
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1430
+ attention_mask (`torch.FloatTensor`, *optional*):
1431
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1432
+ query_sequence_length, key_sequence_length)` if default attention is used.
1433
+ output_attentions (`bool`, *optional*):
1434
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1435
+ returned tensors for more detail.
1436
+ use_cache (`bool`, *optional*):
1437
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1438
+ (see `past_key_values`).
1439
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1440
+ """
1441
+ if "padding_mask" in kwargs:
1442
+ warnings.warn(
1443
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1444
+ )
1445
+ residual = hidden_states
1446
+
1447
+ hidden_states = self.input_layernorm(hidden_states)
1448
+
1449
+ # Self Attention
1450
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1451
+ hidden_states=hidden_states,
1452
+ attention_mask=attention_mask,
1453
+ position_ids=position_ids,
1454
+ past_key_value=past_key_value,
1455
+ output_attentions=output_attentions,
1456
+ use_cache=use_cache,
1457
+ **kwargs,
1458
+ )
1459
+ hidden_states = residual + hidden_states
1460
+
1461
+ # Fully Connected
1462
+ residual = hidden_states
1463
+ hidden_states = self.post_attention_layernorm(hidden_states)
1464
+ hidden_states = self.mlp(hidden_states)
1465
+ hidden_states = residual + hidden_states
1466
+
1467
+ outputs = (hidden_states,)
1468
+
1469
+ if output_attentions:
1470
+ outputs += (self_attn_weights,)
1471
+
1472
+ if use_cache:
1473
+ outputs += (present_key_value,)
1474
+
1475
+ return outputs
1476
+
1477
+
1478
+ DeepseekV3_START_DOCSTRING = r"""
1479
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1480
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1481
+ etc.)
1482
+
1483
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1484
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1485
+ and behavior.
1486
+
1487
+ Parameters:
1488
+ config ([`DeepseekV3Config`]):
1489
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1490
+ load the weights associated with the model, only the configuration. Check out the
1491
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1492
+ """
1493
+
1494
+
1495
+ @add_start_docstrings(
1496
+ "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.",
1497
+ DeepseekV3_START_DOCSTRING,
1498
+ )
1499
+ class DeepseekV3PreTrainedModel(PreTrainedModel):
1500
+ config_class = DeepseekV3Config
1501
+ base_model_prefix = "model"
1502
+ supports_gradient_checkpointing = True
1503
+ _no_split_modules = ["DeepseekV3DecoderLayer"]
1504
+ _skip_keys_device_placement = "past_key_values"
1505
+ _supports_flash_attn_2 = True
1506
+ _supports_cache_class = True
1507
+
1508
+ def _init_weights(self, module):
1509
+ std = self.config.initializer_range
1510
+ if isinstance(module, nn.Linear):
1511
+ module.weight.data.normal_(mean=0.0, std=std)
1512
+ if module.bias is not None:
1513
+ module.bias.data.zero_()
1514
+ elif isinstance(module, nn.Embedding):
1515
+ module.weight.data.normal_(mean=0.0, std=std)
1516
+ if module.padding_idx is not None:
1517
+ module.weight.data[module.padding_idx].zero_()
1518
+
1519
+
1520
+ DeepseekV3_INPUTS_DOCSTRING = r"""
1521
+ Args:
1522
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1523
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1524
+ it.
1525
+
1526
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1527
+ [`PreTrainedTokenizer.__call__`] for details.
1528
+
1529
+ [What are input IDs?](../glossary#input-ids)
1530
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1531
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1532
+
1533
+ - 1 for tokens that are **not masked**,
1534
+ - 0 for tokens that are **masked**.
1535
+
1536
+ [What are attention masks?](../glossary#attention-mask)
1537
+
1538
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1539
+ [`PreTrainedTokenizer.__call__`] for details.
1540
+
1541
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1542
+ `past_key_values`).
1543
+
1544
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1545
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1546
+ information on the default strategy.
1547
+
1548
+ - 1 indicates the head is **not masked**,
1549
+ - 0 indicates the head is **masked**.
1550
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1551
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1552
+ config.n_positions - 1]`.
1553
+
1554
+ [What are position IDs?](../glossary#position-ids)
1555
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1556
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1557
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1558
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1559
+
1560
+ Two formats are allowed:
1561
+ - a [`~cache_utils.Cache`] instance;
1562
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1563
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1564
+ cache format.
1565
+
1566
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1567
+ legacy cache format will be returned.
1568
+
1569
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1570
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1571
+ of shape `(batch_size, sequence_length)`.
1572
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1573
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1574
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1575
+ model's internal embedding lookup matrix.
1576
+ use_cache (`bool`, *optional*):
1577
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1578
+ `past_key_values`).
1579
+ output_attentions (`bool`, *optional*):
1580
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1581
+ tensors for more detail.
1582
+ output_hidden_states (`bool`, *optional*):
1583
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1584
+ more detail.
1585
+ return_dict (`bool`, *optional*):
1586
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1587
+ """
1588
+
1589
+
1590
+ @add_start_docstrings(
1591
+ "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.",
1592
+ DeepseekV3_START_DOCSTRING,
1593
+ )
1594
+ class DeepseekV3Model(DeepseekV3PreTrainedModel):
1595
+ """
1596
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV3DecoderLayer`]
1597
+
1598
+ Args:
1599
+ config: DeepseekV3Config
1600
+ """
1601
+
1602
+ def __init__(self, config: DeepseekV3Config):
1603
+ super().__init__(config)
1604
+ self.padding_idx = config.pad_token_id
1605
+ self.vocab_size = config.vocab_size
1606
+
1607
+ self.embed_tokens = nn.Embedding(
1608
+ config.vocab_size, config.hidden_size, self.padding_idx
1609
+ )
1610
+ layers = [
1611
+ DeepseekV3DecoderLayer(config, layer_idx)
1612
+ for layer_idx in range(config.num_hidden_layers)
1613
+ ]
1614
+ if USE_MTP:
1615
+ layers.append(DeepseekV3MTP(config, config.num_hidden_layers))
1616
+ self.layers = nn.ModuleList(layers)
1617
+ self._num_hidden_layers = config.num_hidden_layers
1618
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1619
+ self.norm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1620
+
1621
+ self.gradient_checkpointing = False
1622
+ # Initialize weights and apply final processing
1623
+ self.post_init()
1624
+
1625
+ def get_input_embeddings(self):
1626
+ return self.embed_tokens
1627
+
1628
+ def set_input_embeddings(self, value):
1629
+ self.embed_tokens = value
1630
+
1631
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1632
+ def forward(
1633
+ self,
1634
+ input_ids: torch.LongTensor = None,
1635
+ attention_mask: Optional[torch.Tensor] = None,
1636
+ position_ids: Optional[torch.LongTensor] = None,
1637
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1638
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1639
+ use_cache: Optional[bool] = None,
1640
+ output_attentions: Optional[bool] = None,
1641
+ output_hidden_states: Optional[bool] = None,
1642
+ return_dict: Optional[bool] = None,
1643
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1644
+ output_attentions = (
1645
+ output_attentions
1646
+ if output_attentions is not None
1647
+ else self.config.output_attentions
1648
+ )
1649
+ output_hidden_states = (
1650
+ output_hidden_states
1651
+ if output_hidden_states is not None
1652
+ else self.config.output_hidden_states
1653
+ )
1654
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1655
+
1656
+ return_dict = (
1657
+ return_dict if return_dict is not None else self.config.use_return_dict
1658
+ )
1659
+
1660
+ # retrieve input_ids and inputs_embeds
1661
+ if input_ids is not None and inputs_embeds is not None:
1662
+ raise ValueError(
1663
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1664
+ )
1665
+ elif input_ids is not None:
1666
+ batch_size, seq_length = input_ids.shape[:2]
1667
+ elif inputs_embeds is not None:
1668
+ batch_size, seq_length = inputs_embeds.shape[:2]
1669
+ else:
1670
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1671
+
1672
+ past_key_values_length = 0
1673
+ if use_cache:
1674
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1675
+ if use_legacy_cache:
1676
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1677
+ past_key_values_length = past_key_values.get_seq_length()
1678
+
1679
+ if position_ids is None:
1680
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1681
+ position_ids = torch.arange(
1682
+ past_key_values_length,
1683
+ seq_length + past_key_values_length,
1684
+ dtype=torch.long,
1685
+ device=device,
1686
+ )
1687
+ position_ids = position_ids.unsqueeze(0)
1688
+
1689
+ if inputs_embeds is None:
1690
+ inputs_embeds = self.embed_tokens(input_ids)
1691
+
1692
+ if self._use_flash_attention_2:
1693
+ # 2d mask is passed through the layers
1694
+ attention_mask = (
1695
+ attention_mask
1696
+ if (attention_mask is not None and 0 in attention_mask)
1697
+ else None
1698
+ )
1699
+ else:
1700
+ # 4d mask is passed through the layers
1701
+ attention_mask = _prepare_4d_causal_attention_mask(
1702
+ attention_mask,
1703
+ (batch_size, seq_length),
1704
+ inputs_embeds,
1705
+ past_key_values_length,
1706
+ )
1707
+
1708
+ # embed positions
1709
+ hidden_states = inputs_embeds
1710
+
1711
+ # decoder layers
1712
+ all_hidden_states = () if output_hidden_states else None
1713
+ all_self_attns = () if output_attentions else None
1714
+ next_decoder_cache = None
1715
+
1716
+ for decoder_layer in self.layers[:self._num_hidden_layers]:
1717
+ if output_hidden_states:
1718
+ all_hidden_states += (hidden_states,)
1719
+
1720
+ layer_outputs = decoder_layer(
1721
+ hidden_states,
1722
+ attention_mask=attention_mask,
1723
+ position_ids=position_ids,
1724
+ past_key_value=past_key_values,
1725
+ output_attentions=output_attentions,
1726
+ use_cache=use_cache,
1727
+ )
1728
+
1729
+ hidden_states = layer_outputs[0]
1730
+
1731
+ if use_cache:
1732
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1733
+
1734
+ if output_attentions:
1735
+ all_self_attns += (layer_outputs[1],)
1736
+
1737
+ if USE_MTP:
1738
+ mtp_layer = self.layers[self._num_hidden_layers]
1739
+ mtp_outputs = mtp_layer(
1740
+ hidden_states,
1741
+ attention_mask=attention_mask,
1742
+ position_ids=position_ids,
1743
+ past_key_value=past_key_values,
1744
+ output_attentions=output_attentions,
1745
+ use_cache=use_cache,
1746
+ input_ids=input_ids,
1747
+ )
1748
+ if use_cache: next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1749
+
1750
+ hidden_states = self.norm(hidden_states)
1751
+
1752
+ # add hidden states from the last decoder layer
1753
+ if output_hidden_states:
1754
+ all_hidden_states += (hidden_states,)
1755
+
1756
+ next_cache = None
1757
+ if use_cache:
1758
+ next_cache = (
1759
+ next_decoder_cache.to_legacy_cache()
1760
+ if use_legacy_cache
1761
+ else next_decoder_cache
1762
+ )
1763
+ if not return_dict:
1764
+ return tuple(
1765
+ v
1766
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1767
+ if v is not None
1768
+ )
1769
+ return BaseModelOutputWithPast(
1770
+ last_hidden_state=hidden_states,
1771
+ past_key_values=next_cache,
1772
+ hidden_states=all_hidden_states,
1773
+ attentions=all_self_attns,
1774
+ )
1775
+
1776
+
1777
+ class DeepseekV3ForCausalLM(DeepseekV3PreTrainedModel):
1778
+ _tied_weights_keys = ["lm_head.weight"]
1779
+
1780
+ def __init__(self, config):
1781
+ super().__init__(config)
1782
+ self.model = DeepseekV3Model(config)
1783
+ self.vocab_size = config.vocab_size
1784
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1785
+
1786
+ # Initialize weights and apply final processing
1787
+ self.post_init()
1788
+
1789
+ def get_input_embeddings(self):
1790
+ return self.model.embed_tokens
1791
+
1792
+ def set_input_embeddings(self, value):
1793
+ self.model.embed_tokens = value
1794
+
1795
+ def get_output_embeddings(self):
1796
+ return self.lm_head
1797
+
1798
+ def set_output_embeddings(self, new_embeddings):
1799
+ self.lm_head = new_embeddings
1800
+
1801
+ def set_decoder(self, decoder):
1802
+ self.model = decoder
1803
+
1804
+ def get_decoder(self):
1805
+ return self.model
1806
+
1807
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1808
+ @replace_return_docstrings(
1809
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1810
+ )
1811
+ def forward(
1812
+ self,
1813
+ input_ids: torch.LongTensor = None,
1814
+ attention_mask: Optional[torch.Tensor] = None,
1815
+ position_ids: Optional[torch.LongTensor] = None,
1816
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1817
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1818
+ labels: Optional[torch.LongTensor] = None,
1819
+ use_cache: Optional[bool] = None,
1820
+ output_attentions: Optional[bool] = None,
1821
+ output_hidden_states: Optional[bool] = None,
1822
+ return_dict: Optional[bool] = None,
1823
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1824
+ r"""
1825
+ Args:
1826
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1827
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1828
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1829
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1830
+
1831
+ Returns:
1832
+
1833
+ Example:
1834
+
1835
+ ```python
1836
+ >>> from transformers import AutoTokenizer, DeepseekV3ForCausalLM
1837
+
1838
+ >>> model = DeepseekV3ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1839
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1840
+
1841
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1842
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1843
+
1844
+ >>> # Generate
1845
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1846
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1847
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1848
+ ```"""
1849
+ output_attentions = (
1850
+ output_attentions
1851
+ if output_attentions is not None
1852
+ else self.config.output_attentions
1853
+ )
1854
+ output_hidden_states = (
1855
+ output_hidden_states
1856
+ if output_hidden_states is not None
1857
+ else self.config.output_hidden_states
1858
+ )
1859
+ return_dict = (
1860
+ return_dict if return_dict is not None else self.config.use_return_dict
1861
+ )
1862
+
1863
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1864
+ outputs = self.model(
1865
+ input_ids=input_ids,
1866
+ attention_mask=attention_mask,
1867
+ position_ids=position_ids,
1868
+ past_key_values=past_key_values,
1869
+ inputs_embeds=inputs_embeds,
1870
+ use_cache=use_cache,
1871
+ output_attentions=output_attentions,
1872
+ output_hidden_states=output_hidden_states,
1873
+ return_dict=return_dict,
1874
+ )
1875
+
1876
+ hidden_states = outputs[0]
1877
+
1878
+ if USE_MTP:
1879
+ logits = hidden_states
1880
+ else:
1881
+ logits = self.lm_head(hidden_states)
1882
+ logits = logits.float()
1883
+
1884
+ loss = None
1885
+ if labels is not None:
1886
+ # Shift so that tokens < n predict n
1887
+ shift_logits = logits[..., :-1, :].contiguous()
1888
+ shift_labels = labels[..., 1:].contiguous()
1889
+ # Flatten the tokens
1890
+ loss_fct = CrossEntropyLoss()
1891
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1892
+ shift_labels = shift_labels.view(-1)
1893
+ # Enable model parallelism
1894
+ shift_labels = shift_labels.to(shift_logits.device)
1895
+ loss = loss_fct(shift_logits, shift_labels)
1896
+
1897
+ if not return_dict:
1898
+ output = (logits,) + outputs[1:]
1899
+ return (loss,) + output if loss is not None else output
1900
+
1901
+ return CausalLMOutputWithPast(
1902
+ loss=loss,
1903
+ logits=logits,
1904
+ past_key_values=outputs.past_key_values,
1905
+ hidden_states=outputs.hidden_states,
1906
+ attentions=outputs.attentions,
1907
+ )
1908
+
1909
+ def prepare_inputs_for_generation(
1910
+ self,
1911
+ input_ids,
1912
+ past_key_values=None,
1913
+ attention_mask=None,
1914
+ inputs_embeds=None,
1915
+ **kwargs,
1916
+ ):
1917
+ if past_key_values is not None:
1918
+ if isinstance(past_key_values, Cache):
1919
+ cache_length = past_key_values.get_seq_length()
1920
+ past_length = past_key_values.seen_tokens
1921
+ max_cache_length = past_key_values.get_max_cache_shape()
1922
+ else:
1923
+ cache_length = past_length = past_key_values[0][0].shape[2]
1924
+ max_cache_length = None
1925
+
1926
+ # Keep only the unprocessed tokens:
1927
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1928
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1929
+ # input)
1930
+ if (
1931
+ attention_mask is not None
1932
+ and attention_mask.shape[1] > input_ids.shape[1]
1933
+ ):
1934
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1935
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1936
+ # input_ids based on the past_length.
1937
+ elif past_length < input_ids.shape[1]:
1938
+ input_ids = input_ids[:, past_length:]
1939
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1940
+
1941
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1942
+ if (
1943
+ max_cache_length is not None
1944
+ and attention_mask is not None
1945
+ and cache_length + input_ids.shape[1] > max_cache_length
1946
+ ):
1947
+ attention_mask = attention_mask[:, -max_cache_length:]
1948
+
1949
+ position_ids = kwargs.get("position_ids", None)
1950
+ if attention_mask is not None and position_ids is None:
1951
+ # create position_ids on the fly for batch generation
1952
+ position_ids = attention_mask.long().cumsum(-1) - 1
1953
+ position_ids.masked_fill_(attention_mask == 0, 1)
1954
+ if past_key_values:
1955
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1956
+
1957
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1958
+ if inputs_embeds is not None and past_key_values is None:
1959
+ model_inputs = {"inputs_embeds": inputs_embeds}
1960
+ else:
1961
+ model_inputs = {"input_ids": input_ids}
1962
+
1963
+ model_inputs.update(
1964
+ {
1965
+ "position_ids": position_ids,
1966
+ "past_key_values": past_key_values,
1967
+ "use_cache": kwargs.get("use_cache"),
1968
+ "attention_mask": attention_mask,
1969
+ }
1970
+ )
1971
+ return model_inputs
1972
+
1973
+ @staticmethod
1974
+ def _reorder_cache(past_key_values, beam_idx):
1975
+ reordered_past = ()
1976
+ for layer_past in past_key_values:
1977
+ reordered_past += (
1978
+ tuple(
1979
+ past_state.index_select(0, beam_idx.to(past_state.device))
1980
+ for past_state in layer_past
1981
+ ),
1982
+ )
1983
+ return reordered_past
1984
+
1985
+
1986
+ @add_start_docstrings(
1987
+ """
1988
+ The DeepseekV3 Model transformer with a sequence classification head on top (linear layer).
1989
+
1990
+ [`DeepseekV3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1991
+ (e.g. GPT-2) do.
1992
+
1993
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1994
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1995
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1996
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1997
+ each row of the batch).
1998
+ """,
1999
+ DeepseekV3_START_DOCSTRING,
2000
+ )
2001
+ class DeepseekV3ForSequenceClassification(DeepseekV3PreTrainedModel):
2002
+ def __init__(self, config):
2003
+ super().__init__(config)
2004
+ self.num_labels = config.num_labels
2005
+ self.model = DeepseekV3Model(config)
2006
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
2007
+
2008
+ # Initialize weights and apply final processing
2009
+ self.post_init()
2010
+
2011
+ def get_input_embeddings(self):
2012
+ return self.model.embed_tokens
2013
+
2014
+ def set_input_embeddings(self, value):
2015
+ self.model.embed_tokens = value
2016
+
2017
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
2018
+ def forward(
2019
+ self,
2020
+ input_ids: torch.LongTensor = None,
2021
+ attention_mask: Optional[torch.Tensor] = None,
2022
+ position_ids: Optional[torch.LongTensor] = None,
2023
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
2024
+ inputs_embeds: Optional[torch.FloatTensor] = None,
2025
+ labels: Optional[torch.LongTensor] = None,
2026
+ use_cache: Optional[bool] = None,
2027
+ output_attentions: Optional[bool] = None,
2028
+ output_hidden_states: Optional[bool] = None,
2029
+ return_dict: Optional[bool] = None,
2030
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
2031
+ r"""
2032
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
2033
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
2034
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
2035
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
2036
+ """
2037
+ return_dict = (
2038
+ return_dict if return_dict is not None else self.config.use_return_dict
2039
+ )
2040
+
2041
+ transformer_outputs = self.model(
2042
+ input_ids,
2043
+ attention_mask=attention_mask,
2044
+ position_ids=position_ids,
2045
+ past_key_values=past_key_values,
2046
+ inputs_embeds=inputs_embeds,
2047
+ use_cache=use_cache,
2048
+ output_attentions=output_attentions,
2049
+ output_hidden_states=output_hidden_states,
2050
+ return_dict=return_dict,
2051
+ )
2052
+ hidden_states = transformer_outputs[0]
2053
+ logits = self.score(hidden_states)
2054
+
2055
+ if input_ids is not None:
2056
+ batch_size = input_ids.shape[0]
2057
+ else:
2058
+ batch_size = inputs_embeds.shape[0]
2059
+
2060
+ if self.config.pad_token_id is None and batch_size != 1:
2061
+ raise ValueError(
2062
+ "Cannot handle batch sizes > 1 if no padding token is defined."
2063
+ )
2064
+ if self.config.pad_token_id is None:
2065
+ sequence_lengths = -1
2066
+ else:
2067
+ if input_ids is not None:
2068
+ sequence_lengths = (
2069
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
2070
+ ).to(logits.device)
2071
+ else:
2072
+ sequence_lengths = -1
2073
+
2074
+ pooled_logits = logits[
2075
+ torch.arange(batch_size, device=logits.device), sequence_lengths
2076
+ ]
2077
+
2078
+ loss = None
2079
+ if labels is not None:
2080
+ labels = labels.to(logits.device)
2081
+ if self.config.problem_type is None:
2082
+ if self.num_labels == 1:
2083
+ self.config.problem_type = "regression"
2084
+ elif self.num_labels > 1 and (
2085
+ labels.dtype == torch.long or labels.dtype == torch.int
2086
+ ):
2087
+ self.config.problem_type = "single_label_classification"
2088
+ else:
2089
+ self.config.problem_type = "multi_label_classification"
2090
+
2091
+ if self.config.problem_type == "regression":
2092
+ loss_fct = MSELoss()
2093
+ if self.num_labels == 1:
2094
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
2095
+ else:
2096
+ loss = loss_fct(pooled_logits, labels)
2097
+ elif self.config.problem_type == "single_label_classification":
2098
+ loss_fct = CrossEntropyLoss()
2099
+ loss = loss_fct(
2100
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
2101
+ )
2102
+ elif self.config.problem_type == "multi_label_classification":
2103
+ loss_fct = BCEWithLogitsLoss()
2104
+ loss = loss_fct(pooled_logits, labels)
2105
+ if not return_dict:
2106
+ output = (pooled_logits,) + transformer_outputs[1:]
2107
+ return ((loss,) + output) if loss is not None else output
2108
+
2109
+ return SequenceClassifierOutputWithPast(
2110
+ loss=loss,
2111
+ logits=pooled_logits,
2112
+ past_key_values=transformer_outputs.past_key_values,
2113
+ hidden_states=transformer_outputs.hidden_states,
2114
+ attentions=transformer_outputs.attentions,
2115
+ )
2116
+
2117
+
2118
+ class DeepseekV3MTP(DeepseekV3DecoderLayer):
2119
+ """
2120
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV3DecoderLayer`]
2121
+
2122
+ Args:
2123
+ config: DeepseekV3Config
2124
+ """
2125
+
2126
+ def __init__(self, config: DeepseekV3Config, layer_idx: int):
2127
+ super().__init__(config, layer_idx)
2128
+ self.padding_idx = config.pad_token_id
2129
+ self.vocab_size = config.vocab_size
2130
+
2131
+ self.embed_tokens = nn.Embedding(
2132
+ config.vocab_size, config.hidden_size, self.padding_idx
2133
+ )
2134
+
2135
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
2136
+ self.enorm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
2137
+ self.hnorm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
2138
+
2139
+ self.eh_proj = nn.Linear(config.hidden_size * 2, config.hidden_size, bias=False)
2140
+
2141
+ self.shared_head = DeepseekV3Head(config)
2142
+
2143
+ def get_input_embeddings(self):
2144
+ return self.embed_tokens
2145
+
2146
+ def set_input_embeddings(self, value):
2147
+ self.embed_tokens = value
2148
+
2149
+ def forward(
2150
+ self,
2151
+ hidden_states: torch.Tensor,
2152
+ input_ids: torch.Tensor,
2153
+ attention_mask: Optional[torch.Tensor] = None,
2154
+ position_ids: Optional[torch.LongTensor] = None,
2155
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
2156
+ output_attentions: Optional[bool] = False,
2157
+ use_cache: Optional[bool] = False,
2158
+ **kwargs,
2159
+ ) -> Tuple[
2160
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
2161
+ ]:
2162
+ """
2163
+ Args:
2164
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
2165
+ attention_mask (`torch.FloatTensor`, *optional*):
2166
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
2167
+ query_sequence_length, key_sequence_length)` if default attention is used.
2168
+ output_attentions (`bool`, *optional*):
2169
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
2170
+ returned tensors for more detail.
2171
+ use_cache (`bool`, *optional*):
2172
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
2173
+ (see `past_key_values`).
2174
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
2175
+ """
2176
+ if "padding_mask" in kwargs:
2177
+ warnings.warn(
2178
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
2179
+ )
2180
+
2181
+ # Pre MTP
2182
+ # embed positions
2183
+ new_embeds = self.embed_tokens(input_ids)
2184
+ new_embeds = self.enorm(new_embeds)
2185
+ inputs_embeds = self.hnorm(hidden_states)
2186
+ eh_states = torch.concat([new_embeds, inputs_embeds], dim=-1)
2187
+ hidden_states = self.eh_proj(eh_states)
2188
+
2189
+ # Transformer block
2190
+ residual = hidden_states
2191
+
2192
+ hidden_states = self.input_layernorm(hidden_states)
2193
+
2194
+ # Self Attention
2195
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
2196
+ hidden_states=hidden_states,
2197
+ attention_mask=attention_mask,
2198
+ position_ids=position_ids,
2199
+ past_key_value=past_key_value,
2200
+ output_attentions=output_attentions,
2201
+ use_cache=use_cache,
2202
+ **kwargs,
2203
+ )
2204
+ hidden_states = residual + hidden_states
2205
+
2206
+ # Fully Connected
2207
+ residual = hidden_states
2208
+ hidden_states = self.post_attention_layernorm(hidden_states)
2209
+ hidden_states = self.mlp(hidden_states)
2210
+ hidden_states = residual + hidden_states
2211
+
2212
+ outputs = (hidden_states,)
2213
+
2214
+ if output_attentions:
2215
+ outputs += (self_attn_weights,)
2216
+
2217
+ if use_cache:
2218
+ outputs += (present_key_value,)
2219
+
2220
+ return outputs
2221
+
2222
+
2223
+ class DeepseekV3Head(nn.Module):
2224
+ def __init__(self, config: DeepseekV3Config):
2225
+ super().__init__()
2226
+ self.hidden_size = config.hidden_size
2227
+
2228
+ self.norm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
2229
+ self.head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
2230
+
2231
+ def forward(
2232
+ self,
2233
+ hidden_states: torch.Tensor,
2234
+ ) -> torch.FloatTensor:
2235
+ """
2236
+ Args:
2237
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
2238
+ attention_mask (`torch.FloatTensor`, *optional*):
2239
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
2240
+ query_sequence_length, key_sequence_length)` if default attention is used.
2241
+ output_attentions (`bool`, *optional*):
2242
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
2243
+ returned tensors for more detail.
2244
+ use_cache (`bool`, *optional*):
2245
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
2246
+ (see `past_key_values`).
2247
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
2248
+ """
2249
+ hidden_states = self.norm(hidden_states)
2250
+ logits = self.head(hidden_states)
2251
+ logits = logits.float()
2252
+
2253
+ return logits
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|begin▁of▁sentence|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|end▁of▁sentence|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|end▁of▁sentence|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
The diff for this file is too large to render. See raw diff