Mariouhhh bigmoyan commited on
Commit
f3f9097
·
0 Parent(s):

Duplicate from moonshotai/Kimi-K3.1-Pro

Browse files

Co-authored-by: moyanwang <bigmoyan@users.noreply.huggingface.co>

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +36 -0
  2. LICENSE +52 -0
  3. README.md +705 -0
  4. assets/kimi-logo.png +0 -0
  5. config.json +330 -0
  6. configuration_kimi_k3.py +277 -0
  7. encoding_k3.py +735 -0
  8. generation_config.json +4 -0
  9. kimi_k3_processor.py +187 -0
  10. kimi_k3_vision_processing.py +179 -0
  11. media_utils.py +376 -0
  12. model-00001-of-000096.safetensors +3 -0
  13. model-00002-of-000096.safetensors +3 -0
  14. model-00003-of-000096.safetensors +3 -0
  15. model-00004-of-000096.safetensors +3 -0
  16. model-00005-of-000096.safetensors +3 -0
  17. model-00006-of-000096.safetensors +3 -0
  18. model-00007-of-000096.safetensors +3 -0
  19. model-00008-of-000096.safetensors +3 -0
  20. model-00009-of-000096.safetensors +3 -0
  21. model-00010-of-000096.safetensors +3 -0
  22. model-00011-of-000096.safetensors +3 -0
  23. model-00012-of-000096.safetensors +3 -0
  24. model-00013-of-000096.safetensors +3 -0
  25. model-00014-of-000096.safetensors +3 -0
  26. model-00015-of-000096.safetensors +3 -0
  27. model-00016-of-000096.safetensors +3 -0
  28. model-00017-of-000096.safetensors +3 -0
  29. model-00018-of-000096.safetensors +3 -0
  30. model-00019-of-000096.safetensors +3 -0
  31. model-00020-of-000096.safetensors +3 -0
  32. model-00021-of-000096.safetensors +3 -0
  33. model-00022-of-000096.safetensors +3 -0
  34. model-00023-of-000096.safetensors +3 -0
  35. model-00024-of-000096.safetensors +3 -0
  36. model-00025-of-000096.safetensors +3 -0
  37. model-00026-of-000096.safetensors +3 -0
  38. model-00027-of-000096.safetensors +3 -0
  39. model-00028-of-000096.safetensors +3 -0
  40. model-00029-of-000096.safetensors +3 -0
  41. model-00030-of-000096.safetensors +3 -0
  42. model-00031-of-000096.safetensors +3 -0
  43. model-00032-of-000096.safetensors +3 -0
  44. model-00033-of-000096.safetensors +3 -0
  45. model-00034-of-000096.safetensors +3 -0
  46. model-00035-of-000096.safetensors +3 -0
  47. model-00036-of-000096.safetensors +3 -0
  48. model-00037-of-000096.safetensors +3 -0
  49. model-00038-of-000096.safetensors +3 -0
  50. model-00039-of-000096.safetensors +3 -0
