Image-Text-to-Text
Transformers
Safetensors
kimi_k3
feature-extraction
compressed-tensors
conversational
custom_code
Eval Results
8-bit precision
Run this model with HF Jobs
Run Samyag/Kimi-K3 on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/Samyag/Kimi-K3. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Samyag/Kimi-K3 on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/Samyag/Kimi-K3. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/Samyag/Kimi-K3. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use Samyag/Kimi-K3 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Samyag/Kimi-K3 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="Samyag/Kimi-K3", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("Samyag/Kimi-K3", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Samyag/Kimi-K3 with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Samyag/Kimi-K3" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Samyag/Kimi-K3", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker
docker model run hf.co/Samyag/Kimi-K3
- SGLang
How to use Samyag/Kimi-K3 with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "Samyag/Kimi-K3" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Samyag/Kimi-K3", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "Samyag/Kimi-K3" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Samyag/Kimi-K3", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }' - Docker Model Runner
How to use Samyag/Kimi-K3 with Docker Model Runner:
docker model run hf.co/Samyag/Kimi-K3
Duplicate from moonshotai/Kimi-K3
Browse filesCo-authored-by: Allen <YyWangMsh@users.noreply.huggingface.co>
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .eval_results/apex-agents.yamlAdded+7
- .eval_results/deep-swe.yamlAdded+7
- .eval_results/gpqa.yamlAdded+7
- .eval_results/hle.yamlAdded+7
- .gitattributesAdded+37
- LICENSEAdded+52
- README.mdAdded+680
- assets/kimi-logo.pngAdded
- config.jsonAdded+300
- configuration_kimi_k3.pyAdded+285
- encoding_k3.pyAdded+647
- generation_config.jsonAdded+4
- kimi_k3_processor.pyAdded+187
- kimi_k3_vision_processing.pyAdded+179
- media_utils.pyAdded+376
- model-00001-of-000096.safetensorsAdded+3
- model-00002-of-000096.safetensorsAdded+3
- model-00003-of-000096.safetensorsAdded+3
- model-00004-of-000096.safetensorsAdded+3
- model-00005-of-000096.safetensorsAdded+3
- model-00006-of-000096.safetensorsAdded+3
- model-00007-of-000096.safetensorsAdded+3
- model-00008-of-000096.safetensorsAdded+3
- model-00009-of-000096.safetensorsAdded+3
- model-00010-of-000096.safetensorsAdded+3
- model-00011-of-000096.safetensorsAdded+3
- model-00012-of-000096.safetensorsAdded+3
- model-00013-of-000096.safetensorsAdded+3
- model-00014-of-000096.safetensorsAdded+3
- model-00015-of-000096.safetensorsAdded+3
- model-00016-of-000096.safetensorsAdded+3
- model-00017-of-000096.safetensorsAdded+3
- model-00018-of-000096.safetensorsAdded+3
- model-00019-of-000096.safetensorsAdded+3
- model-00020-of-000096.safetensorsAdded+3
- model-00021-of-000096.safetensorsAdded+3
- model-00022-of-000096.safetensorsAdded+3
- model-00023-of-000096.safetensorsAdded+3
- model-00024-of-000096.safetensorsAdded+3
- model-00025-of-000096.safetensorsAdded+3
- model-00026-of-000096.safetensorsAdded+3
- model-00027-of-000096.safetensorsAdded+3
- model-00028-of-000096.safetensorsAdded+3
- model-00029-of-000096.safetensorsAdded+3
- model-00030-of-000096.safetensorsAdded+3
- model-00031-of-000096.safetensorsAdded+3
- model-00032-of-000096.safetensorsAdded+3
- model-00033-of-000096.safetensorsAdded+3
- model-00034-of-000096.safetensorsAdded+3
- model-00035-of-000096.safetensorsAdded+3
1234567- dataset: id: mercor/apex-agents task_id: apex-agents value: 41 source: url: https://huggingface.co/moonshotai/Kimi-K3 name: Model Card1234567- dataset: id: datacurve/deep-swe task_id: deep_swe value: 67.5 source: url: https://huggingface.co/moonshotai/Kimi-K3 name: Model Card1234567- dataset: id: Idavidrein/gpqa task_id: diamond value: 93.5 source: url: https://huggingface.co/moonshotai/Kimi-K3 name: Model Card1234567- dataset: id: cais/hle task_id: hle value: 56 source: url: https://huggingface.co/moonshotai/Kimi-K3 name: Model Card12345678910111213141516171819202122232425262728293031323334353637*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textmodel.safetensors.index.json filter=lfs diff=lfs merge=lfs -textassets/k3-hero.jpg filter=lfs diff=lfs merge=lfs -text12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152Kimi K3 License
Copyright (c) 2026 Moonshot AI
Permission is hereby granted, free of charge, to any person (the "Licensee")obtaining a copy of this software — including the model weights, parameters,configuration files, inference and training code, and associated documentation(collectively, the "Software") — to deal in the Software without restriction.This includes, without limitation, the rights to use, copy, modify, merge,publish, distribute, sublicense, and/or sell copies of the Software; to run,deploy, fine-tune, or otherwise modify the Software and create derivative worksfrom it; and to permit persons to whom the Software is furnished to do so, ineach case subject to the following conditions:
1. The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software. Licensee's use of theSoftware must comply with applicable laws and regulations.
2. "Model as a Service" means giving a third party access to language modelinference or fine-tuning (e.g., via API) in a manner that allows such thirdparty to exercise meaningful control over the inputs, parameters, or trainingdata. This does not include (a) end-user products with model capabilities solelyembedded within specific features or harnesses, or (b) mere relaying of requeststo models hosted by others.
If the Licensee or any of its affiliates operates a Model as a Service business,and the aggregate revenue of the Licensee and its affiliates exceeds 20 millionUS dollars (or the equivalent in other currencies) in total over any consecutive12 months, the Licensee must enter into a separate agreement with Moonshot AIbefore using the Software or its derivative works for any commercial purpose.
3. If the Software (or any derivative works thereof) is used for any of theLicensee's commercial products or services that have more than 100 millionmonthly active users, or more than 20 million US dollars (or equivalent in othercurrencies) in monthly revenue, "Kimi K3" must be prominently displayed on theuser interface of such product or service.
4. The requirements set forth in Sections 2 and 3 do not apply to: (a) internaluse of the Software, defined as any use that does not make the Software, itsoutputs, or its underlying capabilities available to third parties; or (b) anyuse of the Software accessed through Moonshot AI's official products orcertified inference partners.
5. THE SOFTWARE AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS”BASIS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOTLIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSEAND NONINFRINGEMENT. IN NO EVENT SHALL MOONSHOT AI OR ITS AFFILIATES ORCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHERIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR INCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
For any questions regarding this license, please contact <license@moonshot.ai>.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680---tags:- compressed-tensors- conversationallicense: otherlicense_name: "kimi-k3"library_name: transformerspipeline_tag: image-text-to-text---<div align="center"> <picture> <img src="assets/kimi-logo.png" width="30%" alt="Kimi K3"> </picture></div><hr><div align="center" style="line-height:1"> <a href="https://www.kimi.com" target="_blank"><img alt="Chat" src="https://img.shields.io/badge/🤖%20Chat-Kimi%20K3-ff6b6b?color=1783ff&logoColor=white"/></a> <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></div>
<div align="center" style="line-height: 1;"> <a href="https://huggingface.co/moonshotai" target="_blank"><img alt="Hugging Face" src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Moonshot%20AI-ffc107?color=ffc107&logoColor=white"/></a> <a href="https://twitter.com/kimi_moonshot" target="_blank"><img alt="Twitter Follow" src="https://img.shields.io/badge/Twitter-Kimi.ai-white?logo=x&logoColor=white"/></a> <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> <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></div><div align="center" style="line-height: 1;"> <a href="https://huggingface.co/moonshotai/Kimi-K3/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/badge/License-Kimi_K3-f5de53?&color=f5de53"/></a></div>
<p align="center">📰 <a href="https://www.kimi.com/blog/kimi-k3">Tech Blog</a> | <b>📄 <a href="https://github.com/MoonshotAI/Kimi-K3/blob/main/k3_tech_report.pdf">Full Report</a></b></p>
## 1. Model Introduction
Kimi K3 is an open-weight, native multimodal agentic model and our most capable model to date. It is a 2.8T-parameter model built on Kimi Delta Attention (KDA) and Attention Residuals (AttnRes), with native vision capabilities and a 1-million-token context window. It is the world's first open 3T-class model, designed for frontier intelligence across long-horizon coding, knowledge work, and reasoning.
### Key Features- **New Architecture**: Kimi K3 is built on Kimi Delta Attention (KDA) and Attention Residuals (AttnRes), and scales up MoE sparsity with a Stable LatentMoE framework that activates 16 out of 896 experts — yielding an approximate 2.5× improvement in overall scaling efficiency over Kimi K2.- **Long-Horizon Coding**: Operating with minimal human oversight, Kimi K3 sustains long engineering sessions, navigates massive repositories, and orchestrates terminal tools — from GPU kernel optimization and compiler development to vision-in-the-loop game dev, CAD, and even chip design.- **Agentic Knowledge Work**: Kimi K3 advances end-to-end knowledge work, producing deep research with interactive visualizations, widgets and dashboards, and motion design and video editing, powered by its native multimodal architecture.- **Native Multimodality & Long Context**: Kimi K3 understands text, images, and video within the same model, and supports a 1-million-token context window.- **Open Frontier Weights**: We release the full Kimi K3 model weights under the Kimi K3 License, making frontier intelligence openly available for research, deployment, and further innovation.## 2. Model Summary
<div align="center"><table><tbody><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Architecture</strong></td><td align="center" style="vertical-align: middle; text-align: center">Mixture-of-Experts (MoE)</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Total Parameters</strong></td><td align="center" style="vertical-align: middle; text-align: center">2.8T</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Activated Parameters</strong></td><td align="center" style="vertical-align: middle; text-align: center">104B</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Number of Layers</strong></td><td align="center" style="vertical-align: middle; text-align: center">93</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Number of Dense Layers</strong></td><td align="center" style="vertical-align: middle; text-align: center">1</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Attention-Layer Composition</strong></td><td align="center" style="vertical-align: middle; text-align: center">69 KDA + 24 Gated MLA</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Attention Hidden Dimension</strong></td><td align="center" style="vertical-align: middle; text-align: center">7168</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Number of Attention Heads</strong></td><td align="center" style="vertical-align: middle; text-align: center">96</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Latent MoE Dimension</strong></td><td align="center" style="vertical-align: middle; text-align: center">3584</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>MoE Hidden Dimension</strong> (per Expert)</td><td align="center" style="vertical-align: middle; text-align: center">3072</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Number of Experts</strong></td><td align="center" style="vertical-align: middle; text-align: center">896</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Selected Experts per Token</strong></td><td align="center" style="vertical-align: middle; text-align: center">16</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Number of Shared Experts</strong></td><td align="center" style="vertical-align: middle; text-align: center">2</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Vocabulary Size</strong></td><td align="center" style="vertical-align: middle; text-align: center">160K</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Context Length</strong></td><td align="center" style="vertical-align: middle; text-align: center">1048576</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Attention Mechanism</strong></td><td align="center" style="vertical-align: middle; text-align: center">KDA & Gated MLA</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Activation Function</strong></td><td align="center" style="vertical-align: middle; text-align: center">SiTU-GLU</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Vision Encoder</strong></td><td align="center" style="vertical-align: middle; text-align: center">MoonViT-V2</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Parameters of Vision Encoder</strong></td><td align="center" style="vertical-align: middle; text-align: center">401M</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Quantization</strong></td><td align="center" style="vertical-align: middle; text-align: center">MXFP4 weights / MXFP8 activations<br>(quantization-aware training)</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>Modality</strong></td><td align="center" style="vertical-align: middle; text-align: center">Text, Image</td></tr></tbody></table></div>
## 3. Evaluation Results
<div align="center"><table><thead><tr><th align="center" style="text-align: center">Benchmark</th><th align="center" style="text-align: center"><sup>Kimi K3<br><sup>(max)</sup></sup></th><th align="center" style="text-align: center"><sup>Claude Fable 5<br><sup>(max, w/ fallback)</sup></sup></th><th align="center" style="text-align: center"><sup>GPT-5.6 Sol<br><sup>(max)</sup></sup></th><th align="center" style="text-align: center"><sup>Claude Opus 4.8<br><sup>(max)</sup></sup></th><th align="center" style="text-align: center"><sup>GPT-5.5<br><sup>(xhigh)</sup></sup></th><th align="center" style="text-align: center"><sup>GLM-5.2<br><sup>(max)</sup></sup></th></tr></thead><tbody><tr><td align="center" colspan=7 style="text-align: center"><strong>Reasoning & Knowledge</strong></td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">GPQA Diamond</td><td align="center" style="vertical-align: middle; text-align: center">93.5</td><td align="center" style="vertical-align: middle; text-align: center">92.6</td><td align="center" style="vertical-align: middle; text-align: center">94.1</td><td align="center" style="vertical-align: middle; text-align: center">91.0</td><td align="center" style="vertical-align: middle; text-align: center">93.5</td><td align="center" style="vertical-align: middle; text-align: center">91.2</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">CritPt</td><td align="center" style="vertical-align: middle; text-align: center">23.4</td><td align="center" style="vertical-align: middle; text-align: center">28.6</td><td align="center" style="vertical-align: middle; text-align: center">32.3</td><td align="center" style="vertical-align: middle; text-align: center">20.9</td><td align="center" style="vertical-align: middle; text-align: center">27.1</td><td align="center" style="vertical-align: middle; text-align: center">20.9</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">AA-LCR</td><td align="center" style="vertical-align: middle; text-align: center">74.7</td><td align="center" style="vertical-align: middle; text-align: center">70.0</td><td align="center" style="vertical-align: middle; text-align: center">73.7</td><td align="center" style="vertical-align: middle; text-align: center">67.7</td><td align="center" style="vertical-align: middle; text-align: center">74.3</td><td align="center" style="vertical-align: middle; text-align: center">71.3</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">HLE-Full</td><td align="center" style="vertical-align: middle; text-align: center">43.5 / 56.0</td><td align="center" style="vertical-align: middle; text-align: center">53.3 / 63.0</td><td align="center" style="vertical-align: middle; text-align: center">44.5 / 58.0</td><td align="center" style="vertical-align: middle; text-align: center">49.8 / 57.9</td><td align="center" style="vertical-align: middle; text-align: center">41.4 / 52.2</td><td align="center" style="vertical-align: middle; text-align: center">—</td></tr><tr><td align="center" colspan=7 style="text-align: center"><strong>Coding</strong></td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">DeepSWE</td><td align="center" style="vertical-align: middle; text-align: center">67.5</td><td align="center" style="vertical-align: middle; text-align: center">70.0</td><td align="center" style="vertical-align: middle; text-align: center">73.0</td><td align="center" style="vertical-align: middle; text-align: center">59.0</td><td align="center" style="vertical-align: middle; text-align: center">67.0</td><td align="center" style="vertical-align: middle; text-align: center">46.2</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">ProgramBench</td><td align="center" style="vertical-align: middle; text-align: center">77.8</td><td align="center" style="vertical-align: middle; text-align: center">76.8</td><td align="center" style="vertical-align: middle; text-align: center">77.6</td><td align="center" style="vertical-align: middle; text-align: center">71.9</td><td align="center" style="vertical-align: middle; text-align: center">70.8</td><td align="center" style="vertical-align: middle; text-align: center">63.7</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">Terminal-Bench 2.1</td><td align="center" style="vertical-align: middle; text-align: center">88.3</td><td align="center" style="vertical-align: middle; text-align: center">88.0</td><td align="center" style="vertical-align: middle; text-align: center">88.8</td><td align="center" style="vertical-align: middle; text-align: center">84.6</td><td align="center" style="vertical-align: middle; text-align: center">83.4</td><td align="center" style="vertical-align: middle; text-align: center">82.7</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">FrontierSWE</td><td align="center" style="vertical-align: middle; text-align: center">81.2</td><td align="center" style="vertical-align: middle; text-align: center">86.6</td><td align="center" style="vertical-align: middle; text-align: center">71.3</td><td align="center" style="vertical-align: middle; text-align: center">66.7</td><td align="center" style="vertical-align: middle; text-align: center">64.9</td><td align="center" style="vertical-align: middle; text-align: center">67.3</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">SWE-Marathon</td><td align="center" style="vertical-align: middle; text-align: center">42.0</td><td align="center" style="vertical-align: middle; text-align: center">35.0</td><td align="center" style="vertical-align: middle; text-align: center">39.0</td><td align="center" style="vertical-align: middle; text-align: center">40.0</td><td align="center" style="vertical-align: middle; text-align: center">14.0</td><td align="center" style="vertical-align: middle; text-align: center">13.0</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">PostTrainBench</td><td align="center" style="vertical-align: middle; text-align: center">36.6</td><td align="center" style="vertical-align: middle; text-align: center">41.4</td><td align="center" style="vertical-align: middle; text-align: center">34.6</td><td align="center" style="vertical-align: middle; text-align: center">34.1</td><td align="center" style="vertical-align: middle; text-align: center">28.4</td><td align="center" style="vertical-align: middle; text-align: center">34.3</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">MLS-Bench-Lite</td><td align="center" style="vertical-align: middle; text-align: center">48.3</td><td align="center" style="vertical-align: middle; text-align: center">49.9</td><td align="center" style="vertical-align: middle; text-align: center">46.2</td><td align="center" style="vertical-align: middle; text-align: center">42.8</td><td align="center" style="vertical-align: middle; text-align: center">35.5</td><td align="center" style="vertical-align: middle; text-align: center">40.4</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">SciCode</td><td align="center" style="vertical-align: middle; text-align: center">58.7</td><td align="center" style="vertical-align: middle; text-align: center">60.2</td><td align="center" style="vertical-align: middle; text-align: center">56.1</td><td align="center" style="vertical-align: middle; text-align: center">53.5</td><td align="center" style="vertical-align: middle; text-align: center">56.1</td><td align="center" style="vertical-align: middle; text-align: center">50.5</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">Kimi Code Bench 2.0</td><td align="center" style="vertical-align: middle; text-align: center">72.9</td><td align="center" style="vertical-align: middle; text-align: center">76.9</td><td align="center" style="vertical-align: middle; text-align: center">64.8</td><td align="center" style="vertical-align: middle; text-align: center">71.7</td><td align="center" style="vertical-align: middle; text-align: center">69.0</td><td align="center" style="vertical-align: middle; text-align: center">64.2</td></tr><tr><td align="center" colspan=7 style="text-align: center"><strong>Agentic</strong></td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">BrowseComp</td><td align="center" style="vertical-align: middle; text-align: center">91.2</td><td align="center" style="vertical-align: middle; text-align: center">88.0</td><td align="center" style="vertical-align: middle; text-align: center">90.4</td><td align="center" style="vertical-align: middle; text-align: center">84.3</td><td align="center" style="vertical-align: middle; text-align: center">84.4</td><td align="center" style="vertical-align: middle; text-align: center">—</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">DeepSearchQA (F1)</td><td align="center" style="vertical-align: middle; text-align: center">95.0</td><td align="center" style="vertical-align: middle; text-align: center">94.2</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">93.1</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">—</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">ResearchRubrics</td><td align="center" style="vertical-align: middle; text-align: center">76.2</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">73.8</td><td align="center" style="vertical-align: middle; text-align: center">73.5</td><td align="center" style="vertical-align: middle; text-align: center">64.0</td><td align="center" style="vertical-align: middle; text-align: center">71.1</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">GDPval-AA v2 (Elo)</td><td align="center" style="vertical-align: middle; text-align: center">1686</td><td align="center" style="vertical-align: middle; text-align: center">1747</td><td align="center" style="vertical-align: middle; text-align: center">1736</td><td align="center" style="vertical-align: middle; text-align: center">1593</td><td align="center" style="vertical-align: middle; text-align: center">1491</td><td align="center" style="vertical-align: middle; text-align: center">1510</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">Toolathlon-Verified</td><td align="center" style="vertical-align: middle; text-align: center">76.5</td><td align="center" style="vertical-align: middle; text-align: center">77.9</td><td align="center" style="vertical-align: middle; text-align: center">74.9</td><td align="center" style="vertical-align: middle; text-align: center">76.2</td><td align="center" style="vertical-align: middle; text-align: center">73.5</td><td align="center" style="vertical-align: middle; text-align: center">59.9</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">MCPMark-Verified</td><td align="center" style="vertical-align: middle; text-align: center">94.5</td><td align="center" style="vertical-align: middle; text-align: center">87.4</td><td align="center" style="vertical-align: middle; text-align: center">92.9</td><td align="center" style="vertical-align: middle; text-align: center">76.4</td><td align="center" style="vertical-align: middle; text-align: center">92.9</td><td align="center" style="vertical-align: middle; text-align: center">—</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">MCP-Atlas</td><td align="center" style="vertical-align: middle; text-align: center">84.2</td><td align="center" style="vertical-align: middle; text-align: center">84.7</td><td align="center" style="vertical-align: middle; text-align: center">83.6</td><td align="center" style="vertical-align: middle; text-align: center">83.6</td><td align="center" style="vertical-align: middle; text-align: center">82.8</td><td align="center" style="vertical-align: middle; text-align: center">82.6</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">AutomationBench</td><td align="center" style="vertical-align: middle; text-align: center">30.8</td><td align="center" style="vertical-align: middle; text-align: center">29.1</td><td align="center" style="vertical-align: middle; text-align: center">29.7</td><td align="center" style="vertical-align: middle; text-align: center">27.2</td><td align="center" style="vertical-align: middle; text-align: center">22.7</td><td align="center" style="vertical-align: middle; text-align: center">12.9</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">JobBench</td><td align="center" style="vertical-align: middle; text-align: center">54.3</td><td align="center" style="vertical-align: middle; text-align: center">57.4</td><td align="center" style="vertical-align: middle; text-align: center">45.4</td><td align="center" style="vertical-align: middle; text-align: center">48.4</td><td align="center" style="vertical-align: middle; text-align: center">38.3</td><td align="center" style="vertical-align: middle; text-align: center">43.4</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">AA-Briefcase (Elo)</td><td align="center" style="vertical-align: middle; text-align: center">1548</td><td align="center" style="vertical-align: middle; text-align: center">1583</td><td align="center" style="vertical-align: middle; text-align: center">1495</td><td align="center" style="vertical-align: middle; text-align: center">1354</td><td align="center" style="vertical-align: middle; text-align: center">1158</td><td align="center" style="vertical-align: middle; text-align: center">1260</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">Agents' Last Exam</td><td align="center" style="vertical-align: middle; text-align: center">28.3</td><td align="center" style="vertical-align: middle; text-align: center">25.7<sup>†</sup></td><td align="center" style="vertical-align: middle; text-align: center">29.6</td><td align="center" style="vertical-align: middle; text-align: center">27.0</td><td align="center" style="vertical-align: middle; text-align: center">26.6</td><td align="center" style="vertical-align: middle; text-align: center">20.4</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">APEX-Agents</td><td align="center" style="vertical-align: middle; text-align: center">41.0</td><td align="center" style="vertical-align: middle; text-align: center">43.3</td><td align="center" style="vertical-align: middle; text-align: center">39.9</td><td align="center" style="vertical-align: middle; text-align: center">39.4</td><td align="center" style="vertical-align: middle; text-align: center">38.5</td><td align="center" style="vertical-align: middle; text-align: center">35.6</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">OfficeQA Pro</td><td align="center" style="vertical-align: middle; text-align: center">63.3</td><td align="center" style="vertical-align: middle; text-align: center">69.9</td><td align="center" style="vertical-align: middle; text-align: center">63.2</td><td align="center" style="vertical-align: middle; text-align: center">63.9</td><td align="center" style="vertical-align: middle; text-align: center">60.9</td><td align="center" style="vertical-align: middle; text-align: center">41.4</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">SpreadsheetBench 2</td><td align="center" style="vertical-align: middle; text-align: center">34.8</td><td align="center" style="vertical-align: middle; text-align: center">34.7</td><td align="center" style="vertical-align: middle; text-align: center">32.4</td><td align="center" style="vertical-align: middle; text-align: center">31.6</td><td align="center" style="vertical-align: middle; text-align: center">29.1</td><td align="center" style="vertical-align: middle; text-align: center">28.1</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">OSWorld-Verified</td><td align="center" style="vertical-align: middle; text-align: center">84.8</td><td align="center" style="vertical-align: middle; text-align: center">85.0</td><td align="center" style="vertical-align: middle; text-align: center">83.0</td><td align="center" style="vertical-align: middle; text-align: center">83.4</td><td align="center" style="vertical-align: middle; text-align: center">79.0</td><td align="center" style="vertical-align: middle; text-align: center">—</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">OSWorld 2.0</td><td align="center" style="vertical-align: middle; text-align: center">58.3</td><td align="center" style="vertical-align: middle; text-align: center">66.1</td><td align="center" style="vertical-align: middle; text-align: center">62.6</td><td align="center" style="vertical-align: middle; text-align: center">55.7</td><td align="center" style="vertical-align: middle; text-align: center">49.5</td><td align="center" style="vertical-align: middle; text-align: center">—</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">SaaS-Bench</td><td align="center" style="vertical-align: middle; text-align: center">60.1</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">61.4</td><td align="center" style="vertical-align: middle; text-align: center">56.1</td><td align="center" style="vertical-align: middle; text-align: center">43.8</td><td align="center" style="vertical-align: middle; text-align: center">—</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">τ³-Banking</td><td align="center" style="vertical-align: middle; text-align: center">33.4</td><td align="center" style="vertical-align: middle; text-align: center">26.8</td><td align="center" style="vertical-align: middle; text-align: center">33.0</td><td align="center" style="vertical-align: middle; text-align: center">27.6</td><td align="center" style="vertical-align: middle; text-align: center">31.3</td><td align="center" style="vertical-align: middle; text-align: center">26.8</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">Harvey Lab-AA</td><td align="center" style="vertical-align: middle; text-align: center">94.6</td><td align="center" style="vertical-align: middle; text-align: center">93.6</td><td align="center" style="vertical-align: middle; text-align: center">87.2</td><td align="center" style="vertical-align: middle; text-align: center">91.1</td><td align="center" style="vertical-align: middle; text-align: center">86.3</td><td align="center" style="vertical-align: middle; text-align: center">91.0</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">CorpFin v2</td><td align="center" style="vertical-align: middle; text-align: center">71.6</td><td align="center" style="vertical-align: middle; text-align: center">71.8</td><td align="center" style="vertical-align: middle; text-align: center">64.4</td><td align="center" style="vertical-align: middle; text-align: center">66.7</td><td align="center" style="vertical-align: middle; text-align: center">68.4</td><td align="center" style="vertical-align: middle; text-align: center">66.1</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">Finance Agent v2</td><td align="center" style="vertical-align: middle; text-align: center">54.4</td><td align="center" style="vertical-align: middle; text-align: center">56.3</td><td align="center" style="vertical-align: middle; text-align: center">53.8</td><td align="center" style="vertical-align: middle; text-align: center">53.9</td><td align="center" style="vertical-align: middle; text-align: center">51.8</td><td align="center" style="vertical-align: middle; text-align: center">49.7</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">Legal Research Bench</td><td align="center" style="vertical-align: middle; text-align: center">44.2</td><td align="center" style="vertical-align: middle; text-align: center">49.5</td><td align="center" style="vertical-align: middle; text-align: center">48.1</td><td align="center" style="vertical-align: middle; text-align: center">43.8</td><td align="center" style="vertical-align: middle; text-align: center">40.4</td><td align="center" style="vertical-align: middle; text-align: center">31.3</td></tr><tr><td align="center" colspan=7 style="text-align: center"><strong>Vision</strong></td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">WorldVQA ForceAnswer</td><td align="center" style="vertical-align: middle; text-align: center">51.0</td><td align="center" style="vertical-align: middle; text-align: center">56.7</td><td align="center" style="vertical-align: middle; text-align: center">41.8</td><td align="center" style="vertical-align: middle; text-align: center">39.1</td><td align="center" style="vertical-align: middle; text-align: center">38.5</td><td align="center" style="vertical-align: middle; text-align: center">—</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">OmniDocBench</td><td align="center" style="vertical-align: middle; text-align: center">91.1</td><td align="center" style="vertical-align: middle; text-align: center">89.8</td><td align="center" style="vertical-align: middle; text-align: center">85.8</td><td align="center" style="vertical-align: middle; text-align: center">87.9</td><td align="center" style="vertical-align: middle; text-align: center">89.4</td><td align="center" style="vertical-align: middle; text-align: center">—</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">PerceptionBench</td><td align="center" style="vertical-align: middle; text-align: center">58.5</td><td align="center" style="vertical-align: middle; text-align: center">57.2</td><td align="center" style="vertical-align: middle; text-align: center">59.7</td><td align="center" style="vertical-align: middle; text-align: center">47.2</td><td align="center" style="vertical-align: middle; text-align: center">55.8</td><td align="center" style="vertical-align: middle; text-align: center">—</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">Video-MME (w. sub)</td><td align="center" style="vertical-align: middle; text-align: center">90.0</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">89.5</td><td align="center" style="vertical-align: middle; text-align: center">86.0</td><td align="center" style="vertical-align: middle; text-align: center">89.3</td><td align="center" style="vertical-align: middle; text-align: center">—</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">MMVU</td><td align="center" style="vertical-align: middle; text-align: center">82.1</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">81.2</td><td align="center" style="vertical-align: middle; text-align: center">79.2</td><td align="center" style="vertical-align: middle; text-align: center">81.7</td><td align="center" style="vertical-align: middle; text-align: center">—</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">BabyVision w/ python</td><td align="center" style="vertical-align: middle; text-align: center">85.7</td><td align="center" style="vertical-align: middle; text-align: center">90.5</td><td align="center" style="vertical-align: middle; text-align: center">88.9</td><td align="center" style="vertical-align: middle; text-align: center">81.2</td><td align="center" style="vertical-align: middle; text-align: center">83.6</td><td align="center" style="vertical-align: middle; text-align: center">—</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">MMMU-Pro</td><td align="center" style="vertical-align: middle; text-align: center">81.6 / 83.4</td><td align="center" style="vertical-align: middle; text-align: center">81.2 / 86.5</td><td align="center" style="vertical-align: middle; text-align: center">83.0 / 84.6</td><td align="center" style="vertical-align: middle; text-align: center">78.9 / 82.7</td><td align="center" style="vertical-align: middle; text-align: center">81.2 / 83.2</td><td align="center" style="vertical-align: middle; text-align: center">—</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">CharXiv (RQ)</td><td align="center" style="vertical-align: middle; text-align: center">84.8 / 91.3</td><td align="center" style="vertical-align: middle; text-align: center">88.9 / 93.5</td><td align="center" style="vertical-align: middle; text-align: center">84.6 / 89.1</td><td align="center" style="vertical-align: middle; text-align: center">80.5 / 89.9</td><td align="center" style="vertical-align: middle; text-align: center">84.1 / 89.0</td><td align="center" style="vertical-align: middle; text-align: center">—</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">MathVision</td><td align="center" style="vertical-align: middle; text-align: center">94.3 / 97.8</td><td align="center" style="vertical-align: middle; text-align: center">94.8 / 98.6</td><td align="center" style="vertical-align: middle; text-align: center">95.8 / 97.8</td><td align="center" style="vertical-align: middle; text-align: center">86.7 / 97.1</td><td align="center" style="vertical-align: middle; text-align: center">92.2 / 96.8</td><td align="center" style="vertical-align: middle; text-align: center">—</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">ZeroBench (pass@5)</td><td align="center" style="vertical-align: middle; text-align: center">23.0 / 41.0</td><td align="center" style="vertical-align: middle; text-align: center">23.0 / 46.0</td><td align="center" style="vertical-align: middle; text-align: center">17.0 / 35.0</td><td align="center" style="vertical-align: middle; text-align: center">17.0 / 34.0</td><td align="center" style="vertical-align: middle; text-align: center">22.0 / 41.0</td><td align="center" style="vertical-align: middle; text-align: center">—</td></tr></tbody></table></div>
<details><summary><b>Footnotes</b></summary>
All Kimi K3 results are obtained with reasoning effort set to 'max' and temperature = 1.0. For single-step tasks, such as GPQA Diamond, HLE-Full, and vision benchmarks without tools, we set top-p = 0.95; for agentic tasks, we set top-p = 1.0. For HLE-Full, MMMU-Pro, CharXiv (RQ), MathVision, and ZeroBench, each cell reports the scores without and with tool augmentation (general tools for HLE-Full, Python for the vision benchmarks), in that order.
1. **Reasoning & knowledge benchmarks** - **CritPt and AA-LCR.** Scores are cited from [Artificial Analysis](https://artificialanalysis.ai/) as of July 23, 2026.2. **Coding benchmarks** - **DeepSWE.** Kimi K3 is evaluated with the Kimi Code harness. The GLM-5.2 score is taken from the [GLM-5.2 release blog](https://z.ai/blog/glm-5.2); all remaining scores are from the official [DeepSWE leaderboard](https://deepswe.datacurve.ai/), under which Kimi K3 attains 67.3 with the mini-SWE-agent harness. We report the DeepSWE v1.1 tasks. - **Terminal-Bench 2.1.** Kimi K3 is evaluated with the Kimi Code harness. For all other models, we report the best score across harnesses: GLM-5.2 with Claude Code ([GLM-5.2 release blog](https://z.ai/blog/glm-5.2)); Claude Opus 4.8 and Claude Fable 5 with Terminus 2 ([Artificial Analysis](https://artificialanalysis.ai/evaluations/terminalbench-v2-1)); GPT-5.5 and GPT-5.6 Sol with Codex ([OpenAI](https://openai.com/index/previewing-gpt-5-6-sol/)). - **ProgramBench.** Kimi K3 is evaluated with the Kimi Code harness. The GLM-5.2 score is from the [GLM-5.2 release blog](https://z.ai/blog/glm-5.2); all other scores are from [Vals AI](https://www.vals.ai/benchmarks/programbench). - **SWE-Marathon.** Kimi K3, Claude Opus 4.8, and Claude Fable 5 are evaluated with the Claude Code harness; GPT-5.6 Sol is evaluated with the Codex harness. The GLM-5.2 score is from the [GLM-5.2 release blog](https://z.ai/blog/glm-5.2). Our evaluation is based on an H20-calibrated branch of the [official tasks](https://www.swe-marathon.org/) as of July 9, 2026, prior to the final v1.1 release: the Docker images, performance gates, and reference oracles for the GPU tasks have been recalibrated for H20, while the correctness and anti-cheat validators remain unchanged. Additionally, Claude Fable 5 hit fallbacks on 35% of the tasks in our evaluation, which may have negatively impacted its measured performance. - **FrontierSWE.** Kimi K3 is evaluated with the Kimi Code harness and GPT-5.6 Sol with the Codex harness; all other results are from [FrontierSWE](https://www.frontierswe.com/). Dominance scores are recomputed from the raw scores using the official evaluation script and are current as of July 16, 2026. - **PostTrainBench.** Scores for GLM-5.2, GPT-5.5, and Claude Opus 4.8 are adopted from the official [PostTrainBench](https://posttrainbench.com/) results. Kimi K3, Claude Fable 5, and GPT-5.6 Sol are evaluated with the official Harbor implementation at maximum reasoning effort, averaged over three runs on H20 GPUs (instead of H100 in the official setting) — Kimi K3 and Claude Fable 5 with the Claude Code harness, and GPT-5.6 Sol with the Codex harness. - **MLS-Bench-Lite.** Kimi K3 is evaluated with the Kimi Code harness; GLM-5.2 and the Claude models with the Claude Code harness; GPT-5.5 and GPT-5.6 Sol with the Codex harness. - **SciCode.** Scores are cited from [Artificial Analysis](https://artificialanalysis.ai/) as of July 23, 2026. - **Kimi Code Bench 2.0 (in-house).** Kimi K3 is evaluated with the Kimi Code harness (it attains 73.7 with the Claude Code harness); GLM-5.2, Claude Opus 4.8, and Claude Fable 5 with the Claude Code harness; GPT-5.5 and GPT-5.6 Sol with the Codex harness. All models are evaluated at maximum reasoning effort, except GPT-5.5, which uses the "xhigh" setting. As the benchmark includes cybersecurity and safety-related tasks, we also disclose the fraction of refused or fallback tasks: Claude Fable 5 hit 13 fallbacks and 1 refusal out of 80 tasks; 10 refusals out of 80 tasks entered GPT-5.6 Sol's cyber guard; GPT-5.5 had 3 refusals out of 80 tasks.3. **Agentic benchmarks** - **OfficeQA Pro.** Each test case provides the agent with the entire PDF corpus, with all PDFs rendered as images and no machine-readable text available. - **OfficeQA Pro and SpreadsheetBench 2.** Kimi K3, GLM-5.2, Claude Opus 4.8, and Claude Fable 5 are evaluated with the Claude Code harness; GPT-5.5 and GPT-5.6 Sol are evaluated with the Codex harness. - **MCP-Atlas.** All models are evaluated on the 500-task public subset with a 100-turn limit, using Gemini 3.1 Pro as the judge. - **AutomationBench.** All models are evaluated on the 600-task public subset, following the official GitHub setup in all other respects. - **BrowseComp.** We adopt a context-compaction strategy triggered at 300K tokens. When evaluated with the full 1M-token context window and no context management, Kimi K3 achieves a score of 90.4. The results of Claude Fable 5, Claude Opus 4.8, GPT-5.6 Sol, and GPT-5.5 are cited from [Anthropic](https://www.anthropic.com/news/claude-fable-5-mythos-5) and [OpenAI](https://openai.com/index/gpt-5-6/). - **GDPval-AA v2, AA-Briefcase, τ³-Banking, Harvey Lab-AA, and APEX-Agents.** Scores are cited from [Artificial Analysis](https://artificialanalysis.ai/) and the [APEX-Agents leaderboard](https://www.mercor.com/apex/apex-agents-leaderboard/) as of July 23, 2026. For Harvey Lab-AA, we report the criterion pass rate. - **CorpFin v2, Finance Agent v2, and Legal Research Bench.** Scores are cited from [Vals AI](https://www.vals.ai/). - **Agents' Last Exam.** Scores are cited from the [official leaderboard](https://agents-last-exam.org/leaderboard) as of July 23, 2026; we report the leaderboard's primary pass-rate metric. On the leaderboard, each model is paired with a specific harness: Kimi K3 with Kimi Code; GPT-5.6 Sol and GPT-5.5 with Codex; Claude Fable 5, Claude Opus 4.8, and GLM-5.2 with Claude Code. <sup>†</sup> The Claude Fable 5 entry runs at xhigh effort with 40% of tasks annotated as downgraded.4. **Multimodal benchmarks** - Except for ZeroBench, which follows the official setting and is run five times, all multimodal scores are averaged over three runs. MMMU-Pro is evaluated following the official protocol, preserving the original input order and prepending images to the text input. - **PerceptionBench** is an in-house benchmark that focuses on atomic visual perception capabilities.
</details>
## 4. Native MXFP4 Quantization
Kimi K3 applies quantization-aware training from the SFT stage onward, using MXFP4 weights with MXFP8 activations for broad hardware compatibility.
## 5. Deployment
> [!Note]> You can access Kimi K3's API on https://platform.kimi.ai by selecting `kimi-k3`, and we provide OpenAI/Anthropic-compatible API for you. Currently, Kimi K3 is recommended to run on the following inference engines:
- [vLLM](https://github.com/vllm-project/vllm) — see [recipes](https://recipes.vllm.ai/moonshotai/Kimi-K3)- [SGLang](https://github.com/sgl-project/sglang) — see [cookbook](https://docs.sglang.io/cookbook/autoregressive/Moonshotai/Kimi-K3)- [TokenSpeed](https://github.com/lightseekorg/tokenspeed) — see [recipes](https://lightseek.org/tokenspeed/recipes/models#kimi-k3)
---## 6. Model Usage
Kimi K3 always has thinking enabled, and will return `reasoning_content`. Thinking effort is configured with the top-level `reasoning_effort` request field, which supports `"low"`, `"high"`, and `"max"` (default `"max"`).
Kimi K3 was trained in the preserved thinking history mode. For multi-turn conversations and tool calls, Kimi K3 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`:
```pythonimport openai
def chat_with_preserved_thinking(client: openai.OpenAI, model_name: str): messages = [ { "role": "user", "content": "Tell me three random numbers." }, { "role": "assistant", "reasoning_content": "I'll start by listing five numbers: 473, 921, 235, 215, 222, and I'll tell you the first three.", "content": "473, 921, 235" }, { "role": "user", "content": "What are the other two numbers you have in mind?" } ]
response = client.chat.completions.create( model=model_name, messages=messages, stream=False, max_tokens=4096, reasoning_effort="max", ) # the assistant should mention 215 and 222 that appear in the prior reasoning content print(f"response: {response.choices[0].message.reasoning}") return response.choices[0].message.content```
For full guides and examples (vision input, structured output, partial mode, tool choice, dynamic tool loading, context caching), see the [Kimi K3 Quickstart](https://platform.kimi.ai/docs/guide/kimi-k3-quickstart) and [Thinking Effort](https://platform.kimi.ai/docs/guide/use-thinking-effort).
### Coding Agent Framework
Kimi K3 works best with [Kimi Code CLI](https://www.kimi.com/code) as its agent framework. We warmly invite you to give it a try — run Kimi Code in your terminal and select Kimi K3 using the `/model` command. We hope you enjoy building with Kimi K3, and we would love to hear your feedback!
---
## 7. License
Both the code repository and the model weights are released under the [Kimi K3 License](https://huggingface.co/moonshotai/Kimi-K3/blob/main/LICENSE).
---
## 8. Contact Us
If you have any questions, please reach out at [support@moonshot.ai](mailto:support@moonshot.ai).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300{ "architectures": [ "KimiK3ForConditionalGeneration" ], "auto_map": { "AutoConfig": "configuration_kimi_k3.KimiK3Config", "AutoModel": "modeling_kimi_k3.KimiK3ForConditionalGeneration", "AutoModelForCausalLM": "modeling_kimi_k3.KimiK3ForConditionalGeneration" }, "bos_token_id": 163584, "dtype": "bfloat16", "eos_token_id": 163586, "ignore_index": -100, "image_placeholder": "<|kimi_image_placeholder|>", "media_placeholder_token_id": 163605, "model_type": "kimi_k3", "pad_token_id": 163839, "text_config": { "_name_or_path": "", "activation_situ_beta": 4.0, "activation_situ_linear_beta": 25.0, "add_cross_attention": false, "architectures": [ "KimiLinearForCausalLM" ], "attn_res_block_size": 12, "auto_map": { "AutoConfig": "configuration_kimi_k3.KimiLinearConfig", "AutoModel": "modeling_kimi_linear.KimiLinearModel", "AutoModelForCausalLM": "modeling_kimi_linear.KimiLinearForCausalLM" }, "bad_words_ids": null, "begin_suppress_tokens": null, "bos_token_id": 163584, "chunk_size_feed_forward": 0, "cross_attention_hidden_size": null, "decoder_start_token_id": null, "diversity_penalty": 0.0, "do_sample": false, "dtype": "bfloat16", "early_stopping": false, "encoder_no_repeat_ngram_size": 0, "eos_token_id": 163586, "exponential_decay_length_penalty": null, "finetuning_task": null, "first_k_dense_replace": 1, "forced_bos_token_id": null, "forced_eos_token_id": null, "hidden_act": "situ", "hidden_size": 7168, "id2label": { "0": "LABEL_0", "1": "LABEL_1" }, "initializer_range": 0.02, "intermediate_size": 33792, "is_decoder": false, "is_encoder_decoder": false, "kv_lora_rank": 512, "label2id": { "LABEL_0": 0, "LABEL_1": 1 }, "latent_moe_use_norm": true, "length_penalty": 1.0, "linear_attn_config": { "full_attn_layers": [ 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80, 84, 88, 92, 93 ], "gate_lower_bound": -5.0, "head_dim": 128, "kda_layers": [ 1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17, 18, 19, 21, 22, 23, 25, 26, 27, 29, 30, 31, 33, 34, 35, 37, 38, 39, 41, 42, 43, 45, 46, 47, 49, 50, 51, 53, 54, 55, 57, 58, 59, 61, 62, 63, 65, 66, 67, 69, 70, 71, 73, 74, 75, 77, 78, 79, 81, 82, 83, 85, 86, 87, 89, 90, 91 ], "num_heads": 96, "short_conv_kernel_size": 4, "use_full_rank_gate": true }, "max_length": 20, "max_position_embeddings": 1048576, "min_length": 0, "mla_use_nope": true, "mla_use_output_gate": true, "model_type": "kimi_linear", "moe_intermediate_size": 3072, "moe_layer_freq": 1, "moe_renormalize": true, "moe_router_activation_func": "sigmoid", "no_repeat_ngram_size": 0, "num_attention_heads": 96, "num_beam_groups": 1, "num_beams": 1, "num_expert_group": 1, "num_experts": 896, "num_experts_per_token": 16, "num_hidden_layers": 93, "num_key_value_heads": 96, "num_nextn_predict_layers": 0, "num_return_sequences": 1, "num_shared_experts": 2, "output_attentions": false, "output_hidden_states": false, "output_scores": false, "pad_token_id": 163839, "prefix": null, "problem_type": null, "pruned_heads": {}, "q_lora_rank": 1536, "qk_nope_head_dim": 128, "qk_rope_head_dim": 64, "quantization_config": { "config_groups": { "group_0": { "format": "mxfp4-pack-quantized", "input_activations": null, "output_activations": null, "targets": [ "Linear" ], "weights": { "actorder": null, "block_structure": null, "dynamic": false, "group_size": 32, "num_bits": 4, "observer": "minmax", "observer_kwargs": {}, "scale_dtype": "torch.uint8", "strategy": "group", "symmetric": true, "type": "float", "zp_dtype": null } } }, "format": "mxfp4-pack-quantized", "global_compression_ratio": null, "ignore": [ "re:.*self_attn.*", "re:.*shared_experts.*", "re:.*mlp\\.(gate|up|gate_up|down)_proj.*", "re:.*lm_head.*", "re:.*vision_tower.*", "re:.*mm_projector.*" ], "kv_cache_scheme": null, "quant_method": "compressed-tensors", "quantization_status": "compressed" }, "remove_invalid_values": false, "repetition_penalty": 1.0, "return_dict": true, "return_dict_in_generate": false, "rms_norm_eps": 1e-05, "routed_expert_hidden_size": 3584, "routed_scaling_factor": 1.0, "sep_token_id": null, "suppress_tokens": null, "task_specific_params": null, "temperature": 1.0, "tf_legacy_loss": false, "tie_encoder_decoder": false, "tie_word_embeddings": false, "tokenizer_class": null, "top_k": 50, "top_p": 1.0, "topk_group": 1, "topk_method": "noaux_tc", "torchscript": false, "transformers_version": "4.56.2", "typical_p": 1.0, "use_bfloat16": false, "use_cache": true, "use_grouped_topk": true, "v_head_dim": 128, "vocab_size": 163840 }, "tie_word_embeddings": false, "vision_config": { "_attn_implementation": "flash_attention_2", "activation_func": "gelu_pytorch_tanh", "attn_bias": false, "init_pos_emb_height": 64, "init_pos_emb_time": 4, "init_pos_emb_width": 64, "linear_bias": false, "merge_kernel_size": [ 2, 2 ], "merge_type": "sd2_tpool", "mlp_type": "mlp2", "mm_hidden_size": 1024, "mm_projector_type": "patchmergerv2", "norm_type": "rmsnorm", "patch_embed_proj_bias": false, "patch_size": 14, "pos_emb_interpolation_mode": "bilinear", "pos_emb_type": "divided_fixed", "projector_hidden_act": "gelu", "projector_ln_eps": 1e-05, "qkv_hidden_size": 1536, "text_hidden_size": 7168, "vt_hidden_size": 1024, "vt_intermediate_size": 4096, "vt_num_attention_heads": 12, "vt_num_hidden_layers": 27 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285from typing import Optional
from transformers.configuration_utils import PretrainedConfig
class KimiLinearConfig(PretrainedConfig): model_type = "kimi_linear" keys_to_ignore_at_inference = ["past_key_values"]
def __init__( self, model_type="kimi_linear", vocab_size=163840, hidden_size=4096, head_dim=None, intermediate_size=11008, num_hidden_layers=32, num_attention_heads=32, num_key_value_heads=None, hidden_act="silu", initializer_range=0.02, rms_norm_eps=1e-6, use_cache=True, pad_token_id=0, bos_token_id=1, eos_token_id=2, rope_theta=10000.0, rope_scaling=None, tie_word_embeddings=False, moe_intermediate_size: Optional[int] = None, moe_renormalize: bool = True, moe_router_activation_func: str = "sigmoid", num_experts: Optional[int] = None, num_experts_per_token: Optional[int] = None, num_shared_experts: int = 0, routed_scaling_factor: float = 1.0, first_k_dense_replace: int = 0, moe_layer_freq: int = 1, use_grouped_topk: bool = True, num_expert_group: int = 1, topk_group: int = 1, q_lora_rank: Optional[int] = None, kv_lora_rank: Optional[int] = None, qk_nope_head_dim: Optional[int] = None, qk_rope_head_dim: Optional[int] = None, v_head_dim: Optional[int] = None, mla_use_nope: Optional[bool] = False, mla_use_output_gate: Optional[bool] = False, num_nextn_predict_layers: int = 0, linear_attn_config: Optional[dict] = None, attn_res_block_size: Optional[int] = None, latent_moe_use_norm: bool = False, activation_situ_beta: Optional[float] = None, activation_situ_linear_beta: Optional[float] = None, max_position_embeddings: int = 4096, routed_expert_hidden_size: Optional[int] = None, topk_method: str = "noaux_tc", **kwargs, ): self.model_type = model_type self.vocab_size = vocab_size self.hidden_size = hidden_size self.head_dim = ( head_dim if head_dim is not None else hidden_size // num_attention_heads ) self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads
# for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache self.rope_theta = rope_theta self.rope_scaling = rope_scaling
self.q_lora_rank = q_lora_rank self.kv_lora_rank = kv_lora_rank self.qk_nope_head_dim = qk_nope_head_dim self.qk_rope_head_dim = qk_rope_head_dim self.v_head_dim = v_head_dim self.mla_use_nope = mla_use_nope self.mla_use_output_gate = mla_use_output_gate # moe config self.num_experts = num_experts self.num_experts_per_token = num_experts_per_token self.moe_renormalize = moe_renormalize self.num_shared_experts = num_shared_experts self.routed_scaling_factor = routed_scaling_factor self.moe_router_activation_func = moe_router_activation_func assert self.moe_router_activation_func in ("softmax", "sigmoid") self.moe_intermediate_size = moe_intermediate_size self.first_k_dense_replace = first_k_dense_replace self.moe_layer_freq = moe_layer_freq self.use_grouped_topk = use_grouped_topk self.num_expert_group = num_expert_group self.topk_group = topk_group self.num_nextn_predict_layers = num_nextn_predict_layers
self.attn_res_block_size = attn_res_block_size self.latent_moe_use_norm = latent_moe_use_norm self.activation_situ_beta = activation_situ_beta self.activation_situ_linear_beta = activation_situ_linear_beta self.max_position_embeddings = max_position_embeddings self.routed_expert_hidden_size = routed_expert_hidden_size self.topk_method = topk_method
if linear_attn_config is not None: assert linear_attn_config["kda_layers"] is not None assert linear_attn_config["full_attn_layers"] is not None self.linear_attn_config = linear_attn_config
super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, )
@property def is_mla(self): return ( self.q_lora_rank is not None or self.kv_lora_rank is not None or self.qk_nope_head_dim is not None or self.qk_rope_head_dim is not None or self.v_head_dim is not None or self.mla_use_nope is True )
@property def is_moe(self): return self.num_experts is not None
@property def is_linear_attn(self) -> bool: return not ( self.linear_attn_config is None or ( isinstance(self.linear_attn_config, dict) and self.linear_attn_config["kda_layers"] is not None and len(self.linear_attn_config["kda_layers"]) == 0 ) )
def is_kda_layer(self, layer_idx: int): return ( self.linear_attn_config is not None and (layer_idx + 1) in self.linear_attn_config["kda_layers"] )
class KimiK3VisionConfig(PretrainedConfig):
def __init__( self, patch_size: int = 14, init_pos_emb_height: int = 64, init_pos_emb_width: int = 64, init_pos_emb_time: int = 4, pos_emb_type: str = 'divided_fixed', vt_num_attention_heads: int = 12, vt_num_hidden_layers: int = 27, vt_hidden_size: int = 1024, vt_intermediate_size: int = 4096, merge_kernel_size: tuple = (2, 2), merge_type: str = 'sd2_tpool', _attn_implementation: str = 'flash_attention_2', # MM Projector parameters mm_projector_type: str = 'patchmergerv2', mm_hidden_size: int | None = None, projector_hidden_act: str = "gelu", projector_ln_eps: float = 1e-5, # vision tower parameters qkv_hidden_size: int = 1536, norm_type: str = 'rmsnorm', attn_bias: bool = False, patch_embed_proj_bias: bool = False, mlp_type: str = 'mlp2', linear_bias: bool = False, activation_func: str = 'gelu_pytorch_tanh', pos_emb_interpolation_mode: str = 'bilinear', # Other parameters ignore_index: int = -100, media_placeholder_token_id: int = 163605, pad_token_id: int = 0, text_hidden_size=7168, **kwargs):
self.patch_size = patch_size self.init_pos_emb_height = init_pos_emb_height self.init_pos_emb_width = init_pos_emb_width self.init_pos_emb_time = init_pos_emb_time self.pos_emb_type = pos_emb_type self.vt_num_attention_heads = vt_num_attention_heads self.vt_num_hidden_layers = vt_num_hidden_layers self.vt_hidden_size = vt_hidden_size self.vt_intermediate_size = vt_intermediate_size self.merge_kernel_size = merge_kernel_size self.merge_type = merge_type self._attn_implementation = _attn_implementation
# MM Projector config self.mm_projector_type = mm_projector_type self.mm_hidden_size = mm_hidden_size if mm_hidden_size is not None else vt_hidden_size self.projector_hidden_act = projector_hidden_act self.projector_ln_eps = projector_ln_eps self.text_hidden_size = text_hidden_size
# vision tower parameters self.qkv_hidden_size = qkv_hidden_size self.norm_type = norm_type self.attn_bias = attn_bias self.patch_embed_proj_bias = patch_embed_proj_bias self.mlp_type = mlp_type self.linear_bias = linear_bias self.activation_func = activation_func self.pos_emb_interpolation_mode = pos_emb_interpolation_mode
super().__init__(**kwargs)
class KimiK3Config(PretrainedConfig): """Kimi-K3 model configuration.
Args: text_config (dict | KimiLinearConfig): Configuration for the text model. Vision Tower Parameters (from MoonViT3dConfig): patch_size (int): Patch size for vision tower. init_pos_emb_height (int): Initial position embedding height. init_pos_emb_width (int): Initial position embedding width. init_pos_emb_time (int): Initial position embedding time dimension. pos_emb_type (str): Type of position embedding. vt_num_attention_heads (int): Number of attention heads in vision tower. vt_num_hidden_layers (int): Number of hidden layers in vision tower. vt_hidden_size (int): Hidden size of vision tower. vt_intermediate_size (int): Intermediate size in vision tower FFN. merge_kernel_size (tuple): Kernel size for patch merging. merge_type (str): Type of merge operation. _attn_implementation (str): Attention implementation type. MM Projector Parameters (from MultiModalProjectorConfig): mm_projector_type (str): Type of multimodal projector. mm_hidden_size (int): Hidden size from vision tower (should match vt_hidden_size). projector_hidden_act (str): Activation function for projector. projector_ln_eps (float): Layer norm epsilon for projector. Other Parameters: ignore_index (int): The ignore index for the loss function. media_placeholder_token_id (int): The token ID to use for media placeholders. pad_token_id (int): The token ID to use for padding. """
model_type = "kimi_k3"
def __init__( self, text_config: dict | KimiLinearConfig = None, vision_config: dict | KimiK3VisionConfig = None, # Other parameters ignore_index: int = -100, media_placeholder_token_id: int = 163605, pad_token_id: int = 0, **kwargs, ): if isinstance(text_config, dict): text_config = KimiLinearConfig(**text_config) if isinstance(vision_config, dict): vision_config = KimiK3VisionConfig(**vision_config) self.text_config = text_config self.vision_config = vision_config # Other config self.ignore_index = ignore_index self.media_placeholder_token_id = media_placeholder_token_id if getattr(self.text_config, "quantization_config", None) is not None: self.quantization_config = self.text_config.quantization_config
super().__init__(pad_token_id=pad_token_id, **kwargs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647"""Kimi K3 XTML encoding helpers.
This module keeps chat rendering in Python.Callers that need token IDs should consume ``EncodeSegment`` objects directly:structural markers may be encoded as tiktoken special tokens, while user/tooltext and attribute values are encoded as ordinary text."""
from __future__ import annotations
import jsonfrom dataclasses import dataclassfrom typing import Any, Iterable, Optional
OPEN_TOKEN = "<|open|>"CLOSE_TOKEN = "<|close|>"SEP_TOKEN = "<|sep|>"END_OF_MSG_TOKEN = "<|end_of_msg|>"IMAGE_PLACEHOLDER = "<|kimi_image_placeholder|>"
_VALID_THINKING_EFFORTS = {"low", "high", "max"}
@dataclass(frozen=True)class EncodeSegment: text: str allow_special: bool = False
class _ImagePromptState: def __init__(self, image_prompts: Optional[list[str]] = None): self.image_prompts = image_prompts self.index = 0
def next_prompt(self) -> str: if self.image_prompts is None: return IMAGE_PLACEHOLDER if self.index >= len(self.image_prompts): raise ValueError("More image placeholders than image prompts.") prompt = self.image_prompts[self.index] self.index += 1 return prompt
def assert_consumed(self) -> None: if self.image_prompts is None: return if self.index != len(self.image_prompts): raise ValueError( f"image prompt count {len(self.image_prompts)} != " f"consumed placeholder count {self.index}" )
def _segment(text: Any, *, allow_special: bool = False) -> list[EncodeSegment]: text = str(text) if not text: return [] return [EncodeSegment(text, allow_special=allow_special)]
def _control(text: str) -> list[EncodeSegment]: return _segment(text, allow_special=True)
def _text(text: Any) -> list[EncodeSegment]: return _segment(text, allow_special=False)
def _append_text( segments: list[EncodeSegment], text: Any, image_state: _ImagePromptState,) -> None: text = str(text) if text == "": return if image_state.image_prompts is None or IMAGE_PLACEHOLDER not in text: segments.extend(_text(text)) return
parts = text.split(IMAGE_PLACEHOLDER) for i, part in enumerate(parts): segments.extend(_text(part)) if i < len(parts) - 1: segments.extend(_segment(image_state.next_prompt(), allow_special=True))
def _escape_attr_value(value: Any) -> str: return str(value).replace("&", "&").replace('"', """)
def _attr(key: str, value: Any) -> list[EncodeSegment]: return ( _text(f" {key}") + _text('="') + _text(_escape_attr_value(value)) + _text('"') )
def _open_tag(tag: str, attrs: Iterable[tuple[str, Any]] = ()) -> list[EncodeSegment]: segments: list[EncodeSegment] = [] segments.extend(_control(OPEN_TOKEN)) segments.extend(_text(tag)) for key, value in attrs: segments.extend(_attr(key, value)) segments.extend(_control(SEP_TOKEN)) return segments
def _close_tag(tag: str) -> list[EncodeSegment]: segments: list[EncodeSegment] = [] segments.extend(_control(CLOSE_TOKEN)) segments.extend(_text(tag)) segments.extend(_control(SEP_TOKEN)) return segments
def _end_of_msg() -> list[EncodeSegment]: return _control(END_OF_MSG_TOKEN)
def _json_compact(value: Any) -> str: return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
def _is_mapping(value: Any) -> bool: return isinstance(value, dict)
def _xtml_type(value: Any) -> str: if isinstance(value, bool): return "boolean" if value is None: return "null" if isinstance(value, (int, float)) and not isinstance(value, bool): return "number" if isinstance(value, str): return "string" if _is_mapping(value): return "object" return "array"
def _xtml_value(value: Any) -> str: if isinstance(value, str): return value return json.dumps(value, ensure_ascii=False)
def _get_value(obj: Any, key: str, default: Any = None) -> Any: if isinstance(obj, dict): return obj.get(key, default) return getattr(obj, key, default)
def extract_response_schema(response_format: Any) -> Any: if response_format is None: return None
json_schema = _get_value(response_format, "json_schema") if json_schema is None: return None
if isinstance(json_schema, dict): return json_schema.get( "schema", json_schema.get("json_schema", json_schema), )
schema = _get_value(json_schema, "schema") if schema is not None: return schema
schema = _get_value(json_schema, "json_schema") if schema is not None: return schema
return json_schema
def deep_sort_dict(obj: Any) -> Any: if isinstance(obj, dict): return {k: deep_sort_dict(v) for k, v in sorted(obj.items())} if isinstance(obj, list): return [deep_sort_dict(item) for item in obj] return obj
def normalize_tool_arguments(arguments: Any) -> tuple[dict[str, Any], Optional[str]]: if arguments is None: return {}, None if isinstance(arguments, dict): return arguments, None if isinstance(arguments, str): if not arguments.strip(): return {}, None try: parsed = json.loads(arguments) except json.JSONDecodeError: return {}, arguments if not isinstance(parsed, dict): raise ValueError("Kimi K3 tool call arguments must be a JSON object.") return parsed, None raise TypeError( "Kimi K3 tool call arguments must be a dict or a JSON object string." )
def normalize_message(message: Any) -> Any: if not isinstance(message, dict): return message
normalized = dict(message)
tools = normalized.get("tools") if tools is not None: normalized["tools"] = deep_sort_dict(tools)
tool_calls = normalized.get("tool_calls") if not tool_calls: return normalized
normalized_calls = [] for tool_call in tool_calls: if not isinstance(tool_call, dict): normalized_calls.append(tool_call) continue
tc = dict(tool_call) function = tc.get("function") if isinstance(function, dict): fn = dict(function) arguments, json_block = normalize_tool_arguments(fn.get("arguments")) fn["arguments"] = arguments if json_block is None: fn.pop("_xtml_json_block", None) else: fn["_xtml_json_block"] = json_block tc["function"] = fn else: arguments, json_block = normalize_tool_arguments(tc.get("arguments")) tc["arguments"] = arguments if json_block is None: tc.pop("_xtml_json_block", None) else: tc["_xtml_json_block"] = json_block normalized_calls.append(tc)
normalized["tool_calls"] = normalized_calls return normalized
def normalize_conversation(conversation: Any) -> Any: if not isinstance(conversation, list): return conversation
def normalize_messages(messages: list[Any]) -> list[Any]: return [normalize_message(message) for message in messages]
if conversation and isinstance(conversation[0], list): return [normalize_messages(messages) for messages in conversation] return normalize_messages(conversation)
def _tool_call_id_index(tool_calls: Any) -> dict: """Map assistant ``tool_calls[].id`` to ``(1-based position, function name)``.
The position mirrors the chat template's enumeration over ``tool_calls`` (every entry advances the position, even an id-less one). Duplicate ids keep their first occurrence. """ index: dict = {} if not isinstance(tool_calls, list): return index for position, tool_call in enumerate(tool_calls, start=1): if not isinstance(tool_call, dict): continue call_id = tool_call.get("id") if call_id is None: continue key = str(call_id) if key in index: continue function = tool_call.get("function") name = ( function.get("name") if isinstance(function, dict) else tool_call.get("name") ) index[key] = (position, name) return index
def normalize_xtml_tool_result_messages(messages: list[Any]) -> list[Any]: """Re-sort K3 XTML tool results into assistant ``tool_calls`` order.
Serving frameworks generally deliver tool results already in call order. A direct Transformers caller, however, may pass OpenAI-style tool messages in any order, so each run of consecutive tool messages is matched against the most recent preceding assistant ``tool_calls`` by opaque ``tool_call_id`` == ``tool_calls[].id`` (K3 drops the ``func:index`` format requirement) and sorted by the matched 1-based position. The matched call is authoritative, so each matched message's ``tool`` is set to that call's function name -- this keeps an explicit (and possibly stale) ``tool``/``name`` from drifting out of sync with the reordered position. ``index`` is still derived from the rendered position by the chat template. A run that cannot be fully matched is left untouched. Re-running is idempotent.
This function is side-effect free: matched tool messages are shallow-copied before their ``tool``/``name`` is rewritten, and every other message is appended to the output as-is. The input list and its message objects are never mutated. """ if not isinstance(messages, list): return messages
output: list[Any] = [] current_index: dict = {} i = 0 n = len(messages)
while i < n: message = messages[i]
if isinstance(message, dict) and message.get("role") == "assistant": tool_calls = message.get("tool_calls") current_index = _tool_call_id_index(tool_calls) if tool_calls else {} output.append(message) i += 1 continue
if not isinstance(message, dict) or message.get("role") != "tool": output.append(message) i += 1 continue
run: list[tuple] = [] # (position, original_offset, message, name) unresolved = False offset = 0 while ( i < n and isinstance(messages[i], dict) and messages[i].get("role") == "tool" ): tool_message = messages[i] call_id = tool_message.get("tool_call_id", tool_message.get("id")) matched = current_index.get(str(call_id)) if call_id is not None else None if matched is None: unresolved = True run.append((None, offset, tool_message, None)) else: position, name = matched run.append((position, offset, tool_message, name)) offset += 1 i += 1
if unresolved: output.extend(item[2] for item in run) else: run.sort(key=lambda item: (item[0], item[1])) for _, _, tool_message, name in run: if name is None: output.append(tool_message) continue # The id-matched call is authoritative: align tool (and any # explicit name) so the rendered XTML tool attribute cannot # disagree with the reordered position. Copy first so the # caller's message object is never mutated. resolved = dict(tool_message) resolved["tool"] = name if "name" in resolved: resolved["name"] = name output.append(resolved)
return output
def is_batched_conversation(conversation: Any) -> bool: return ( isinstance(conversation, list) and bool(conversation) and isinstance(conversation[0], list) )
def _render_content_segments( content: Any, image_state: _ImagePromptState,) -> list[EncodeSegment]: segments: list[EncodeSegment] = [] if isinstance(content, str): _append_text(segments, content, image_state) elif content is not None: for part in content: if part["type"] in ["image", "image_url"]: segments.extend( _segment(image_state.next_prompt(), allow_special=True)) else: _append_text(segments, part["text"], image_state) return segments
def _internal_system_message(message_type: str, body: str) -> list[EncodeSegment]: segments: list[EncodeSegment] = [] segments.extend(_open_tag("message", [("role", "system"), ("type", message_type)])) segments.extend(_text(body.strip())) segments.extend(_close_tag("message")) segments.extend(_end_of_msg()) return segments
def _render_assistant_segments( message: dict[str, Any], image_state: _ImagePromptState, thinking: bool = True,) -> list[EncodeSegment]: segments: list[EncodeSegment] = [] # The <think> channel is structural: in thinking mode every assistant # message carries the open/close tags even when there is no reasoning # content to fill in. In non-thinking mode the channel is dropped # entirely. if thinking: reasoning_content = message.get("reasoning_content") or message.get( "reasoning" ) segments.extend(_open_tag("think")) if reasoning_content is not None and str(reasoning_content).strip(): _append_text(segments, reasoning_content, image_state) segments.extend(_close_tag("think"))
segments.extend(_open_tag("response")) segments.extend(_render_content_segments(message.get("content"), image_state)) segments.extend(_close_tag("response"))
tool_calls = message.get("tool_calls") if tool_calls: segments.extend(_open_tag("tools")) for index, tool_call in enumerate(tool_calls, start=1): fn = tool_call.get("function", tool_call) segments.extend( _open_tag("call", [("tool", fn["name"]), ("index", index)]) ) args = fn.get("arguments", {}) json_block = fn.get("_xtml_json_block") if json_block is not None: segments.extend(_open_tag("json", [("type", "object")])) _append_text(segments, json_block, image_state) segments.extend(_close_tag("json")) elif _is_mapping(args): for key, value in args.items(): segments.extend( _open_tag( "argument", [("key", key), ("type", _xtml_type(value))], ) ) _append_text(segments, _xtml_value(value), image_state) segments.extend(_close_tag("argument")) segments.extend(_close_tag("call")) segments.extend(_close_tag("tools"))
return segments
def _render_tool_declare(tools: Any, *, dynamic: bool = False) -> list[EncodeSegment]: if dynamic: body = ( "## New Tools Available\n" "The system dynamically extends the toolset via lazy-loading.\n" "You have access to all existing and extended tools.\n" "Here are the specs for the extended tools.\n\n" "```json\n" f"{_json_compact(tools)}\n" "```" ) else: body = ( "# Tools\n" "Here are the available tools, described in JSONSchema.\n\n" "```json\n" f"{_json_compact(tools)}\n" "```" ) segments: list[EncodeSegment] = [] segments.extend(_open_tag("message", [("role", "system"), ("type", "tool-declare")])) segments.extend(_text(body)) segments.extend(_close_tag("message")) segments.extend(_end_of_msg()) return segments
def build_chat_segments( messages: list[Any], tools: Optional[list[dict]] = None, *, add_generation_prompt: bool = True, thinking: bool = True, image_prompts: Optional[list[str]] = None, **kwargs: Any,) -> list[EncodeSegment]: # Re-sort tool results by tool_call_id at the lowest layer so every caller # (processor or direct tokenizer) gets correctly ordered XTML. The helper is # side-effect free, so the caller's message objects are left untouched. messages = normalize_xtml_tool_result_messages(messages) messages = normalize_conversation(messages) tools = deep_sort_dict(tools)
kwargs = dict(kwargs) response_format = kwargs.get("response_format") if "response_schema" not in kwargs: response_schema = extract_response_schema(response_format) if response_schema is not None: kwargs["response_schema"] = response_schema if kwargs.get("response_schema") is not None: kwargs["response_schema"] = deep_sort_dict(kwargs["response_schema"])
image_state = _ImagePromptState(image_prompts) segments: list[EncodeSegment] = []
tool_calls = None tool_index = 0
if tools: segments.extend(_render_tool_declare(tools))
thinking_effort = kwargs.get("thinking_effort") if thinking and thinking_effort is not None: assert thinking_effort in _VALID_THINKING_EFFORTS, ( f"Unsupported thinking_effort={thinking_effort!r}; " f"supported values are {sorted(_VALID_THINKING_EFFORTS)}." ) if thinking and thinking_effort in _VALID_THINKING_EFFORTS: segments.extend( _internal_system_message( "thinking-effort", "`thinking_effort` guides on how much to think in your " "thinking channel (not including the response channel), " "supported values include `low`, `medium`, `high`, and `max`.\n" f"Now the system is invoked with `thinking_effort={thinking_effort}`.", ) )
for message_index, message in enumerate(messages): if not isinstance(message, dict): continue
role = message["role"] if role == "user": attrs = [("role", "user")] if message.get("name"): attrs.append(("name", message["name"])) segments.extend(_open_tag("message", attrs)) segments.extend(_render_content_segments(message.get("content"), image_state)) segments.extend(_close_tag("message")) segments.extend(_end_of_msg()) elif role == "system" and message.get("tools"): segments.extend(_render_tool_declare(message["tools"], dynamic=True)) elif role == "system": attrs = [("role", "system")] if message.get("name"): attrs.append(("name", message["name"])) segments.extend(_open_tag("message", attrs)) segments.extend(_render_content_segments(message.get("content"), image_state)) segments.extend(_close_tag("message")) segments.extend(_end_of_msg()) elif role == "tool": tool_index += 1 tool_name = message.get("tool", message.get("name")) if ( tool_name is None and tool_calls is not None and tool_index <= len(tool_calls) ): tc = tool_calls[tool_index - 1] fn = tc.get("function", tc) tool_name = fn["name"] if tool_name is None: raise ValueError( "Kimi K3 tool messages need a resolvable tool name: " "carry `tool`/`name`, or match a preceding assistant " "tool_call by order." ) segments.extend( _open_tag( "message", [("role", "tool"), ("tool", tool_name), ("index", tool_index)], ) ) segments.extend(_render_content_segments(message.get("content"), image_state)) segments.extend(_close_tag("message")) segments.extend(_end_of_msg()) elif role == "assistant": tool_calls = message.get("tool_calls") tool_index = 0 attrs = [("role", "assistant")] if message.get("name"): attrs.append(("name", message["name"])) segments.extend(_open_tag("message", attrs)) segments.extend(_render_assistant_segments(message, image_state, thinking)) segments.extend(_close_tag("message")) segments.extend(_end_of_msg())
tool_choice = kwargs.get("tool_choice") if tool_choice == "required": segments.extend( _internal_system_message( "tool-choice", "The system is invoked with `tool_choice=required`.\n" "You MUST call tools in the next message.", ) ) elif tool_choice == "none": segments.extend( _internal_system_message( "tool-choice", "The system is invoked with `tool_choice=none`.\n" "You MUST NOT call any tools in the next message.", ) )
rf = kwargs.get("response_format") rf_type = _get_value(rf, "type", rf) if isinstance(rf, dict) else rf if rf_type == "json_object": segments.extend( _internal_system_message( "response-format", "The system is invoked with `response_format=json_object`.\n" "Your response must be raw JSON data without markdown code " "blocks (```json) or any additional formatting.", ) ) elif rf_type == "json_schema": schema = _json_compact(kwargs.get("response_schema")) segments.extend( _internal_system_message( "response-format", "The system is invoked with `response_format=json_schema`.\n" "Your response must be raw JSON data without markdown code " "blocks (```json) or any additional formatting.\n" "The JSON data must match the following schema:\n" f"```json\n{schema}\n```", ) )
if add_generation_prompt: segments.extend(_open_tag("message", [("role", "assistant")])) segments.extend(_open_tag("think" if thinking else "response"))
image_state.assert_consumed() return segments1234{ "max_length": 1048576, "eos_token_id": 163586}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187"""Kimi-K3 processor: wraps vision processor + tokenizer into a single interface.
Chat rendering (including XTML tool-result ordering) is handled by thetokenizer's Python encoder; this processor adds multimodal media preprocessing."""
from transformers.feature_extraction_utils import BatchFeaturefrom transformers.processing_utils import ProcessorMixinfrom transformers.utils import logging
from .media_utils import ensure_media_type
logger = logging.get_logger(__name__)
# ── KimiK3Processor ───────────────────────────────────────────────────
class KimiK3Processor(ProcessorMixin): r""" Constructs a KimiK3 processor which wraps a KimiK3 image processor and a tokenizer into a single processor.
[`KimiK3Processor`] offers all the functionalities of [`KimiK3VisionProcessor`] and [`TikTokenTokenizer`].
Args: image_processor ([`KimiK3VisionProcessor`], *optional*): The image processor is a required input. tokenizer ([`TikTokenTokenizer`], *optional*): The tokenizer is a required input. chat_template (`str`, *optional*): Kept for ProcessorMixin compatibility. Kimi K3 chat encoding is implemented in Python by the tokenizer. """
attributes = ["image_processor", "tokenizer"] valid_kwargs = ["chat_template"] image_processor_class = "AutoImageProcessor" tokenizer_class = "AutoTokenizer"
def __init__( self, image_processor=None, tokenizer=None, chat_template=None, **kwargs, ): super().__init__(image_processor, tokenizer, chat_template=chat_template) self.media_processor = image_processor self.image_placeholder = "<|kimi_image_placeholder|>"
# ── Media preprocessing ────────────────────────────────────────────
def update_raw_text(self, text: str, image_prompts: list[str]) -> str: # Replace image placeholders image_count = text.count(self.image_placeholder) if image_count > 0: assert image_count == len(image_prompts), ( f"image placeholder count {image_count} != " f"image_prompts count {len(image_prompts)}") text_parts = text.split(self.image_placeholder) assert len(text_parts) == len(image_prompts) + 1 text = "".join([ text_parts[i] + image_prompts[i] for i in range(len(image_prompts)) ]) text += text_parts[-1]
return text
def preprocess_medias(self, medias: list[dict]) -> tuple[list[dict], list[str]]: """Process media items and generate corresponding prompts.
Returns: A tuple of (updated_medias, image_prompts). """ updated_medias = [] image_prompts = [] for media in medias: if media['type'] == 'image': updated_medias.append(media) img = ensure_media_type( media, transparent_bg_config=self.media_processor. _transparent_bg_config, transparent_bg_fill_stage=self.media_processor. _transparent_bg_fill_stage, )['image'] w, h = img.size image_prompts.append( self.media_processor.make_image_prompt(w, h)) else: raise ValueError(f"unsupported media type: {media['type']}") return updated_medias, image_prompts
# ── Main entry points ──────────────────────────────────────────────
def __call__(self, messages: list[dict] = None, medias: list[dict] = None, text: str = None, return_tensors: str = "pt", **kwargs) -> BatchFeature: """ Process multimodal inputs for Kimi-K3 model.
Args: messages: List of message dicts with 'role' and 'content' fields. If provided, medias and text will be extracted automatically. medias: Pre-extracted list of media dicts. text: Pre-formatted text string. return_tensors: Format of returned tensors. Default: 'pt'. **kwargs: Additional arguments passed to apply_chat_template.
Returns: BatchFeature with fields: input_ids, attention_mask, pixel_values, grid_thws. """ if messages is None and (medias is None or text is None): raise ValueError( "Provide either 'messages' or both 'medias' and 'text'")
if medias is not None and text is not None: updated_medias, image_prompts = (self.preprocess_medias(medias)) preprocessed = self.media_processor.preprocess( updated_medias, return_tensors=return_tensors) text = self.update_raw_text(text, image_prompts) text_inputs = self.tokenizer(text, return_tensors=return_tensors) return BatchFeature(data={**text_inputs, **preprocessed.data})
if medias is None: medias = self._extract_medias_from_messages(messages) updated_medias, image_prompts = (self.preprocess_medias(medias)) preprocessed = self.media_processor.preprocess( updated_medias, return_tensors=return_tensors)
if text is None: text_inputs = self.tokenizer.apply_chat_template( messages, tokenize=True, return_tensors=return_tensors, return_dict=True, image_prompts=image_prompts, **kwargs) return BatchFeature(data={**text_inputs, **preprocessed.data})
text = self.update_raw_text(text, image_prompts) text_inputs = self.tokenizer(text, return_tensors=return_tensors) return BatchFeature(data={**text_inputs, **preprocessed.data})
@staticmethod def _extract_medias_from_messages(messages: list[dict]) -> list[dict]: """Extract media items from messages in a single pass.""" medias = [] for msg in messages: if msg['role'] != 'user' or not msg.get('content'): continue
for content_part in msg['content']: if not isinstance(content_part, dict): continue
content_type = content_part.get('type') if content_type in ['image_url', 'image']: image_data = content_part.get(content_type) assert image_data is not None, f"image data is missing for content part: {content_part}" medias.append({ 'type': 'image', 'image': image_data, }) return medias
def apply_chat_template(self, messages, **kwargs): return self.tokenizer.apply_chat_template(messages, **kwargs)
def batch_decode(self, *args, **kwargs): return self.tokenizer.batch_decode(*args, **kwargs)
def decode(self, *args, **kwargs): return self.tokenizer.decode(*args, **kwargs)
@property def model_input_names(self): return ['input_ids', 'attention_mask', 'pixel_values', 'grid_thws']123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179"""Image processor class for Kimi-K3."""
import jsonfrom typing import Any, Dict, Optional, Union
import numpy as npimport torchfrom PIL import Imagefrom transformers.image_processing_utils import (BaseImageProcessor, BatchFeature)from transformers.utils import TensorType
from .media_utils import (MediaInput, TransparentBgConfig, _to_tensor, ensure_media_type, image_to_np, navit_patchify, navit_resize_image, normalize)
class KimiK3VisionProcessor(BaseImageProcessor): model_type = "kimi_k3"
def __init__( self, media_proc_cfg: dict, **kwargs, ): super().__init__(**kwargs) self.media_proc_cfg = media_proc_cfg
@property def _transparent_bg_config(self) -> Optional[TransparentBgConfig]: cfg = self.media_proc_cfg.get("transparent_bg_config") if cfg is None: return None if isinstance(cfg, TransparentBgConfig): return cfg return TransparentBgConfig(**cfg)
@property def _transparent_bg_fill_stage(self) -> str: return self.media_proc_cfg.get("transparent_bg_fill_stage", "before_resize")
def media_tokens_calculator(self, media: MediaInput): media = ensure_media_type( media, transparent_bg_config=self._transparent_bg_config, transparent_bg_fill_stage=self._transparent_bg_fill_stage, ) ret = self.get_resize_config(media) return ret['num_tokens']
@classmethod def make_image_prompt(cls, width: int, height: int) -> str: """Build the K3 image placeholder with resolution info.""" return (f"<|media_begin|>image {width}x{height}" f"<|media_content|><|media_pad|><|media_end|>")
def get_resize_config(self, media_input: MediaInput) -> dict: if media_input['type'] == 'image': w, h = media_input['image'].size ret = navit_resize_image( w, h, self.media_proc_cfg['patch_size'], self.media_proc_cfg['merge_kernel_size'], self.media_proc_cfg['in_patch_limit'], self.media_proc_cfg['patch_limit_on_one_side'], self.media_proc_cfg['fixed_output_tokens']) return ret else: raise ValueError("Unsupported type: {}".format( media_input['type']))
def resize_image(self, image: Image.Image, new_width: int, new_height: int, pad_width: int, pad_height: int) -> np.ndarray: image_np = image_to_np( image, (new_width, new_height), "resize", transparent_bg_config=self._transparent_bg_config, transparent_bg_fill_stage=self._transparent_bg_fill_stage, ) image_np = np.pad( image_np, ((0, pad_height), (0, pad_width), (0, 0)), mode="constant", constant_values=0, ) return image_np
def preprocess( self, medias: list[MediaInput], return_tensors: Optional[Union[str, TensorType]] = None, ) -> BatchFeature: """ Preprocess a atom vision input (images) into model-ready tensors.
Args: medias: List of MediaInput. return_tensors: Desired output format ('pt', 'np', 'tf', or None).
Returns: BatchFeature containing 'pixel_values' and 'grid_thws' tensors. """ if not isinstance(medias, list): medias = [medias] if medias: pixel_values = [] for item in medias: item = ensure_media_type( item, transparent_bg_config=self._transparent_bg_config, transparent_bg_fill_stage=self._transparent_bg_fill_stage, ) resize_config = self.get_resize_config(item) new_width, new_height, pad_width, pad_height = resize_config[ 'new_width'], resize_config['new_height'], resize_config[ 'pad_width'], resize_config['pad_height'] if item['type'] == 'image': image = item['image'] image_np = self.resize_image(image, new_width, new_height, pad_width, pad_height) pixel_values.append(np.expand_dims(image_np, axis=0)) else: raise ValueError("Unsupported type: {}".format( item['type'])) normalized_pixel_values = [] image_std_inv = 1.0 / np.array(self.media_proc_cfg['image_std']) image_mean = np.array(self.media_proc_cfg['image_mean']) for pixels in pixel_values: pixels = normalize(pixels, image_mean, image_std_inv) pixels_and_thw = navit_patchify( pixels, self.media_proc_cfg['patch_size'], ) normalized_pixel_values.append(pixels_and_thw)
pixel_values = torch.cat([ _to_tensor(pixel_value['pixel_values']) for pixel_value in normalized_pixel_values ]) grid_thws = torch.cat([ _to_tensor(pixel_value['grid_thw'], dtype=torch.int64).unsqueeze(0) for pixel_value in normalized_pixel_values ])
data = { 'pixel_values': pixel_values, 'grid_thws': grid_thws, }
else: data = {}
return BatchFeature(data=data, tensor_type=return_tensors)
def __repr__(self): return f"KimiK3VisionProcessor(media_proc_cfg={self.media_proc_cfg})"
def to_dict(self) -> Dict[str, Any]: output = super().to_dict() output["media_proc_cfg"] = self.media_proc_cfg if "media_processor" in output: del output["media_processor"] return output
@classmethod def from_dict(cls, config_dict: Dict[str, Any], **kwargs): config = config_dict.copy() media_proc_cfg = config.pop("media_proc_cfg", {}) return cls(media_proc_cfg=media_proc_cfg, **config, **kwargs)
def to_json_string(self): dictionary = self.to_dict() for key, value in dictionary.items(): if hasattr(value, 'tolist'): dictionary[key] = value.tolist() return json.dumps(dictionary, indent=2, sort_keys=True) + "\n"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376import base64import functoolsimport ioimport mathfrom dataclasses import dataclassfrom typing import Literal, TypedDict
import numpy as npfrom PIL import Image
class ImageInput(TypedDict): type: Literal['image'] image: Image.Image
MediaInput = ImageInput
@dataclassclass TransparentBgConfig: """The config of the transparent background."""
pattern: Literal["white", "black", "gray", "chessboard"] = "black" """The pattern of the transparent background."""
chessboard_square_size: int = 16 """The size of the squares in the chessboard background."""
chessboard_square_on_top_left: bool = True """Whether to start the chessboard with a white square on the top left."""
chessboard_white_value: int = 255 """The value of the white pixels in the background."""
chessboard_gray_value: int = 200 """The value of the gray pixels in the background."""
@functools.lru_cache(maxsize=256)def _create_chessboard_background( height: int, width: int, square_size: int, square_on_top_left: bool, white_value: int, gray_value: int,) -> np.ndarray: """Create a chessboard background.""" bg = np.ones((height, width, 3), dtype=np.uint8) * white_value for y in range(0, height, square_size): for x in range(0, width, square_size): if (y // square_size + x // square_size) % 2 == ( 1 if square_on_top_left else 0): bg[y:y + square_size, x:x + square_size] = gray_value return bg
def fill_transparent_bg_with( image: Image.Image, transparent_bg_config: TransparentBgConfig | None = None,) -> Image.Image: """Composite a (possibly) transparent image onto a configured background.
When ``transparent_bg_config`` is ``None``, the image is simply converted to RGB (preserving the historical behavior). Otherwise the alpha channel is alpha-composited over a background generated according to the config. """ if transparent_bg_config is None: return image.convert("RGB")
if image.mode == "RGB": return image
has_alpha = "A" in image.getbands() or "transparency" in image.info if not has_alpha: return image.convert("RGB")
img = np.array(image.convert("RGBA")) height, width = img.shape[:2] bg_pattern = transparent_bg_config.pattern if bg_pattern == "white": bg = np.full((height, width, 3), 255, dtype=np.uint8) elif bg_pattern == "black": bg = np.zeros((height, width, 3), dtype=np.uint8) elif bg_pattern == "gray": bg = np.full((height, width, 3), 128, dtype=np.uint8) elif bg_pattern == "chessboard": bg = _create_chessboard_background( height, width, transparent_bg_config.chessboard_square_size, transparent_bg_config.chessboard_square_on_top_left, transparent_bg_config.chessboard_white_value, transparent_bg_config.chessboard_gray_value, ) else: raise ValueError(f"Invalid background pattern: {bg_pattern}")
alpha = img[:, :, 3] img_rgb = img[:, :, :3] alpha_normalized = alpha.astype(np.float32) / 255.0 alpha_3d = np.stack([alpha_normalized] * 3, axis=2) result = alpha_3d * img_rgb + (1 - alpha_3d) * bg result = result.astype(np.uint8) return Image.fromarray(result)
def navit_resize_image( width: int, height: int, patch_size: int, merge_kernel_size: int, in_patch_limit: int, patch_limit_on_one_side: int, fixed_output_tokens: int | None,): # Apply the patch limits. s1 = math.sqrt( in_patch_limit / (max(1.0, width // patch_size) * max(1.0, height // patch_size))) s2 = patch_limit_on_one_side * patch_size / width s3 = patch_limit_on_one_side * patch_size / height scale = min(1.0, s1, s2, s3) new_w, new_h = max(1, int(width * scale)), max(1, int(height * scale)) new_w = min(new_w, patch_limit_on_one_side * patch_size) new_h = min(new_h, patch_limit_on_one_side * patch_size)
# Calculate the padding to make the height and width divisible by the merge kernel size and patch size. factor = merge_kernel_size * patch_size
pad_height = (factor - new_h % factor) % factor pad_width = (factor - new_w % factor) % factor
if fixed_output_tokens is not None: num_tokens = fixed_output_tokens else: # Calculate new dimensions after padding and patching token_height = (new_h + pad_height) // factor token_width = (new_w + pad_width) // factor
assert token_height * merge_kernel_size <= patch_limit_on_one_side, ( f"token_height {token_height} * merge_kernel_size {merge_kernel_size} > patch_limit_on_one_side {patch_limit_on_one_side}" ) assert token_width * merge_kernel_size <= patch_limit_on_one_side, ( f"token_width {token_width} * merge_kernel_size {merge_kernel_size} > patch_limit_on_one_side {patch_limit_on_one_side}" )
num_tokens = token_height * token_width return { "num_tokens": num_tokens, "new_width": new_w, "new_height": new_h, "pad_width": pad_width, "pad_height": pad_height, "sampled_nframes": 1, }
def _to_pil( data: str | bytes | Image.Image, transparent_bg_config: TransparentBgConfig | None = None, to_rgb: bool = True,) -> Image.Image: """Load an image and (optionally) composite its transparent background.
Args: data: A PIL Image, a base64 ``data:`` URL, a file path, or raw bytes. transparent_bg_config: The config used to fill the transparent background. ``None`` keeps the historical behavior of converting to RGB without compositing. to_rgb: If ``False`` the image is returned as-is (the ``transparent_bg_config`` is ignored). The caller is then expected to call :func:`fill_transparent_bg_with` later — e.g. after a resize. """ if isinstance(data, Image.Image): image = data elif isinstance(data, str): if data.startswith("data:"): raw_base64 = data.split(",")[1] image = Image.open(io.BytesIO(base64.b64decode(raw_base64))) else: image = Image.open(data) elif isinstance(data, bytes): image = Image.open(io.BytesIO(data)) else: raise ValueError(f"Unsupported data type: {type(data)}")
if not to_rgb: return image
return fill_transparent_bg_with(image, transparent_bg_config)
def ensure_media_type( media: MediaInput, transparent_bg_config: TransparentBgConfig | None = None, transparent_bg_fill_stage: Literal["before_resize", "after_resize"] = "before_resize",) -> MediaInput: if media['type'] == 'image': media['image'] = _to_pil( media['image'], transparent_bg_config=transparent_bg_config, to_rgb=transparent_bg_fill_stage == "before_resize", ) return media else: raise ValueError(f"Unsupported media type: {media['type']}")
def image_to_np( image: Image.Image, resize_to: tuple[int, int] | None = None, mode: str = "resize", raise_error_for_ill_resize: bool = True, transparent_bg_config: TransparentBgConfig | None = None, transparent_bg_fill_stage: Literal["before_resize", "after_resize"] = "before_resize",) -> np.ndarray: """Convert an image to a numpy array.
Args: content: The image to convert. resize_to: The size to resize the image to. mode: The mode to resize the image to. raise_error_for_ill_resize: Whether to raise an error for ill-sized resize. transparent_bg_config: The config of the transparent background. Only used when ``transparent_bg_fill_stage == "after_resize"`` (the caller is responsible for filling before resize otherwise). transparent_bg_fill_stage: When to composite the transparent background — before or after the resize step.
Returns: A numpy array. """ assert isinstance(image, Image.Image), "image must be a PIL Image" if resize_to is not None: if mode == "resize": image = image.resize(resize_to, resample=Image.Resampling.BICUBIC) if transparent_bg_fill_stage == "after_resize": image = fill_transparent_bg_with(image, transparent_bg_config)
elif mode == "rescale_and_pad_to_center": scale = min(resize_to[0] / image.width, resize_to[1] / image.height, 1.0) new_width = round(image.width * scale) new_height = round(image.height * scale) if new_width == 0 or new_height == 0: if raise_error_for_ill_resize: raise ValueError( f"Invalid resize to: {resize_to}, from image size: {image.size}" ) else: return np.zeros((resize_to[1], resize_to[0], 3), dtype=np.uint8)
image = image.resize((new_width, new_height), resample=Image.Resampling.BICUBIC) if transparent_bg_fill_stage == "after_resize": image = fill_transparent_bg_with(image, transparent_bg_config) padding_left = (resize_to[0] - new_width) // 2 padding_right = resize_to[0] - new_width - padding_left padding_top = (resize_to[1] - new_height) // 2 padding_bottom = resize_to[1] - new_height - padding_top image = np.asarray(image) image = np.pad( image, ((padding_top, padding_bottom), (padding_left, padding_right), (0, 0)), mode="constant", constant_values=0, ) assert image.shape == (resize_to[1], resize_to[0], 3)
elif mode == "rescale_and_pad_to_rightbottom": scale = min(resize_to[0] / image.width, resize_to[1] / image.height, 1.0) new_width = round(image.width * scale) new_height = round(image.height * scale) if new_width == 0 or new_height == 0: if raise_error_for_ill_resize: raise ValueError( f"Invalid resize to: {resize_to}, from image size: {image.size}" ) else: return np.zeros((resize_to[1], resize_to[0], 3), dtype=np.uint8)
image = image.resize((new_width, new_height), resample=Image.Resampling.BICUBIC) if transparent_bg_fill_stage == "after_resize": image = fill_transparent_bg_with(image, transparent_bg_config) padding_right = resize_to[0] - new_width padding_bottom = resize_to[1] - new_height image = np.asarray(image) image = np.pad( image, ((0, padding_bottom), (0, padding_right), (0, 0)), mode="constant", constant_values=0, ) assert image.shape == (resize_to[1], resize_to[0], 3)
else: raise ValueError(f"Invalid mode: {mode}")
if isinstance(image, Image.Image): return np.asarray(image) else: return image
def navit_patchify(pixel_values: np.ndarray, patch_size: int) -> dict[str, np.ndarray]: """Reshape the pixel values to a navit shape.
Args: pixel_values: np.ndarray, shape (t, h, w, c) patch_size: int
Returns: dict[str, np.ndarray] - patches: np.ndarray, shape (t * h//patch_size * w//patch_size, c, patch_size, patch_size) - grid_thw: np.ndarray, (t, h//patch_size, w//patch_size) """ T, H, W, C = pixel_values.shape assert C == 3, "pixel_values must have 3 channels"
patches = pixel_values.reshape(T, H // patch_size, patch_size, W // patch_size, patch_size, C) # (T, H//patch_size, W//patch_size, C, patch_size, patch_size) patches = patches.transpose(0, 1, 3, 5, 2, 4) patches = patches.reshape(-1, C, patch_size, patch_size) grid_thw = np.array([T, H // patch_size, W // patch_size]) return {"pixel_values": patches, "grid_thw": grid_thw}
def normalize(x: np.ndarray, mean, std_inv, pixels_dtype: np.dtype = np.float32) -> np.ndarray: """Normalize the image.
Args: x: The image to normalize. The shape is (..., 3). The dtype is uint8. The range is [0, 255]. mean: The mean of the image. std_inv: The inverse of the std of the image. pixels_dtype: The dtype of the image. Returns: The normalized image. The shape is (..., 3). The dtype is determined by the pixels_dtype. """ x = (x / 255.0).astype(pixels_dtype) x -= mean x *= std_inv return x
def _to_tensor(data, **kwargs): import torch
if isinstance(data, np.ndarray): return torch.from_numpy(data).to(**kwargs) elif isinstance(data, torch.Tensor): return data.to(**kwargs) elif isinstance(data, list): return [_to_tensor(item, **kwargs) for item in data] elif isinstance(data, tuple): return tuple(_to_tensor(item, **kwargs) for item in data) elif isinstance(data, dict): return {k: _to_tensor(v, **kwargs) for k, v in data.items()} elif data is None: return None else: raise ValueError(f"Unsupported data type: {type(data)}")123version https://git-lfs.github.com/spec/v1oid sha256:975584c00f85a95fce8ae0f840af8cef69c2ef4db00d34cab3e2cbdfc60f6e51size 2341216112123version https://git-lfs.github.com/spec/v1oid sha256:26a3284e1d2cb567934ebef002e6a1813551d646739e8bcb1e9e3fe7f878e0f5size 16990911504123version https://git-lfs.github.com/spec/v1oid sha256:e54af9de4c554956082364010f732443bcd5097390f0121a33fb35e37280b5a9size 16990911504123version https://git-lfs.github.com/spec/v1oid sha256:5955fd8feda89b1af8400c25e885e7177d47edff155f54b318beb8dd1cec5c05size 16567501776123version https://git-lfs.github.com/spec/v1oid sha256:d60d68ad0381ffd2d8716d5991a65993cc81837455bf05d1c76ea3a75662e268size 16990911504123version https://git-lfs.github.com/spec/v1oid sha256:b1d4805767471a9721cd087d2047843ab9262d4f9bbe0d4a306e72c07179f939size 16990911504123version https://git-lfs.github.com/spec/v1oid sha256:fb1120fef34c0416e73a3259ae6114b9a82b6081871b368a199e0b265cac7df7size 16990911504123version https://git-lfs.github.com/spec/v1oid sha256:2318dda54fc1985b63d6068de54fbe312ac87317c902666c9075aa5e10e8a1c9size 16567501776123version https://git-lfs.github.com/spec/v1oid sha256:8b66cdde34f5130cf4f99ec35b16f1f6d33bf0ec946cf2a5612004f5d399f998size 16990911504123version https://git-lfs.github.com/spec/v1oid sha256:d34f55f7b734a1eaecc986fc7f92bcaa1b7d18fad90a33befd3fae4f1b2771a9size 16990911504123version https://git-lfs.github.com/spec/v1oid sha256:1738856a4cca2e356510892de4accf3c3f94b9f598b0394a87e7951740ba4a21size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:c6b9bef38415f509898fa7b5c04d20c6fee84b0e02c05d74259d201fe6f3868bsize 16567507176123version https://git-lfs.github.com/spec/v1oid sha256:3cbf43d56d9c80be0f848a4866e290741c697e09d885dc2351b0a11de514d9c8size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:ce5f343f07d408c64fb247bbe8691edb84d54e3976d3ff586ebcf5929fd143adsize 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:b55caa8013348498525eef2b1416a657f0c28264ada9b245df19d2eea168b4c1size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:5a63e63ced659c1996b02ccabdea977546a39ecce025af1e54552de3bfc0489esize 16567507176123version https://git-lfs.github.com/spec/v1oid sha256:622bfa605205f4ef65e44dac07246bea79e18123ae8b84ab33eec89b6364c3a9size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:838b265ebb86a1320e589685779125d224663160823873b9e5930cf63fafe796size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:599a8ecf88f21d4c91295b4160e7564e501807535e522195ee45050a04f17dedsize 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:8e01b61ab76655ca0c5bd6645303a00c05fb58da94e00f978a9ef1e8114a6f0fsize 16567507176123version https://git-lfs.github.com/spec/v1oid sha256:1944265bd024ea6caa23796326e420260a801e5c52e6253155f22ce97e9578d0size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:2d32d3e3c8da0764f73830289c6a22224f755c0cf058df0262fb0f83b3777029size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:c291f2ec15788cb24cdf791c6d68dbf8803b26d01415cff3fab367cba581a169size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:278855ab81d42337e2a1857f136d740911fe3f5b1813dc21ce2cb03dc5c3cde3size 16567507176123version https://git-lfs.github.com/spec/v1oid sha256:6e3ae6ad868f5b38fa7ddface520796ea251568b07447deee3d164a0a32d862bsize 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:cdd79fb52c7a3350926c4b947ae82cccd0af17fa3fb537c5694a4cedf2b59811size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:1d974b40c4aeb5cc0adeba6f9fbad25fc99f8cd39f9dd3513aeb2fb30a9c4188size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:1bec58e89ab7835d3ca40e581cc6f047cb93de47fda804eaea4e2407e01c3ed3size 16567507176123version https://git-lfs.github.com/spec/v1oid sha256:c3bf0e738aa5fbd6ca3ecad982aba8d09efffd58b40cd8fb62d02fe0492f5cebsize 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:7b996410482ad3c21700ed35d3f2b36282540db92b5631a31aeda1c5e90d6343size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:c26689540a2471fe690c441a6cf9bec8f00471930e3131962206fd992e0d377csize 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:f7dc9e726d46d5c7c2c35af2eea4860cc89dd38a52b60591358a5ca7899c5159size 16567507176123version https://git-lfs.github.com/spec/v1oid sha256:615afa33b69cbaa42122bb3bcce92e40d6de86713a301c43c5d1bc2ac4342c1bsize 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:a53b27fe92df11e77aec7c5de93ac148b9e2a7bac95020535f68854a7977bde7size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:9f4b44c89e4965a973f4fa71eaa0f8ada110f588065541e83bf52692feaa886dsize 16990916912.eval_results/apex-agents.yamlAdded+7
.eval_results/deep-swe.yamlAdded+7
.eval_results/gpqa.yamlAdded+7
.eval_results/hle.yamlAdded+7
.gitattributesAdded+37
LICENSEAdded+52
README.mdAdded+680
assets/kimi-logo.pngAdded

config.jsonAdded+300
configuration_kimi_k3.pyAdded+285
encoding_k3.pyAdded+647
generation_config.jsonAdded+4
kimi_k3_processor.pyAdded+187
kimi_k3_vision_processing.pyAdded+179
media_utils.pyAdded+376
model-00001-of-000096.safetensorsAdded+3
model-00002-of-000096.safetensorsAdded+3
model-00003-of-000096.safetensorsAdded+3
model-00004-of-000096.safetensorsAdded+3
model-00005-of-000096.safetensorsAdded+3
model-00006-of-000096.safetensorsAdded+3
model-00007-of-000096.safetensorsAdded+3
model-00008-of-000096.safetensorsAdded+3
model-00009-of-000096.safetensorsAdded+3
model-00010-of-000096.safetensorsAdded+3
model-00011-of-000096.safetensorsAdded+3
model-00012-of-000096.safetensorsAdded+3
model-00013-of-000096.safetensorsAdded+3
model-00014-of-000096.safetensorsAdded+3
model-00015-of-000096.safetensorsAdded+3
model-00016-of-000096.safetensorsAdded+3
model-00017-of-000096.safetensorsAdded+3
model-00018-of-000096.safetensorsAdded+3
model-00019-of-000096.safetensorsAdded+3
model-00020-of-000096.safetensorsAdded+3
model-00021-of-000096.safetensorsAdded+3
model-00022-of-000096.safetensorsAdded+3
model-00023-of-000096.safetensorsAdded+3
model-00024-of-000096.safetensorsAdded+3
model-00025-of-000096.safetensorsAdded+3
model-00026-of-000096.safetensorsAdded+3
model-00027-of-000096.safetensorsAdded+3
model-00028-of-000096.safetensorsAdded+3
model-00029-of-000096.safetensorsAdded+3
model-00030-of-000096.safetensorsAdded+3
model-00031-of-000096.safetensorsAdded+3
model-00032-of-000096.safetensorsAdded+3
model-00033-of-000096.safetensorsAdded+3
model-00034-of-000096.safetensorsAdded+3
model-00035-of-000096.safetensorsAdded+3