Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +2 -0
- LICENSE +27 -0
- README.md +224 -0
- THIRD_PARTY_NOTICES.md +47 -0
- chat_template.jinja +46 -0
- config.json +73 -0
- configuration_deepseek.py +212 -0
- docs/deploy_guidance.md +196 -0
- docs/tool_call_guidance.md +258 -0
- figures/Base-Evaluation.png +3 -0
- figures/banner.png +3 -0
- figures/kimi-logo.png +0 -0
- generation_config.json +4 -0
- model-00001-of-000062.safetensors +3 -0
- model-00002-of-000062.safetensors +3 -0
- model-00003-of-000062.safetensors +3 -0
- model-00004-of-000062.safetensors +3 -0
- model-00005-of-000062.safetensors +3 -0
- model-00006-of-000062.safetensors +3 -0
- model-00007-of-000062.safetensors +3 -0
- model-00008-of-000062.safetensors +3 -0
- model-00009-of-000062.safetensors +3 -0
- model-00010-of-000062.safetensors +3 -0
- model-00011-of-000062.safetensors +3 -0
- model-00012-of-000062.safetensors +3 -0
- model-00013-of-000062.safetensors +3 -0
- model-00014-of-000062.safetensors +3 -0
- model-00015-of-000062.safetensors +3 -0
- model-00016-of-000062.safetensors +3 -0
- model-00017-of-000062.safetensors +3 -0
- model-00018-of-000062.safetensors +3 -0
- model-00019-of-000062.safetensors +3 -0
- model-00020-of-000062.safetensors +3 -0
- model-00021-of-000062.safetensors +3 -0
- model-00022-of-000062.safetensors +3 -0
- model-00023-of-000062.safetensors +3 -0
- model-00024-of-000062.safetensors +3 -0
- model-00025-of-000062.safetensors +3 -0
- model-00026-of-000062.safetensors +3 -0
- model-00027-of-000062.safetensors +3 -0
- model-00028-of-000062.safetensors +3 -0
- model-00029-of-000062.safetensors +3 -0
- model-00030-of-000062.safetensors +3 -0
- model-00031-of-000062.safetensors +3 -0
- model-00032-of-000062.safetensors +3 -0
- model-00033-of-000062.safetensors +3 -0
- model-00034-of-000062.safetensors +3 -0
- model-00035-of-000062.safetensors +3 -0
- model-00036-of-000062.safetensors +3 -0
- model-00037-of-000062.safetensors +3 -0
.gitattributes
CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
model.safetensors.index.json filter=lfs diff=lfs merge=lfs -text
|
37 |
+
figures/*.png filter=lfs diff=lfs merge=lfs -text
|
LICENSE
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Modified MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2025 Moonshot AI
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the “Software”), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
22 |
+
|
23 |
+
Our only modification part is that, if the Software (or any derivative works
|
24 |
+
thereof) is used for any of your commercial products or services that have
|
25 |
+
more than 100 million monthly active users, or more than 20 million US dollars
|
26 |
+
(or equivalent in other currencies) in monthly revenue, you shall prominently
|
27 |
+
display "Kimi K2" on the user interface of such product or service.
|
README.md
ADDED
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
tags:
|
3 |
+
- unsloth
|
4 |
+
base_model:
|
5 |
+
- moonshotai/Kimi-K2-Instruct-0905
|
6 |
+
license: other
|
7 |
+
license_name: modified-mit
|
8 |
+
library_name: transformers
|
9 |
+
---
|
10 |
+
<div align="center">
|
11 |
+
<picture>
|
12 |
+
<img src="figures/kimi-logo.png" width="30%" alt="Kimi K2: Open Agentic Intellignece">
|
13 |
+
</picture>
|
14 |
+
</div>
|
15 |
+
<hr>
|
16 |
+
|
17 |
+
<div align="center" style="line-height:1">
|
18 |
+
<a href="https://www.kimi.com" target="_blank"><img alt="Chat" src="https://img.shields.io/badge/🤖%20Chat-Kimi%20K2-ff6b6b?color=1783ff&logoColor=white"/></a>
|
19 |
+
<a href="https://github.com/moonshotai/Kimi-K2"><img alt="github" src="https://img.shields.io/badge/🤖%20Github-Kimi%20K2-ff6b6b?color=1783ff&logoColor=white"/></a>
|
20 |
+
<a href="https://www.moonshot.ai" target="_blank"><img alt="Homepage" src="https://img.shields.io/badge/Homepage-Moonshot%20AI-white?logo=Kimi&logoColor=white"/></a>
|
21 |
+
</div>
|
22 |
+
|
23 |
+
<div align="center" style="line-height: 1;">
|
24 |
+
<a href="https://huggingface.co/moonshotai" target="_blank"><img alt="Hugging Face" src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Moonshot%20AI-ffc107?color=ffc107&logoColor=white"/></a>
|
25 |
+
<a href="https://twitter.com/kimi_moonshot" target="_blank"><img alt="Twitter Follow" src="https://img.shields.io/badge/Twitter-Kimi.ai-white?logo=x&logoColor=white"/></a>
|
26 |
+
<a href="https://discord.gg/TYU2fdJykW" target="_blank"><img alt="Discord" src="https://img.shields.io/badge/Discord-Kimi.ai-white?logo=discord&logoColor=white"/></a>
|
27 |
+
</div>
|
28 |
+
<div align="center" style="line-height: 1;">
|
29 |
+
<a href="https://huggingface.co/moonshotai/Kimi-K2-Instruct-0905/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/badge/License-Modified_MIT-f5de53?&color=f5de53"/></a>
|
30 |
+
</div>
|
31 |
+
|
32 |
+
<p align="center">
|
33 |
+
<b>📰 <a href="https://moonshotai.github.io/Kimi-K2/">Tech Blog</a></b> | <b>📄 <a href="https://github.com/MoonshotAI/Kimi-K2/blob/main/tech_report.pdf">Paper</a></b>
|
34 |
+
</p>
|
35 |
+
|
36 |
+
|
37 |
+
## 1. Model Introduction
|
38 |
+
|
39 |
+
Kimi K2-Instruct-0905 is the latest, most capable version of Kimi K2. It is a state-of-the-art mixture-of-experts (MoE) language model, featuring 32 billion activated parameters and a total of 1 trillion parameters.
|
40 |
+
|
41 |
+
### Key Features
|
42 |
+
- Enhanced agentic coding intelligence: Kimi K2-Instruct-0905 demonstrates significant improvements in performance on public benchmarks and real-world coding agent tasks.
|
43 |
+
- Improved frontend coding experience: Kimi K2-Instruct-0905 offers advancements in both the aesthetics and practicality of frontend programming.
|
44 |
+
- Extended context length: Kimi K2-Instruct-0905’s context window has been increased from 128k to 256k tokens, providing better support for long-horizon tasks.
|
45 |
+
|
46 |
+
|
47 |
+
## 2. Model Summary
|
48 |
+
|
49 |
+
<div align="center">
|
50 |
+
|
51 |
+
|
52 |
+
| | |
|
53 |
+
|:---:|:---:|
|
54 |
+
| **Architecture** | Mixture-of-Experts (MoE) |
|
55 |
+
| **Total Parameters** | 1T |
|
56 |
+
| **Activated Parameters** | 32B |
|
57 |
+
| **Number of Layers** (Dense layer included) | 61 |
|
58 |
+
| **Number of Dense Layers** | 1 |
|
59 |
+
| **Attention Hidden Dimension** | 7168 |
|
60 |
+
| **MoE Hidden Dimension** (per Expert) | 2048 |
|
61 |
+
| **Number of Attention Heads** | 64 |
|
62 |
+
| **Number of Experts** | 384 |
|
63 |
+
| **Selected Experts per Token** | 8 |
|
64 |
+
| **Number of Shared Experts** | 1 |
|
65 |
+
| **Vocabulary Size** | 160K |
|
66 |
+
| **Context Length** | 256K |
|
67 |
+
| **Attention Mechanism** | MLA |
|
68 |
+
| **Activation Function** | SwiGLU |
|
69 |
+
</div>
|
70 |
+
|
71 |
+
## 3. Evaluation Results
|
72 |
+
|
73 |
+
| Benchmark | Metric | K2-Instruct-0905 | K2-Instruct-0711 | Qwen3-Coder-480B-A35B-Instruct | GLM-4.5 | DeepSeek-V3.1 | Claude-Sonnet-4 | Claude-Opus-4 |
|
74 |
+
|------------------------|--------|------------------|------------------|--------|--------|--------|-----------------|---------------|
|
75 |
+
| SWE-Bench verified | ACC | 69.2 ± 0.63 | 65.8 | 69.6* | 64.2* | 66.0* | 72.7* | 72.5* |
|
76 |
+
| SWE-Bench Multilingual | ACC | 55.9 ± 0.72 | 47.3 | 54.7* | 52.7 | 54.5* | 53.3* | - |
|
77 |
+
| Multi-SWE-Bench | ACC | 33.5 ± 0.28 | 31.3 | 32.7 | 31.7 | 29.0 | 35.7 | - |
|
78 |
+
| Terminal-Bench | ACC | 44.5 ± 2.03 | 37.5 | 37.5* | 39.9* | 31.3* | 36.4* | 43.2* |
|
79 |
+
| SWE-Dev | ACC | 66.6 ± 0.72 | 61.9 | 64.7 | 63.2 | 53.3 | 67.1 | - |
|
80 |
+
|
81 |
+
|
82 |
+
All K2-Instruct-0905 numbers are reported as mean ± std over five independent, full-test-set runs.
|
83 |
+
Before each run we prune the repository so that every Git object unreachable from the target commit disappears; this guarantees the agent sees only the code that would legitimately be available at that point in history.
|
84 |
+
|
85 |
+
Except for Terminal-Bench (Terminus-2), every result was produced with our in-house evaluation harness. The harness is derived from SWE-agent, but we clamp the context windows of the Bash and Edit tools and rewrite the system prompt to match the task semantics. All baseline figures denoted with an asterisk (*) are excerpted directly from their official report or public leaderboard; the remaining metrics were evaluated by us under conditions identical to those used for K2-Instruct-0905.
|
86 |
+
|
87 |
+
For SWE-Dev we go one step further: we overwrite the original repository files and delete any test file that exercises the functions the agent is expected to generate, eliminating any indirect hints about the desired implementation.
|
88 |
+
|
89 |
+
|
90 |
+
## 4. Deployment
|
91 |
+
> [!Note]
|
92 |
+
> You can access Kimi K2's API on https://platform.moonshot.ai , we provide OpenAI/Anthropic-compatible API for you.
|
93 |
+
>
|
94 |
+
> The Anthropic-compatible API maps temperature by `real_temperature = request_temperature * 0.6` for better compatible with existing applications.
|
95 |
+
|
96 |
+
Our model checkpoints are stored in the block-fp8 format, you can find it on [Huggingface](https://huggingface.co/moonshotai/Kimi-K2-Instruct).
|
97 |
+
|
98 |
+
Currently, Kimi-K2 is recommended to run on the following inference engines:
|
99 |
+
|
100 |
+
* vLLM
|
101 |
+
* SGLang
|
102 |
+
* KTransformers
|
103 |
+
* TensorRT-LLM
|
104 |
+
|
105 |
+
Deployment examples for vLLM and SGLang can be found in the [Model Deployment Guide](docs/deploy_guidance.md).
|
106 |
+
|
107 |
+
---
|
108 |
+
|
109 |
+
## 5. Model Usage
|
110 |
+
|
111 |
+
### Chat Completion
|
112 |
+
|
113 |
+
Once the local inference service is up, you can interact with it through the chat endpoint:
|
114 |
+
|
115 |
+
```python
|
116 |
+
def simple_chat(client: OpenAI, model_name: str):
|
117 |
+
messages = [
|
118 |
+
{"role": "system", "content": "You are Kimi, an AI assistant created by Moonshot AI."},
|
119 |
+
{"role": "user", "content": [{"type": "text", "text": "Please give a brief self-introduction."}]},
|
120 |
+
]
|
121 |
+
response = client.chat.completions.create(
|
122 |
+
model=model_name,
|
123 |
+
messages=messages,
|
124 |
+
stream=False,
|
125 |
+
temperature=0.6,
|
126 |
+
max_tokens=256
|
127 |
+
)
|
128 |
+
print(response.choices[0].message.content)
|
129 |
+
```
|
130 |
+
|
131 |
+
> [!NOTE]
|
132 |
+
> The recommended temperature for Kimi-K2-Instruct-0905 is `temperature = 0.6`.
|
133 |
+
> If no special instructions are required, the system prompt above is a good default.
|
134 |
+
|
135 |
+
---
|
136 |
+
|
137 |
+
### Tool Calling
|
138 |
+
|
139 |
+
Kimi-K2-Instruct-0905 has strong tool-calling capabilities.
|
140 |
+
To enable them, you need to pass the list of available tools in each request, then the model will autonomously decide when and how to invoke them.
|
141 |
+
|
142 |
+
The following example demonstrates calling a weather tool end-to-end:
|
143 |
+
|
144 |
+
```python
|
145 |
+
# Your tool implementation
|
146 |
+
def get_weather(city: str) -> dict:
|
147 |
+
return {"weather": "Sunny"}
|
148 |
+
# Tool schema definition
|
149 |
+
tools = [{
|
150 |
+
"type": "function",
|
151 |
+
"function": {
|
152 |
+
"name": "get_weather",
|
153 |
+
"description": "Retrieve current weather information. Call this when the user asks about the weather.",
|
154 |
+
"parameters": {
|
155 |
+
"type": "object",
|
156 |
+
"required": ["city"],
|
157 |
+
"properties": {
|
158 |
+
"city": {
|
159 |
+
"type": "string",
|
160 |
+
"description": "Name of the city"
|
161 |
+
}
|
162 |
+
}
|
163 |
+
}
|
164 |
+
}
|
165 |
+
}]
|
166 |
+
# Map tool names to their implementations
|
167 |
+
tool_map = {
|
168 |
+
"get_weather": get_weather
|
169 |
+
}
|
170 |
+
def tool_call_with_client(client: OpenAI, model_name: str):
|
171 |
+
messages = [
|
172 |
+
{"role": "system", "content": "You are Kimi, an AI assistant created by Moonshot AI."},
|
173 |
+
{"role": "user", "content": "What's the weather like in Beijing today? Use the tool to check."}
|
174 |
+
]
|
175 |
+
finish_reason = None
|
176 |
+
while finish_reason is None or finish_reason == "tool_calls":
|
177 |
+
completion = client.chat.completions.create(
|
178 |
+
model=model_name,
|
179 |
+
messages=messages,
|
180 |
+
temperature=0.6,
|
181 |
+
tools=tools, # tool list defined above
|
182 |
+
tool_choice="auto"
|
183 |
+
)
|
184 |
+
choice = completion.choices[0]
|
185 |
+
finish_reason = choice.finish_reason
|
186 |
+
if finish_reason == "tool_calls":
|
187 |
+
messages.append(choice.message)
|
188 |
+
for tool_call in choice.message.tool_calls:
|
189 |
+
tool_call_name = tool_call.function.name
|
190 |
+
tool_call_arguments = json.loads(tool_call.function.arguments)
|
191 |
+
tool_function = tool_map[tool_call_name]
|
192 |
+
tool_result = tool_function(**tool_call_arguments)
|
193 |
+
print("tool_result:", tool_result)
|
194 |
+
messages.append({
|
195 |
+
"role": "tool",
|
196 |
+
"tool_call_id": tool_call.id,
|
197 |
+
"name": tool_call_name,
|
198 |
+
"content": json.dumps(tool_result)
|
199 |
+
})
|
200 |
+
print("-" * 100)
|
201 |
+
print(choice.message.content)
|
202 |
+
```
|
203 |
+
|
204 |
+
The `tool_call_with_client` function implements the pipeline from user query to tool execution.
|
205 |
+
This pipeline requires the inference engine to support Kimi-K2’s native tool-parsing logic.
|
206 |
+
For more information, see the [Tool Calling Guide](docs/tool_call_guidance.md).
|
207 |
+
|
208 |
+
---
|
209 |
+
|
210 |
+
## 6. License
|
211 |
+
|
212 |
+
Both the code repository and the model weights are released under the [Modified MIT License](LICENSE).
|
213 |
+
|
214 |
+
---
|
215 |
+
|
216 |
+
## 7. Third Party Notices
|
217 |
+
|
218 |
+
See [THIRD PARTY NOTICES](THIRD_PARTY_NOTICES.md)
|
219 |
+
|
220 |
+
---
|
221 |
+
|
222 |
+
## 7. Contact Us
|
223 |
+
|
224 |
+
If you have any questions, please reach out at [[email protected]](mailto:[email protected]).
|
THIRD_PARTY_NOTICES.md
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# THIRD_PARTY_NOTICES
|
2 |
+
|
3 |
+
This file lists third-party software contained in Kimi-K2 along with their licenses, in compliance with the redistribution clauses of those licenses.
|
4 |
+
|
5 |
+
---
|
6 |
+
|
7 |
+
## 1. DeepSeek-V3
|
8 |
+
|
9 |
+
Our model archietecture is DeepSeek-V3-like. Some of modeling codes are copied from the source repository.
|
10 |
+
|
11 |
+
- **Source Repository**
|
12 |
+
https://huggingface.co/deepseek-ai/DeepSeek-V3
|
13 |
+
|
14 |
+
- **Files / Directories Used**
|
15 |
+
- configuration_deepseek.py
|
16 |
+
- modeling_deepseek.py
|
17 |
+
|
18 |
+
- **License Type**
|
19 |
+
MIT License
|
20 |
+
|
21 |
+
- **Copyright Notice**
|
22 |
+
Copyright (c) 2023 DeepSeek
|
23 |
+
|
24 |
+
- **Full License Text**
|
25 |
+
```
|
26 |
+
MIT License
|
27 |
+
|
28 |
+
Copyright (c) 2023 DeepSeek
|
29 |
+
|
30 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
31 |
+
of this software and associated documentation files (the "Software"), to deal
|
32 |
+
in the Software without restriction, including without limitation the rights
|
33 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
34 |
+
copies of the Software, and to permit persons to whom the Software is
|
35 |
+
furnished to do so, subject to the following conditions:
|
36 |
+
|
37 |
+
The above copyright notice and this permission notice shall be included in all
|
38 |
+
copies or substantial portions of the Software.
|
39 |
+
|
40 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
41 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
42 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
43 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
44 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
45 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
46 |
+
SOFTWARE.
|
47 |
+
```
|
chat_template.jinja
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{%- if tools -%}
|
2 |
+
<|im_system|>tool_declare<|im_middle|>
|
3 |
+
# Tools
|
4 |
+
{{ tools | tojson }}<|im_end|>
|
5 |
+
{%- endif -%}
|
6 |
+
{%- for message in messages -%}
|
7 |
+
{%- if loop.first and messages[0]['role'] != 'system' -%}
|
8 |
+
<|im_system|>system<|im_middle|>You are Kimi, an AI assistant created by Moonshot AI.<|im_end|>
|
9 |
+
{%- endif -%}
|
10 |
+
|
11 |
+
{%- set role_name = message.get('name') or message['role'] -%}
|
12 |
+
{%- if message['role'] == 'user' -%}
|
13 |
+
<|im_user|>{{role_name}}<|im_middle|>
|
14 |
+
{%- elif message['role'] == 'assistant' -%}
|
15 |
+
<|im_assistant|>{{role_name}}<|im_middle|>
|
16 |
+
{%- else -%}
|
17 |
+
<|im_system|>{{role_name}}<|im_middle|>
|
18 |
+
{% endif %}
|
19 |
+
|
20 |
+
{%- if message['role'] == 'assistant' and message.get('tool_calls') -%}
|
21 |
+
{%- if message['content'] -%}{{ message['content'] }}{%- endif -%}
|
22 |
+
<|tool_calls_section_begin|>
|
23 |
+
{%- for tool_call in message['tool_calls'] -%}
|
24 |
+
{%- set formatted_id = tool_call['id'] -%}
|
25 |
+
<|tool_call_begin|>{{ formatted_id }}<|tool_call_argument_begin|>{% if tool_call['function']['arguments'] is string %}{{ tool_call['function']['arguments'] }}{% else %}{{ tool_call['function']['arguments'] | tojson }}{% endif %}<|tool_call_end|>
|
26 |
+
{%- endfor -%}
|
27 |
+
<|tool_calls_section_end|>
|
28 |
+
{%- elif message['role'] == 'tool' -%}
|
29 |
+
## Return of {{ message.tool_call_id }}
|
30 |
+
{{ message['content'] }}
|
31 |
+
{%- elif message['content'] is string -%}
|
32 |
+
{{ message['content'] }}
|
33 |
+
{%- elif message['content'] is not none -%}
|
34 |
+
{% for content in message['content'] -%}
|
35 |
+
{% if content['type'] == 'image' or 'image' in content or 'image_url' in content -%}
|
36 |
+
<|media_start|>image<|media_content|><|media_pad|><|media_end|>
|
37 |
+
{% else -%}
|
38 |
+
{{ content['text'] }}
|
39 |
+
{%- endif -%}
|
40 |
+
{%- endfor -%}
|
41 |
+
{%- endif -%}
|
42 |
+
<|im_end|>
|
43 |
+
{%- endfor -%}
|
44 |
+
{%- if add_generation_prompt -%}
|
45 |
+
<|im_assistant|>assistant<|im_middle|>
|
46 |
+
{%- endif -%}
|
config.json
ADDED
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_attn_implementation_autoset": false,
|
3 |
+
"architectures": [
|
4 |
+
"DeepseekV3ForCausalLM"
|
5 |
+
],
|
6 |
+
"attention_bias": false,
|
7 |
+
"attention_dropout": 0.0,
|
8 |
+
"auto_map": {
|
9 |
+
"AutoConfig": "configuration_deepseek.DeepseekV3Config",
|
10 |
+
"AutoModel": "modeling_deepseek.DeepseekV3Model",
|
11 |
+
"AutoModelForCausalLM": "modeling_deepseek.DeepseekV3ForCausalLM"
|
12 |
+
},
|
13 |
+
"aux_loss_alpha": 0.001,
|
14 |
+
"bos_token_id": 163584,
|
15 |
+
"dtype": "bfloat16",
|
16 |
+
"eos_token_id": 163585,
|
17 |
+
"ep_size": 1,
|
18 |
+
"first_k_dense_replace": 1,
|
19 |
+
"hidden_act": "silu",
|
20 |
+
"hidden_size": 7168,
|
21 |
+
"initializer_range": 0.02,
|
22 |
+
"intermediate_size": 18432,
|
23 |
+
"kv_lora_rank": 512,
|
24 |
+
"max_position_embeddings": 262144,
|
25 |
+
"model_type": "deepseek_v3",
|
26 |
+
"moe_intermediate_size": 2048,
|
27 |
+
"moe_layer_freq": 1,
|
28 |
+
"n_group": 1,
|
29 |
+
"n_routed_experts": 384,
|
30 |
+
"n_shared_experts": 1,
|
31 |
+
"norm_topk_prob": true,
|
32 |
+
"num_attention_heads": 64,
|
33 |
+
"num_experts_per_tok": 8,
|
34 |
+
"num_hidden_layers": 61,
|
35 |
+
"num_key_value_heads": 64,
|
36 |
+
"num_nextn_predict_layers": 0,
|
37 |
+
"pad_token_id": 163839,
|
38 |
+
"pretraining_tp": 1,
|
39 |
+
"q_lora_rank": 1536,
|
40 |
+
"qk_nope_head_dim": 128,
|
41 |
+
"qk_rope_head_dim": 64,
|
42 |
+
"quantization_config": {
|
43 |
+
"activation_scheme": "dynamic",
|
44 |
+
"fmt": "e4m3",
|
45 |
+
"quant_method": "fp8",
|
46 |
+
"weight_block_size": [
|
47 |
+
128,
|
48 |
+
128
|
49 |
+
]
|
50 |
+
},
|
51 |
+
"rms_norm_eps": 1e-05,
|
52 |
+
"rope_scaling": {
|
53 |
+
"beta_fast": 1.0,
|
54 |
+
"beta_slow": 1.0,
|
55 |
+
"factor": 64.0,
|
56 |
+
"mscale": 1.0,
|
57 |
+
"mscale_all_dim": 1.0,
|
58 |
+
"original_max_position_embeddings": 4096,
|
59 |
+
"type": "yarn"
|
60 |
+
},
|
61 |
+
"rope_theta": 50000.0,
|
62 |
+
"routed_scaling_factor": 2.827,
|
63 |
+
"scoring_func": "sigmoid",
|
64 |
+
"seq_aux": true,
|
65 |
+
"tie_word_embeddings": false,
|
66 |
+
"topk_group": 1,
|
67 |
+
"topk_method": "noaux_tc",
|
68 |
+
"transformers_version": "4.56.1",
|
69 |
+
"unsloth_fixed": true,
|
70 |
+
"use_cache": true,
|
71 |
+
"v_head_dim": 128,
|
72 |
+
"vocab_size": 163840
|
73 |
+
}
|
configuration_deepseek.py
ADDED
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copy from https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/configuration_deepseek.py
|
2 |
+
|
3 |
+
from transformers.configuration_utils import PretrainedConfig
|
4 |
+
from transformers.utils import logging
|
5 |
+
|
6 |
+
logger = logging.get_logger(__name__)
|
7 |
+
|
8 |
+
DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
9 |
+
class DeepseekV3Config(PretrainedConfig):
|
10 |
+
r"""
|
11 |
+
This is the configuration class to store the configuration of a [`DeepseekV3Model`]. It is used to instantiate an DeepSeek
|
12 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
13 |
+
defaults will yield a similar configuration to that of the DeepSeek-V3.
|
14 |
+
|
15 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
16 |
+
documentation from [`PretrainedConfig`] for more information.
|
17 |
+
|
18 |
+
|
19 |
+
Args:
|
20 |
+
vocab_size (`int`, *optional*, defaults to 129280):
|
21 |
+
Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
|
22 |
+
`inputs_ids` passed when calling [`DeepseekV3Model`]
|
23 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
24 |
+
Dimension of the hidden representations.
|
25 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
26 |
+
Dimension of the MLP representations.
|
27 |
+
moe_intermediate_size (`int`, *optional*, defaults to 1407):
|
28 |
+
Dimension of the MoE representations.
|
29 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
30 |
+
Number of hidden layers in the Transformer decoder.
|
31 |
+
num_nextn_predict_layers (`int`, *optional*, defaults to 1):
|
32 |
+
Number of nextn predict layers in the DeepSeekV3 Model.
|
33 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
34 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
35 |
+
n_shared_experts (`int`, *optional*, defaults to None):
|
36 |
+
Number of shared experts, None means dense model.
|
37 |
+
n_routed_experts (`int`, *optional*, defaults to None):
|
38 |
+
Number of routed experts, None means dense model.
|
39 |
+
routed_scaling_factor (`float`, *optional*, defaults to 1.0):
|
40 |
+
Scaling factor or routed experts.
|
41 |
+
topk_method (`str`, *optional*, defaults to `gready`):
|
42 |
+
Topk method used in routed gate.
|
43 |
+
n_group (`int`, *optional*, defaults to None):
|
44 |
+
Number of groups for routed experts.
|
45 |
+
topk_group (`int`, *optional*, defaults to None):
|
46 |
+
Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
|
47 |
+
num_experts_per_tok (`int`, *optional*, defaults to None):
|
48 |
+
Number of selected experts, None means dense model.
|
49 |
+
moe_layer_freq (`int`, *optional*, defaults to 1):
|
50 |
+
The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.
|
51 |
+
first_k_dense_replace (`int`, *optional*, defaults to 0):
|
52 |
+
Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
|
53 |
+
\--k dense layers--/
|
54 |
+
norm_topk_prob (`bool`, *optional*, defaults to False):
|
55 |
+
Whether to normalize the weights of the routed experts.
|
56 |
+
scoring_func (`str`, *optional*, defaults to 'softmax'):
|
57 |
+
Method of computing expert weights.
|
58 |
+
aux_loss_alpha (`float`, *optional*, defaults to 0.001):
|
59 |
+
Auxiliary loss weight coefficient.
|
60 |
+
seq_aux = (`bool`, *optional*, defaults to True):
|
61 |
+
Whether to compute the auxiliary loss for each individual sample.
|
62 |
+
num_key_value_heads (`int`, *optional*):
|
63 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
64 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
65 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
66 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
67 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
68 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
69 |
+
`num_attention_heads`.
|
70 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
71 |
+
The non-linear activation function (function or string) in the decoder.
|
72 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
73 |
+
The maximum sequence length that this model might ever be used with.
|
74 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
75 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
76 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
77 |
+
The epsilon used by the rms normalization layers.
|
78 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
79 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
80 |
+
relevant if `config.is_decoder=True`.
|
81 |
+
pad_token_id (`int`, *optional*):
|
82 |
+
Padding token id.
|
83 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
84 |
+
Beginning of stream token id.
|
85 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
86 |
+
End of stream token id.
|
87 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
88 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
89 |
+
document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
|
90 |
+
necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
|
91 |
+
issue](https://github.com/pytorch/pytorch/issues/76232).
|
92 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
93 |
+
Whether to tie weight embeddings
|
94 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
95 |
+
The base period of the RoPE embeddings.
|
96 |
+
rope_scaling (`Dict`, *optional*):
|
97 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
98 |
+
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
|
99 |
+
`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
100 |
+
`max_position_embeddings` to the expected new maximum.
|
101 |
+
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
102 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
103 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
104 |
+
The dropout ratio for the attention probabilities.
|
105 |
+
|
106 |
+
```python
|
107 |
+
>>> from transformers import DeepseekV3Model, DeepseekV3Config
|
108 |
+
|
109 |
+
>>> # Initializing a Deepseek-V3 style configuration
|
110 |
+
>>> configuration = DeepseekV3Config()
|
111 |
+
|
112 |
+
>>> # Accessing the model configuration
|
113 |
+
>>> configuration = model.config
|
114 |
+
```"""
|
115 |
+
|
116 |
+
model_type = "deepseek_v3"
|
117 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
118 |
+
|
119 |
+
def __init__(
|
120 |
+
self,
|
121 |
+
vocab_size=129280,
|
122 |
+
hidden_size=7168,
|
123 |
+
intermediate_size=18432,
|
124 |
+
moe_intermediate_size = 2048,
|
125 |
+
num_hidden_layers=61,
|
126 |
+
num_nextn_predict_layers=1,
|
127 |
+
num_attention_heads=128,
|
128 |
+
num_key_value_heads=128,
|
129 |
+
n_shared_experts = 1,
|
130 |
+
n_routed_experts = 256,
|
131 |
+
ep_size = 1,
|
132 |
+
routed_scaling_factor = 2.5,
|
133 |
+
kv_lora_rank = 512,
|
134 |
+
q_lora_rank = 1536,
|
135 |
+
qk_rope_head_dim = 64,
|
136 |
+
v_head_dim = 128,
|
137 |
+
qk_nope_head_dim = 128,
|
138 |
+
topk_method = 'noaux_tc',
|
139 |
+
n_group = 8,
|
140 |
+
topk_group = 4,
|
141 |
+
num_experts_per_tok = 8,
|
142 |
+
moe_layer_freq = 1,
|
143 |
+
first_k_dense_replace = 3,
|
144 |
+
norm_topk_prob = True,
|
145 |
+
scoring_func = 'sigmoid',
|
146 |
+
aux_loss_alpha = 0.001,
|
147 |
+
seq_aux = True,
|
148 |
+
hidden_act="silu",
|
149 |
+
max_position_embeddings=4096,
|
150 |
+
initializer_range=0.02,
|
151 |
+
rms_norm_eps=1e-6,
|
152 |
+
use_cache=True,
|
153 |
+
pad_token_id=None,
|
154 |
+
bos_token_id=0,
|
155 |
+
eos_token_id=1,
|
156 |
+
pretraining_tp=1,
|
157 |
+
tie_word_embeddings=False,
|
158 |
+
rope_theta=10000.0,
|
159 |
+
rope_scaling=None,
|
160 |
+
attention_bias=False,
|
161 |
+
attention_dropout=0.0,
|
162 |
+
**kwargs,
|
163 |
+
):
|
164 |
+
self.vocab_size = vocab_size
|
165 |
+
self.max_position_embeddings = max_position_embeddings
|
166 |
+
self.hidden_size = hidden_size
|
167 |
+
self.intermediate_size = intermediate_size
|
168 |
+
self.moe_intermediate_size = moe_intermediate_size
|
169 |
+
self.num_hidden_layers = num_hidden_layers
|
170 |
+
self.num_nextn_predict_layers = num_nextn_predict_layers
|
171 |
+
self.num_attention_heads = num_attention_heads
|
172 |
+
self.n_shared_experts = n_shared_experts
|
173 |
+
self.n_routed_experts = n_routed_experts
|
174 |
+
self.ep_size = ep_size
|
175 |
+
self.routed_scaling_factor = routed_scaling_factor
|
176 |
+
self.kv_lora_rank = kv_lora_rank
|
177 |
+
self.q_lora_rank = q_lora_rank
|
178 |
+
self.qk_rope_head_dim = qk_rope_head_dim
|
179 |
+
self.v_head_dim = v_head_dim
|
180 |
+
self.qk_nope_head_dim = qk_nope_head_dim
|
181 |
+
self.topk_method = topk_method
|
182 |
+
self.n_group = n_group
|
183 |
+
self.topk_group = topk_group
|
184 |
+
self.num_experts_per_tok = num_experts_per_tok
|
185 |
+
self.moe_layer_freq = moe_layer_freq
|
186 |
+
self.first_k_dense_replace = first_k_dense_replace
|
187 |
+
self.norm_topk_prob = norm_topk_prob
|
188 |
+
self.scoring_func = scoring_func
|
189 |
+
self.aux_loss_alpha = aux_loss_alpha
|
190 |
+
self.seq_aux = seq_aux
|
191 |
+
# for backward compatibility
|
192 |
+
if num_key_value_heads is None:
|
193 |
+
num_key_value_heads = num_attention_heads
|
194 |
+
|
195 |
+
self.num_key_value_heads = num_key_value_heads
|
196 |
+
self.hidden_act = hidden_act
|
197 |
+
self.initializer_range = initializer_range
|
198 |
+
self.rms_norm_eps = rms_norm_eps
|
199 |
+
self.pretraining_tp = pretraining_tp
|
200 |
+
self.use_cache = use_cache
|
201 |
+
self.rope_theta = rope_theta
|
202 |
+
self.rope_scaling = rope_scaling
|
203 |
+
self.attention_bias = attention_bias
|
204 |
+
self.attention_dropout = attention_dropout
|
205 |
+
|
206 |
+
super().__init__(
|
207 |
+
pad_token_id=pad_token_id,
|
208 |
+
bos_token_id=bos_token_id,
|
209 |
+
eos_token_id=eos_token_id,
|
210 |
+
tie_word_embeddings=tie_word_embeddings,
|
211 |
+
**kwargs,
|
212 |
+
)
|
docs/deploy_guidance.md
ADDED
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Kimi-K2 Deployment Guide
|
2 |
+
|
3 |
+
> [!Note]
|
4 |
+
> This guide only provides some examples of deployment commands for Kimi-K2, which may not be the optimal configuration. Since inference engines are still being updated frequenty, please continue to follow the guidance from their homepage if you want to achieve better inference performance.
|
5 |
+
|
6 |
+
|
7 |
+
## vLLM Deployment
|
8 |
+
|
9 |
+
The smallest deployment unit for Kimi-K2 FP8 weights with 256k seqlen on mainstream H200 platform is a cluster with 16 GPUs with either Tensor Parallel (TP) or "data parallel + expert parallel" (DP+EP).
|
10 |
+
Running parameters for this environment are provided below. You may scale up to more nodes and increase expert-parallelism to enlarge the inference batch size and overall throughput.
|
11 |
+
|
12 |
+
### Tensor Parallelism
|
13 |
+
|
14 |
+
When the parallelism degree ≤ 16, you can run inference with pure Tensor Parallelism. A sample launch command is:
|
15 |
+
|
16 |
+
``` bash
|
17 |
+
# start ray on node 0 and node 1
|
18 |
+
|
19 |
+
# node 0:
|
20 |
+
vllm serve $MODEL_PATH \
|
21 |
+
--port 8000 \
|
22 |
+
--served-model-name kimi-k2 \
|
23 |
+
--trust-remote-code \
|
24 |
+
--tensor-parallel-size 16 \
|
25 |
+
--enable-auto-tool-choice \
|
26 |
+
--tool-call-parser kimi_k2
|
27 |
+
```
|
28 |
+
|
29 |
+
**Key parameter notes:**
|
30 |
+
- `--tensor-parallel-size 16`: If using more than 16 GPUs, combine with pipeline-parallelism.
|
31 |
+
- `--enable-auto-tool-choice`: Required when enabling tool usage.
|
32 |
+
- `--tool-call-parser kimi_k2`: Required when enabling tool usage.
|
33 |
+
|
34 |
+
### Data Parallelism + Expert Parallelism
|
35 |
+
|
36 |
+
You can install libraries like DeepEP and DeepGEMM as needed. Then run the command (example on H200):
|
37 |
+
|
38 |
+
``` bash
|
39 |
+
# node 0
|
40 |
+
vllm serve $MODEL_PATH --port 8000 --served-model-name kimi-k2 --trust-remote-code --data-parallel-size 16 --data-parallel-size-local 8 --data-parallel-address $MASTER_IP --data-parallel-rpc-port $PORT --enable-expert-parallel --max-num-batched-tokens 8192 --max-num-seqs 256 --gpu-memory-utilization 0.85 --enable-auto-tool-choice --tool-call-parser kimi_k2
|
41 |
+
|
42 |
+
# node 1
|
43 |
+
vllm serve $MODEL_PATH --headless --data-parallel-start-rank 8 --port 8000 --served-model-name kimi-k2 --trust-remote-code --data-parallel-size 16 --data-parallel-size-local 8 --data-parallel-address $MASTER_IP --data-parallel-rpc-port $PORT --enable-expert-parallel --max-num-batched-tokens 8192 --max-num-seqs 256 --gpu-memory-utilization 0.85 --enable-auto-tool-choice --tool-call-parser kimi_k2
|
44 |
+
```
|
45 |
+
|
46 |
+
## SGLang Deployment
|
47 |
+
|
48 |
+
Similarly, we can use TP or DP+EP in SGLang for Deployment, here are the examples.
|
49 |
+
|
50 |
+
|
51 |
+
### Tensor Parallelism
|
52 |
+
|
53 |
+
Here is the simple example code to run TP16 with two nodes on H200:
|
54 |
+
|
55 |
+
``` bash
|
56 |
+
# Node 0
|
57 |
+
python -m sglang.launch_server --model-path $MODEL_PATH --tp 16 --dist-init-addr $MASTER_IP:50000 --nnodes 2 --node-rank 0 --trust-remote-code --tool-call-parser kimi_k2
|
58 |
+
|
59 |
+
# Node 1
|
60 |
+
python -m sglang.launch_server --model-path $MODEL_PATH --tp 16 --dist-init-addr $MASTER_IP:50000 --nnodes 2 --node-rank 1 --trust-remote-code --tool-call-parser kimi_k2
|
61 |
+
```
|
62 |
+
|
63 |
+
**Key parameter notes:**
|
64 |
+
- `--tool-call-parser kimi_k2`: Required when enabling tool usage.
|
65 |
+
|
66 |
+
### Data Parallelism + Expert Parallelism
|
67 |
+
|
68 |
+
Here is an example for large scale Prefill-Decode Disaggregation (4P12D H200) with DP+EP in SGLang:
|
69 |
+
|
70 |
+
``` bash
|
71 |
+
# for prefill node
|
72 |
+
MC_TE_METRIC=true SGLANG_DISAGGREGATION_HEARTBEAT_INTERVAL=10000000 SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=100000 SGLANG_DISAGGREGATION_WAITING_TIMEOUT=100000 PYTHONUNBUFFERED=1 \
|
73 |
+
python -m sglang.launch_server --model-path $MODEL_PATH \
|
74 |
+
--trust-remote-code --disaggregation-mode prefill --dist-init-addr $PREFILL_NODE0$:5757 --tp-size 32 --dp-size 32 --enable-dp-attention --host $LOCAL_IP --decode-log-interval 1 --disable-radix-cache --enable-deepep-moe --moe-dense-tp-size 1 --enable-dp-lm-head --disable-shared-experts-fusion --watchdog-timeout 1000000 --enable-two-batch-overlap --disaggregation-ib-device $IB_DEVICE --chunked-prefill-size 262144 --mem-fraction-static 0.85 --deepep-mode normal --ep-dispatch-algorithm dynamic --eplb-algorithm deepseek --max-running-requests 1024 --nnodes 4 --node-rank $RANK --tool-call-parser kimi_k2
|
75 |
+
|
76 |
+
|
77 |
+
# for decode node
|
78 |
+
SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=480 MC_TE_METRIC=true SGLANG_DISAGGREGATION_HEARTBEAT_INTERVAL=10000000 SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=100000 SGLANG_DISAGGREGATION_WAITING_TIMEOUT=100000 PYTHONUNBUFFERED=1 \
|
79 |
+
python -m sglang.launch_server --model-path $MODEL_PATH --trust-remote-code --disaggregation-mode decode --dist-init-addr $DECODE_NODE0:5757 --tp-size 96 --dp-size 96 --enable-dp-attention --host $LOCAL_IP --decode-log-interval 1 --context-length 2176 --disable-radix-cache --enable-deepep-moe --moe-dense-tp-size 1 --enable-dp-lm-head --disable-shared-experts-fusion --watchdog-timeout 1000000 --enable-two-batch-overlap --disaggregation-ib-device $IB_DEVICE --deepep-mode low_latency --mem-fraction-static 0.8 --cuda-graph-bs 480 --max-running-requests 46080 --ep-num-redundant-experts 96 --nnodes 12 --node-rank $RANK --tool-call-parser kimi_k2
|
80 |
+
|
81 |
+
# pdlb
|
82 |
+
PYTHONUNBUFFERED=1 python -m sglang.srt.disaggregation.launch_lb --prefill http://${PREFILL_NODE0}:30000 --decode http://${DECODE_NODE0}:30000
|
83 |
+
```
|
84 |
+
|
85 |
+
## KTransformers Deployment
|
86 |
+
|
87 |
+
Please copy all configuration files (i.e., everything except the .safetensors files) into the GGUF checkpoint folder at /path/to/K2. Then run:
|
88 |
+
``` bash
|
89 |
+
python ktransformers/server/main.py --model_path /path/to/K2 --gguf_path /path/to/K2 --cache_lens 30000
|
90 |
+
```
|
91 |
+
|
92 |
+
To enable AMX optimization, run:
|
93 |
+
|
94 |
+
``` bash
|
95 |
+
python ktransformers/server/main.py --model_path /path/to/K2 --gguf_path /path/to/K2 --cache_lens 30000 --optimize_config_path ktransformers/optimize/optimize_rules/DeepSeek-V3-Chat-fp8-linear-ggml-experts-serve-amx.yaml
|
96 |
+
```
|
97 |
+
|
98 |
+
## TensoRT-LLM Deployment
|
99 |
+
### Prerequisite
|
100 |
+
Please refer to [this guide](https://nvidia.github.io/TensorRT-LLM/installation/build-from-source-linux.html) to build TensorRT-LLM v1.0.0-rc2 from source and start a TRT-LLM docker container.
|
101 |
+
|
102 |
+
install blobfile by:
|
103 |
+
```bash
|
104 |
+
pip install blobfile
|
105 |
+
```
|
106 |
+
### Multi-node Serving
|
107 |
+
TensorRT-LLM supports multi-node inference. You can use mpirun to launch Kimi-K2 with multi-node jobs. We will use two nodes for this example.
|
108 |
+
|
109 |
+
#### mpirun
|
110 |
+
mpirun requires each node to have passwordless ssh access to the other node. We need to setup the environment inside the docker container. Run the container with host network and mount the current directory as well as model directory to the container.
|
111 |
+
|
112 |
+
```bash
|
113 |
+
# use host network
|
114 |
+
IMAGE=<YOUR_IMAGE>
|
115 |
+
NAME=test_2node_docker
|
116 |
+
# host1
|
117 |
+
docker run -it --name ${NAME}_host1 --ipc=host --gpus=all --network host --privileged --ulimit memlock=-1 --ulimit stack=67108864 -v ${PWD}:/workspace -v <YOUR_MODEL_DIR>:/models/DeepSeek-V3 -w /workspace ${IMAGE}
|
118 |
+
# host2
|
119 |
+
docker run -it --name ${NAME}_host2 --ipc=host --gpus=all --network host --privileged --ulimit memlock=-1 --ulimit stack=67108864 -v ${PWD}:/workspace -v <YOUR_MODEL_DIR>:/models/DeepSeek-V3 -w /workspace ${IMAGE}
|
120 |
+
```
|
121 |
+
|
122 |
+
Set up ssh inside the container
|
123 |
+
|
124 |
+
```bash
|
125 |
+
apt-get update && apt-get install -y openssh-server
|
126 |
+
|
127 |
+
# modify /etc/ssh/sshd_config
|
128 |
+
PermitRootLogin yes
|
129 |
+
PubkeyAuthentication yes
|
130 |
+
# modify /etc/ssh/sshd_config, change default port 22 to another unused port
|
131 |
+
port 2233
|
132 |
+
|
133 |
+
# modify /etc/ssh
|
134 |
+
```
|
135 |
+
|
136 |
+
Generate ssh key on host1 and copy to host2, vice versa.
|
137 |
+
|
138 |
+
```bash
|
139 |
+
# on host1
|
140 |
+
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519
|
141 |
+
ssh-copy-id -i ~/.ssh/id_ed25519.pub root@<HOST2>
|
142 |
+
# on host2
|
143 |
+
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519
|
144 |
+
ssh-copy-id -i ~/.ssh/id_ed25519.pub root@<HOST1>
|
145 |
+
|
146 |
+
# restart ssh service on host1 and host2
|
147 |
+
service ssh restart # or
|
148 |
+
/etc/init.d/ssh restart # or
|
149 |
+
systemctl restart ssh
|
150 |
+
```
|
151 |
+
|
152 |
+
Generate additional config for trtllm serve.
|
153 |
+
```bash
|
154 |
+
cat >/path/to/TensorRT-LLM/extra-llm-api-config.yml <<EOF
|
155 |
+
cuda_graph_config:
|
156 |
+
padding_enabled: true
|
157 |
+
batch_sizes:
|
158 |
+
- 1
|
159 |
+
- 2
|
160 |
+
- 4
|
161 |
+
- 8
|
162 |
+
- 16
|
163 |
+
- 32
|
164 |
+
- 64
|
165 |
+
- 128
|
166 |
+
print_iter_log: true
|
167 |
+
enable_attention_dp: true
|
168 |
+
EOF
|
169 |
+
```
|
170 |
+
|
171 |
+
|
172 |
+
After the preparations,you can run the trtllm-serve on two nodes using mpirun:
|
173 |
+
|
174 |
+
```bash
|
175 |
+
mpirun -np 16 \
|
176 |
+
-H <HOST1>:8,<HOST2>:8 \
|
177 |
+
-mca plm_rsh_args "-p 2233" \
|
178 |
+
--allow-run-as-root \
|
179 |
+
trtllm-llmapi-launch trtllm-serve serve \
|
180 |
+
--backend pytorch \
|
181 |
+
--tp_size 16 \
|
182 |
+
--ep_size 8 \
|
183 |
+
--kv_cache_free_gpu_memory_fraction 0.95 \
|
184 |
+
--trust_remote_code \
|
185 |
+
--max_batch_size 128 \
|
186 |
+
--max_num_tokens 4096 \
|
187 |
+
--extra_llm_api_options /path/to/TensorRT-LLM/extra-llm-api-config.yml \
|
188 |
+
--port 8000 \
|
189 |
+
<YOUR_MODEL_DIR>
|
190 |
+
```
|
191 |
+
|
192 |
+
## Others
|
193 |
+
|
194 |
+
Kimi-K2 reuses the `DeepSeekV3CausalLM` architecture and convert it's weight into proper shape to save redevelopment effort. To let inference engines distinguish it from DeepSeek-V3 and apply the best optimizations, we set `"model_type": "kimi_k2"` in `config.json`.
|
195 |
+
|
196 |
+
If you are using a framework that is not on the recommended list, you can still run the model by manually changing `model_type` to "deepseek_v3" in `config.json` as a temporary workaround. You may need to manually parse tool calls in case no tool call parser is available in your framework.
|
docs/tool_call_guidance.md
ADDED
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## Tool Calling
|
2 |
+
To enable the tool calling feature, you may need to set certain tool calling parser options when starting the service. See [deploy_guidance](./deploy_guidance.md) for details.
|
3 |
+
In Kimi-K2, a tool calling process includes:
|
4 |
+
- Passing function descriptions to Kimi-K2
|
5 |
+
- Kimi-K2 decides to make a function call and returns the necessary information for the function call to the user
|
6 |
+
- The user performs the function call, collects the call results, and passes the function call results to Kimi-K2
|
7 |
+
- Kimi-K2 continues to generate content based on the function call results until the model believes it has obtained sufficient information to respond to the user
|
8 |
+
|
9 |
+
### Preparing Tools
|
10 |
+
Suppose we have a function `get_weather` that can query the weather conditions in real-time.
|
11 |
+
This function accepts a city name as a parameter and returns the weather conditions. We need to prepare a structured description for it so that Kimi-K2 can understand its functionality.
|
12 |
+
|
13 |
+
```python
|
14 |
+
def get_weather(city):
|
15 |
+
return {"weather": "Sunny"}
|
16 |
+
|
17 |
+
# Collect the tool descriptions in tools
|
18 |
+
tools = [{
|
19 |
+
"type": "function",
|
20 |
+
"function": {
|
21 |
+
"name": "get_weather",
|
22 |
+
"description": "Get weather information. Call this tool when the user needs to get weather information",
|
23 |
+
"parameters": {
|
24 |
+
"type": "object",
|
25 |
+
"required": ["city"],
|
26 |
+
"properties": {
|
27 |
+
"city": {
|
28 |
+
"type": "string",
|
29 |
+
"description": "City name",
|
30 |
+
}
|
31 |
+
}
|
32 |
+
}
|
33 |
+
}
|
34 |
+
}]
|
35 |
+
|
36 |
+
# Tool name->object mapping for easy calling later
|
37 |
+
tool_map = {
|
38 |
+
"get_weather": get_weather
|
39 |
+
}
|
40 |
+
```
|
41 |
+
### Chat with tools
|
42 |
+
We use `openai.OpenAI` to send messages to Kimi-K2 along with tool descriptions. Kimi-K2 will autonomously decide whether to use and how to use the provided tools.
|
43 |
+
If Kimi-K2 believes a tool call is needed, it will return a result with `finish_reason='tool_calls'`. At this point, the returned result includes the tool call information.
|
44 |
+
After calling tools with the provided information, we then need to append the tool call results to the chat history and continue calling Kimi-K2.
|
45 |
+
Kimi-K2 may need to call tools multiple times until the model believes the current results can answer the user's question. We should check `finish_reason` until it is not `tool_calls`.
|
46 |
+
|
47 |
+
The results obtained by the user after calling the tools should be added to `messages` with `role='tool'`.
|
48 |
+
|
49 |
+
```python
|
50 |
+
import json
|
51 |
+
from openai import OpenAI
|
52 |
+
model_name='moonshotai/Kimi-K2-Instruct'
|
53 |
+
client = OpenAI(base_url=endpoint,
|
54 |
+
api_key='xxx')
|
55 |
+
|
56 |
+
messages = [
|
57 |
+
{"role": "user", "content": "What's the weather like in Beijing today? Let's check using the tool."}
|
58 |
+
]
|
59 |
+
finish_reason = None
|
60 |
+
while finish_reason is None or finish_reason == "tool_calls":
|
61 |
+
completion = client.chat.completions.create(
|
62 |
+
model=model_name,
|
63 |
+
messages=messages,
|
64 |
+
temperature=0.3,
|
65 |
+
tools=tools,
|
66 |
+
tool_choice="auto",
|
67 |
+
)
|
68 |
+
choice = completion.choices[0]
|
69 |
+
finish_reason = choice.finish_reason
|
70 |
+
# Note: The finish_reason when tool calls end may vary across different engines, so this condition check needs to be adjusted accordingly
|
71 |
+
if finish_reason == "tool_calls":
|
72 |
+
messages.append(choice.message)
|
73 |
+
for tool_call in choice.message.tool_calls:
|
74 |
+
tool_call_name = tool_call.function.name
|
75 |
+
tool_call_arguments = json.loads(tool_call.function.arguments)
|
76 |
+
tool_function = tool_map[tool_call_name]
|
77 |
+
tool_result = tool_function(tool_call_arguments)
|
78 |
+
print("tool_result", tool_result)
|
79 |
+
|
80 |
+
messages.append({
|
81 |
+
"role": "tool",
|
82 |
+
"tool_call_id": tool_call.id,
|
83 |
+
"name": tool_call_name,
|
84 |
+
"content": json.dumps(tool_result),
|
85 |
+
})
|
86 |
+
print('-' * 100)
|
87 |
+
print(choice.message.content)
|
88 |
+
```
|
89 |
+
### Tool Calling in Streaming Mode
|
90 |
+
Tool calling can also be used in streaming mode. In this case, we need to collect the tool call information returned in the stream until we have a complete tool call. Please refer to the code below:
|
91 |
+
|
92 |
+
```python
|
93 |
+
messages = [
|
94 |
+
{"role": "user", "content": "What's the weather like in Beijing today? Let's check using the tool."}
|
95 |
+
]
|
96 |
+
finish_reason = None
|
97 |
+
msg = ''
|
98 |
+
while finish_reason is None or finish_reason == "tool_calls":
|
99 |
+
completion = client.chat.completions.create(
|
100 |
+
model=model_name,
|
101 |
+
messages=messages,
|
102 |
+
temperature=0.3,
|
103 |
+
tools=tools,
|
104 |
+
tool_choice="auto",
|
105 |
+
stream=True
|
106 |
+
)
|
107 |
+
tool_calls = []
|
108 |
+
for chunk in completion:
|
109 |
+
delta = chunk.choices[0].delta
|
110 |
+
if delta.content:
|
111 |
+
msg += delta.content
|
112 |
+
if delta.tool_calls:
|
113 |
+
for tool_call_chunk in delta.tool_calls:
|
114 |
+
if tool_call_chunk.index is not None:
|
115 |
+
# Extend the tool_calls list
|
116 |
+
while len(tool_calls) <= tool_call_chunk.index:
|
117 |
+
tool_calls.append({
|
118 |
+
"id": "",
|
119 |
+
"type": "function",
|
120 |
+
"function": {
|
121 |
+
"name": "",
|
122 |
+
"arguments": ""
|
123 |
+
}
|
124 |
+
})
|
125 |
+
|
126 |
+
tc = tool_calls[tool_call_chunk.index]
|
127 |
+
|
128 |
+
if tool_call_chunk.id:
|
129 |
+
tc["id"] += tool_call_chunk.id
|
130 |
+
if tool_call_chunk.function.name:
|
131 |
+
tc["function"]["name"] += tool_call_chunk.function.name
|
132 |
+
if tool_call_chunk.function.arguments:
|
133 |
+
tc["function"]["arguments"] += tool_call_chunk.function.arguments
|
134 |
+
|
135 |
+
finish_reason = chunk.choices[0].finish_reason
|
136 |
+
# Note: The finish_reason when tool calls end may vary across different engines, so this condition check needs to be adjusted accordingly
|
137 |
+
if finish_reason == "tool_calls":
|
138 |
+
for tool_call in tool_calls:
|
139 |
+
tool_call_name = tool_call['function']['name']
|
140 |
+
tool_call_arguments = json.loads(tool_call['function']['arguments'])
|
141 |
+
tool_function = tool_map[tool_call_name]
|
142 |
+
tool_result = tool_function(tool_call_arguments)
|
143 |
+
messages.append({
|
144 |
+
"role": "tool",
|
145 |
+
"tool_call_id": tool_call['id'],
|
146 |
+
"name": tool_call_name,
|
147 |
+
"content": json.dumps(tool_result),
|
148 |
+
})
|
149 |
+
# The text generated by the tool call is not the final version, reset msg
|
150 |
+
msg = ''
|
151 |
+
|
152 |
+
print(msg)
|
153 |
+
```
|
154 |
+
### Manually Parsing Tool Calls
|
155 |
+
The tool call requests generated by Kimi-K2 can also be parsed manually, which is especially useful when the service you are using does not provide a tool-call parser.
|
156 |
+
The tool call requests generated by Kimi-K2 are wrapped by `<|tool_calls_section_begin|>` and `<|tool_calls_section_end|>`,
|
157 |
+
with each tool call wrapped by `<|tool_call_begin|>` and `<|tool_call_end|>`. The tool ID and arguments are separated by `<|tool_call_argument_begin|>`.
|
158 |
+
The format of the tool ID is `functions.{func_name}:{idx}`, from which we can parse the function name.
|
159 |
+
|
160 |
+
Based on the above rules, we can directly post request to the completions interface and manually parse tool calls.
|
161 |
+
|
162 |
+
```python
|
163 |
+
import requests
|
164 |
+
from transformers import AutoTokenizer
|
165 |
+
messages = [
|
166 |
+
{"role": "user", "content": "What's the weather like in Beijing today? Let's check using the tool."}
|
167 |
+
]
|
168 |
+
msg = ''
|
169 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
170 |
+
while True:
|
171 |
+
text = tokenizer.apply_chat_template(
|
172 |
+
messages,
|
173 |
+
tokenize=False,
|
174 |
+
tools=tools,
|
175 |
+
add_generation_prompt=True,
|
176 |
+
)
|
177 |
+
payload = {
|
178 |
+
"model": model_name,
|
179 |
+
"prompt": text,
|
180 |
+
"max_tokens": 512
|
181 |
+
}
|
182 |
+
response = requests.post(
|
183 |
+
f"{endpoint}/completions",
|
184 |
+
headers={"Content-Type": "application/json"},
|
185 |
+
json=payload,
|
186 |
+
stream=False,
|
187 |
+
)
|
188 |
+
raw_out = response.json()
|
189 |
+
|
190 |
+
raw_output = raw_out["choices"][0]["text"]
|
191 |
+
tool_calls = extract_tool_call_info(raw_output)
|
192 |
+
if len(tool_calls) == 0:
|
193 |
+
# No tool calls
|
194 |
+
msg = raw_output
|
195 |
+
break
|
196 |
+
else:
|
197 |
+
for tool_call in tool_calls:
|
198 |
+
tool_call_name = tool_call['function']['name']
|
199 |
+
tool_call_arguments = json.loads(tool_call['function']['arguments'])
|
200 |
+
tool_function = tool_map[tool_call_name]
|
201 |
+
tool_result = tool_function(tool_call_arguments)
|
202 |
+
|
203 |
+
messages.append({
|
204 |
+
"role": "tool",
|
205 |
+
"tool_call_id": tool_call['id'],
|
206 |
+
"name": tool_call_name,
|
207 |
+
"content": json.dumps(tool_result),
|
208 |
+
})
|
209 |
+
print('-' * 100)
|
210 |
+
print(msg)
|
211 |
+
```
|
212 |
+
Here, `extract_tool_call_info` parses the model output and returns the model call information. A simple implementation would be:
|
213 |
+
```python
|
214 |
+
def extract_tool_call_info(tool_call_rsp: str):
|
215 |
+
if '<|tool_calls_section_begin|>' not in tool_call_rsp:
|
216 |
+
# No tool calls
|
217 |
+
return []
|
218 |
+
import re
|
219 |
+
pattern = r"<\|tool_calls_section_begin\|>(.*?)<\|tool_calls_section_end\|>"
|
220 |
+
|
221 |
+
tool_calls_sections = re.findall(pattern, tool_call_rsp, re.DOTALL)
|
222 |
+
|
223 |
+
# Extract multiple tool calls
|
224 |
+
func_call_pattern = r"<\|tool_call_begin\|>\s*(?P<tool_call_id>[\w\.]+:\d+)\s*<\|tool_call_argument_begin\|>\s*(?P<function_arguments>.*?)\s*<\|tool_call_end\|>"
|
225 |
+
tool_calls = []
|
226 |
+
for match in re.findall(func_call_pattern, tool_calls_sections[0], re.DOTALL):
|
227 |
+
function_id, function_args = match
|
228 |
+
# function_id: functions.get_weather:0
|
229 |
+
function_name = function_id.split('.')[1].split(':')[0]
|
230 |
+
tool_calls.append(
|
231 |
+
{
|
232 |
+
"id": function_id,
|
233 |
+
"type": "function",
|
234 |
+
"function": {
|
235 |
+
"name": function_name,
|
236 |
+
"arguments": function_args
|
237 |
+
}
|
238 |
+
}
|
239 |
+
)
|
240 |
+
return tool_calls
|
241 |
+
```
|
242 |
+
|
243 |
+
## FAQ
|
244 |
+
|
245 |
+
#### Q1: I received special tokens like '<|tool_call_begin|>' in the 'content' field instead of a normal tool_call.
|
246 |
+
|
247 |
+
This indicates a tool-call crash, which most often occurs in multi-turn tool-calling scenarios due to incorrect tool-call ID. K2 expects the ID to follow the format `functions.func_name:idx`, where `functions` is a fixed string; `func_name` is the actual function name, like `get_weather`, and `idx` is a global counter that starts at 0 and increments with each function invocation.
|
248 |
+
Please check all tool-call IDs in the message list.
|
249 |
+
|
250 |
+
|
251 |
+
#### Q2: My tool-call ID is incorrect—how can I fix it?
|
252 |
+
|
253 |
+
First, make sure your code and chat template are up to date with the latest version from the Hugging Face repo.
|
254 |
+
If you're using vLLM or SGLang and they are generating random tool-call IDs, upgrade them to the latest release. For other frameworks, you must either parse the tool-call ID from the model output and set it correctly in the server-side response, or rewrite every tool-call ID according to the rules above on the client side before sending the messages to Kimi K2.
|
255 |
+
|
256 |
+
#### Q3: My tool call id is correct, but I still get crashed in multiturn tool call.
|
257 |
+
|
258 |
+
Please describe your situation in the [discussion](https://huggingface.co/moonshotai/Kimi-K2-Instruct-0905/discussions)
|
figures/Base-Evaluation.png
ADDED
![]() |
Git LFS Details
|
figures/banner.png
ADDED
![]() |
Git LFS Details
|
figures/kimi-logo.png
ADDED
![]() |
generation_config.json
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"max_length": 131072,
|
3 |
+
"eos_token_id": 163586
|
4 |
+
}
|
model-00001-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:217d3bff3b5c828640ad1de9a40edf408dd1834776136929b04d37365601b73d
|
3 |
+
size 497640784
|
model-00002-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8c143999508effc326c9d752f83a5f10c40d688fe779613047c68934aca1df65
|
3 |
+
size 17066593248
|
model-00003-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:fcb55ad4f225af2c0cf5e2266ee30410bd3ae1a13476cb4bb70b2d629e22dac7
|
3 |
+
size 17066593248
|
model-00004-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:76d350c0af2de2c10b37281e4e49bab364c5d6c77c0b17189b2c18cd4ac94225
|
3 |
+
size 17066593248
|
model-00005-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8b097587a9d0961131e94f239b831018732c3e63fe03e309ed55f55400f1f261
|
3 |
+
size 17066593248
|
model-00006-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:db196c7434b6793fd787bcd00b8c53b18ae6735bb2ebf69022ab93532042d75a
|
3 |
+
size 17066593248
|
model-00007-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5055892e2d9358cd889ae8910840366a2cd058e1434c0d85305c97c538362679
|
3 |
+
size 17066593248
|
model-00008-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cc371efa5ae4a270468f862beb7cb5d9cca21c491cf5c010d28de850436593b1
|
3 |
+
size 17066593248
|
model-00009-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:42ebfd6fb5b4994ea60f660686062b0a4e2da41ed1edd39039c520c81fe1ef08
|
3 |
+
size 17066593248
|
model-00010-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f789cea036fdaa064c566a3027cf2b5e4332b0d428ba8e9af39642c7ac93371f
|
3 |
+
size 17066593248
|
model-00011-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1bf145f988fff9c4c91af9de9cac6cc0eed1cb8fd577e8d9f8c0d333fa57f3bb
|
3 |
+
size 17066595576
|
model-00012-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:31a3939d7e13df4e8bd28580a8335d5af547af00ab8e55d574080aa55ae1ad58
|
3 |
+
size 17066595576
|
model-00013-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:24f7c4b1461818e25e22d98fdd3176ffe6736774e63a87c500b69165d8c5250d
|
3 |
+
size 17066595576
|
model-00014-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e602cbb4338287e1469a585b1da9fc278f089e3d2b6173fb163998bf391d806a
|
3 |
+
size 17066595576
|
model-00015-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a4bfe5f51ad5bdf0f8abae77d0bf98f59219a8a07ae4c2418def41f09407431e
|
3 |
+
size 17066595576
|
model-00016-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d04ba1def02c9857fe358a13429ebb327481fedf61bda2dc39b715ad14f6c912
|
3 |
+
size 17066595576
|
model-00017-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f387d123138de726d5a3b9510de92226b434a35afdd0d8d747d816d046d09fa7
|
3 |
+
size 17066595576
|
model-00018-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0c389fbc1650abae269608878cfc4e09cc14f6a15a197b48d74a554dddab2276
|
3 |
+
size 17066595576
|
model-00019-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cab4d08df217d0f9a83b7de9817b87f4814fe64aaeceae5f53033a40c6b79c09
|
3 |
+
size 17066595576
|
model-00020-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c5adc605f9d1674663c47af61343f53310cc7b1eb3f73d67518402ee0ccac9f4
|
3 |
+
size 17066595576
|
model-00021-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ae7cdc14f29a12b93bb372877d014c032d847534b689ab0e24ec8ade265b3c09
|
3 |
+
size 17066595576
|
model-00022-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b9af68304e86fece5f3421ae0f95dedaa371823806758c62ef528871f1037e58
|
3 |
+
size 17066595576
|
model-00023-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:64d8d1ba10b31078a117cac1697d45022902c3625fe335b914c6212c6e9373f3
|
3 |
+
size 17066595576
|
model-00024-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0c91513b45c21cb11ddc05aadf6b6771624f9dc1e90ec9331fddaeeadbc50b0b
|
3 |
+
size 17066595576
|
model-00025-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8ea0ac8f0f58ac86481fd62f273b31b4873653f21081ebfe0baf474a68eb4bba
|
3 |
+
size 17066595576
|
model-00026-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1666ce470ea6fd6007e053cf335025ec72c7f9fd3e9db5a08af7f592220ef574
|
3 |
+
size 17066595576
|
model-00027-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8517bb3ec651877dafe7999721fe04cb592f1d6ab6e5843d84d35f9abc9c83e4
|
3 |
+
size 17066595576
|
model-00028-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:63c06645a51acc82a20f2f0f4d38678301f81ffce798aafec8bbc778a4128ad2
|
3 |
+
size 17066595576
|
model-00029-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6e1657d88bf04aee3306446487130d248cfbf3ab462fa8cd92dc37da15212e1e
|
3 |
+
size 17066595576
|
model-00030-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9a7dbfdc95cf3ced5295061d4e6cf1e0b91ee158db0053d70b436e448959a056
|
3 |
+
size 17066595576
|
model-00031-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:de3a7d60f9431f8dfa8dcd18571eca968720bf3a0dc7aa6a3a02febbb0b0f270
|
3 |
+
size 17066595576
|
model-00032-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a086a12e3bf0468ca7cf92216fc4bf0602655a9abd127df6619b4dea2187f8fd
|
3 |
+
size 17066595576
|
model-00033-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:6e84ce6c39c0ad3761cac4ee40d524d589fa3c74c58a8893338b5591eefcfeb7
|
3 |
+
size 17066595576
|
model-00034-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:95dd148b2911c845974db92fe943c56751cc02063225fb0096515873dfc42dce
|
3 |
+
size 17066595576
|
model-00035-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f28ccbcd75552d66ed742952df491549e6e07ef726727926b7dd4d51205331f7
|
3 |
+
size 17066595576
|
model-00036-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1e2033181f88960c6f1af48f5fb7f8909add510c395db0a01aadd1eb2b9789ba
|
3 |
+
size 17066595576
|
model-00037-of-000062.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e083612acfa1bbd74aa667b0ccbe27b67b52d1b3ba13f1c7fb11838143295234
|
3 |
+
size 17066595576
|