.gitattributes ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
36
+ model.safetensors.index.json filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Kimi K3.1-Pro License
2
+
3
+ Copyright (c) 2026 Moonshot AI
4
+
5
+ Permission is hereby granted, free of charge, to any person (the "Licensee")
6
+ obtaining a copy of this software — including the model weights, parameters,
7
+ configuration files, inference and training code, and associated documentation
8
+ (collectively, the "Software") — to deal in the Software without restriction.
9
+ This includes, without limitation, the rights to use, copy, modify, merge,
10
+ publish, distribute, sublicense, and/or sell copies of the Software; to run,
11
+ deploy, fine-tune, or otherwise modify the Software and create derivative works
12
+ from it; and to permit persons to whom the Software is furnished to do so, in
13
+ each case subject to the following conditions:
14
+
15
+ 1. The above copyright notice and this permission notice shall be included in
16
+ all copies or substantial portions of the Software. Licensee's use of the
17
+ Software must comply with applicable laws and regulations.
18
+
19
+ 2. "Model as a Service" means giving a third party access to language model
20
+ inference or fine-tuning (e.g., via API) in a manner that allows such third
21
+ party to exercise meaningful control over the inputs, parameters, or training
22
+ data. This does not include (a) end-user products with model capabilities solely
23
+ embedded within specific features or harnesses, or (b) mere relaying of requests
24
+ to models hosted by others.
25
+
26
+ If the Licensee or any of its affiliates operates a Model as a Service business,
27
+ and the aggregate revenue of the Licensee and its affiliates exceeds 20 million
28
+ US dollars (or the equivalent in other currencies) in total over any consecutive
29
+ 12 months, the Licensee must enter into a separate agreement with Moonshot AI
30
+ before using the Software or its derivative works for any commercial purpose.
31
+
32
+ 3. If the Software (or any derivative works thereof) is used for any of the
33
+ Licensee's commercial products or services that have more than 100 million
34
+ monthly active users, or more than 20 million US dollars (or equivalent in other
35
+ currencies) in monthly revenue, "Kimi K3.1-Pro" must be prominently displayed on the
36
+ user interface of such product or service.
37
+
38
+ 4. The requirements set forth in Sections 2 and 3 do not apply to: (a) internal
39
+ use of the Software, defined as any use that does not make the Software, its
40
+ outputs, or its underlying capabilities available to third parties; or (b) any
41
+ use of the Software accessed through Moonshot AI's official products or
42
+ certified inference partners.
43
+
44
+ 5. THE SOFTWARE AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS”
45
+ BASIS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
46
+ LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
47
+ AND NONINFRINGEMENT. IN NO EVENT SHALL MOONSHOT AI OR ITS AFFILIATES OR
48
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
49
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
50
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
51
+
52
+ For any questions regarding this license, please contact <license@moonshot.ai>.
README.md ADDED
@@ -0,0 +1,705 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - compressed-tensors
4
+ - conversational
5
+ license: other
6
+ license_name: "kimi-k3.1-pro"
7
+ library_name: transformers
8
+ pipeline_tag: image-text-to-text
9
+ ---
10
+
11
+ <div align="center">
12
+ <picture>
13
+ <img src="assets/kimi-logo.png" width="30%" alt="Kimi K3.1 Pro">
14
+ </picture>
15
+ </div>
16
+ <div align="center" style="line-height:1">
17
+ <a href="https://www.kimi.ai" target="_blank"><img alt="Chat" src="https://img.shields.io/badge/Chat-Kimi%20K3.1%20Pro-1783ff"/></a>
18
+ <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>
19
+ </div>
20
+ <div align="center" style="line-height:1">
21
+ <a href="https://huggingface.co/moonshotai" target="_blank"><img alt="Hugging Face" src="https://img.shields.io/badge/Hugging%20Face-Moonshot%20AI-ffc107"/></a>
22
+ <a href="https://twitter.com/kimi_moonshot" target="_blank"><img alt="X" src="https://img.shields.io/badge/X-Kimi.ai-white?logo=x&logoColor=white"/></a>
23
+ <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>
24
+ <a href="https://modelscope.cn/organization/moonshotai" target="_blank"><img alt="ModelScope" src="https://img.shields.io/badge/ModelScope-Moonshot%20AI-white?labelColor=rgb(99%2C%2074%2C%255)"/></a>
25
+ </div>
26
+ <div align="center" style="line-height: 1;">
27
+ <a href="https://huggingface.co/moonshotai/Kimi-K3.1-Pro/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/badge/License-Kimi_K3.1_Pro-f5de53?&color=f5de53"/></a>
28
+ </div>
29
+
30
+ <p align="center">
31
+ 📰&nbsp;&nbsp;<a href="https://www.kimi.ai/blog/kimi-k3-1-pro">Tech Blog</a> | &nbsp;&nbsp;&nbsp; <b>🚀&nbsp;&nbsp;<a href="https://platform.kimi.ai/docs/guide/kimi-k3-1-pro-quickstart">API Quickstart</a></b>
32
+ </p>
33
+
34
+
35
+
36
+ ## 1. Model Introduction
37
+
38
+ Kimi K3.1 Pro is an open-weight, natively multimodal agentic model, and our most capable 3T-class model to date. Post-trained from Kimi K3 with large-scale joint reinforcement learning across hundreds of downstream domains, it is the first model in the K3.1 series. With a 1-million-token context window, Kimi K3.1 Pro delivers substantial improvements in coding, 3D creation, financial research, factual accuracy, and other agentic capabilities.
39
+
40
+ ## 2. Model Summary
41
+
42
+ <div align="center">
43
+ <table>
44
+ <tbody>
45
+ <tr>
46
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Architecture</strong></td>
47
+ <td align="center" style="vertical-align: middle; text-align: center">Mixture-of-Experts (MoE)</td>
48
+ </tr>
49
+ <tr>
50
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Total Parameters</strong></td>
51
+ <td align="center" style="vertical-align: middle; text-align: center">2.8T</td>
52
+ </tr>
53
+ <tr>
54
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Activated Parameters</strong></td>
55
+ <td align="center" style="vertical-align: middle; text-align: center">104B</td>
56
+ </tr>
57
+ <tr>
58
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Number of Layers</strong></td>
59
+ <td align="center" style="vertical-align: middle; text-align: center">93</td>
60
+ </tr>
61
+ <tr>
62
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Number of Dense Layers</strong></td>
63
+ <td align="center" style="vertical-align: middle; text-align: center">1</td>
64
+ </tr>
65
+ <tr>
66
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Attention-Layer Composition</strong></td>
67
+ <td align="center" style="vertical-align: middle; text-align: center">69 KDA + 24 Gated DSA<sup>*</sup></td>
68
+ </tr>
69
+ <tr>
70
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Attention Hidden Dimension</strong></td>
71
+ <td align="center" style="vertical-align: middle; text-align: center">7168</td>
72
+ </tr>
73
+ <tr>
74
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Number of Attention Heads</strong></td>
75
+ <td align="center" style="vertical-align: middle; text-align: center">96</td>
76
+ </tr>
77
+ <tr>
78
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>DSA Index Head Dimension</strong></td>
79
+ <td align="center" style="vertical-align: middle; text-align: center">128</td>
80
+ </tr>
81
+ <tr>
82
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>DSA Index Number of Heads</strong></td>
83
+ <td align="center" style="vertical-align: middle; text-align: center">32</td>
84
+ </tr>
85
+ <tr>
86
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>DSA Index Top-K</strong></td>
87
+ <td align="center" style="vertical-align: middle; text-align: center">2048</td>
88
+ </tr>
89
+ <tr>
90
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Latent MoE Dimension</strong></td>
91
+ <td align="center" style="vertical-align: middle; text-align: center">3584</td>
92
+ </tr>
93
+ <tr>
94
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>MoE Hidden Dimension</strong> (per Expert)</td>
95
+ <td align="center" style="vertical-align: middle; text-align: center">3072</td>
96
+ </tr>
97
+ <tr>
98
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Number of Experts</strong></td>
99
+ <td align="center" style="vertical-align: middle; text-align: center">896</td>
100
+ </tr>
101
+ <tr>
102
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Selected Experts per Token</strong></td>
103
+ <td align="center" style="vertical-align: middle; text-align: center">16</td>
104
+ </tr>
105
+ <tr>
106
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Number of Shared Experts</strong></td>
107
+ <td align="center" style="vertical-align: middle; text-align: center">2</td>
108
+ </tr>
109
+ <tr>
110
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Vocabulary Size</strong></td>
111
+ <td align="center" style="vertical-align: middle; text-align: center">160K</td>
112
+ </tr>
113
+ <tr>
114
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Context Length</strong></td>
115
+ <td align="center" style="vertical-align: middle; text-align: center">1048576</td>
116
+ </tr>
117
+ <tr>
118
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Attention Mechanism</strong></td>
119
+ <td align="center" style="vertical-align: middle; text-align: center">KDA &amp; Gated DSA</td>
120
+ </tr>
121
+ <tr>
122
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Activation Function</strong></td>
123
+ <td align="center" style="vertical-align: middle; text-align: center">SiTU-GLU</td>
124
+ </tr>
125
+ <tr>
126
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Vision Encoder</strong></td>
127
+ <td align="center" style="vertical-align: middle; text-align: center">MoonViT-V2</td>
128
+ </tr>
129
+ <tr>
130
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Parameters of Vision Encoder</strong></td>
131
+ <td align="center" style="vertical-align: middle; text-align: center">401M</td>
132
+ </tr>
133
+ <tr>
134
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Quantization</strong></td>
135
+ <td align="center" style="vertical-align: middle; text-align: center">MXFP4 weights / MXFP8 activations<br>(quantization-aware training)</td>
136
+ </tr>
137
+ <tr>
138
+ <td align="center" style="vertical-align: middle; text-align: center"><strong>Modality</strong></td>
139
+ <td align="center" style="vertical-align: middle; text-align: center">Text, Image</td>
140
+ </tr>
141
+ </tbody>
142
+ </table>
143
+ </div>
144
+
145
+ <p><sup>*</sup> Compared with Kimi K3, we replace the full-attention Gated MLA layers with Gated DeepSeek Sparse Attention (Gated DSA) layers for more efficient long-context modeling.</p>
146
+
147
+ ## 3. Evaluation Results
148
+
149
+ Unless otherwise specified, all Kimi K3.1 Pro results use reasoning effort `max`, `temperature = 1.0`, and `top-p = 0.95`. A dash (`—`) means that the source table does not report a score. Higher scores are better except where the benchmark name explicitly states `lower is better`; Elo scores and other benchmark-specific metrics are not directly comparable with accuracy or pass-rate scores.
150
+
151
+ <div align="center">
152
+ <table>
153
+ <thead>
154
+ <tr>
155
+ <th align="center" style="text-align: center">Benchmark</th>
156
+ <th align="center" style="text-align: center"><sup>Kimi K3.1 Pro<br><sup>(max)</sup></sup></th>
157
+ <th align="center" style="text-align: center"><sup>Claude Fable 5.1<br><sup>(max, w/ fallback)</sup></sup></th>
158
+ <th align="center" style="text-align: center"><sup>GPT-6 Astra<br><sup>(max, w/ fallback)</sup></sup></th>
159
+ <th align="center" style="text-align: center"><sup>Claude Opus 5.5<br><sup>(max, w/ fallback)</sup></sup></th>
160
+ <th align="center" style="text-align: center"><sup>DeepSeek-V4.1-Flash-1017<br><sup>(max)</sup></sup></th>
161
+ <th align="center" style="text-align: center"><sup>GLM-5.3<br><sup>(max)</sup></sup></th>
162
+ </tr>
163
+ </thead>
164
+ <tbody>
165
+ <tr>
166
+ <td align="center" colspan=7 style="text-align: center"><strong>Coding</strong></td>
167
+ </tr>
168
+ <tr>
169
+ <td align="center" style="vertical-align: middle; text-align: center">Terminal-Bench 4.0</td>
170
+ <td align="center" style="vertical-align: middle; text-align: center">65.7</td>
171
+ <td align="center" style="vertical-align: middle; text-align: center">57.9</td>
172
+ <td align="center" style="vertical-align: middle; text-align: center">58.2</td>
173
+ <td align="center" style="vertical-align: middle; text-align: center">66.4</td>
174
+ <td align="center" style="vertical-align: middle; text-align: center">42.3</td>
175
+ <td align="center" style="vertical-align: middle; text-align: center">41.8</td>
176
+ </tr>
177
+ <tr>
178
+ <td align="center" style="vertical-align: middle; text-align: center">Terminal-Bench-Science 0.1</td>
179
+ <td align="center" style="vertical-align: middle; text-align: center">38.1</td>
180
+ <td align="center" style="vertical-align: middle; text-align: center">40.0</td>
181
+ <td align="center" style="vertical-align: middle; text-align: center">68.1</td>
182
+ <td align="center" style="vertical-align: middle; text-align: center">63.3</td>
183
+ <td align="center" style="vertical-align: middle; text-align: center">15.7</td>
184
+ <td align="center" style="vertical-align: middle; text-align: center">8.1</td>
185
+ </tr>
186
+ <tr>
187
+ <td align="center" style="vertical-align: middle; text-align: center">SWE Marathon v1.1</td>
188
+ <td align="center" style="vertical-align: middle; text-align: center">51.7</td>
189
+ <td align="center" style="vertical-align: middle; text-align: center">45.6</td>
190
+ <td align="center" style="vertical-align: middle; text-align: center">42.5</td>
191
+ <td align="center" style="vertical-align: middle; text-align: center">46.3</td>
192
+ <td align="center" style="vertical-align: middle; text-align: center">40.0</td>
193
+ <td align="center" style="vertical-align: middle; text-align: center">42.5</td>
194
+ </tr>
195
+ <tr>
196
+ <td align="center" style="vertical-align: middle; text-align: center">BenchCAD w/o tools</td>
197
+ <td align="center" style="vertical-align: middle; text-align: center">72.8</td>
198
+ <td align="center" style="vertical-align: middle; text-align: center">60.6</td>
199
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
200
+ <td align="center" style="vertical-align: middle; text-align: center">73.0</td>
201
+ <td align="center" style="vertical-align: middle; text-align: center">41.2</td>
202
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
203
+ </tr>
204
+ <tr>
205
+ <td align="center" style="vertical-align: middle; text-align: center">BenchCAD w/ tools</td>
206
+ <td align="center" style="vertical-align: middle; text-align: center">92.7</td>
207
+ <td align="center" style="vertical-align: middle; text-align: center">92.6</td>
208
+ <td align="center" style="vertical-align: middle; text-align: center">95.9</td>
209
+ <td align="center" style="vertical-align: middle; text-align: center">96.2</td>
210
+ <td align="center" style="vertical-align: middle; text-align: center">81.6</td>
211
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
212
+ </tr>
213
+ <tr>
214
+ <td align="center" style="vertical-align: middle; text-align: center">Program Bench</td>
215
+ <td align="center" style="vertical-align: middle; text-align: center">31.5</td>
216
+ <td align="center" style="vertical-align: middle; text-align: center">53.5</td>
217
+ <td align="center" style="vertical-align: middle; text-align: center">50.0</td>
218
+ <td align="center" style="vertical-align: middle; text-align: center">65.0</td>
219
+ <td align="center" style="vertical-align: middle; text-align: center">29.1</td>
220
+ <td align="center" style="vertical-align: middle; text-align: center">19.0</td>
221
+ </tr>
222
+ <tr>
223
+ <td align="center" style="vertical-align: middle; text-align: center">DeepSWE v1.1</td>
224
+ <td align="center" style="vertical-align: middle; text-align: center">75.5</td>
225
+ <td align="center" style="vertical-align: middle; text-align: center">67.4</td>
226
+ <td align="center" style="vertical-align: middle; text-align: center">74.1</td>
227
+ <td align="center" style="vertical-align: middle; text-align: center">74.2</td>
228
+ <td align="center" style="vertical-align: middle; text-align: center">77.0</td>
229
+ <td align="center" style="vertical-align: middle; text-align: center">66.9</td>
230
+ </tr>
231
+ <tr>
232
+ <td align="center" style="vertical-align: middle; text-align: center">PostTrain Bench v1.2</td>
233
+ <td align="center" style="vertical-align: middle; text-align: center">36.5</td>
234
+ <td align="center" style="vertical-align: middle; text-align: center">44.6</td>
235
+ <td align="center" style="vertical-align: middle; text-align: center">41.9</td>
236
+ <td align="center" style="vertical-align: middle; text-align: center">43.8</td>
237
+ <td align="center" style="vertical-align: middle; text-align: center">30.5</td>
238
+ <td align="center" style="vertical-align: middle; text-align: center">34.5</td>
239
+ </tr>
240
+ <tr>
241
+ <td align="center" style="vertical-align: middle; text-align: center">Kimi Code Bench 2.0 (Internal)</td>
242
+ <td align="center" style="vertical-align: middle; text-align: center">77.1</td>
243
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
244
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
245
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
246
+ <td align="center" style="vertical-align: middle; text-align: center">76.1</td>
247
+ <td align="center" style="vertical-align: middle; text-align: center">61.7</td>
248
+ </tr>
249
+ <tr>
250
+ <td align="center" style="vertical-align: middle; text-align: center">Kimi Code Bench 3.0 Long-horizon (Internal)</td>
251
+ <td align="center" style="vertical-align: middle; text-align: center">61.2</td>
252
+ <td align="center" style="vertical-align: middle; text-align: center">58.8</td>
253
+ <td align="center" style="vertical-align: middle; text-align: center">66.5</td>
254
+ <td align="center" style="vertical-align: middle; text-align: center">58.5</td>
255
+ <td align="center" style="vertical-align: middle; text-align: center">51.5</td>
256
+ <td align="center" style="vertical-align: middle; text-align: center">45.5</td>
257
+ </tr>
258
+ <tr>
259
+ <td align="center" colspan=7 style="text-align: center"><strong>Agentic</strong></td>
260
+ </tr>
261
+ <tr>
262
+ <td align="center" style="vertical-align: middle; text-align: center">HLE-Full w/ tools</td>
263
+ <td align="center" style="vertical-align: middle; text-align: center">70.0</td>
264
+ <td align="center" style="vertical-align: middle; text-align: center">65.6</td>
265
+ <td align="center" style="vertical-align: middle; text-align: center">57.2</td>
266
+ <td align="center" style="vertical-align: middle; text-align: center">67.7</td>
267
+ <td align="center" style="vertical-align: middle; text-align: center">58.8</td>
268
+ <td align="center" style="vertical-align: middle; text-align: center">62.5</td>
269
+ </tr>
270
+ <tr>
271
+ <td align="center" style="vertical-align: middle; text-align: center">BrowseComp</td>
272
+ <td align="center" style="vertical-align: middle; text-align: center">92.1</td>
273
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
274
+ <td align="center" style="vertical-align: middle; text-align: center">91.5</td>
275
+ <td align="center" style="vertical-align: middle; text-align: center">90.8</td>
276
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
277
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
278
+ </tr>
279
+ <tr>
280
+ <td align="center" style="vertical-align: middle; text-align: center">BioMysteryBench</td>
281
+ <td align="center" style="vertical-align: middle; text-align: center">80.6</td>
282
+ <td align="center" style="vertical-align: middle; text-align: center">81.6</td>
283
+ <td align="center" style="vertical-align: middle; text-align: center">78.9</td>
284
+ <td align="center" style="vertical-align: middle; text-align: center">81.9</td>
285
+ <td align="center" style="vertical-align: middle; text-align: center">80.0</td>
286
+ <td align="center" style="vertical-align: middle; text-align: center">79.6</td>
287
+ </tr>
288
+ <tr>
289
+ <td align="center" style="vertical-align: middle; text-align: center">CharXiv (RQ) w/ python</td>
290
+ <td align="center" style="vertical-align: middle; text-align: center">93.4</td>
291
+ <td align="center" style="vertical-align: middle; text-align: center">92.7</td>
292
+ <td align="center" style="vertical-align: middle; text-align: center">92.8</td>
293
+ <td align="center" style="vertical-align: middle; text-align: center">93.8</td>
294
+ <td align="center" style="vertical-align: middle; text-align: center">85.6</td>
295
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
296
+ </tr>
297
+ <tr>
298
+ <td align="center" style="vertical-align: middle; text-align: center">MMMU-Pro w/ python</td>
299
+ <td align="center" style="vertical-align: middle; text-align: center">90.0</td>
300
+ <td align="center" style="vertical-align: middle; text-align: center">88.4</td>
301
+ <td align="center" style="vertical-align: middle; text-align: center">87.8</td>
302
+ <td align="center" style="vertical-align: middle; text-align: center">89.8</td>
303
+ <td align="center" style="vertical-align: middle; text-align: center">82.5</td>
304
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
305
+ </tr>
306
+ <tr>
307
+ <td align="center" style="vertical-align: middle; text-align: center">GDP.pdf w/ python</td>
308
+ <td align="center" style="vertical-align: middle; text-align: center">85.7</td>
309
+ <td align="center" style="vertical-align: middle; text-align: center">83.8</td>
310
+ <td align="center" style="vertical-align: middle; text-align: center">85.5</td>
311
+ <td align="center" style="vertical-align: middle; text-align: center">83.9</td>
312
+ <td align="center" style="vertical-align: middle; text-align: center">73.0</td>
313
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
314
+ </tr>
315
+ <tr>
316
+ <td align="center" style="vertical-align: middle; text-align: center">ChartoGraphy w/ python</td>
317
+ <td align="center" style="vertical-align: middle; text-align: center">90.2</td>
318
+ <td align="center" style="vertical-align: middle; text-align: center">88.4</td>
319
+ <td align="center" style="vertical-align: middle; text-align: center">91.0</td>
320
+ <td align="center" style="vertical-align: middle; text-align: center">89.0</td>
321
+ <td align="center" style="vertical-align: middle; text-align: center">83.0</td>
322
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
323
+ </tr>
324
+ <tr>
325
+ <td align="center" style="vertical-align: middle; text-align: center">BabyVision w/ python</td>
326
+ <td align="center" style="vertical-align: middle; text-align: center">95.4</td>
327
+ <td align="center" style="vertical-align: middle; text-align: center">95.1</td>
328
+ <td align="center" style="vertical-align: middle; text-align: center">96.6</td>
329
+ <td align="center" style="vertical-align: middle; text-align: center">97.7</td>
330
+ <td align="center" style="vertical-align: middle; text-align: center">92.5</td>
331
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
332
+ </tr>
333
+ <tr>
334
+ <td align="center" style="vertical-align: middle; text-align: center">ZeroBench_main w/ python (pass@5)</td>
335
+ <td align="center" style="vertical-align: middle; text-align: center">63.0</td>
336
+ <td align="center" style="vertical-align: middle; text-align: center">59.0</td>
337
+ <td align="center" style="vertical-align: middle; text-align: center">58.0</td>
338
+ <td align="center" style="vertical-align: middle; text-align: center">61.0</td>
339
+ <td align="center" style="vertical-align: middle; text-align: center">51.0</td>
340
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
341
+ </tr>
342
+ <tr>
343
+ <td align="center" style="vertical-align: middle; text-align: center">Agents' Last Exam (ALL)</td>
344
+ <td align="center" style="vertical-align: middle; text-align: center">43.2</td>
345
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
346
+ <td align="center" style="vertical-align: middle; text-align: center">41.8</td>
347
+ <td align="center" style="vertical-align: middle; text-align: center">42.6</td>
348
+ <td align="center" style="vertical-align: middle; text-align: center">37.7</td>
349
+ <td align="center" style="vertical-align: middle; text-align: center">26.2</td>
350
+ </tr>
351
+ <tr>
352
+ <td align="center" style="vertical-align: middle; text-align: center">Agents' Last Exam (CLI)</td>
353
+ <td align="center" style="vertical-align: middle; text-align: center">44.2</td>
354
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
355
+ <td align="center" style="vertical-align: middle; text-align: center">44.2</td>
356
+ <td align="center" style="vertical-align: middle; text-align: center">40.7</td>
357
+ <td align="center" style="vertical-align: middle; text-align: center">36.0</td>
358
+ <td align="center" style="vertical-align: middle; text-align: center">29.4</td>
359
+ </tr>
360
+ <tr>
361
+ <td align="center" style="vertical-align: middle; text-align: center">Automation Bench-AA</td>
362
+ <td align="center" style="vertical-align: middle; text-align: center">73.3</td>
363
+ <td align="center" style="vertical-align: middle; text-align: center">59.4</td>
364
+ <td align="center" style="vertical-align: middle; text-align: center">68.5</td>
365
+ <td align="center" style="vertical-align: middle; text-align: center">69.5</td>
366
+ <td align="center" style="vertical-align: middle; text-align: center">66.6</td>
367
+ <td align="center" style="vertical-align: middle; text-align: center">62.2</td>
368
+ </tr>
369
+ <tr>
370
+ <td align="center" style="vertical-align: middle; text-align: center">GDPval-AA v2.1 (Elo-score)</td>
371
+ <td align="center" style="vertical-align: middle; text-align: center">1846</td>
372
+ <td align="center" style="vertical-align: middle; text-align: center">1754</td>
373
+ <td align="center" style="vertical-align: middle; text-align: center">1573</td>
374
+ <td align="center" style="vertical-align: middle; text-align: center">1866</td>
375
+ <td align="center" style="vertical-align: middle; text-align: center">1746</td>
376
+ <td align="center" style="vertical-align: middle; text-align: center">1650</td>
377
+ </tr>
378
+ <tr>
379
+ <td align="center" style="vertical-align: middle; text-align: center">AA-Briefcase v1.1 (Elo-score)</td>
380
+ <td align="center" style="vertical-align: middle; text-align: center">1678</td>
381
+ <td align="center" style="vertical-align: middle; text-align: center">1672</td>
382
+ <td align="center" style="vertical-align: middle; text-align: center">1569</td>
383
+ <td align="center" style="vertical-align: middle; text-align: center">1803</td>
384
+ <td align="center" style="vertical-align: middle; text-align: center">1570</td>
385
+ <td align="center" style="vertical-align: middle; text-align: center">1507</td>
386
+ </tr>
387
+ <tr>
388
+ <td align="center" style="vertical-align: middle; text-align: center">APEX-Agents</td>
389
+ <td align="center" style="vertical-align: middle; text-align: center">69.4</td>
390
+ <td align="center" style="vertical-align: middle; text-align: center">68.6</td>
391
+ <td align="center" style="vertical-align: middle; text-align: center">64.7</td>
392
+ <td align="center" style="vertical-align: middle; text-align: center">73.5</td>
393
+ <td align="center" style="vertical-align: middle; text-align: center">69.8</td>
394
+ <td align="center" style="vertical-align: middle; text-align: center">56.6</td>
395
+ </tr>
396
+ <tr>
397
+ <td align="center" style="vertical-align: middle; text-align: center">OfficeQA Pro v2</td>
398
+ <td align="center" style="vertical-align: middle; text-align: center">64.4</td>
399
+ <td align="center" style="vertical-align: middle; text-align: center">54.5</td>
400
+ <td align="center" style="vertical-align: middle; text-align: center">54.4</td>
401
+ <td align="center" style="vertical-align: middle; text-align: center">62.2</td>
402
+ <td align="center" style="vertical-align: middle; text-align: center">40.4</td>
403
+ <td align="center" style="vertical-align: middle; text-align: center">31.1</td>
404
+ </tr>
405
+ <tr>
406
+ <td align="center" style="vertical-align: middle; text-align: center">OfficeQA Pro</td>
407
+ <td align="center" style="vertical-align: middle; text-align: center">67.4</td>
408
+ <td align="center" style="vertical-align: middle; text-align: center">68.6</td>
409
+ <td align="center" style="vertical-align: middle; text-align: center">66.2</td>
410
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
411
+ <td align="center" style="vertical-align: middle; text-align: center">62.4</td>
412
+ <td align="center" style="vertical-align: middle; text-align: center">58.6</td>
413
+ </tr>
414
+ <tr>
415
+ <td align="center" style="vertical-align: middle; text-align: center">Frontier Finance</td>
416
+ <td align="center" style="vertical-align: middle; text-align: center">58.6</td>
417
+ <td align="center" style="vertical-align: middle; text-align: center">60.8</td>
418
+ <td align="center" style="vertical-align: middle; text-align: center">45.0</td>
419
+ <td align="center" style="vertical-align: middle; text-align: center">56.7</td>
420
+ <td align="center" style="vertical-align: middle; text-align: center">54.5</td>
421
+ <td align="center" style="vertical-align: middle; text-align: center">57.5</td>
422
+ </tr>
423
+ <tr>
424
+ <td align="center" style="vertical-align: middle; text-align: center">Harvey Legal Agent</td>
425
+ <td align="center" style="vertical-align: middle; text-align: center">23.7</td>
426
+ <td align="center" style="vertical-align: middle; text-align: center">19.1</td>
427
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
428
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
429
+ <td align="center" style="vertical-align: middle; text-align: center">21.0</td>
430
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
431
+ </tr>
432
+ <tr>
433
+ <td align="center" style="vertical-align: middle; text-align: center">HANDBOOK.md</td>
434
+ <td align="center" style="vertical-align: middle; text-align: center">44.6</td>
435
+ <td align="center" style="vertical-align: middle; text-align: center">38.8</td>
436
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
437
+ <td align="center" style="vertical-align: middle; text-align: center">41.5</td>
438
+ <td align="center" style="vertical-align: middle; text-align: center">28.9</td>
439
+ <td align="center" style="vertical-align: middle; text-align: center">20.8</td>
440
+ </tr>
441
+ <tr>
442
+ <td align="center" style="vertical-align: middle; text-align: center">OSWorld V2.1</td>
443
+ <td align="center" style="vertical-align: middle; text-align: center">79.6</td>
444
+ <td align="center" style="vertical-align: middle; text-align: center">80.7</td>
445
+ <td align="center" style="vertical-align: middle; text-align: center">75.8</td>
446
+ <td align="center" style="vertical-align: middle; text-align: center">81.8</td>
447
+ <td align="center" style="vertical-align: middle; text-align: center">69.3</td>
448
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
449
+ </tr>
450
+ <tr>
451
+ <td align="center" style="vertical-align: middle; text-align: center">Business Operation (Internal)</td>
452
+ <td align="center" style="vertical-align: middle; text-align: center">37.8</td>
453
+ <td align="center" style="vertical-align: middle; text-align: center">30.7</td>
454
+ <td align="center" style="vertical-align: middle; text-align: center">32.3</td>
455
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
456
+ <td align="center" style="vertical-align: middle; text-align: center">8.9</td>
457
+ <td align="center" style="vertical-align: middle; text-align: center">18.6</td>
458
+ </tr>
459
+ <tr>
460
+ <td align="center" style="vertical-align: middle; text-align: center">DECK-Arena (Internal, Elo-score)</td>
461
+ <td align="center" style="vertical-align: middle; text-align: center">1456</td>
462
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
463
+ <td align="center" style="vertical-align: middle; text-align: center">1423</td>
464
+ <td align="center" style="vertical-align: middle; text-align: center">1253</td>
465
+ <td align="center" style="vertical-align: middle; text-align: center">1231</td>
466
+ <td align="center" style="vertical-align: middle; text-align: center">1119</td>
467
+ </tr>
468
+ <tr>
469
+ <td align="center" style="vertical-align: middle; text-align: center">Design Bench (Internal, Elo-score)</td>
470
+ <td align="center" style="vertical-align: middle; text-align: center">957</td>
471
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
472
+ <td align="center" style="vertical-align: middle; text-align: center">1076</td>
473
+ <td align="center" style="vertical-align: middle; text-align: center">927</td>
474
+ <td align="center" style="vertical-align: middle; text-align: center">863</td>
475
+ <td align="center" style="vertical-align: middle; text-align: center">718</td>
476
+ </tr>
477
+ <tr>
478
+ <td align="center" style="vertical-align: middle; text-align: center">Kimi Hallu Bench Hard w/ tools (Internal, lower is better)</td>
479
+ <td align="center" style="vertical-align: middle; text-align: center">8.3</td>
480
+ <td align="center" style="vertical-align: middle; text-align: center">23.3</td>
481
+ <td align="center" style="vertical-align: middle; text-align: center">5.5</td>
482
+ <td align="center" style="vertical-align: middle; text-align: center">15.0</td>
483
+ <td align="center" style="vertical-align: middle; text-align: center">23.3</td>
484
+ <td align="center" style="vertical-align: middle; text-align: center">22.6</td>
485
+ </tr>
486
+ <tr>
487
+ <td align="center" colspan=7 style="text-align: center"><strong>Reasoning &amp; Knowledge &amp; Multimodal</strong></td>
488
+ </tr>
489
+ <tr>
490
+ <td align="center" style="vertical-align: middle; text-align: center">GDP.pdf</td>
491
+ <td align="center" style="vertical-align: middle; text-align: center">34.6</td>
492
+ <td align="center" style="vertical-align: middle; text-align: center">27.6</td>
493
+ <td align="center" style="vertical-align: middle; text-align: center">34.2</td>
494
+ <td align="center" style="vertical-align: middle; text-align: center">30.6</td>
495
+ <td align="center" style="vertical-align: middle; text-align: center">17.2</td>
496
+ <td align="center" style="vertical-align: middle; text-align: center">11.2</td>
497
+ </tr>
498
+ <tr>
499
+ <td align="center" style="vertical-align: middle; text-align: center">HLE-Full</td>
500
+ <td align="center" style="vertical-align: middle; text-align: center">51.1</td>
501
+ <td align="center" style="vertical-align: middle; text-align: center">57.6</td>
502
+ <td align="center" style="vertical-align: middle; text-align: center">53.6</td>
503
+ <td align="center" style="vertical-align: middle; text-align: center">59.8</td>
504
+ <td align="center" style="vertical-align: middle; text-align: center">42.6</td>
505
+ <td align="center" style="vertical-align: middle; text-align: center">43.0*</td>
506
+ </tr>
507
+ <tr>
508
+ <td align="center" style="vertical-align: middle; text-align: center">HLE-Diamond</td>
509
+ <td align="center" style="vertical-align: middle; text-align: center">39.4</td>
510
+ <td align="center" style="vertical-align: middle; text-align: center">55.1</td>
511
+ <td align="center" style="vertical-align: middle; text-align: center">65.8</td>
512
+ <td align="center" style="vertical-align: middle; text-align: center">60.9</td>
513
+ <td align="center" style="vertical-align: middle; text-align: center">21.6</td>
514
+ <td align="center" style="vertical-align: middle; text-align: center">25.1*</td>
515
+ </tr>
516
+ <tr>
517
+ <td align="center" style="vertical-align: middle; text-align: center">GPQA-Diamond</td>
518
+ <td align="center" style="vertical-align: middle; text-align: center">94.2</td>
519
+ <td align="center" style="vertical-align: middle; text-align: center">93.7</td>
520
+ <td align="center" style="vertical-align: middle; text-align: center">96.1</td>
521
+ <td align="center" style="vertical-align: middle; text-align: center">93.9</td>
522
+ <td align="center" style="vertical-align: middle; text-align: center">92.2</td>
523
+ <td align="center" style="vertical-align: middle; text-align: center">91.7</td>
524
+ </tr>
525
+ <tr>
526
+ <td align="center" style="vertical-align: middle; text-align: center">CharXiv (RQ)</td>
527
+ <td align="center" style="vertical-align: middle; text-align: center">89.0</td>
528
+ <td align="center" style="vertical-align: middle; text-align: center">88.8</td>
529
+ <td align="center" style="vertical-align: middle; text-align: center">90.0</td>
530
+ <td align="center" style="vertical-align: middle; text-align: center">92.1</td>
531
+ <td align="center" style="vertical-align: middle; text-align: center">77.0</td>
532
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
533
+ </tr>
534
+ <tr>
535
+ <td align="center" style="vertical-align: middle; text-align: center">MMMU-Pro</td>
536
+ <td align="center" style="vertical-align: middle; text-align: center">84.1</td>
537
+ <td align="center" style="vertical-align: middle; text-align: center">86.3</td>
538
+ <td align="center" style="vertical-align: middle; text-align: center">86.9</td>
539
+ <td align="center" style="vertical-align: middle; text-align: center">87.7</td>
540
+ <td align="center" style="vertical-align: middle; text-align: center">80.6</td>
541
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
542
+ </tr>
543
+ <tr>
544
+ <td align="center" style="vertical-align: middle; text-align: center">ZeroBench_main (avg@5 / pass@5)</td>
545
+ <td align="center" style="vertical-align: middle; text-align: center">29.8 / 39.0</td>
546
+ <td align="center" style="vertical-align: middle; text-align: center">23.0 / 35.0</td>
547
+ <td align="center" style="vertical-align: middle; text-align: center">43.2 / 52.0</td>
548
+ <td align="center" style="vertical-align: middle; text-align: center">35.0 / 43.0</td>
549
+ <td align="center" style="vertical-align: middle; text-align: center">11.8 / 23.0</td>
550
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
551
+ </tr>
552
+ <tr>
553
+ <td align="center" style="vertical-align: middle; text-align: center">PerceptionBench</td>
554
+ <td align="center" style="vertical-align: middle; text-align: center">68.3</td>
555
+ <td align="center" style="vertical-align: middle; text-align: center">63.0</td>
556
+ <td align="center" style="vertical-align: middle; text-align: center">77.6</td>
557
+ <td align="center" style="vertical-align: middle; text-align: center">72.1</td>
558
+ <td align="center" style="vertical-align: middle; text-align: center">47.7</td>
559
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
560
+ </tr>
561
+ <tr>
562
+ <td align="center" style="vertical-align: middle; text-align: center">Kimi Hallu Bench w/o tools (Internal, lower is better)</td>
563
+ <td align="center" style="vertical-align: middle; text-align: center">5.4</td>
564
+ <td align="center" style="vertical-align: middle; text-align: center">11.4</td>
565
+ <td align="center" style="vertical-align: middle; text-align: center">4.2</td>
566
+ <td align="center" style="vertical-align: middle; text-align: center">6.8</td>
567
+ <td align="center" style="vertical-align: middle; text-align: center">13.1</td>
568
+ <td align="center" style="vertical-align: middle; text-align: center">14.8</td>
569
+ </tr>
570
+ <tr>
571
+ <td align="center" colspan=7 style="text-align: center"><strong>Cyber Security</strong></td>
572
+ </tr>
573
+ <tr>
574
+ <td align="center" style="vertical-align: middle; text-align: center">ExploitBench</td>
575
+ <td align="center" style="vertical-align: middle; text-align: center">74.7</td>
576
+ <td align="center" style="vertical-align: middle; text-align: center">83.0</td>
577
+ <td align="center" style="vertical-align: middle; text-align: center">100</td>
578
+ <td align="center" style="vertical-align: middle; text-align: center">91.0</td>
579
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
580
+ <td align="center" style="vertical-align: middle; text-align: center">54.4</td>
581
+ </tr>
582
+ <tr>
583
+ <td align="center" style="vertical-align: middle; text-align: center">ExploitGym</td>
584
+ <td align="center" style="vertical-align: middle; text-align: center">20.7</td>
585
+ <td align="center" style="vertical-align: middle; text-align: center">30.4</td>
586
+ <td align="center" style="vertical-align: middle; text-align: center">42.4</td>
587
+ <td align="center" style="vertical-align: middle; text-align: center">34.5</td>
588
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
589
+ <td align="center" style="vertical-align: middle; text-align: center">15.0</td>
590
+ </tr>
591
+ <tr>
592
+ <td align="center" style="vertical-align: middle; text-align: center">xdev-bench-hard (Internal)</td>
593
+ <td align="center" style="vertical-align: middle; text-align: center">81.0</td>
594
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
595
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
596
+ <td align="center" style="vertical-align: middle; text-align: center">—</td>
597
+ <td align="center" style="vertical-align: middle; text-align: center">85.7</td>
598
+ <td align="center" style="vertical-align: middle; text-align: center">57.1</td>
599
+ </tr>
600
+ </tbody>
601
+ </table>
602
+ </div>
603
+
604
+ <details>
605
+ <summary><b>Evaluation Footnotes</b></summary>
606
+
607
+ #### Coding benchmarks
608
+
609
+ 1. **Terminal-Bench 4.0.** Kimi K3.1 Pro is evaluated with the Claude Code harness. The DeepSeek-V4.1-Flash-1017 score is taken from its [release blog](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash-1017). All remaining scores are the maximum values reported in model blog posts or on the [official Terminal-Bench leaderboard](https://www.tbench.ai/).
610
+ 2. **Terminal-Bench-Science 0.1.** Kimi K3.1 Pro is evaluated with Claude Code. Internal evaluation of DeepSeek-V4.1-Flash-1017 yields 9.3; the table instead reports 15.7 for the older DeepSeek-V4.1-Flash from the official leaderboard. All remaining scores are from the [Terminal-Bench-Science leaderboard](https://www.terminal-bench-science.ai/).
611
+ 3. **SWE-Marathon v1.1.** Kimi K3.1 Pro and DeepSeek-V4.1-Flash-1017 are evaluated with Claude Code. Other scores are from the [official leaderboard](https://www.swe-marathon.org/).
612
+ 4. **ProgramBench.** The table reports binary scores: a task receives 1 if its ProgramBench score is at least 95%, and 0 otherwise. K3.1 Pro is evaluated with Claude Code. DeepSeek and GLM scores are taken from the [DeepSeek release blog](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash-1017); remaining scores are from [Vals AI](https://www.vals.ai/benchmarks/programbench).
613
+ 5. **DeepSWE v1.1.** K3.1 Pro is evaluated with Claude Code. Other scores come from the respective technical reports for [GPT-6 Astra](https://openai.com/index/gpt-6-astra/), [Claude Opus 5.5](https://www.anthropic.com/claude-opus-5-5-system-card), [Claude Fable 5.1](https://www.anthropic.com/claude-fable-5-1-mythos-5-1-system-card), [DeepSeek-V4.1-Flash-1017](https://api-docs.deepseek.com/news/news261017/), and [GLM-5.3](https://z.ai/blog/glm-5.3).
614
+ 6. **PostTrainBench.** K3.1 Pro and DeepSeek-V4.1-Flash-1017 are evaluated internally on v1.2 with Claude Code and H20 GPUs rather than H100 GPUs. For stable evaluation, all judge models use DeepSeek-V4.1-Flash-1017 at maximum effort, which best matched the official GPT-5.6-Terra (xhigh) judge in testing. Other scores are from the [official leaderboard](https://posttrainbench.com/).
615
+ 7. **Kimi Code Bench 2.0 and Kimi Code Bench 3.0 Long-horizon.** These are internal benchmarks. K3.1 Pro is evaluated with Claude Code; all other models use their maximum-effort setting. Proprietary-model testing may involve fallback behavior.
616
+ 8. **BenchCAD.** Open models are evaluated on 1,000-case subsets randomly sampled from the 17,900-case Vision2Code dataset at maximum reasoning effort. With-tools results use Claude Code; without-tools results use single-shot generation with official prompts and scoring. Claude scores are from the Opus 5.5 System Card, and GPT-6 Astra's with-tools score is from its official report. GPT-6 Astra has no reported without-tools score.
617
+
618
+ #### Agentic benchmarks
619
+
620
+ 1. **BioMysteryBench.** Uses the [official v11 release](https://huggingface.co/datasets/Anthropic/BioMysteryBench-full/commit/b5a889c), with Kimi K3 as judge. K3.1 Pro uses Kimi Code; GLM-5.3 and DeepSeek-V4.1-Flash-1017 use Claude Code; GPT-6 Astra uses Codex. Claude scores are from official system cards.
621
+ 2. **Agents' Last Exam.** Uses the [official v1.1 release](https://github.com/rdi-berkeley/agents-last-exam), comprising 122 tasks, including 86 CLI tasks. Runs that bypass stated requirements receive zero. DeepSeek and Kimi are evaluated with Claude Code and Kimi Code, respectively; other results are from the official benchmark website.
622
+ 3. **OfficeQA Pro and OfficeQA Pro v2.** GPT-6 Astra uses Codex; other models use Claude Code. Each task provides the complete PDF corpus as page images without machine-readable text. External-model trajectories that retrieve reference answers online receive zero for those tasks.
623
+ 4. **Frontier Finance.** Evaluated with the official Finance Agent v2 harness.
624
+ 5. **HANDBOOK.md.** Evaluated with the official OpenHands-based harness, using tasks from the benchmark's early open-source v1 release.
625
+ 6. **Harvey Legal Agent.** Evaluated on 1,251 public tasks with Artificial Analysis's Stirrup harness. The reported score is the all-pass rate: the percentage of tasks passing every rubric criterion.
626
+ 7. **OSWorld V2.1.** Kimi models use the Kimi Agent harness in the official OSWorld v2 repository. GPT-6 Astra's score is taken from Muse Wonder's technical report.
627
+ 8. **DECK-Arena and Design Bench.** DECK-Arena evaluates presentation generation on real-world queries; Design Bench covers graphic design through direct and reference-image few-shot prompting. Both evaluate python-pptx, pptxjs, and Kimi's in-house DSL in a harness with integrated search and image generation. The automated grader is calibrated on more than 10,000 human judgments.
628
+ 9. **BrowseComp.** Uses context compaction triggered at 200K tokens and a 500-step maximum. If the limit is reached, the agent is forced to answer before judging. All runs use `temperature = 1.0` and `top-p = 1.0`.
629
+ 10. **GDPval-AA v2.1, AA-Briefcase v1.1, and AutomationBench-AA.** Scores are cited from [Artificial Analysis](https://artificialanalysis.ai/). **APEX-Agents.** Scores are cited from the [official leaderboard](https://www.mercor.com/apex/apex-agents-leaderboard/).
630
+ 11. **Tool-augmented multimodal evaluations.** GDP.pdf w/ python, ZeroBench w/ python, and ChartoGraphy w/ python are averaged over five runs; other multimodal benchmarks with Python are averaged over four. For GDP.pdf w/ python, each original PDF is sent to a sandbox for IPython processing. Responses are graded against each rubric criterion using Gemini-3.5-Flash at medium reasoning effort and the official judging prompt. The reported score is the task-macro mean rubric pass rate.
631
+
632
+ #### Reasoning, knowledge, and multimodal benchmarks
633
+
634
+ 1. **GDP.pdf.** Each PDF is provided as page images resized to a longest edge of 1,152 pixels, interleaved with Docling-extracted text in page order. Responses are graded against each rubric criterion using Gemini-3.5-Flash Medium and the official judging prompt. The table reports the strict pass rate among fully scored responses. GLM-5.3 Max and DeepSeek-V4.1-Flash-1017 Max scores are cited from [Artificial Analysis](https://artificialanalysis.ai/).
635
+ 2. **HLE-Full and HLE-Diamond.** The full evaluation sets contain 2,500 and 1,000 questions, respectively. For scores marked `*`, accuracy is reported on the text-only subset.
636
+ 3. **Run counts.** GDP.pdf, ZeroBench, and ChartoGraphy are averaged over five runs; other multimodal benchmarks are averaged over four.
637
+ 4. **MMMU-Pro.** Evaluated using the official protocol, preserving the original input order and prepending images to the text input.
638
+ 5. **PerceptionBench.** An in-house benchmark focused on atomic visual perception capabilities.
639
+ 6. **Kimi Hallucination Benchmark.** Evaluates factual accuracy on an internal set of challenging, de-identified prompts drawn from practical work tasks. The table reports claim-level hallucination rates assessed by fact-checking agents.
640
+
641
+ #### Cybersecurity benchmarks
642
+
643
+ 1. **ExploitBench.** K3.1 Pro is evaluated with the official harness under a 300-turn budget. The table reports the pass@5 maximum-capability score: for each environment, the best of five seeds is scored by capability flags reached out of 16; arbitrary code execution counts as all 16 capabilities. Comparison scores are from [OpenAI](https://openai.com/index/gpt-6-astra/), [Anthropic](https://www.anthropic.com/claude-opus-5-5-system-card), and [GLM-5.3](https://z.ai/blog/glm-5.3).
644
+ 2. **ExploitGym.** K3.1 Pro is evaluated with Kimi Code under a six-hour wall-clock budget per task. GPT-6 Astra, Claude, and GLM comparison scores are taken from their respective official reports, with Claude results using the same six-hour budget.
645
+ 3. **xdev-bench-hard.** K3.1 Pro is evaluated with Kimi Code; GLM-5.3 and DeepSeek-V4.1-Flash-1017 use Claude Code. The internal benchmark contains expert-curated, source-code-based vulnerability discovery and exploitation tasks. The final model is evaluated at pass@3 over a random subset of runs, without hard timeouts or output-token limits.
646
+
647
+ </details>
648
+
649
+ ## 4. Deployment and Availability
650
+
651
+ > [!Note]
652
+ > You can access Kimi K3.1 Pro's API on https://platform.kimi.ai by selecting `kimi-k3.1-pro`, and we provide OpenAI/Anthropic-compatible API for you.
653
+ > Currently, Kimi K3.1 Pro is recommended to run on the following inference engines:
654
+
655
+ - [vLLM](https://github.com/vllm-project/vllm) — see [recipes](https://recipes.vllm.ai/moonshotai/Kimi-K3.1-Pro)
656
+ - [SGLang](https://github.com/sgl-project/sglang) — see [cookbook](https://docs.sglang.io/cookbook/autoregressive/Moonshotai/Kimi-K3.1-Pro)
657
+ - [TokenSpeed](https://github.com/lightseekorg/tokenspeed) — see [recipes](https://lightseek.org/tokenspeed/recipes/models#kimi-k3-1-pro)
658
+
659
+ ---
660
+ ## 5. Model Usage
661
+ The thinking effort of Kimi K3.1 Pro is configured with the top-level `reasoning_effort` request field, which supports `"low"`, `"high"`, and `"max"` (default `"max"`).
662
+
663
+ For multi-turn conversations and tool calls, Kimi K3.1 Pro requires the complete assistant message returned by the API to be passed back to `messages` as-is — including `reasoning_content` and `tool_calls`, not just `content`:
664
+
665
+ ```python
666
+ import openai
667
+
668
+ def chat_with_preserved_thinking(client: openai.OpenAI, model_name: str):
669
+ messages = [
670
+ {
671
+ "role": "user",
672
+ "content": "Tell me three random numbers."
673
+ },
674
+ {
675
+ "role": "assistant",
676
+ "reasoning_content": "I'll start by listing five numbers: 473, 921, 235, 215, 222, and I'll tell you the first three.",
677
+ "content": "473, 921, 235"
678
+ },
679
+ {
680
+ "role": "user",
681
+ "content": "What are the other two numbers you have in mind?"
682
+ }
683
+ ]
684
+
685
+ response = client.chat.completions.create(
686
+ model=model_name,
687
+ messages=messages,
688
+ stream=False,
689
+ max_tokens=4096,
690
+ reasoning_effort="max",
691
+ )
692
+ # the assistant should mention 215 and 222 that appear in the prior reasoning content
693
+ print(f"response: {response.choices[0].message.reasoning}")
694
+ return response.choices[0].message.content
695
+ ```
696
+ For full guides and examples (vision input, structured output, partial mode, tool choice, dynamic tool loading, context caching), see the [Kimi K3.1 Pro Quickstart](https://platform.kimi.ai/docs/guide/kimi-k3-1-pro-quickstart) and [Thinking Effort](https://platform.kimi.ai/docs/guide/use-thinking-effort).
697
+
698
+
699
+ ## 6. License
700
+
701
+ Kimi K3.1 Pro is released under the [Kimi K3.1 Pro License](https://huggingface.co/moonshotai/Kimi-K3.1-Pro/blob/main/LICENSE).
702
+
703
+ ## 7. Contact Us
704
+
705
+ If you have any questions, please reach out at [support@moonshot.ai](mailto:support@moonshot.ai).
assets/kimi-logo.png ADDED
config.json ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "KimiK31ForConditionalGeneration"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_kimi_k3.KimiK3Config"
7
+ },
8
+ "bos_token_id": 163584,
9
+ "dtype": "bfloat16",
10
+ "eos_token_id": 163586,
11
+ "ignore_index": -100,
12
+ "image_placeholder": "<|kimi_image_placeholder|>",
13
+ "media_placeholder_token_id": 163605,
14
+ "model_type": "kimi_k31",
15
+ "pad_token_id": 163839,
16
+ "text_config": {
17
+ "_name_or_path": "",
18
+ "activation_situ_beta": 4.0,
19
+ "activation_situ_linear_beta": 25.0,
20
+ "add_cross_attention": false,
21
+ "architectures": [
22
+ "KimiLinearForCausalLM"
23
+ ],
24
+ "attn_res_block_size": 12,
25
+ "bad_words_ids": null,
26
+ "begin_suppress_tokens": null,
27
+ "bos_token_id": 163584,
28
+ "chunk_size_feed_forward": 0,
29
+ "cross_attention_hidden_size": null,
30
+ "decoder_start_token_id": null,
31
+ "diversity_penalty": 0.0,
32
+ "do_sample": false,
33
+ "dsa_config": {
34
+ "dsa_layers": [
35
+ 4,
36
+ 8,
37
+ 12,
38
+ 16,
39
+ 20,
40
+ 24,
41
+ 28,
42
+ 32,
43
+ 36,
44
+ 40,
45
+ 44,
46
+ 48,
47
+ 52,
48
+ 56,
49
+ 60,
50
+ 64,
51
+ 68,
52
+ 72,
53
+ 76,
54
+ 80,
55
+ 84,
56
+ 88,
57
+ 92,
58
+ 93
59
+ ],
60
+ "index_topk": 2048,
61
+ "index_head_dim": 128,
62
+ "index_num_heads": 32,
63
+ "index_rope_dim": 0,
64
+ "index_k_norm_type": "layernorm",
65
+ "index_topk_freq": 1,
66
+ "index_skip_topk_offset": 1
67
+ },
68
+ "dtype": "bfloat16",
69
+ "early_stopping": false,
70
+ "encoder_no_repeat_ngram_size": 0,
71
+ "eos_token_id": 163586,
72
+ "exponential_decay_length_penalty": null,
73
+ "finetuning_task": null,
74
+ "first_k_dense_replace": 1,
75
+ "forced_bos_token_id": null,
76
+ "forced_eos_token_id": null,
77
+ "hidden_act": "situ",
78
+ "hidden_size": 7168,
79
+ "id2label": {
80
+ "0": "LABEL_0",
81
+ "1": "LABEL_1"
82
+ },
83
+ "initializer_range": 0.02,
84
+ "intermediate_size": 33792,
85
+ "is_decoder": false,
86
+ "is_encoder_decoder": false,
87
+ "kv_lora_rank": 512,
88
+ "label2id": {
89
+ "LABEL_0": 0,
90
+ "LABEL_1": 1
91
+ },
92
+ "latent_moe_use_norm": true,
93
+ "length_penalty": 1.0,
94
+ "linear_attn_config": {
95
+ "full_attn_layers": [
96
+ 4,
97
+ 8,
98
+ 12,
99
+ 16,
100
+ 20,
101
+ 24,
102
+ 28,
103
+ 32,
104
+ 36,
105
+ 40,
106
+ 44,
107
+ 48,
108
+ 52,
109
+ 56,
110
+ 60,
111
+ 64,
112
+ 68,
113
+ 72,
114
+ 76,
115
+ 80,
116
+ 84,
117
+ 88,
118
+ 92,
119
+ 93
120
+ ],
121
+ "gate_lower_bound": -5.0,
122
+ "head_dim": 128,
123
+ "kda_layers": [
124
+ 1,
125
+ 2,
126
+ 3,
127
+ 5,
128
+ 6,
129
+ 7,
130
+ 9,
131
+ 10,
132
+ 11,
133
+ 13,
134
+ 14,
135
+ 15,
136
+ 17,
137
+ 18,
138
+ 19,
139
+ 21,
140
+ 22,
141
+ 23,
142
+ 25,
143
+ 26,
144
+ 27,
145
+ 29,
146
+ 30,
147
+ 31,
148
+ 33,
149
+ 34,
150
+ 35,
151
+ 37,
152
+ 38,
153
+ 39,
154
+ 41,
155
+ 42,
156
+ 43,
157
+ 45,
158
+ 46,
159
+ 47,
160
+ 49,
161
+ 50,
162
+ 51,
163
+ 53,
164
+ 54,
165
+ 55,
166
+ 57,
167
+ 58,
168
+ 59,
169
+ 61,
170
+ 62,
171
+ 63,
172
+ 65,
173
+ 66,
174
+ 67,
175
+ 69,
176
+ 70,
177
+ 71,
178
+ 73,
179
+ 74,
180
+ 75,
181
+ 77,
182
+ 78,
183
+ 79,
184
+ 81,
185
+ 82,
186
+ 83,
187
+ 85,
188
+ 86,
189
+ 87,
190
+ 89,
191
+ 90,
192
+ 91
193
+ ],
194
+ "num_heads": 96,
195
+ "short_conv_kernel_size": 4,
196
+ "use_full_rank_gate": true
197
+ },
198
+ "max_length": 20,
199
+ "max_position_embeddings": 1048576,
200
+ "min_length": 0,
201
+ "mla_use_nope": true,
202
+ "mla_use_output_gate": true,
203
+ "model_type": "kimi_linear",
204
+ "moe_intermediate_size": 3072,
205
+ "moe_layer_freq": 1,
206
+ "moe_renormalize": true,
207
+ "moe_router_activation_func": "sigmoid",
208
+ "no_repeat_ngram_size": 0,
209
+ "num_attention_heads": 96,
210
+ "num_beam_groups": 1,
211
+ "num_beams": 1,
212
+ "num_expert_group": 1,
213
+ "num_experts": 896,
214
+ "num_experts_per_token": 16,
215
+ "num_hidden_layers": 93,
216
+ "num_key_value_heads": 96,
217
+ "num_nextn_predict_layers": 0,
218
+ "num_return_sequences": 1,
219
+ "num_shared_experts": 2,
220
+ "output_attentions": false,
221
+ "output_hidden_states": false,
222
+ "output_scores": false,
223
+ "pad_token_id": 163839,
224
+ "prefix": null,
225
+ "problem_type": null,
226
+ "pruned_heads": {},
227
+ "q_lora_rank": 1536,
228
+ "qk_nope_head_dim": 128,
229
+ "qk_rope_head_dim": 64,
230
+ "quantization_config": {
231
+ "config_groups": {
232
+ "group_0": {
233
+ "format": "mxfp4-pack-quantized",
234
+ "input_activations": null,
235
+ "output_activations": null,
236
+ "targets": [
237
+ "Linear"
238
+ ],
239
+ "weights": {
240
+ "actorder": null,
241
+ "block_structure": null,
242
+ "dynamic": false,
243
+ "group_size": 32,
244
+ "num_bits": 4,
245
+ "observer": "minmax",
246
+ "observer_kwargs": {},
247
+ "scale_dtype": "torch.uint8",
248
+ "strategy": "group",
249
+ "symmetric": true,
250
+ "type": "float",
251
+ "zp_dtype": null
252
+ }
253
+ }
254
+ },
255
+ "format": "mxfp4-pack-quantized",
256
+ "global_compression_ratio": null,
257
+ "ignore": [
258
+ "re:.*self_attn.*",
259
+ "re:.*shared_experts.*",
260
+ "re:.*mlp\\.(gate|up|gate_up|down)_proj.*",
261
+ "re:.*block_sparse_moe\\.gate$",
262
+ "re:.*block_sparse_moe\\.routed_expert_(up|down)_proj.*",
263
+ "re:.*lm_head.*",
264
+ "re:.*vision_tower.*",
265
+ "re:.*mm_projector.*"
266
+ ],
267
+ "kv_cache_scheme": null,
268
+ "quant_method": "compressed-tensors",
269
+ "quantization_status": "compressed"
270
+ },
271
+ "remove_invalid_values": false,
272
+ "repetition_penalty": 1.0,
273
+ "return_dict": true,
274
+ "return_dict_in_generate": false,
275
+ "rms_norm_eps": 1e-05,
276
+ "routed_expert_hidden_size": 3584,
277
+ "routed_scaling_factor": 1.0,
278
+ "sep_token_id": null,
279
+ "suppress_tokens": null,
280
+ "task_specific_params": null,
281
+ "temperature": 1.0,
282
+ "tf_legacy_loss": false,
283
+ "tie_encoder_decoder": false,
284
+ "tie_word_embeddings": false,
285
+ "tokenizer_class": null,
286
+ "top_k": 50,
287
+ "top_p": 1.0,
288
+ "topk_group": 1,
289
+ "topk_method": "noaux_tc",
290
+ "torchscript": false,
291
+ "transformers_version": "4.57.6",
292
+ "typical_p": 1.0,
293
+ "use_bfloat16": false,
294
+ "use_cache": true,
295
+ "use_grouped_topk": true,
296
+ "v_head_dim": 128,
297
+ "vocab_size": 163840
298
+ },
299
+ "tie_word_embeddings": false,
300
+ "vision_config": {
301
+ "_attn_implementation": "flash_attention_2",
302
+ "activation_func": "gelu_pytorch_tanh",
303
+ "attn_bias": false,
304
+ "init_pos_emb_height": 64,
305
+ "init_pos_emb_time": 4,
306
+ "init_pos_emb_width": 64,
307
+ "linear_bias": false,
308
+ "merge_kernel_size": [
309
+ 2,
310
+ 2
311
+ ],
312
+ "merge_type": "sd2_tpool",
313
+ "mlp_type": "mlp2",
314
+ "mm_hidden_size": 1024,
315
+ "mm_projector_type": "patchmergerv2",
316
+ "norm_type": "rmsnorm",
317
+ "patch_embed_proj_bias": false,
318
+ "patch_size": 14,
319
+ "pos_emb_interpolation_mode": "bilinear",
320
+ "pos_emb_type": "divided_fixed",
321
+ "projector_hidden_act": "gelu",
322
+ "projector_ln_eps": 1e-05,
323
+ "qkv_hidden_size": 1536,
324
+ "text_hidden_size": 7168,
325
+ "vt_hidden_size": 1024,
326
+ "vt_intermediate_size": 4096,
327
+ "vt_num_attention_heads": 12,
328
+ "vt_num_hidden_layers": 27
329
+ }
330
+ }
configuration_kimi_k3.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ from transformers.configuration_utils import PretrainedConfig
4
+
5
+
6
+ class KimiLinearConfig(PretrainedConfig):
7
+ model_type = "kimi_linear"
8
+ keys_to_ignore_at_inference = ["past_key_values"]
9
+
10
+ def __init__(
11
+ self,
12
+ model_type="kimi_linear",
13
+ vocab_size=163840,
14
+ hidden_size=4096,
15
+ head_dim=None,
16
+ intermediate_size=11008,
17
+ num_hidden_layers=32,
18
+ num_attention_heads=32,
19
+ num_key_value_heads=None,
20
+ hidden_act="silu",
21
+ initializer_range=0.02,
22
+ rms_norm_eps=1e-6,
23
+ use_cache=True,
24
+ pad_token_id=0,
25
+ bos_token_id=1,
26
+ eos_token_id=2,
27
+ rope_theta=10000.0,
28
+ rope_scaling=None,
29
+ tie_word_embeddings=False,
30
+ moe_intermediate_size: Optional[int] = None,
31
+ moe_renormalize: bool = True,
32
+ moe_router_activation_func: str = "sigmoid",
33
+ num_experts: Optional[int] = None,
34
+ num_experts_per_token: Optional[int] = None,
35
+ num_shared_experts: int = 0,
36
+ routed_scaling_factor: float = 1.0,
37
+ first_k_dense_replace: int = 0,
38
+ moe_layer_freq: int = 1,
39
+ use_grouped_topk: bool = True,
40
+ num_expert_group: int = 1,
41
+ topk_group: int = 1,
42
+ q_lora_rank: Optional[int] = None,
43
+ kv_lora_rank: Optional[int] = None,
44
+ qk_nope_head_dim: Optional[int] = None,
45
+ qk_rope_head_dim: Optional[int] = None,
46
+ v_head_dim: Optional[int] = None,
47
+ mla_use_nope: Optional[bool] = False,
48
+ mla_use_output_gate: Optional[bool] = False,
49
+ num_nextn_predict_layers: int = 0,
50
+ linear_attn_config: Optional[dict] = None,
51
+ dsa_config: Optional[dict] = None,
52
+ attn_res_block_size: Optional[int] = None,
53
+ latent_moe_use_norm: bool = False,
54
+ activation_situ_beta: Optional[float] = None,
55
+ activation_situ_linear_beta: Optional[float] = None,
56
+ max_position_embeddings: int = 4096,
57
+ routed_expert_hidden_size: Optional[int] = None,
58
+ topk_method: str = "noaux_tc",
59
+ **kwargs,
60
+ ):
61
+ self.model_type = model_type
62
+ self.vocab_size = vocab_size
63
+ self.hidden_size = hidden_size
64
+ self.head_dim = (head_dim if head_dim is not None else hidden_size //
65
+ num_attention_heads)
66
+ self.intermediate_size = intermediate_size
67
+ self.num_hidden_layers = num_hidden_layers
68
+ self.num_attention_heads = num_attention_heads
69
+
70
+ # for backward compatibility
71
+ if num_key_value_heads is None:
72
+ num_key_value_heads = num_attention_heads
73
+
74
+ self.num_key_value_heads = num_key_value_heads
75
+ self.hidden_act = hidden_act
76
+ self.initializer_range = initializer_range
77
+ self.rms_norm_eps = rms_norm_eps
78
+ self.use_cache = use_cache
79
+ self.rope_theta = rope_theta
80
+ self.rope_scaling = rope_scaling
81
+
82
+ self.q_lora_rank = q_lora_rank
83
+ self.kv_lora_rank = kv_lora_rank
84
+ self.qk_nope_head_dim = qk_nope_head_dim
85
+ self.qk_rope_head_dim = qk_rope_head_dim
86
+ self.v_head_dim = v_head_dim
87
+ self.mla_use_nope = mla_use_nope
88
+ self.mla_use_output_gate = mla_use_output_gate
89
+ # moe config
90
+ self.num_experts = num_experts
91
+ self.num_experts_per_token = num_experts_per_token
92
+ self.moe_renormalize = moe_renormalize
93
+ self.num_shared_experts = num_shared_experts
94
+ self.routed_scaling_factor = routed_scaling_factor
95
+ self.moe_router_activation_func = moe_router_activation_func
96
+ assert self.moe_router_activation_func in ("softmax", "sigmoid")
97
+ self.moe_intermediate_size = moe_intermediate_size
98
+ self.first_k_dense_replace = first_k_dense_replace
99
+ self.moe_layer_freq = moe_layer_freq
100
+ self.use_grouped_topk = use_grouped_topk
101
+ self.num_expert_group = num_expert_group
102
+ self.topk_group = topk_group
103
+ self.num_nextn_predict_layers = num_nextn_predict_layers
104
+
105
+ self.attn_res_block_size = attn_res_block_size
106
+ self.latent_moe_use_norm = latent_moe_use_norm
107
+ self.activation_situ_beta = activation_situ_beta
108
+ self.activation_situ_linear_beta = activation_situ_linear_beta
109
+ self.max_position_embeddings = max_position_embeddings
110
+ self.routed_expert_hidden_size = routed_expert_hidden_size
111
+ self.topk_method = topk_method
112
+
113
+ if linear_attn_config is not None:
114
+ assert linear_attn_config["kda_layers"] is not None
115
+ assert linear_attn_config["full_attn_layers"] is not None
116
+ self.linear_attn_config = linear_attn_config
117
+ # k31(KDA + DSA 混合):DSA 参数以嵌套子结构随包导出
118
+ self.dsa_config = dsa_config
119
+
120
+ super().__init__(
121
+ pad_token_id=pad_token_id,
122
+ bos_token_id=bos_token_id,
123
+ eos_token_id=eos_token_id,
124
+ tie_word_embeddings=tie_word_embeddings,
125
+ **kwargs,
126
+ )
127
+
128
+ @property
129
+ def is_mla(self):
130
+ return (self.q_lora_rank is not None or self.kv_lora_rank is not None
131
+ or self.qk_nope_head_dim is not None
132
+ or self.qk_rope_head_dim is not None
133
+ or self.v_head_dim is not None or self.mla_use_nope is True)
134
+
135
+ @property
136
+ def is_moe(self):
137
+ return self.num_experts is not None
138
+
139
+ @property
140
+ def is_linear_attn(self) -> bool:
141
+ return not (self.linear_attn_config is None or
142
+ (isinstance(self.linear_attn_config, dict)
143
+ and self.linear_attn_config["kda_layers"] is not None
144
+ and len(self.linear_attn_config["kda_layers"]) == 0))
145
+
146
+ def is_kda_layer(self, layer_idx: int):
147
+ return (self.linear_attn_config is not None
148
+ and (layer_idx + 1) in self.linear_attn_config["kda_layers"])
149
+
150
+
151
+ class KimiK3VisionConfig(PretrainedConfig):
152
+
153
+ def __init__(
154
+ self,
155
+ patch_size: int = 14,
156
+ init_pos_emb_height: int = 64,
157
+ init_pos_emb_width: int = 64,
158
+ init_pos_emb_time: int = 4,
159
+ pos_emb_type: str = 'divided_fixed',
160
+ vt_num_attention_heads: int = 12,
161
+ vt_num_hidden_layers: int = 27,
162
+ vt_hidden_size: int = 1024,
163
+ vt_intermediate_size: int = 4096,
164
+ merge_kernel_size: tuple = (2, 2),
165
+ merge_type: str = 'sd2_tpool',
166
+ _attn_implementation: str = 'flash_attention_2',
167
+ # MM Projector parameters
168
+ mm_projector_type: str = 'patchmergerv2',
169
+ mm_hidden_size: int | None = None,
170
+ projector_hidden_act: str = "gelu",
171
+ projector_ln_eps: float = 1e-5,
172
+ # vision tower parameters
173
+ qkv_hidden_size: int = 1536,
174
+ norm_type: str = 'rmsnorm',
175
+ attn_bias: bool = False,
176
+ patch_embed_proj_bias: bool = False,
177
+ mlp_type: str = 'mlp2',
178
+ linear_bias: bool = False,
179
+ activation_func: str = 'gelu_pytorch_tanh',
180
+ pos_emb_interpolation_mode: str = 'bilinear',
181
+ # Other parameters
182
+ ignore_index: int = -100,
183
+ media_placeholder_token_id: int = 163605,
184
+ pad_token_id: int = 0,
185
+ text_hidden_size=7168,
186
+ **kwargs):
187
+
188
+ self.patch_size = patch_size
189
+ self.init_pos_emb_height = init_pos_emb_height
190
+ self.init_pos_emb_width = init_pos_emb_width
191
+ self.init_pos_emb_time = init_pos_emb_time
192
+ self.pos_emb_type = pos_emb_type
193
+ self.vt_num_attention_heads = vt_num_attention_heads
194
+ self.vt_num_hidden_layers = vt_num_hidden_layers
195
+ self.vt_hidden_size = vt_hidden_size
196
+ self.vt_intermediate_size = vt_intermediate_size
197
+ self.merge_kernel_size = merge_kernel_size
198
+ self.merge_type = merge_type
199
+ self._attn_implementation = _attn_implementation
200
+
201
+ # MM Projector config
202
+ self.mm_projector_type = mm_projector_type
203
+ self.mm_hidden_size = mm_hidden_size if mm_hidden_size is not None else vt_hidden_size
204
+ self.projector_hidden_act = projector_hidden_act
205
+ self.projector_ln_eps = projector_ln_eps
206
+ self.text_hidden_size = text_hidden_size
207
+
208
+ # vision tower parameters
209
+ self.qkv_hidden_size = qkv_hidden_size
210
+ self.norm_type = norm_type
211
+ self.attn_bias = attn_bias
212
+ self.patch_embed_proj_bias = patch_embed_proj_bias
213
+ self.mlp_type = mlp_type
214
+ self.linear_bias = linear_bias
215
+ self.activation_func = activation_func
216
+ self.pos_emb_interpolation_mode = pos_emb_interpolation_mode
217
+
218
+ super().__init__(**kwargs)
219
+
220
+
221
+ class KimiK3Config(PretrainedConfig):
222
+ """Kimi-K3 model configuration.
223
+
224
+ Args:
225
+ text_config (dict | KimiLinearConfig): Configuration for the text model.
226
+
227
+ Vision Tower Parameters (from MoonViT3dConfig):
228
+ patch_size (int): Patch size for vision tower.
229
+ init_pos_emb_height (int): Initial position embedding height.
230
+ init_pos_emb_width (int): Initial position embedding width.
231
+ init_pos_emb_time (int): Initial position embedding time dimension.
232
+ pos_emb_type (str): Type of position embedding.
233
+ vt_num_attention_heads (int): Number of attention heads in vision tower.
234
+ vt_num_hidden_layers (int): Number of hidden layers in vision tower.
235
+ vt_hidden_size (int): Hidden size of vision tower.
236
+ vt_intermediate_size (int): Intermediate size in vision tower FFN.
237
+ merge_kernel_size (tuple): Kernel size for patch merging.
238
+ merge_type (str): Type of merge operation.
239
+ _attn_implementation (str): Attention implementation type.
240
+
241
+ MM Projector Parameters (from MultiModalProjectorConfig):
242
+ mm_projector_type (str): Type of multimodal projector.
243
+ mm_hidden_size (int): Hidden size from vision tower (should match vt_hidden_size).
244
+ projector_hidden_act (str): Activation function for projector.
245
+ projector_ln_eps (float): Layer norm epsilon for projector.
246
+
247
+ Other Parameters:
248
+ ignore_index (int): The ignore index for the loss function.
249
+ media_placeholder_token_id (int): The token ID to use for media placeholders.
250
+ pad_token_id (int): The token ID to use for padding.
251
+ """
252
+
253
+ model_type = "kimi_k31"
254
+
255
+ def __init__(
256
+ self,
257
+ text_config: dict | KimiLinearConfig = None,
258
+ vision_config: dict | KimiK3VisionConfig = None,
259
+ # Other parameters
260
+ ignore_index: int = -100,
261
+ media_placeholder_token_id: int = 163605,
262
+ pad_token_id: int = 0,
263
+ **kwargs,
264
+ ):
265
+ if isinstance(text_config, dict):
266
+ text_config = KimiLinearConfig(**text_config)
267
+ if isinstance(vision_config, dict):
268
+ vision_config = KimiK3VisionConfig(**vision_config)
269
+ self.text_config = text_config
270
+ self.vision_config = vision_config
271
+ # Other config
272
+ self.ignore_index = ignore_index
273
+ self.media_placeholder_token_id = media_placeholder_token_id
274
+ if getattr(self.text_config, "quantization_config", None) is not None:
275
+ self.quantization_config = self.text_config.quantization_config
276
+
277
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
encoding_k3.py ADDED
@@ -0,0 +1,735 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Kimi K3 XTML encoding helpers.
2
+
3
+ This module keeps chat rendering in Python.
4
+ Callers that need token IDs should consume ``EncodeSegment`` objects directly:
5
+ structural markers may be encoded as tiktoken special tokens, while user/tool
6
+ text and attribute values are encoded as ordinary text.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from dataclasses import dataclass
13
+ from typing import Any, Iterable, Optional
14
+
15
+ OPEN_TOKEN = "<|open|>"
16
+ CLOSE_TOKEN = "<|close|>"
17
+ SEP_TOKEN = "<|sep|>"
18
+ END_OF_MSG_TOKEN = "<|end_of_msg|>"
19
+ IMAGE_PLACEHOLDER = "<|kimi_image_placeholder|>"
20
+
21
+ _VALID_THINKING_EFFORTS = {"low", "high", "max"}
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class EncodeSegment:
26
+ text: str
27
+ allow_special: bool = False
28
+
29
+
30
+ class _ImagePromptState:
31
+
32
+ def __init__(self, image_prompts: Optional[list[str]] = None):
33
+ self.image_prompts = image_prompts
34
+ self.index = 0
35
+
36
+ def next_prompt(self) -> str:
37
+ if self.image_prompts is None:
38
+ return IMAGE_PLACEHOLDER
39
+ if self.index >= len(self.image_prompts):
40
+ raise ValueError("More image placeholders than image prompts.")
41
+ prompt = self.image_prompts[self.index]
42
+ self.index += 1
43
+ return prompt
44
+
45
+ def assert_consumed(self) -> None:
46
+ if self.image_prompts is None:
47
+ return
48
+ if self.index != len(self.image_prompts):
49
+ raise ValueError(
50
+ f"image prompt count {len(self.image_prompts)} != "
51
+ f"consumed placeholder count {self.index}")
52
+
53
+
54
+ def _segment(text: Any, *, allow_special: bool = False) -> list[EncodeSegment]:
55
+ text = str(text)
56
+ if not text:
57
+ return []
58
+ return [EncodeSegment(text, allow_special=allow_special)]
59
+
60
+
61
+ def _control(text: str) -> list[EncodeSegment]:
62
+ return _segment(text, allow_special=True)
63
+
64
+
65
+ def _text(text: Any) -> list[EncodeSegment]:
66
+ return _segment(text, allow_special=False)
67
+
68
+
69
+ def _append_text(
70
+ segments: list[EncodeSegment],
71
+ text: Any,
72
+ image_state: _ImagePromptState,
73
+ ) -> None:
74
+ text = str(text)
75
+ if text == "":
76
+ return
77
+ if image_state.image_prompts is None or IMAGE_PLACEHOLDER not in text:
78
+ segments.extend(_text(text))
79
+ return
80
+
81
+ parts = text.split(IMAGE_PLACEHOLDER)
82
+ for i, part in enumerate(parts):
83
+ segments.extend(_text(part))
84
+ if i < len(parts) - 1:
85
+ segments.extend(
86
+ _segment(image_state.next_prompt(), allow_special=True))
87
+
88
+
89
+ def _escape_attr_value(value: Any) -> str:
90
+ return str(value).replace("&", "&amp;").replace('"', "&quot;")
91
+
92
+
93
+ def _attr(key: str, value: Any) -> list[EncodeSegment]:
94
+ return (_text(f" {key}") + _text('="') + _text(_escape_attr_value(value)) +
95
+ _text('"'))
96
+
97
+
98
+ def _open_tag(
99
+ tag: str, attrs: Iterable[tuple[str, Any]] = ()) -> list[EncodeSegment]:
100
+ segments: list[EncodeSegment] = []
101
+ segments.extend(_control(OPEN_TOKEN))
102
+ segments.extend(_text(tag))
103
+ for key, value in attrs:
104
+ segments.extend(_attr(key, value))
105
+ segments.extend(_control(SEP_TOKEN))
106
+ return segments
107
+
108
+
109
+ def _close_tag(tag: str) -> list[EncodeSegment]:
110
+ segments: list[EncodeSegment] = []
111
+ segments.extend(_control(CLOSE_TOKEN))
112
+ segments.extend(_text(tag))
113
+ segments.extend(_control(SEP_TOKEN))
114
+ return segments
115
+
116
+
117
+ def _end_of_msg() -> list[EncodeSegment]:
118
+ return _control(END_OF_MSG_TOKEN)
119
+
120
+
121
+ def _json_compact(value: Any) -> str:
122
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
123
+
124
+
125
+ def _is_mapping(value: Any) -> bool:
126
+ return isinstance(value, dict)
127
+
128
+
129
+ def _xtml_type(value: Any) -> str:
130
+ if isinstance(value, bool):
131
+ return "boolean"
132
+ if value is None:
133
+ return "null"
134
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
135
+ return "number"
136
+ if isinstance(value, str):
137
+ return "string"
138
+ if _is_mapping(value):
139
+ return "object"
140
+ return "array"
141
+
142
+
143
+ def _xtml_value(value: Any) -> str:
144
+ if isinstance(value, str):
145
+ return value
146
+ return json.dumps(value, ensure_ascii=False)
147
+
148
+
149
+ def _get_value(obj: Any, key: str, default: Any = None) -> Any:
150
+ if isinstance(obj, dict):
151
+ return obj.get(key, default)
152
+ return getattr(obj, key, default)
153
+
154
+
155
+ def extract_response_schema(response_format: Any) -> Any:
156
+ if response_format is None:
157
+ return None
158
+
159
+ json_schema = _get_value(response_format, "json_schema")
160
+ if json_schema is None:
161
+ return None
162
+
163
+ if isinstance(json_schema, dict):
164
+ return json_schema.get(
165
+ "schema",
166
+ json_schema.get("json_schema", json_schema),
167
+ )
168
+
169
+ schema = _get_value(json_schema, "schema")
170
+ if schema is not None:
171
+ return schema
172
+
173
+ schema = _get_value(json_schema, "json_schema")
174
+ if schema is not None:
175
+ return schema
176
+
177
+ return json_schema
178
+
179
+
180
+ def deep_sort_dict(obj: Any) -> Any:
181
+ if isinstance(obj, dict):
182
+ return {k: deep_sort_dict(v) for k, v in sorted(obj.items())}
183
+ if isinstance(obj, list):
184
+ return [deep_sort_dict(item) for item in obj]
185
+ return obj
186
+
187
+
188
+ # One normalized tool-call argument: (key, XTML type, rendered text). The
189
+ # text keeps the original JSON literal for non-string values and is the
190
+ # decoded string for string values.
191
+ XtmlArgument = tuple[str, str, str]
192
+
193
+
194
+ def _parse_arguments_object(s: str) -> list[XtmlArgument]:
195
+ """Parse a JSON object string one level deep.
196
+
197
+ Each top-level key-value pair yields one ``(key, type, text)`` triple. The
198
+ text keeps the original JSON literal for non-string values (``1e2`` stays
199
+ ``1e2``, ``[1,2]`` keeps its exact bytes) and is the decoded (unescaped)
200
+ string for string values. Nested values are never re-serialized. Anything
201
+ after the closing ``}`` is ignored. Raises ``ValueError`` on malformed
202
+ input (including a valid non-object JSON document).
203
+ """
204
+ idx = 0
205
+
206
+ def _skip_whitespaces() -> None:
207
+ nonlocal idx
208
+ while idx < len(s) and s[idx] in (" ", "\t", "\n", "\r"):
209
+ idx += 1
210
+
211
+ def _next_char() -> Optional[str]:
212
+ nonlocal idx
213
+ if idx < len(s):
214
+ c = s[idx]
215
+ idx += 1
216
+ return c
217
+ return None
218
+
219
+ _skip_whitespaces()
220
+ if _next_char() != "{":
221
+ raise ValueError("JSON arguments must be an object")
222
+ _skip_whitespaces()
223
+
224
+ parsed: list[XtmlArgument] = []
225
+
226
+ if idx >= len(s):
227
+ raise ValueError("Unexpected end of JSON object")
228
+ if s[idx] == "}":
229
+ return parsed
230
+
231
+ json_decoder = json.JSONDecoder(strict=False)
232
+
233
+ def _raw_decode(start_idx: int) -> tuple[Any, int]:
234
+ try:
235
+ return json_decoder.raw_decode(s, idx=start_idx)
236
+ except json.JSONDecodeError as e:
237
+ raise ValueError(str(e)) from e
238
+
239
+ while True:
240
+ decoded_key, idx = _raw_decode(idx)
241
+ if not isinstance(decoded_key, str):
242
+ raise ValueError(
243
+ f"JSON object key must be a string, got {decoded_key!r}")
244
+ _skip_whitespaces()
245
+ if _next_char() != ":":
246
+ raise ValueError(f"Expects ':' after {decoded_key}")
247
+ _skip_whitespaces()
248
+
249
+ value_start_idx = idx
250
+ decoded_value, idx = _raw_decode(idx)
251
+ value_end_idx = idx
252
+
253
+ text = (decoded_value if isinstance(decoded_value, str) else
254
+ s[value_start_idx:value_end_idx])
255
+ parsed.append((decoded_key, _xtml_type(decoded_value), text))
256
+
257
+ _skip_whitespaces()
258
+ c = _next_char()
259
+ _skip_whitespaces()
260
+
261
+ if c == "}":
262
+ break
263
+ elif c == ",":
264
+ continue
265
+ else:
266
+ raise ValueError(f"Expect '}}' or ',', got {c!r}")
267
+
268
+ return parsed
269
+
270
+
271
+ def normalize_tool_arguments(
272
+ arguments: Any, ) -> tuple[list[XtmlArgument], Optional[str]]:
273
+ """Normalize tool call arguments for XTML rendering.
274
+
275
+ Returns ``(argument_triples, raw_json_block)``. String arguments are parsed
276
+ one level deep so non-string values keep their original JSON literal text,
277
+ and anything after the closing ``}`` is discarded; dict arguments (already
278
+ Python objects) are serialized on the spot. Any string that is not a
279
+ well-formed JSON object -- unparsable, whitespace only, or valid
280
+ non-object JSON -- falls back to the raw ``<json>`` block.
281
+ """
282
+ if arguments is None:
283
+ return [], None
284
+ if isinstance(arguments, dict):
285
+ return [(str(key), _xtml_type(value), _xtml_value(value))
286
+ for key, value in arguments.items()], None
287
+ if isinstance(arguments, str):
288
+ if arguments == "":
289
+ return [], None
290
+ try:
291
+ return _parse_arguments_object(arguments), None
292
+ except ValueError:
293
+ return [], arguments
294
+ raise TypeError(
295
+ "Kimi K3 tool call arguments must be a dict or a JSON object string.")
296
+
297
+
298
+ def normalize_message(message: Any) -> Any:
299
+ if not isinstance(message, dict):
300
+ return message
301
+
302
+ normalized = dict(message)
303
+
304
+ tools = normalized.get("tools")
305
+ if tools is not None:
306
+ normalized["tools"] = deep_sort_dict(tools)
307
+
308
+ tool_calls = normalized.get("tool_calls")
309
+ if not tool_calls:
310
+ return normalized
311
+
312
+ normalized_calls = []
313
+ for tool_call in tool_calls:
314
+ if not isinstance(tool_call, dict):
315
+ normalized_calls.append(tool_call)
316
+ continue
317
+
318
+ tc = dict(tool_call)
319
+ function = tc.get("function")
320
+ if isinstance(function, dict):
321
+ fn = dict(function)
322
+ arguments, json_block = normalize_tool_arguments(
323
+ fn.get("arguments"))
324
+ fn["arguments"] = arguments
325
+ if json_block is None:
326
+ fn.pop("_xtml_json_block", None)
327
+ else:
328
+ fn["_xtml_json_block"] = json_block
329
+ tc["function"] = fn
330
+ else:
331
+ arguments, json_block = normalize_tool_arguments(
332
+ tc.get("arguments"))
333
+ tc["arguments"] = arguments
334
+ if json_block is None:
335
+ tc.pop("_xtml_json_block", None)
336
+ else:
337
+ tc["_xtml_json_block"] = json_block
338
+ normalized_calls.append(tc)
339
+
340
+ normalized["tool_calls"] = normalized_calls
341
+ return normalized
342
+
343
+
344
+ def normalize_conversation(conversation: Any) -> Any:
345
+ if not isinstance(conversation, list):
346
+ return conversation
347
+
348
+ def normalize_messages(messages: list[Any]) -> list[Any]:
349
+ return [normalize_message(message) for message in messages]
350
+
351
+ if conversation and isinstance(conversation[0], list):
352
+ return [normalize_messages(messages) for messages in conversation]
353
+ return normalize_messages(conversation)
354
+
355
+
356
+ def _tool_call_id_index(tool_calls: Any) -> dict:
357
+ """Map assistant ``tool_calls[].id`` to ``(1-based position, function name)``.
358
+
359
+ The position mirrors the chat template's enumeration over ``tool_calls``
360
+ (every entry advances the position, even an id-less one). Duplicate ids keep
361
+ their first occurrence.
362
+ """
363
+ index: dict = {}
364
+ if not isinstance(tool_calls, list):
365
+ return index
366
+ for position, tool_call in enumerate(tool_calls, start=1):
367
+ if not isinstance(tool_call, dict):
368
+ continue
369
+ call_id = tool_call.get("id")
370
+ if call_id is None:
371
+ continue
372
+ key = str(call_id)
373
+ if key in index:
374
+ continue
375
+ function = tool_call.get("function")
376
+ name = (function.get("name")
377
+ if isinstance(function, dict) else tool_call.get("name"))
378
+ index[key] = (position, name)
379
+ return index
380
+
381
+
382
+ def normalize_xtml_tool_result_messages(messages: list[Any]) -> list[Any]:
383
+ """Re-sort K3 XTML tool results into assistant ``tool_calls`` order.
384
+
385
+ Serving frameworks generally deliver tool results already in call order. A
386
+ direct Transformers caller, however, may pass OpenAI-style tool messages in any
387
+ order, so each run of consecutive tool messages is matched against the most
388
+ recent preceding assistant ``tool_calls`` by opaque ``tool_call_id`` ==
389
+ ``tool_calls[].id`` (K3 drops the ``func:index`` format requirement) and
390
+ sorted by the matched 1-based position. The matched call is authoritative,
391
+ so each matched message's ``tool`` is set to that call's function name --
392
+ this keeps an explicit (and possibly stale) ``tool``/``name`` from drifting
393
+ out of sync with the reordered position. ``index`` is still derived from the
394
+ rendered position by the chat template. A run that cannot be fully matched is
395
+ left untouched. Re-running is idempotent.
396
+
397
+ This function is side-effect free: matched tool messages are shallow-copied
398
+ before their ``tool``/``name`` is rewritten, and every other message is
399
+ appended to the output as-is. The input list and its message objects are
400
+ never mutated.
401
+ """
402
+ if not isinstance(messages, list):
403
+ return messages
404
+
405
+ output: list[Any] = []
406
+ current_index: dict = {}
407
+ i = 0
408
+ n = len(messages)
409
+
410
+ while i < n:
411
+ message = messages[i]
412
+
413
+ if isinstance(message, dict) and message.get("role") == "assistant":
414
+ tool_calls = message.get("tool_calls")
415
+ current_index = _tool_call_id_index(
416
+ tool_calls) if tool_calls else {}
417
+ output.append(message)
418
+ i += 1
419
+ continue
420
+
421
+ if not isinstance(message, dict) or message.get("role") != "tool":
422
+ output.append(message)
423
+ i += 1
424
+ continue
425
+
426
+ run: list[tuple] = [] # (position, original_offset, message, name)
427
+ unresolved = False
428
+ offset = 0
429
+ while (i < n and isinstance(messages[i], dict)
430
+ and messages[i].get("role") == "tool"):
431
+ tool_message = messages[i]
432
+ call_id = tool_message.get("tool_call_id", tool_message.get("id"))
433
+ matched = current_index.get(
434
+ str(call_id)) if call_id is not None else None
435
+ if matched is None:
436
+ unresolved = True
437
+ run.append((None, offset, tool_message, None))
438
+ else:
439
+ position, name = matched
440
+ run.append((position, offset, tool_message, name))
441
+ offset += 1
442
+ i += 1
443
+
444
+ if unresolved:
445
+ output.extend(item[2] for item in run)
446
+ else:
447
+ run.sort(key=lambda item: (item[0], item[1]))
448
+ for _, _, tool_message, name in run:
449
+ if name is None:
450
+ output.append(tool_message)
451
+ continue
452
+ # The id-matched call is authoritative: align tool (and any
453
+ # explicit name) so the rendered XTML tool attribute cannot
454
+ # disagree with the reordered position. Copy first so the
455
+ # caller's message object is never mutated.
456
+ resolved = dict(tool_message)
457
+ resolved["tool"] = name
458
+ if "name" in resolved:
459
+ resolved["name"] = name
460
+ output.append(resolved)
461
+
462
+ return output
463
+
464
+
465
+ def is_batched_conversation(conversation: Any) -> bool:
466
+ return (isinstance(conversation, list) and bool(conversation)
467
+ and isinstance(conversation[0], list))
468
+
469
+
470
+ def _render_content_segments(
471
+ content: Any,
472
+ image_state: _ImagePromptState,
473
+ ) -> list[EncodeSegment]:
474
+ segments: list[EncodeSegment] = []
475
+ if isinstance(content, str):
476
+ _append_text(segments, content, image_state)
477
+ elif content is not None:
478
+ for part in content:
479
+ if part["type"] in ["image", "image_url"]:
480
+ segments.extend(
481
+ _segment(image_state.next_prompt(), allow_special=True))
482
+ else:
483
+ _append_text(segments, part["text"], image_state)
484
+ return segments
485
+
486
+
487
+ def _internal_system_message(message_type: str,
488
+ body: str) -> list[EncodeSegment]:
489
+ segments: list[EncodeSegment] = []
490
+ segments.extend(
491
+ _open_tag("message", [("role", "system"), ("type", message_type)]))
492
+ segments.extend(_text(body.strip()))
493
+ segments.extend(_close_tag("message"))
494
+ segments.extend(_end_of_msg())
495
+ return segments
496
+
497
+
498
+ def _render_assistant_segments(
499
+ message: dict[str, Any],
500
+ image_state: _ImagePromptState,
501
+ thinking: bool = True,
502
+ ) -> list[EncodeSegment]:
503
+ segments: list[EncodeSegment] = []
504
+ # The <think> channel is structural: in thinking mode every assistant
505
+ # message carries the open/close tags even when there is no reasoning
506
+ # content to fill in. In non-thinking mode the channel is dropped
507
+ # entirely.
508
+ if thinking:
509
+ reasoning_content = message.get("reasoning_content") or message.get(
510
+ "reasoning")
511
+ segments.extend(_open_tag("think"))
512
+ # Only an empty string counts as no reasoning, so whitespace-only
513
+ # reasoning is still rendered into the think channel.
514
+ if reasoning_content is not None and str(reasoning_content) != "":
515
+ _append_text(segments, reasoning_content, image_state)
516
+ segments.extend(_close_tag("think"))
517
+
518
+ segments.extend(_open_tag("response"))
519
+ segments.extend(
520
+ _render_content_segments(message.get("content"), image_state))
521
+ segments.extend(_close_tag("response"))
522
+
523
+ tool_calls = message.get("tool_calls")
524
+ if tool_calls:
525
+ segments.extend(_open_tag("tools"))
526
+ for index, tool_call in enumerate(tool_calls, start=1):
527
+ fn = tool_call.get("function", tool_call)
528
+ segments.extend(
529
+ _open_tag("call", [("tool", fn["name"]), ("index", index)]))
530
+ args = fn.get("arguments", [])
531
+ json_block = fn.get("_xtml_json_block")
532
+ if json_block is not None:
533
+ segments.extend(_open_tag("json", [("type", "object")]))
534
+ _append_text(segments, json_block, image_state)
535
+ segments.extend(_close_tag("json"))
536
+ else:
537
+ for key, arg_type, arg_text in args:
538
+ segments.extend(
539
+ _open_tag("argument", [("key", key),
540
+ ("type", arg_type)]))
541
+ _append_text(segments, arg_text, image_state)
542
+ segments.extend(_close_tag("argument"))
543
+ segments.extend(_close_tag("call"))
544
+ segments.extend(_close_tag("tools"))
545
+
546
+ return segments
547
+
548
+
549
+ def _render_tool_declare(tools: Any,
550
+ *,
551
+ dynamic: bool = False) -> list[EncodeSegment]:
552
+ if dynamic:
553
+ body = (
554
+ "## New Tools Available\n"
555
+ "The system dynamically extends the toolset via lazy-loading.\n"
556
+ "You have access to all existing and extended tools.\n"
557
+ "Here are the specs for the extended tools.\n\n"
558
+ "```json\n"
559
+ f"{_json_compact(tools)}\n"
560
+ "```")
561
+ else:
562
+ body = ("# Tools\n"
563
+ "Here are the available tools, described in JSONSchema.\n\n"
564
+ "```json\n"
565
+ f"{_json_compact(tools)}\n"
566
+ "```")
567
+ segments: list[EncodeSegment] = []
568
+ segments.extend(
569
+ _open_tag("message", [("role", "system"), ("type", "tool-declare")]))
570
+ segments.extend(_text(body))
571
+ segments.extend(_close_tag("message"))
572
+ segments.extend(_end_of_msg())
573
+ return segments
574
+
575
+
576
+ def build_chat_segments(
577
+ messages: list[Any],
578
+ tools: Optional[list[dict]] = None,
579
+ *,
580
+ add_generation_prompt: bool = True,
581
+ thinking: bool = True,
582
+ image_prompts: Optional[list[str]] = None,
583
+ **kwargs: Any,
584
+ ) -> list[EncodeSegment]:
585
+ # Re-sort tool results by tool_call_id at the lowest layer so every caller
586
+ # (processor or direct tokenizer) gets correctly ordered XTML. The helper is
587
+ # side-effect free, so the caller's message objects are left untouched.
588
+ messages = normalize_xtml_tool_result_messages(messages)
589
+ messages = normalize_conversation(messages)
590
+ tools = deep_sort_dict(tools)
591
+
592
+ kwargs = dict(kwargs)
593
+ response_format = kwargs.get("response_format")
594
+ if "response_schema" not in kwargs:
595
+ response_schema = extract_response_schema(response_format)
596
+ if response_schema is not None:
597
+ kwargs["response_schema"] = response_schema
598
+ if kwargs.get("response_schema") is not None:
599
+ kwargs["response_schema"] = deep_sort_dict(kwargs["response_schema"])
600
+
601
+ image_state = _ImagePromptState(image_prompts)
602
+ segments: list[EncodeSegment] = []
603
+
604
+ tool_calls = None
605
+ tool_index = 0
606
+
607
+ if tools:
608
+ segments.extend(_render_tool_declare(tools))
609
+
610
+ thinking_effort = kwargs.get("thinking_effort")
611
+ if thinking and thinking_effort is not None:
612
+ assert thinking_effort in _VALID_THINKING_EFFORTS, (
613
+ f"Unsupported thinking_effort={thinking_effort!r}; "
614
+ f"supported values are {sorted(_VALID_THINKING_EFFORTS)}.")
615
+ if thinking and thinking_effort in _VALID_THINKING_EFFORTS:
616
+ segments.extend(
617
+ _internal_system_message(
618
+ "thinking-effort",
619
+ "`thinking_effort` guides on how much to think in your "
620
+ "thinking channel (not including the response channel), "
621
+ "supported values include `low`, `medium`, `high`, and `max`.\n"
622
+ f"Now the system is invoked with `thinking_effort={thinking_effort}`.",
623
+ ))
624
+
625
+ for message_index, message in enumerate(messages):
626
+ # Malformed messages are rejected instead of being silently skipped.
627
+ if not isinstance(message, dict):
628
+ raise ValueError(
629
+ f"Kimi K3 messages must be dicts, got {type(message).__name__} "
630
+ f"at index {message_index}.")
631
+
632
+ role = message.get("role")
633
+ if role == "user":
634
+ attrs = [("role", "user")]
635
+ if message.get("name"):
636
+ attrs.append(("name", message["name"]))
637
+ segments.extend(_open_tag("message", attrs))
638
+ segments.extend(
639
+ _render_content_segments(message.get("content"), image_state))
640
+ segments.extend(_close_tag("message"))
641
+ segments.extend(_end_of_msg())
642
+ elif role == "system" and message.get("tools"):
643
+ segments.extend(
644
+ _render_tool_declare(message["tools"], dynamic=True))
645
+ elif role == "system":
646
+ attrs = [("role", "system")]
647
+ if message.get("name"):
648
+ attrs.append(("name", message["name"]))
649
+ segments.extend(_open_tag("message", attrs))
650
+ segments.extend(
651
+ _render_content_segments(message.get("content"), image_state))
652
+ segments.extend(_close_tag("message"))
653
+ segments.extend(_end_of_msg())
654
+ elif role == "tool":
655
+ tool_index += 1
656
+ tool_name = message.get("tool", message.get("name"))
657
+ if (tool_name is None and tool_calls is not None
658
+ and tool_index <= len(tool_calls)):
659
+ tc = tool_calls[tool_index - 1]
660
+ fn = tc.get("function", tc)
661
+ tool_name = fn["name"]
662
+ if tool_name is None:
663
+ raise ValueError(
664
+ "Kimi K3 tool messages need a resolvable tool name: "
665
+ "carry `tool`/`name`, or match a preceding assistant "
666
+ "tool_call by order.")
667
+ segments.extend(
668
+ _open_tag(
669
+ "message",
670
+ [("role", "tool"), ("tool", tool_name),
671
+ ("index", tool_index)],
672
+ ))
673
+ segments.extend(
674
+ _render_content_segments(message.get("content"), image_state))
675
+ segments.extend(_close_tag("message"))
676
+ segments.extend(_end_of_msg())
677
+ elif role == "assistant":
678
+ tool_calls = message.get("tool_calls")
679
+ tool_index = 0
680
+ attrs = [("role", "assistant")]
681
+ if message.get("name"):
682
+ attrs.append(("name", message["name"]))
683
+ segments.extend(_open_tag("message", attrs))
684
+ segments.extend(
685
+ _render_assistant_segments(message, image_state, thinking))
686
+ segments.extend(_close_tag("message"))
687
+ segments.extend(_end_of_msg())
688
+ else:
689
+ raise ValueError(
690
+ f"Unknown message role {role!r} at index {message_index}.")
691
+
692
+ tool_choice = kwargs.get("tool_choice")
693
+ if tool_choice == "required":
694
+ segments.extend(
695
+ _internal_system_message(
696
+ "tool-choice",
697
+ "The system is invoked with `tool_choice=required`.\n"
698
+ "You MUST call tools in the next message.",
699
+ ))
700
+ elif tool_choice == "none":
701
+ segments.extend(
702
+ _internal_system_message(
703
+ "tool-choice",
704
+ "The system is invoked with `tool_choice=none`.\n"
705
+ "You MUST NOT call any tools in the next message.",
706
+ ))
707
+
708
+ rf = kwargs.get("response_format")
709
+ rf_type = _get_value(rf, "type", rf) if isinstance(rf, dict) else rf
710
+ if rf_type == "json_object":
711
+ segments.extend(
712
+ _internal_system_message(
713
+ "response-format",
714
+ "The system is invoked with `response_format=json_object`.\n"
715
+ "Your response must be raw JSON data without markdown code "
716
+ "blocks (```json) or any additional formatting.",
717
+ ))
718
+ elif rf_type == "json_schema":
719
+ schema = _json_compact(kwargs.get("response_schema"))
720
+ segments.extend(
721
+ _internal_system_message(
722
+ "response-format",
723
+ "The system is invoked with `response_format=json_schema`.\n"
724
+ "Your response must be raw JSON data without markdown code "
725
+ "blocks (```json) or any additional formatting.\n"
726
+ "The JSON data must match the following schema:\n"
727
+ f"```json\n{schema}\n```",
728
+ ))
729
+
730
+ if add_generation_prompt:
731
+ segments.extend(_open_tag("message", [("role", "assistant")]))
732
+ segments.extend(_open_tag("think" if thinking else "response"))
733
+
734
+ image_state.assert_consumed()
735
+ return segments
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "max_length": 1048576,
3
+ "eos_token_id": 163586
4
+ }
kimi_k3_processor.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Kimi-K3 processor: wraps vision processor + tokenizer into a single interface.
2
+
3
+ Chat rendering (including XTML tool-result ordering) is handled by the
4
+ tokenizer's Python encoder; this processor adds multimodal media preprocessing.
5
+ """
6
+
7
+ from transformers.feature_extraction_utils import BatchFeature
8
+ from transformers.processing_utils import ProcessorMixin
9
+ from transformers.utils import logging
10
+
11
+ from .media_utils import ensure_media_type
12
+
13
+ logger = logging.get_logger(__name__)
14
+
15
+ # ── KimiK3Processor ───────────────────────────────────────────────────
16
+
17
+
18
+ class KimiK3Processor(ProcessorMixin):
19
+ r"""
20
+ Constructs a KimiK3 processor which wraps a KimiK3 image processor
21
+ and a tokenizer into a single processor.
22
+
23
+ [`KimiK3Processor`] offers all the functionalities of
24
+ [`KimiK3VisionProcessor`] and [`TikTokenTokenizer`].
25
+
26
+ Args:
27
+ image_processor ([`KimiK3VisionProcessor`], *optional*):
28
+ The image processor is a required input.
29
+ tokenizer ([`TikTokenTokenizer`], *optional*):
30
+ The tokenizer is a required input.
31
+ chat_template (`str`, *optional*): Kept for ProcessorMixin
32
+ compatibility. Kimi K3 chat encoding is implemented in Python by
33
+ the tokenizer.
34
+ """
35
+
36
+ attributes = ["image_processor", "tokenizer"]
37
+ valid_kwargs = ["chat_template"]
38
+ image_processor_class = "AutoImageProcessor"
39
+ tokenizer_class = "AutoTokenizer"
40
+
41
+ def __init__(
42
+ self,
43
+ image_processor=None,
44
+ tokenizer=None,
45
+ chat_template=None,
46
+ **kwargs,
47
+ ):
48
+ super().__init__(image_processor,
49
+ tokenizer,
50
+ chat_template=chat_template)
51
+ self.media_processor = image_processor
52
+ self.image_placeholder = "<|kimi_image_placeholder|>"
53
+
54
+ # ── Media preprocessing ────────────────────────────────────────────
55
+
56
+ def update_raw_text(self, text: str, image_prompts: list[str]) -> str:
57
+ # Replace image placeholders
58
+ image_count = text.count(self.image_placeholder)
59
+ if image_count > 0:
60
+ assert image_count == len(image_prompts), (
61
+ f"image placeholder count {image_count} != "
62
+ f"image_prompts count {len(image_prompts)}")
63
+ text_parts = text.split(self.image_placeholder)
64
+ assert len(text_parts) == len(image_prompts) + 1
65
+ text = "".join([
66
+ text_parts[i] + image_prompts[i]
67
+ for i in range(len(image_prompts))
68
+ ])
69
+ text += text_parts[-1]
70
+
71
+ return text
72
+
73
+ def preprocess_medias(self,
74
+ medias: list[dict]) -> tuple[list[dict], list[str]]:
75
+ """Process media items and generate corresponding prompts.
76
+
77
+ Returns:
78
+ A tuple of (updated_medias, image_prompts).
79
+ """
80
+ updated_medias = []
81
+ image_prompts = []
82
+ for media in medias:
83
+ if media['type'] == 'image':
84
+ updated_medias.append(media)
85
+ img = ensure_media_type(
86
+ media,
87
+ transparent_bg_config=self.media_processor.
88
+ _transparent_bg_config,
89
+ transparent_bg_fill_stage=self.media_processor.
90
+ _transparent_bg_fill_stage,
91
+ )['image']
92
+ w, h = img.size
93
+ image_prompts.append(
94
+ self.media_processor.make_image_prompt(w, h))
95
+ else:
96
+ raise ValueError(f"unsupported media type: {media['type']}")
97
+ return updated_medias, image_prompts
98
+
99
+ # ── Main entry points ──────────────────────────────────────────────
100
+
101
+ def __call__(self,
102
+ messages: list[dict] = None,
103
+ medias: list[dict] = None,
104
+ text: str = None,
105
+ return_tensors: str = "pt",
106
+ **kwargs) -> BatchFeature:
107
+ """
108
+ Process multimodal inputs for Kimi-K3 model.
109
+
110
+ Args:
111
+ messages: List of message dicts with 'role' and 'content' fields.
112
+ If provided, medias and text will be extracted automatically.
113
+ medias: Pre-extracted list of media dicts.
114
+ text: Pre-formatted text string.
115
+ return_tensors: Format of returned tensors. Default: 'pt'.
116
+ **kwargs: Additional arguments passed to apply_chat_template.
117
+
118
+ Returns:
119
+ BatchFeature with fields: input_ids, attention_mask,
120
+ pixel_values, grid_thws.
121
+ """
122
+ if messages is None and (medias is None or text is None):
123
+ raise ValueError(
124
+ "Provide either 'messages' or both 'medias' and 'text'")
125
+
126
+ if medias is not None and text is not None:
127
+ updated_medias, image_prompts = (self.preprocess_medias(medias))
128
+ preprocessed = self.media_processor.preprocess(
129
+ updated_medias, return_tensors=return_tensors)
130
+ text = self.update_raw_text(text, image_prompts)
131
+ text_inputs = self.tokenizer(text, return_tensors=return_tensors)
132
+ return BatchFeature(data={**text_inputs, **preprocessed.data})
133
+
134
+ if medias is None:
135
+ medias = self._extract_medias_from_messages(messages)
136
+ updated_medias, image_prompts = (self.preprocess_medias(medias))
137
+ preprocessed = self.media_processor.preprocess(
138
+ updated_medias, return_tensors=return_tensors)
139
+
140
+ if text is None:
141
+ text_inputs = self.tokenizer.apply_chat_template(
142
+ messages,
143
+ tokenize=True,
144
+ return_tensors=return_tensors,
145
+ return_dict=True,
146
+ image_prompts=image_prompts,
147
+ **kwargs)
148
+ return BatchFeature(data={**text_inputs, **preprocessed.data})
149
+
150
+ text = self.update_raw_text(text, image_prompts)
151
+ text_inputs = self.tokenizer(text, return_tensors=return_tensors)
152
+ return BatchFeature(data={**text_inputs, **preprocessed.data})
153
+
154
+ @staticmethod
155
+ def _extract_medias_from_messages(messages: list[dict]) -> list[dict]:
156
+ """Extract media items from messages in a single pass."""
157
+ medias = []
158
+ for msg in messages:
159
+ if msg['role'] != 'user' or not msg.get('content'):
160
+ continue
161
+
162
+ for content_part in msg['content']:
163
+ if not isinstance(content_part, dict):
164
+ continue
165
+
166
+ content_type = content_part.get('type')
167
+ if content_type in ['image_url', 'image']:
168
+ image_data = content_part.get(content_type)
169
+ assert image_data is not None, f"image data is missing for content part: {content_part}"
170
+ medias.append({
171
+ 'type': 'image',
172
+ 'image': image_data,
173
+ })
174
+ return medias
175
+
176
+ def apply_chat_template(self, messages, **kwargs):
177
+ return self.tokenizer.apply_chat_template(messages, **kwargs)
178
+
179
+ def batch_decode(self, *args, **kwargs):
180
+ return self.tokenizer.batch_decode(*args, **kwargs)
181
+
182
+ def decode(self, *args, **kwargs):
183
+ return self.tokenizer.decode(*args, **kwargs)
184
+
185
+ @property
186
+ def model_input_names(self):
187
+ return ['input_ids', 'attention_mask', 'pixel_values', 'grid_thws']
kimi_k3_vision_processing.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Image processor class for Kimi-K3.
2
+ """
3
+
4
+ import json
5
+ from typing import Any, Dict, Optional, Union
6
+
7
+ import numpy as np
8
+ import torch
9
+ from PIL import Image
10
+ from transformers.image_processing_utils import (BaseImageProcessor,
11
+ BatchFeature)
12
+ from transformers.utils import TensorType
13
+
14
+ from .media_utils import (MediaInput, TransparentBgConfig, _to_tensor,
15
+ ensure_media_type, image_to_np, navit_patchify,
16
+ navit_resize_image, normalize)
17
+
18
+
19
+ class KimiK3VisionProcessor(BaseImageProcessor):
20
+ model_type = "kimi_k3"
21
+
22
+ def __init__(
23
+ self,
24
+ media_proc_cfg: dict,
25
+ **kwargs,
26
+ ):
27
+ super().__init__(**kwargs)
28
+ self.media_proc_cfg = media_proc_cfg
29
+
30
+ @property
31
+ def _transparent_bg_config(self) -> Optional[TransparentBgConfig]:
32
+ cfg = self.media_proc_cfg.get("transparent_bg_config")
33
+ if cfg is None:
34
+ return None
35
+ if isinstance(cfg, TransparentBgConfig):
36
+ return cfg
37
+ return TransparentBgConfig(**cfg)
38
+
39
+ @property
40
+ def _transparent_bg_fill_stage(self) -> str:
41
+ return self.media_proc_cfg.get("transparent_bg_fill_stage",
42
+ "before_resize")
43
+
44
+ def media_tokens_calculator(self, media: MediaInput):
45
+ media = ensure_media_type(
46
+ media,
47
+ transparent_bg_config=self._transparent_bg_config,
48
+ transparent_bg_fill_stage=self._transparent_bg_fill_stage,
49
+ )
50
+ ret = self.get_resize_config(media)
51
+ return ret['num_tokens']
52
+
53
+ @classmethod
54
+ def make_image_prompt(cls, width: int, height: int) -> str:
55
+ """Build the K3 image placeholder with resolution info."""
56
+ return (f"<|media_begin|>image {width}x{height}"
57
+ f"<|media_content|><|media_pad|><|media_end|>")
58
+
59
+ def get_resize_config(self, media_input: MediaInput) -> dict:
60
+ if media_input['type'] == 'image':
61
+ w, h = media_input['image'].size
62
+ ret = navit_resize_image(
63
+ w, h, self.media_proc_cfg['patch_size'],
64
+ self.media_proc_cfg['merge_kernel_size'],
65
+ self.media_proc_cfg['in_patch_limit'],
66
+ self.media_proc_cfg['patch_limit_on_one_side'],
67
+ self.media_proc_cfg['fixed_output_tokens'])
68
+ return ret
69
+ else:
70
+ raise ValueError("Unsupported type: {}".format(
71
+ media_input['type']))
72
+
73
+ def resize_image(self, image: Image.Image, new_width: int, new_height: int,
74
+ pad_width: int, pad_height: int) -> np.ndarray:
75
+ image_np = image_to_np(
76
+ image,
77
+ (new_width, new_height),
78
+ "resize",
79
+ transparent_bg_config=self._transparent_bg_config,
80
+ transparent_bg_fill_stage=self._transparent_bg_fill_stage,
81
+ )
82
+ image_np = np.pad(
83
+ image_np,
84
+ ((0, pad_height), (0, pad_width), (0, 0)),
85
+ mode="constant",
86
+ constant_values=0,
87
+ )
88
+ return image_np
89
+
90
+ def preprocess(
91
+ self,
92
+ medias: list[MediaInput],
93
+ return_tensors: Optional[Union[str, TensorType]] = None,
94
+ ) -> BatchFeature:
95
+ """
96
+ Preprocess a atom vision input (images) into model-ready tensors.
97
+
98
+ Args:
99
+ medias: List of MediaInput.
100
+ return_tensors: Desired output format ('pt', 'np', 'tf', or None).
101
+
102
+ Returns:
103
+ BatchFeature containing 'pixel_values' and 'grid_thws' tensors.
104
+ """
105
+ if not isinstance(medias, list):
106
+ medias = [medias]
107
+ if medias:
108
+ pixel_values = []
109
+ for item in medias:
110
+ item = ensure_media_type(
111
+ item,
112
+ transparent_bg_config=self._transparent_bg_config,
113
+ transparent_bg_fill_stage=self._transparent_bg_fill_stage,
114
+ )
115
+ resize_config = self.get_resize_config(item)
116
+ new_width, new_height, pad_width, pad_height = resize_config[
117
+ 'new_width'], resize_config['new_height'], resize_config[
118
+ 'pad_width'], resize_config['pad_height']
119
+ if item['type'] == 'image':
120
+ image = item['image']
121
+ image_np = self.resize_image(image, new_width, new_height,
122
+ pad_width, pad_height)
123
+ pixel_values.append(np.expand_dims(image_np, axis=0))
124
+ else:
125
+ raise ValueError("Unsupported type: {}".format(
126
+ item['type']))
127
+ normalized_pixel_values = []
128
+ image_std_inv = 1.0 / np.array(self.media_proc_cfg['image_std'])
129
+ image_mean = np.array(self.media_proc_cfg['image_mean'])
130
+ for pixels in pixel_values:
131
+ pixels = normalize(pixels, image_mean, image_std_inv)
132
+ pixels_and_thw = navit_patchify(
133
+ pixels,
134
+ self.media_proc_cfg['patch_size'],
135
+ )
136
+ normalized_pixel_values.append(pixels_and_thw)
137
+
138
+ pixel_values = torch.cat([
139
+ _to_tensor(pixel_value['pixel_values'])
140
+ for pixel_value in normalized_pixel_values
141
+ ])
142
+ grid_thws = torch.cat([
143
+ _to_tensor(pixel_value['grid_thw'],
144
+ dtype=torch.int64).unsqueeze(0)
145
+ for pixel_value in normalized_pixel_values
146
+ ])
147
+
148
+ data = {
149
+ 'pixel_values': pixel_values,
150
+ 'grid_thws': grid_thws,
151
+ }
152
+
153
+ else:
154
+ data = {}
155
+
156
+ return BatchFeature(data=data, tensor_type=return_tensors)
157
+
158
+ def __repr__(self):
159
+ return f"KimiK3VisionProcessor(media_proc_cfg={self.media_proc_cfg})"
160
+
161
+ def to_dict(self) -> Dict[str, Any]:
162
+ output = super().to_dict()
163
+ output["media_proc_cfg"] = self.media_proc_cfg
164
+ if "media_processor" in output:
165
+ del output["media_processor"]
166
+ return output
167
+
168
+ @classmethod
169
+ def from_dict(cls, config_dict: Dict[str, Any], **kwargs):
170
+ config = config_dict.copy()
171
+ media_proc_cfg = config.pop("media_proc_cfg", {})
172
+ return cls(media_proc_cfg=media_proc_cfg, **config, **kwargs)
173
+
174
+ def to_json_string(self):
175
+ dictionary = self.to_dict()
176
+ for key, value in dictionary.items():
177
+ if hasattr(value, 'tolist'):
178
+ dictionary[key] = value.tolist()
179
+ return json.dumps(dictionary, indent=2, sort_keys=True) + "\n"
media_utils.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import functools
3
+ import io
4
+ import math
5
+ from dataclasses import dataclass
6
+ from typing import Literal, TypedDict
7
+
8
+ import numpy as np
9
+ from PIL import Image
10
+
11
+
12
+ class ImageInput(TypedDict):
13
+ type: Literal['image']
14
+ image: Image.Image
15
+
16
+
17
+ MediaInput = ImageInput
18
+
19
+
20
+ @dataclass
21
+ class TransparentBgConfig:
22
+ """The config of the transparent background."""
23
+
24
+ pattern: Literal["white", "black", "gray", "chessboard"] = "black"
25
+ """The pattern of the transparent background."""
26
+
27
+ chessboard_square_size: int = 16
28
+ """The size of the squares in the chessboard background."""
29
+
30
+ chessboard_square_on_top_left: bool = True
31
+ """Whether to start the chessboard with a white square on the top left."""
32
+
33
+ chessboard_white_value: int = 255
34
+ """The value of the white pixels in the background."""
35
+
36
+ chessboard_gray_value: int = 200
37
+ """The value of the gray pixels in the background."""
38
+
39
+
40
+ @functools.lru_cache(maxsize=256)
41
+ def _create_chessboard_background(
42
+ height: int,
43
+ width: int,
44
+ square_size: int,
45
+ square_on_top_left: bool,
46
+ white_value: int,
47
+ gray_value: int,
48
+ ) -> np.ndarray:
49
+ """Create a chessboard background."""
50
+ bg = np.ones((height, width, 3), dtype=np.uint8) * white_value
51
+ for y in range(0, height, square_size):
52
+ for x in range(0, width, square_size):
53
+ if (y // square_size + x // square_size) % 2 == (
54
+ 1 if square_on_top_left else 0):
55
+ bg[y:y + square_size, x:x + square_size] = gray_value
56
+ return bg
57
+
58
+
59
+ def fill_transparent_bg_with(
60
+ image: Image.Image,
61
+ transparent_bg_config: TransparentBgConfig | None = None,
62
+ ) -> Image.Image:
63
+ """Composite a (possibly) transparent image onto a configured background.
64
+
65
+ When ``transparent_bg_config`` is ``None``, the image is simply converted
66
+ to RGB (preserving the historical behavior). Otherwise the alpha channel
67
+ is alpha-composited over a background generated according to the config.
68
+ """
69
+ if transparent_bg_config is None:
70
+ return image.convert("RGB")
71
+
72
+ if image.mode == "RGB":
73
+ return image
74
+
75
+ has_alpha = "A" in image.getbands() or "transparency" in image.info
76
+ if not has_alpha:
77
+ return image.convert("RGB")
78
+
79
+ img = np.array(image.convert("RGBA"))
80
+ height, width = img.shape[:2]
81
+ bg_pattern = transparent_bg_config.pattern
82
+ if bg_pattern == "white":
83
+ bg = np.full((height, width, 3), 255, dtype=np.uint8)
84
+ elif bg_pattern == "black":
85
+ bg = np.zeros((height, width, 3), dtype=np.uint8)
86
+ elif bg_pattern == "gray":
87
+ bg = np.full((height, width, 3), 128, dtype=np.uint8)
88
+ elif bg_pattern == "chessboard":
89
+ bg = _create_chessboard_background(
90
+ height,
91
+ width,
92
+ transparent_bg_config.chessboard_square_size,
93
+ transparent_bg_config.chessboard_square_on_top_left,
94
+ transparent_bg_config.chessboard_white_value,
95
+ transparent_bg_config.chessboard_gray_value,
96
+ )
97
+ else:
98
+ raise ValueError(f"Invalid background pattern: {bg_pattern}")
99
+
100
+ alpha = img[:, :, 3]
101
+ img_rgb = img[:, :, :3]
102
+ alpha_normalized = alpha.astype(np.float32) / 255.0
103
+ alpha_3d = np.stack([alpha_normalized] * 3, axis=2)
104
+ result = alpha_3d * img_rgb + (1 - alpha_3d) * bg
105
+ result = result.astype(np.uint8)
106
+ return Image.fromarray(result)
107
+
108
+
109
+ def navit_resize_image(
110
+ width: int,
111
+ height: int,
112
+ patch_size: int,
113
+ merge_kernel_size: int,
114
+ in_patch_limit: int,
115
+ patch_limit_on_one_side: int,
116
+ fixed_output_tokens: int | None,
117
+ ):
118
+ # Apply the patch limits.
119
+ s1 = math.sqrt(
120
+ in_patch_limit /
121
+ (max(1.0, width // patch_size) * max(1.0, height // patch_size)))
122
+ s2 = patch_limit_on_one_side * patch_size / width
123
+ s3 = patch_limit_on_one_side * patch_size / height
124
+ scale = min(1.0, s1, s2, s3)
125
+ new_w, new_h = max(1, int(width * scale)), max(1, int(height * scale))
126
+ new_w = min(new_w, patch_limit_on_one_side * patch_size)
127
+ new_h = min(new_h, patch_limit_on_one_side * patch_size)
128
+
129
+ # Calculate the padding to make the height and width divisible by the merge kernel size and patch size.
130
+ factor = merge_kernel_size * patch_size
131
+
132
+ pad_height = (factor - new_h % factor) % factor
133
+ pad_width = (factor - new_w % factor) % factor
134
+
135
+ if fixed_output_tokens is not None:
136
+ num_tokens = fixed_output_tokens
137
+ else:
138
+ # Calculate new dimensions after padding and patching
139
+ token_height = (new_h + pad_height) // factor
140
+ token_width = (new_w + pad_width) // factor
141
+
142
+ assert token_height * merge_kernel_size <= patch_limit_on_one_side, (
143
+ f"token_height {token_height} * merge_kernel_size {merge_kernel_size} > patch_limit_on_one_side {patch_limit_on_one_side}"
144
+ )
145
+ assert token_width * merge_kernel_size <= patch_limit_on_one_side, (
146
+ f"token_width {token_width} * merge_kernel_size {merge_kernel_size} > patch_limit_on_one_side {patch_limit_on_one_side}"
147
+ )
148
+
149
+ num_tokens = token_height * token_width
150
+ return {
151
+ "num_tokens": num_tokens,
152
+ "new_width": new_w,
153
+ "new_height": new_h,
154
+ "pad_width": pad_width,
155
+ "pad_height": pad_height,
156
+ "sampled_nframes": 1,
157
+ }
158
+
159
+
160
+ def _to_pil(
161
+ data: str | bytes | Image.Image,
162
+ transparent_bg_config: TransparentBgConfig | None = None,
163
+ to_rgb: bool = True,
164
+ ) -> Image.Image:
165
+ """Load an image and (optionally) composite its transparent background.
166
+
167
+ Args:
168
+ data: A PIL Image, a base64 ``data:`` URL, a file path, or raw bytes.
169
+ transparent_bg_config: The config used to fill the transparent
170
+ background. ``None`` keeps the historical behavior of converting
171
+ to RGB without compositing.
172
+ to_rgb: If ``False`` the image is returned as-is (the
173
+ ``transparent_bg_config`` is ignored). The caller is then
174
+ expected to call :func:`fill_transparent_bg_with` later — e.g.
175
+ after a resize.
176
+ """
177
+ if isinstance(data, Image.Image):
178
+ image = data
179
+ elif isinstance(data, str):
180
+ if data.startswith("data:"):
181
+ raw_base64 = data.split(",")[1]
182
+ image = Image.open(io.BytesIO(base64.b64decode(raw_base64)))
183
+ else:
184
+ image = Image.open(data)
185
+ elif isinstance(data, bytes):
186
+ image = Image.open(io.BytesIO(data))
187
+ else:
188
+ raise ValueError(f"Unsupported data type: {type(data)}")
189
+
190
+ if not to_rgb:
191
+ return image
192
+
193
+ return fill_transparent_bg_with(image, transparent_bg_config)
194
+
195
+
196
+ def ensure_media_type(
197
+ media: MediaInput,
198
+ transparent_bg_config: TransparentBgConfig | None = None,
199
+ transparent_bg_fill_stage: Literal["before_resize",
200
+ "after_resize"] = "before_resize",
201
+ ) -> MediaInput:
202
+ if media['type'] == 'image':
203
+ media['image'] = _to_pil(
204
+ media['image'],
205
+ transparent_bg_config=transparent_bg_config,
206
+ to_rgb=transparent_bg_fill_stage == "before_resize",
207
+ )
208
+ return media
209
+ else:
210
+ raise ValueError(f"Unsupported media type: {media['type']}")
211
+
212
+
213
+ def image_to_np(
214
+ image: Image.Image,
215
+ resize_to: tuple[int, int] | None = None,
216
+ mode: str = "resize",
217
+ raise_error_for_ill_resize: bool = True,
218
+ transparent_bg_config: TransparentBgConfig | None = None,
219
+ transparent_bg_fill_stage: Literal["before_resize",
220
+ "after_resize"] = "before_resize",
221
+ ) -> np.ndarray:
222
+ """Convert an image to a numpy array.
223
+
224
+ Args:
225
+ content: The image to convert.
226
+ resize_to: The size to resize the image to.
227
+ mode: The mode to resize the image to.
228
+ raise_error_for_ill_resize: Whether to raise an error for ill-sized resize.
229
+ transparent_bg_config: The config of the transparent background. Only
230
+ used when ``transparent_bg_fill_stage == "after_resize"`` (the
231
+ caller is responsible for filling before resize otherwise).
232
+ transparent_bg_fill_stage: When to composite the transparent
233
+ background — before or after the resize step.
234
+
235
+ Returns:
236
+ A numpy array.
237
+ """
238
+ assert isinstance(image, Image.Image), "image must be a PIL Image"
239
+ if resize_to is not None:
240
+ if mode == "resize":
241
+ image = image.resize(resize_to, resample=Image.Resampling.BICUBIC)
242
+ if transparent_bg_fill_stage == "after_resize":
243
+ image = fill_transparent_bg_with(image, transparent_bg_config)
244
+
245
+ elif mode == "rescale_and_pad_to_center":
246
+ scale = min(resize_to[0] / image.width,
247
+ resize_to[1] / image.height, 1.0)
248
+ new_width = round(image.width * scale)
249
+ new_height = round(image.height * scale)
250
+ if new_width == 0 or new_height == 0:
251
+ if raise_error_for_ill_resize:
252
+ raise ValueError(
253
+ f"Invalid resize to: {resize_to}, from image size: {image.size}"
254
+ )
255
+ else:
256
+ return np.zeros((resize_to[1], resize_to[0], 3),
257
+ dtype=np.uint8)
258
+
259
+ image = image.resize((new_width, new_height),
260
+ resample=Image.Resampling.BICUBIC)
261
+ if transparent_bg_fill_stage == "after_resize":
262
+ image = fill_transparent_bg_with(image, transparent_bg_config)
263
+ padding_left = (resize_to[0] - new_width) // 2
264
+ padding_right = resize_to[0] - new_width - padding_left
265
+ padding_top = (resize_to[1] - new_height) // 2
266
+ padding_bottom = resize_to[1] - new_height - padding_top
267
+ image = np.asarray(image)
268
+ image = np.pad(
269
+ image,
270
+ ((padding_top, padding_bottom), (padding_left, padding_right),
271
+ (0, 0)),
272
+ mode="constant",
273
+ constant_values=0,
274
+ )
275
+ assert image.shape == (resize_to[1], resize_to[0], 3)
276
+
277
+ elif mode == "rescale_and_pad_to_rightbottom":
278
+ scale = min(resize_to[0] / image.width,
279
+ resize_to[1] / image.height, 1.0)
280
+ new_width = round(image.width * scale)
281
+ new_height = round(image.height * scale)
282
+ if new_width == 0 or new_height == 0:
283
+ if raise_error_for_ill_resize:
284
+ raise ValueError(
285
+ f"Invalid resize to: {resize_to}, from image size: {image.size}"
286
+ )
287
+ else:
288
+ return np.zeros((resize_to[1], resize_to[0], 3),
289
+ dtype=np.uint8)
290
+
291
+ image = image.resize((new_width, new_height),
292
+ resample=Image.Resampling.BICUBIC)
293
+ if transparent_bg_fill_stage == "after_resize":
294
+ image = fill_transparent_bg_with(image, transparent_bg_config)
295
+ padding_right = resize_to[0] - new_width
296
+ padding_bottom = resize_to[1] - new_height
297
+ image = np.asarray(image)
298
+ image = np.pad(
299
+ image,
300
+ ((0, padding_bottom), (0, padding_right), (0, 0)),
301
+ mode="constant",
302
+ constant_values=0,
303
+ )
304
+ assert image.shape == (resize_to[1], resize_to[0], 3)
305
+
306
+ else:
307
+ raise ValueError(f"Invalid mode: {mode}")
308
+
309
+ if isinstance(image, Image.Image):
310
+ return np.asarray(image)
311
+ else:
312
+ return image
313
+
314
+
315
+ def navit_patchify(pixel_values: np.ndarray,
316
+ patch_size: int) -> dict[str, np.ndarray]:
317
+ """Reshape the pixel values to a navit shape.
318
+
319
+ Args:
320
+ pixel_values: np.ndarray, shape (t, h, w, c)
321
+ patch_size: int
322
+
323
+ Returns:
324
+ dict[str, np.ndarray]
325
+ - patches: np.ndarray, shape (t * h//patch_size * w//patch_size, c, patch_size, patch_size)
326
+ - grid_thw: np.ndarray, (t, h//patch_size, w//patch_size)
327
+ """
328
+ T, H, W, C = pixel_values.shape
329
+ assert C == 3, "pixel_values must have 3 channels"
330
+
331
+ patches = pixel_values.reshape(T, H // patch_size, patch_size,
332
+ W // patch_size, patch_size, C)
333
+ # (T, H//patch_size, W//patch_size, C, patch_size, patch_size)
334
+ patches = patches.transpose(0, 1, 3, 5, 2, 4)
335
+ patches = patches.reshape(-1, C, patch_size, patch_size)
336
+ grid_thw = np.array([T, H // patch_size, W // patch_size])
337
+ return {"pixel_values": patches, "grid_thw": grid_thw}
338
+
339
+
340
+ def normalize(x: np.ndarray,
341
+ mean,
342
+ std_inv,
343
+ pixels_dtype: np.dtype = np.float32) -> np.ndarray:
344
+ """Normalize the image.
345
+
346
+ Args:
347
+ x: The image to normalize. The shape is (..., 3). The dtype is uint8. The range is [0, 255].
348
+ mean: The mean of the image.
349
+ std_inv: The inverse of the std of the image.
350
+ pixels_dtype: The dtype of the image.
351
+ Returns:
352
+ The normalized image. The shape is (..., 3). The dtype is determined by the pixels_dtype.
353
+ """
354
+ x = (x / 255.0).astype(pixels_dtype)
355
+ x -= mean
356
+ x *= std_inv
357
+ return x
358
+
359
+
360
+ def _to_tensor(data, **kwargs):
361
+ import torch
362
+
363
+ if isinstance(data, np.ndarray):
364
+ return torch.from_numpy(data).to(**kwargs)
365
+ elif isinstance(data, torch.Tensor):
366
+ return data.to(**kwargs)
367
+ elif isinstance(data, list):
368
+ return [_to_tensor(item, **kwargs) for item in data]
369
+ elif isinstance(data, tuple):
370
+ return tuple(_to_tensor(item, **kwargs) for item in data)
371
+ elif isinstance(data, dict):
372
+ return {k: _to_tensor(v, **kwargs) for k, v in data.items()}
373
+ elif data is None:
374
+ return None
375
+ else:
376
+ raise ValueError(f"Unsupported data type: {type(data)}")
model-00001-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7f60e41909fb16712100c311ca4402cc4e66ecc9dff9dad4ebc06f05106c58a1
3
+ size 2341216112
model-00002-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3896d0f0d987abeb75f90ff0c047b9fb7faf3ff39a6e31cbd49a1358f48b7ffa
3
+ size 16990911504
model-00003-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8db356979d0b5e4fdf16f13d56edee900261cc59d81395e498a52847518abf4c
3
+ size 16990911504
model-00004-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:01ca3a36220afc36a9f2891045c8c9d0e64fc2cd08fffe1b3851e24bd2a93a40
3
+ size 16582379656
model-00005-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:596fc235fe92c9656cbbd63eb719cd46f68b19e22d792224ef307c156f699682
3
+ size 16990911504
model-00006-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a9f6a9d6682b2f5177553b9986bdc0774fe84a2181b76a6b7d7482de0ecf049b
3
+ size 16990911504
model-00007-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ea268a3cb5978f50079ffd111d78d785bdd313fb9c7dafda8df0d841daeba4ab
3
+ size 16990911504
model-00008-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e514e45c4a17a187657fbcd1d4f9eb6a0c33bcdbbe54049da391ed54ce57f60f
3
+ size 16582379656
model-00009-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c5f9adff3d853bcf1e14c27bca0f1a74de985e7afb3149acd00eb2de3732ca12
3
+ size 16990911504
model-00010-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ee9b1762da09dad17d6f8a22732645b070149266c40c3ae1e8ee90f48fec6742
3
+ size 16990911504
model-00011-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0bb52ff6b774c289888854203726e0cd955fc650dda2f5cf9e4f825037f4af72
3
+ size 16990916912
model-00012-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2c2c9be2d6b722d75bec065e545826a88a8839b8100766442e7f476143e7ba44
3
+ size 16582385056
model-00013-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bbf5db5833f4607cd201156229aa7f05183f70f2ffd2cf0ca8a6d781ee7f139c
3
+ size 16990916912
model-00014-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f412b94c799903bc4b3694e662e6ef342bcc3712a3108a63b157bef16ec59df
3
+ size 16990916912
model-00015-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:28e678ecfc2286eb86aa6dfe20df03bd7c8873b34d96f0b230d1aab64365a889
3
+ size 16990916912
model-00016-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:896fd658f4cddad15eaca16ed54471ad265ad73d48d291bb4bb792767dc4d617
3
+ size 16582385056
model-00017-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b82b33835679910ad9f87ec4662e38f8dc111421fb2a56f538cec5be6c55b74
3
+ size 16990916912
model-00018-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:db91d8251d9bc0f47e31fc18955e8428a6a1fa25460a5e54578e4b261660e3ef
3
+ size 16990916912
model-00019-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:281ef055e54eff0c8ffacdf886e983ff27de43d002abf9aa97b663e9a3ae9ee7
3
+ size 16990916912
model-00020-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:783cbb7d6056c0ad3f32b8f1c10c20e6b2d7e5356e0cfd6ce6123f43d3648e60
3
+ size 16582385056
model-00021-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9774e732cae20192427c8777f79bd9a9fb7c9ef3bc71c2784a2f72e891e1b51e
3
+ size 16990916912
model-00022-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5e3f0905780d988b0fcb974479731e751f8bed319e22224f5f9d0ec76b1b755e
3
+ size 16990916912
model-00023-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:69940e5bde762834f2731401194a8fb2c2784274890bd6d23e0c0aca91383451
3
+ size 16990916912
model-00024-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f48efe6ad27d75b51564a3de48ab312ee7c06969db35d7b2b764d9515c00b0a7
3
+ size 16582385056
model-00025-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:833a0f761b2944cde386def5bdb7dabbfdf30f2927dd26304d0f7723b4ff018c
3
+ size 16990916912
model-00026-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:02bff688e36ec90942dcb3ece1bfc7f102fd3c78bffdabba79fd4ec4bedb9230
3
+ size 16990916912
model-00027-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4fe3e6f06b9c341d06eee45c0add2c7f8aff48a4c48bdcd97130c48c91b93202
3
+ size 16990916912
model-00028-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:832b28d66ea0c9bca4b42c8b206463b3f8fa8cafd13d4118911604351c27dc22
3
+ size 16582385056
model-00029-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf8f4f4f10a3cbf72d95851232c17d20c58d44f024a8c4e421b344cb0f871659
3
+ size 16990916912
model-00030-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a974612d9f6300e9a86eb882e2c6dbad2446d491e15289b576acd015f1f69928
3
+ size 16990916912
model-00031-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aa227f8eddaf25975915e8a161446fb042e1db7bb176aafd29d4953f01a4e2dd
3
+ size 16990916912
model-00032-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4520a3321b8fd7e3f7da7c29afc084802af2f1498f8c96e5103fe4476b204957
3
+ size 16582385056
model-00033-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:32a8f004afb58539f28fe5333fef3e1604c60f2113bbe2e173c99502a0f0cd89
3
+ size 16990916912
model-00034-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4310c7808e7bf72506168fc1e521852ee95da94c6ee2f6ee6b8fa6b800c559c8
3
+ size 16990916912
model-00035-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5ba50bc47a6b48c057208b7e2ea5aaccb6e8ce27041402e469cbb18661858ce2
3
+ size 16990916912
model-00036-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a64e3f0e0988dda1e568fcbf37d4f0a03493e536daff572a8d8378442ef26ec
3
+ size 16582385056
model-00037-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:43ab18d28759e45ba316e03423b2c0d447ebc7f8ffea7972c4634a7630349262
3
+ size 16990916912
model-00038-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a518377eff993b5b0b0337296072bb32a3ed249776b0c1459aaef20f9749fcf1
3
+ size 16990916912
model-00039-of-000096.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0c693043cdf7910af15e649039a7bfd8e924b923f7224cc1222e0d56edd36358
3
+ size 16990916912