Image-Text-to-Text
Transformers
Safetensors
kimi_k31
text-generation
compressed-tensors
conversational
custom_code
8-bit precision
Run this model with HF Jobs
Run AdelKazzaz/Kimi-K3.1-Pro 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/AdelKazzaz/Kimi-K3.1-Pro. 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/AdelKazzaz/Kimi-K3.1-Pro 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/AdelKazzaz/Kimi-K3.1-Pro. 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/AdelKazzaz/Kimi-K3.1-Pro. 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 AdelKazzaz/Kimi-K3.1-Pro with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use AdelKazzaz/Kimi-K3.1-Pro with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="AdelKazzaz/Kimi-K3.1-Pro", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForSeq2SeqLM model = AutoModelForSeq2SeqLM.from_pretrained("AdelKazzaz/Kimi-K3.1-Pro", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use AdelKazzaz/Kimi-K3.1-Pro with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "AdelKazzaz/Kimi-K3.1-Pro" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "AdelKazzaz/Kimi-K3.1-Pro", "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/AdelKazzaz/Kimi-K3.1-Pro
- SGLang
How to use AdelKazzaz/Kimi-K3.1-Pro 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 "AdelKazzaz/Kimi-K3.1-Pro" \ --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": "AdelKazzaz/Kimi-K3.1-Pro", "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 "AdelKazzaz/Kimi-K3.1-Pro" \ --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": "AdelKazzaz/Kimi-K3.1-Pro", "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 AdelKazzaz/Kimi-K3.1-Pro with Docker Model Runner:
docker model run hf.co/AdelKazzaz/Kimi-K3.1-Pro
Commit ·
48539fd
0
Parent(s):
Duplicate from moonshotai/Kimi-K3.1-Pro
Browse filesCo-authored-by: moyanwang <bigmoyan@users.noreply.huggingface.co>
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributesAdded+36
- LICENSEAdded+52
- README.mdAdded+705
- assets/kimi-logo.pngAdded
- config.jsonAdded+330
- configuration_kimi_k3.pyAdded+277
- encoding_k3.pyAdded+735
- 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
- model-00036-of-000096.safetensorsAdded+3
- model-00037-of-000096.safetensorsAdded+3
- model-00038-of-000096.safetensorsAdded+3
- model-00039-of-000096.safetensorsAdded+3
123456789101112131415161718192021222324252627282930313233343536*.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 -text12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152Kimi K3.1-Pro 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.1-Pro" 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>.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705---tags:- compressed-tensors- conversationallicense: otherlicense_name: "kimi-k3.1-pro"library_name: transformerspipeline_tag: image-text-to-text---
<div align="center"> <picture> <img src="assets/kimi-logo.png" width="30%" alt="Kimi K3.1 Pro"> </picture></div><div align="center" style="line-height:1"> <a href="https://www.kimi.ai" target="_blank"><img alt="Chat" src="https://img.shields.io/badge/Chat-Kimi%20K3.1%20Pro-1783ff"/></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/Hugging%20Face-Moonshot%20AI-ffc107"/></a> <a href="https://twitter.com/kimi_moonshot" target="_blank"><img alt="X" src="https://img.shields.io/badge/X-Kimi.ai-white?logo=x&logoColor=white"/></a> <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.1-Pro/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/badge/License-Kimi_K3.1_Pro-f5de53?&color=f5de53"/></a></div>
<p align="center">📰 <a href="https://www.kimi.ai/blog/kimi-k3-1-pro">Tech Blog</a> | <b>🚀 <a href="https://platform.kimi.ai/docs/guide/kimi-k3-1-pro-quickstart">API Quickstart</a></b></p>
## 1. Model Introduction
Kimi K3.1 Pro is an open-weight, natively multimodal agentic model, and our most capable 3T-class model to date. Post-trained from Kimi K3 with large-scale joint reinforcement learning across hundreds of downstream domains, it is the first model in the K3.1 series. With a 1-million-token context window, Kimi K3.1 Pro delivers substantial improvements in coding, 3D creation, financial research, factual accuracy, and other agentic capabilities.
## 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 DSA<sup>*</sup></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>DSA Index Head Dimension</strong></td><td align="center" style="vertical-align: middle; text-align: center">128</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>DSA Index Number of Heads</strong></td><td align="center" style="vertical-align: middle; text-align: center">32</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center"><strong>DSA Index Top-K</strong></td><td align="center" style="vertical-align: middle; text-align: center">2048</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 DSA</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>
<p><sup>*</sup> Compared with Kimi K3, we replace the full-attention Gated MLA layers with Gated DeepSeek Sparse Attention (Gated DSA) layers for more efficient long-context modeling.</p>
## 3. Evaluation Results
Unless otherwise specified, all Kimi K3.1 Pro results use reasoning effort `max`, `temperature = 1.0`, and `top-p = 0.95`. A dash (`—`) means that the source table does not report a score. Higher scores are better except where the benchmark name explicitly states `lower is better`; Elo scores and other benchmark-specific metrics are not directly comparable with accuracy or pass-rate scores.
<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.1 Pro<br><sup>(max)</sup></sup></th><th align="center" style="text-align: center"><sup>Claude Fable 5.1<br><sup>(max, w/ fallback)</sup></sup></th><th align="center" style="text-align: center"><sup>GPT-6 Astra<br><sup>(max, w/ fallback)</sup></sup></th><th align="center" style="text-align: center"><sup>Claude Opus 5.5<br><sup>(max, w/ fallback)</sup></sup></th><th align="center" style="text-align: center"><sup>DeepSeek-V4.1-Flash-1017<br><sup>(max)</sup></sup></th><th align="center" style="text-align: center"><sup>GLM-5.3<br><sup>(max)</sup></sup></th></tr></thead><tbody><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">Terminal-Bench 4.0</td><td align="center" style="vertical-align: middle; text-align: center">65.7</td><td align="center" style="vertical-align: middle; text-align: center">57.9</td><td align="center" style="vertical-align: middle; text-align: center">58.2</td><td align="center" style="vertical-align: middle; text-align: center">66.4</td><td align="center" style="vertical-align: middle; text-align: center">42.3</td><td align="center" style="vertical-align: middle; text-align: center">41.8</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">Terminal-Bench-Science 0.1</td><td align="center" style="vertical-align: middle; text-align: center">38.1</td><td align="center" style="vertical-align: middle; text-align: center">40.0</td><td align="center" style="vertical-align: middle; text-align: center">68.1</td><td align="center" style="vertical-align: middle; text-align: center">63.3</td><td align="center" style="vertical-align: middle; text-align: center">15.7</td><td align="center" style="vertical-align: middle; text-align: center">8.1</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">SWE Marathon v1.1</td><td align="center" style="vertical-align: middle; text-align: center">51.7</td><td align="center" style="vertical-align: middle; text-align: center">45.6</td><td align="center" style="vertical-align: middle; text-align: center">42.5</td><td align="center" style="vertical-align: middle; text-align: center">46.3</td><td align="center" style="vertical-align: middle; text-align: center">40.0</td><td align="center" style="vertical-align: middle; text-align: center">42.5</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">BenchCAD w/o tools</td><td align="center" style="vertical-align: middle; text-align: center">72.8</td><td align="center" style="vertical-align: middle; text-align: center">60.6</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">73.0</td><td align="center" style="vertical-align: middle; text-align: center">41.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">BenchCAD w/ tools</td><td align="center" style="vertical-align: middle; text-align: center">92.7</td><td align="center" style="vertical-align: middle; text-align: center">92.6</td><td align="center" style="vertical-align: middle; text-align: center">95.9</td><td align="center" style="vertical-align: middle; text-align: center">96.2</td><td align="center" style="vertical-align: middle; text-align: center">81.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">Program Bench</td><td align="center" style="vertical-align: middle; text-align: center">31.5</td><td align="center" style="vertical-align: middle; text-align: center">53.5</td><td align="center" style="vertical-align: middle; text-align: center">50.0</td><td align="center" style="vertical-align: middle; text-align: center">65.0</td><td align="center" style="vertical-align: middle; text-align: center">29.1</td><td align="center" style="vertical-align: middle; text-align: center">19.0</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">DeepSWE v1.1</td><td align="center" style="vertical-align: middle; text-align: center">75.5</td><td align="center" style="vertical-align: middle; text-align: center">67.4</td><td align="center" style="vertical-align: middle; text-align: center">74.1</td><td align="center" style="vertical-align: middle; text-align: center">74.2</td><td align="center" style="vertical-align: middle; text-align: center">77.0</td><td align="center" style="vertical-align: middle; text-align: center">66.9</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">PostTrain Bench v1.2</td><td align="center" style="vertical-align: middle; text-align: center">36.5</td><td align="center" style="vertical-align: middle; text-align: center">44.6</td><td align="center" style="vertical-align: middle; text-align: center">41.9</td><td align="center" style="vertical-align: middle; text-align: center">43.8</td><td align="center" style="vertical-align: middle; text-align: center">30.5</td><td align="center" style="vertical-align: middle; text-align: center">34.5</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">Kimi Code Bench 2.0 (Internal)</td><td align="center" style="vertical-align: middle; text-align: center">77.1</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">76.1</td><td align="center" style="vertical-align: middle; text-align: center">61.7</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">Kimi Code Bench 3.0 Long-horizon (Internal)</td><td align="center" style="vertical-align: middle; text-align: center">61.2</td><td align="center" style="vertical-align: middle; text-align: center">58.8</td><td align="center" style="vertical-align: middle; text-align: center">66.5</td><td align="center" style="vertical-align: middle; text-align: center">58.5</td><td align="center" style="vertical-align: middle; text-align: center">51.5</td><td align="center" style="vertical-align: middle; text-align: center">45.5</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">HLE-Full w/ tools</td><td align="center" style="vertical-align: middle; text-align: center">70.0</td><td align="center" style="vertical-align: middle; text-align: center">65.6</td><td align="center" style="vertical-align: middle; text-align: center">57.2</td><td align="center" style="vertical-align: middle; text-align: center">67.7</td><td align="center" style="vertical-align: middle; text-align: center">58.8</td><td align="center" style="vertical-align: middle; text-align: center">62.5</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">92.1</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">91.5</td><td align="center" style="vertical-align: middle; text-align: center">90.8</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">BioMysteryBench</td><td align="center" style="vertical-align: middle; text-align: center">80.6</td><td align="center" style="vertical-align: middle; text-align: center">81.6</td><td align="center" style="vertical-align: middle; text-align: center">78.9</td><td align="center" style="vertical-align: middle; text-align: center">81.9</td><td align="center" style="vertical-align: middle; text-align: center">80.0</td><td align="center" style="vertical-align: middle; text-align: center">79.6</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">CharXiv (RQ) w/ python</td><td align="center" style="vertical-align: middle; text-align: center">93.4</td><td align="center" style="vertical-align: middle; text-align: center">92.7</td><td align="center" style="vertical-align: middle; text-align: center">92.8</td><td align="center" style="vertical-align: middle; text-align: center">93.8</td><td align="center" style="vertical-align: middle; text-align: center">85.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 w/ python</td><td align="center" style="vertical-align: middle; text-align: center">90.0</td><td align="center" style="vertical-align: middle; text-align: center">88.4</td><td align="center" style="vertical-align: middle; text-align: center">87.8</td><td align="center" style="vertical-align: middle; text-align: center">89.8</td><td align="center" style="vertical-align: middle; text-align: center">82.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">GDP.pdf 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">83.8</td><td align="center" style="vertical-align: middle; text-align: center">85.5</td><td align="center" style="vertical-align: middle; text-align: center">83.9</td><td align="center" style="vertical-align: middle; text-align: center">73.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">ChartoGraphy w/ python</td><td align="center" style="vertical-align: middle; text-align: center">90.2</td><td align="center" style="vertical-align: middle; text-align: center">88.4</td><td align="center" style="vertical-align: middle; text-align: center">91.0</td><td align="center" style="vertical-align: middle; text-align: center">89.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">—</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">95.4</td><td align="center" style="vertical-align: middle; text-align: center">95.1</td><td align="center" style="vertical-align: middle; text-align: center">96.6</td><td align="center" style="vertical-align: middle; text-align: center">97.7</td><td align="center" style="vertical-align: middle; text-align: center">92.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">ZeroBench_main w/ python (pass@5)</td><td align="center" style="vertical-align: middle; text-align: center">63.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">58.0</td><td align="center" style="vertical-align: middle; text-align: center">61.0</td><td align="center" style="vertical-align: middle; text-align: center">51.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">Agents' Last Exam (ALL)</td><td align="center" style="vertical-align: middle; text-align: center">43.2</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">41.8</td><td align="center" style="vertical-align: middle; text-align: center">42.6</td><td align="center" style="vertical-align: middle; text-align: center">37.7</td><td align="center" style="vertical-align: middle; text-align: center">26.2</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">Agents' Last Exam (CLI)</td><td align="center" style="vertical-align: middle; text-align: center">44.2</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">44.2</td><td align="center" style="vertical-align: middle; text-align: center">40.7</td><td align="center" style="vertical-align: middle; text-align: center">36.0</td><td align="center" style="vertical-align: middle; text-align: center">29.4</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">Automation Bench-AA</td><td align="center" style="vertical-align: middle; text-align: center">73.3</td><td align="center" style="vertical-align: middle; text-align: center">59.4</td><td align="center" style="vertical-align: middle; text-align: center">68.5</td><td align="center" style="vertical-align: middle; text-align: center">69.5</td><td align="center" style="vertical-align: middle; text-align: center">66.6</td><td align="center" style="vertical-align: middle; text-align: center">62.2</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">GDPval-AA v2.1 (Elo-score)</td><td align="center" style="vertical-align: middle; text-align: center">1846</td><td align="center" style="vertical-align: middle; text-align: center">1754</td><td align="center" style="vertical-align: middle; text-align: center">1573</td><td align="center" style="vertical-align: middle; text-align: center">1866</td><td align="center" style="vertical-align: middle; text-align: center">1746</td><td align="center" style="vertical-align: middle; text-align: center">1650</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">AA-Briefcase v1.1 (Elo-score)</td><td align="center" style="vertical-align: middle; text-align: center">1678</td><td align="center" style="vertical-align: middle; text-align: center">1672</td><td align="center" style="vertical-align: middle; text-align: center">1569</td><td align="center" style="vertical-align: middle; text-align: center">1803</td><td align="center" style="vertical-align: middle; text-align: center">1570</td><td align="center" style="vertical-align: middle; text-align: center">1507</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">69.4</td><td align="center" style="vertical-align: middle; text-align: center">68.6</td><td align="center" style="vertical-align: middle; text-align: center">64.7</td><td align="center" style="vertical-align: middle; text-align: center">73.5</td><td align="center" style="vertical-align: middle; text-align: center">69.8</td><td align="center" style="vertical-align: middle; text-align: center">56.6</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">OfficeQA Pro v2</td><td align="center" style="vertical-align: middle; text-align: center">64.4</td><td align="center" style="vertical-align: middle; text-align: center">54.5</td><td align="center" style="vertical-align: middle; text-align: center">54.4</td><td align="center" style="vertical-align: middle; text-align: center">62.2</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.1</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">67.4</td><td align="center" style="vertical-align: middle; text-align: center">68.6</td><td align="center" style="vertical-align: middle; text-align: center">66.2</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">62.4</td><td align="center" style="vertical-align: middle; text-align: center">58.6</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">Frontier Finance</td><td align="center" style="vertical-align: middle; text-align: center">58.6</td><td align="center" style="vertical-align: middle; text-align: center">60.8</td><td align="center" style="vertical-align: middle; text-align: center">45.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">54.5</td><td align="center" style="vertical-align: middle; text-align: center">57.5</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">Harvey Legal Agent</td><td align="center" style="vertical-align: middle; text-align: center">23.7</td><td align="center" style="vertical-align: middle; text-align: center">19.1</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">21.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">HANDBOOK.md</td><td align="center" style="vertical-align: middle; text-align: center">44.6</td><td align="center" style="vertical-align: middle; text-align: center">38.8</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">41.5</td><td align="center" style="vertical-align: middle; text-align: center">28.9</td><td align="center" style="vertical-align: middle; text-align: center">20.8</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">OSWorld V2.1</td><td align="center" style="vertical-align: middle; text-align: center">79.6</td><td align="center" style="vertical-align: middle; text-align: center">80.7</td><td align="center" style="vertical-align: middle; text-align: center">75.8</td><td align="center" style="vertical-align: middle; text-align: center">81.8</td><td align="center" style="vertical-align: middle; text-align: center">69.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">Business Operation (Internal)</td><td align="center" style="vertical-align: middle; text-align: center">37.8</td><td align="center" style="vertical-align: middle; text-align: center">30.7</td><td align="center" style="vertical-align: middle; text-align: center">32.3</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">8.9</td><td align="center" style="vertical-align: middle; text-align: center">18.6</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">DECK-Arena (Internal, Elo-score)</td><td align="center" style="vertical-align: middle; text-align: center">1456</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">1423</td><td align="center" style="vertical-align: middle; text-align: center">1253</td><td align="center" style="vertical-align: middle; text-align: center">1231</td><td align="center" style="vertical-align: middle; text-align: center">1119</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">Design Bench (Internal, Elo-score)</td><td align="center" style="vertical-align: middle; text-align: center">957</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">1076</td><td align="center" style="vertical-align: middle; text-align: center">927</td><td align="center" style="vertical-align: middle; text-align: center">863</td><td align="center" style="vertical-align: middle; text-align: center">718</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">Kimi Hallu Bench Hard w/ tools (Internal, lower is better)</td><td align="center" style="vertical-align: middle; text-align: center">8.3</td><td align="center" style="vertical-align: middle; text-align: center">23.3</td><td align="center" style="vertical-align: middle; text-align: center">5.5</td><td align="center" style="vertical-align: middle; text-align: center">15.0</td><td align="center" style="vertical-align: middle; text-align: center">23.3</td><td align="center" style="vertical-align: middle; text-align: center">22.6</td></tr><tr><td align="center" colspan=7 style="text-align: center"><strong>Reasoning & Knowledge & Multimodal</strong></td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">GDP.pdf</td><td align="center" style="vertical-align: middle; text-align: center">34.6</td><td align="center" style="vertical-align: middle; text-align: center">27.6</td><td align="center" style="vertical-align: middle; text-align: center">34.2</td><td align="center" style="vertical-align: middle; text-align: center">30.6</td><td align="center" style="vertical-align: middle; text-align: center">17.2</td><td align="center" style="vertical-align: middle; text-align: center">11.2</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">51.1</td><td align="center" style="vertical-align: middle; text-align: center">57.6</td><td align="center" style="vertical-align: middle; text-align: center">53.6</td><td align="center" style="vertical-align: middle; text-align: center">59.8</td><td align="center" style="vertical-align: middle; text-align: center">42.6</td><td align="center" style="vertical-align: middle; text-align: center">43.0*</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">HLE-Diamond</td><td align="center" style="vertical-align: middle; text-align: center">39.4</td><td align="center" style="vertical-align: middle; text-align: center">55.1</td><td align="center" style="vertical-align: middle; text-align: center">65.8</td><td align="center" style="vertical-align: middle; text-align: center">60.9</td><td align="center" style="vertical-align: middle; text-align: center">21.6</td><td align="center" style="vertical-align: middle; text-align: center">25.1*</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">94.2</td><td align="center" style="vertical-align: middle; text-align: center">93.7</td><td align="center" style="vertical-align: middle; text-align: center">96.1</td><td align="center" style="vertical-align: middle; text-align: center">93.9</td><td align="center" style="vertical-align: middle; text-align: center">92.2</td><td align="center" style="vertical-align: middle; text-align: center">91.7</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">89.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">90.0</td><td align="center" style="vertical-align: middle; text-align: center">92.1</td><td align="center" style="vertical-align: middle; text-align: center">77.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">MMMU-Pro</td><td align="center" style="vertical-align: middle; text-align: center">84.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">86.9</td><td align="center" style="vertical-align: middle; text-align: center">87.7</td><td align="center" style="vertical-align: middle; text-align: center">80.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">ZeroBench_main (avg@5 / pass@5)</td><td align="center" style="vertical-align: middle; text-align: center">29.8 / 39.0</td><td align="center" style="vertical-align: middle; text-align: center">23.0 / 35.0</td><td align="center" style="vertical-align: middle; text-align: center">43.2 / 52.0</td><td align="center" style="vertical-align: middle; text-align: center">35.0 / 43.0</td><td align="center" style="vertical-align: middle; text-align: center">11.8 / 23.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">PerceptionBench</td><td align="center" style="vertical-align: middle; text-align: center">68.3</td><td align="center" style="vertical-align: middle; text-align: center">63.0</td><td align="center" style="vertical-align: middle; text-align: center">77.6</td><td align="center" style="vertical-align: middle; text-align: center">72.1</td><td align="center" style="vertical-align: middle; text-align: center">47.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">Kimi Hallu Bench w/o tools (Internal, lower is better)</td><td align="center" style="vertical-align: middle; text-align: center">5.4</td><td align="center" style="vertical-align: middle; text-align: center">11.4</td><td align="center" style="vertical-align: middle; text-align: center">4.2</td><td align="center" style="vertical-align: middle; text-align: center">6.8</td><td align="center" style="vertical-align: middle; text-align: center">13.1</td><td align="center" style="vertical-align: middle; text-align: center">14.8</td></tr><tr><td align="center" colspan=7 style="text-align: center"><strong>Cyber Security</strong></td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">ExploitBench</td><td align="center" style="vertical-align: middle; text-align: center">74.7</td><td align="center" style="vertical-align: middle; text-align: center">83.0</td><td align="center" style="vertical-align: middle; text-align: center">100</td><td align="center" style="vertical-align: middle; text-align: center">91.0</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">54.4</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">ExploitGym</td><td align="center" style="vertical-align: middle; text-align: center">20.7</td><td align="center" style="vertical-align: middle; text-align: center">30.4</td><td align="center" style="vertical-align: middle; text-align: center">42.4</td><td align="center" style="vertical-align: middle; text-align: center">34.5</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">15.0</td></tr><tr><td align="center" style="vertical-align: middle; text-align: center">xdev-bench-hard (Internal)</td><td align="center" style="vertical-align: middle; text-align: center">81.0</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">—</td><td align="center" style="vertical-align: middle; text-align: center">85.7</td><td align="center" style="vertical-align: middle; text-align: center">57.1</td></tr></tbody></table></div>
<details><summary><b>Evaluation Footnotes</b></summary>
#### Coding benchmarks
1. **Terminal-Bench 4.0.** Kimi K3.1 Pro is evaluated with the Claude Code harness. The DeepSeek-V4.1-Flash-1017 score is taken from its [release blog](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash-1017). All remaining scores are the maximum values reported in model blog posts or on the [official Terminal-Bench leaderboard](https://www.tbench.ai/).2. **Terminal-Bench-Science 0.1.** Kimi K3.1 Pro is evaluated with Claude Code. Internal evaluation of DeepSeek-V4.1-Flash-1017 yields 9.3; the table instead reports 15.7 for the older DeepSeek-V4.1-Flash from the official leaderboard. All remaining scores are from the [Terminal-Bench-Science leaderboard](https://www.terminal-bench-science.ai/).3. **SWE-Marathon v1.1.** Kimi K3.1 Pro and DeepSeek-V4.1-Flash-1017 are evaluated with Claude Code. Other scores are from the [official leaderboard](https://www.swe-marathon.org/).4. **ProgramBench.** The table reports binary scores: a task receives 1 if its ProgramBench score is at least 95%, and 0 otherwise. K3.1 Pro is evaluated with Claude Code. DeepSeek and GLM scores are taken from the [DeepSeek release blog](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash-1017); remaining scores are from [Vals AI](https://www.vals.ai/benchmarks/programbench).5. **DeepSWE v1.1.** K3.1 Pro is evaluated with Claude Code. Other scores come from the respective technical reports for [GPT-6 Astra](https://openai.com/index/gpt-6-astra/), [Claude Opus 5.5](https://www.anthropic.com/claude-opus-5-5-system-card), [Claude Fable 5.1](https://www.anthropic.com/claude-fable-5-1-mythos-5-1-system-card), [DeepSeek-V4.1-Flash-1017](https://api-docs.deepseek.com/news/news261017/), and [GLM-5.3](https://z.ai/blog/glm-5.3).6. **PostTrainBench.** K3.1 Pro and DeepSeek-V4.1-Flash-1017 are evaluated internally on v1.2 with Claude Code and H20 GPUs rather than H100 GPUs. For stable evaluation, all judge models use DeepSeek-V4.1-Flash-1017 at maximum effort, which best matched the official GPT-5.6-Terra (xhigh) judge in testing. Other scores are from the [official leaderboard](https://posttrainbench.com/).7. **Kimi Code Bench 2.0 and Kimi Code Bench 3.0 Long-horizon.** These are internal benchmarks. K3.1 Pro is evaluated with Claude Code; all other models use their maximum-effort setting. Proprietary-model testing may involve fallback behavior.8. **BenchCAD.** Open models are evaluated on 1,000-case subsets randomly sampled from the 17,900-case Vision2Code dataset at maximum reasoning effort. With-tools results use Claude Code; without-tools results use single-shot generation with official prompts and scoring. Claude scores are from the Opus 5.5 System Card, and GPT-6 Astra's with-tools score is from its official report. GPT-6 Astra has no reported without-tools score.
#### Agentic benchmarks
1. **BioMysteryBench.** Uses the [official v11 release](https://huggingface.co/datasets/Anthropic/BioMysteryBench-full/commit/b5a889c), with Kimi K3 as judge. K3.1 Pro uses Kimi Code; GLM-5.3 and DeepSeek-V4.1-Flash-1017 use Claude Code; GPT-6 Astra uses Codex. Claude scores are from official system cards.2. **Agents' Last Exam.** Uses the [official v1.1 release](https://github.com/rdi-berkeley/agents-last-exam), comprising 122 tasks, including 86 CLI tasks. Runs that bypass stated requirements receive zero. DeepSeek and Kimi are evaluated with Claude Code and Kimi Code, respectively; other results are from the official benchmark website.3. **OfficeQA Pro and OfficeQA Pro v2.** GPT-6 Astra uses Codex; other models use Claude Code. Each task provides the complete PDF corpus as page images without machine-readable text. External-model trajectories that retrieve reference answers online receive zero for those tasks.4. **Frontier Finance.** Evaluated with the official Finance Agent v2 harness.5. **HANDBOOK.md.** Evaluated with the official OpenHands-based harness, using tasks from the benchmark's early open-source v1 release.6. **Harvey Legal Agent.** Evaluated on 1,251 public tasks with Artificial Analysis's Stirrup harness. The reported score is the all-pass rate: the percentage of tasks passing every rubric criterion.7. **OSWorld V2.1.** Kimi models use the Kimi Agent harness in the official OSWorld v2 repository. GPT-6 Astra's score is taken from Muse Wonder's technical report.8. **DECK-Arena and Design Bench.** DECK-Arena evaluates presentation generation on real-world queries; Design Bench covers graphic design through direct and reference-image few-shot prompting. Both evaluate python-pptx, pptxjs, and Kimi's in-house DSL in a harness with integrated search and image generation. The automated grader is calibrated on more than 10,000 human judgments.9. **BrowseComp.** Uses context compaction triggered at 200K tokens and a 500-step maximum. If the limit is reached, the agent is forced to answer before judging. All runs use `temperature = 1.0` and `top-p = 1.0`.10. **GDPval-AA v2.1, AA-Briefcase v1.1, and AutomationBench-AA.** Scores are cited from [Artificial Analysis](https://artificialanalysis.ai/). **APEX-Agents.** Scores are cited from the [official leaderboard](https://www.mercor.com/apex/apex-agents-leaderboard/).11. **Tool-augmented multimodal evaluations.** GDP.pdf w/ python, ZeroBench w/ python, and ChartoGraphy w/ python are averaged over five runs; other multimodal benchmarks with Python are averaged over four. For GDP.pdf w/ python, each original PDF is sent to a sandbox for IPython processing. Responses are graded against each rubric criterion using Gemini-3.5-Flash at medium reasoning effort and the official judging prompt. The reported score is the task-macro mean rubric pass rate.
#### Reasoning, knowledge, and multimodal benchmarks
1. **GDP.pdf.** Each PDF is provided as page images resized to a longest edge of 1,152 pixels, interleaved with Docling-extracted text in page order. Responses are graded against each rubric criterion using Gemini-3.5-Flash Medium and the official judging prompt. The table reports the strict pass rate among fully scored responses. GLM-5.3 Max and DeepSeek-V4.1-Flash-1017 Max scores are cited from [Artificial Analysis](https://artificialanalysis.ai/).2. **HLE-Full and HLE-Diamond.** The full evaluation sets contain 2,500 and 1,000 questions, respectively. For scores marked `*`, accuracy is reported on the text-only subset.3. **Run counts.** GDP.pdf, ZeroBench, and ChartoGraphy are averaged over five runs; other multimodal benchmarks are averaged over four.4. **MMMU-Pro.** Evaluated using the official protocol, preserving the original input order and prepending images to the text input.5. **PerceptionBench.** An in-house benchmark focused on atomic visual perception capabilities.6. **Kimi Hallucination Benchmark.** Evaluates factual accuracy on an internal set of challenging, de-identified prompts drawn from practical work tasks. The table reports claim-level hallucination rates assessed by fact-checking agents.
#### Cybersecurity benchmarks
1. **ExploitBench.** K3.1 Pro is evaluated with the official harness under a 300-turn budget. The table reports the pass@5 maximum-capability score: for each environment, the best of five seeds is scored by capability flags reached out of 16; arbitrary code execution counts as all 16 capabilities. Comparison scores are from [OpenAI](https://openai.com/index/gpt-6-astra/), [Anthropic](https://www.anthropic.com/claude-opus-5-5-system-card), and [GLM-5.3](https://z.ai/blog/glm-5.3).2. **ExploitGym.** K3.1 Pro is evaluated with Kimi Code under a six-hour wall-clock budget per task. GPT-6 Astra, Claude, and GLM comparison scores are taken from their respective official reports, with Claude results using the same six-hour budget.3. **xdev-bench-hard.** K3.1 Pro is evaluated with Kimi Code; GLM-5.3 and DeepSeek-V4.1-Flash-1017 use Claude Code. The internal benchmark contains expert-curated, source-code-based vulnerability discovery and exploitation tasks. The final model is evaluated at pass@3 over a random subset of runs, without hard timeouts or output-token limits.
</details>
## 4. Deployment and Availability
> [!Note]> You can access Kimi K3.1 Pro's API on https://platform.kimi.ai by selecting `kimi-k3.1-pro`, and we provide OpenAI/Anthropic-compatible API for you.> Currently, Kimi K3.1 Pro 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.1-Pro)- [SGLang](https://github.com/sgl-project/sglang) — see [cookbook](https://docs.sglang.io/cookbook/autoregressive/Moonshotai/Kimi-K3.1-Pro)- [TokenSpeed](https://github.com/lightseekorg/tokenspeed) — see [recipes](https://lightseek.org/tokenspeed/recipes/models#kimi-k3-1-pro)
---## 5. Model UsageThe thinking effort of Kimi K3.1 Pro is configured with the top-level `reasoning_effort` request field, which supports `"low"`, `"high"`, and `"max"` (default `"max"`).
For multi-turn conversations and tool calls, Kimi K3.1 Pro requires the complete assistant message returned by the API to be passed back to `messages` as-is — including `reasoning_content` and `tool_calls`, not just `content`:
```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.1 Pro Quickstart](https://platform.kimi.ai/docs/guide/kimi-k3-1-pro-quickstart) and [Thinking Effort](https://platform.kimi.ai/docs/guide/use-thinking-effort).
## 6. License
Kimi K3.1 Pro is released under the [Kimi K3.1 Pro License](https://huggingface.co/moonshotai/Kimi-K3.1-Pro/blob/main/LICENSE).
## 7. Contact Us
If you have any questions, please reach out at [support@moonshot.ai](mailto:support@moonshot.ai).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330{ "architectures": [ "KimiK31ForConditionalGeneration" ], "auto_map": { "AutoConfig": "configuration_kimi_k3.KimiK3Config" }, "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_k31", "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, "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, "dsa_config": { "dsa_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 ], "index_topk": 2048, "index_head_dim": 128, "index_num_heads": 32, "index_rope_dim": 0, "index_k_norm_type": "layernorm", "index_topk_freq": 1, "index_skip_topk_offset": 1 }, "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:.*block_sparse_moe\\.gate$", "re:.*block_sparse_moe\\.routed_expert_(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.57.6", "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 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277from 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, dsa_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 # k31(KDA + DSA 混合):DSA 参数以嵌套子结构随包导出 self.dsa_config = dsa_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_k31"
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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735"""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
# One normalized tool-call argument: (key, XTML type, rendered text). The# text keeps the original JSON literal for non-string values and is the# decoded string for string values.XtmlArgument = tuple[str, str, str]
def _parse_arguments_object(s: str) -> list[XtmlArgument]: """Parse a JSON object string one level deep.
Each top-level key-value pair yields one ``(key, type, text)`` triple. The text keeps the original JSON literal for non-string values (``1e2`` stays ``1e2``, ``[1,2]`` keeps its exact bytes) and is the decoded (unescaped) string for string values. Nested values are never re-serialized. Anything after the closing ``}`` is ignored. Raises ``ValueError`` on malformed input (including a valid non-object JSON document). """ idx = 0
def _skip_whitespaces() -> None: nonlocal idx while idx < len(s) and s[idx] in (" ", "\t", "\n", "\r"): idx += 1
def _next_char() -> Optional[str]: nonlocal idx if idx < len(s): c = s[idx] idx += 1 return c return None
_skip_whitespaces() if _next_char() != "{": raise ValueError("JSON arguments must be an object") _skip_whitespaces()
parsed: list[XtmlArgument] = []
if idx >= len(s): raise ValueError("Unexpected end of JSON object") if s[idx] == "}": return parsed
json_decoder = json.JSONDecoder(strict=False)
def _raw_decode(start_idx: int) -> tuple[Any, int]: try: return json_decoder.raw_decode(s, idx=start_idx) except json.JSONDecodeError as e: raise ValueError(str(e)) from e
while True: decoded_key, idx = _raw_decode(idx) if not isinstance(decoded_key, str): raise ValueError( f"JSON object key must be a string, got {decoded_key!r}") _skip_whitespaces() if _next_char() != ":": raise ValueError(f"Expects ':' after {decoded_key}") _skip_whitespaces()
value_start_idx = idx decoded_value, idx = _raw_decode(idx) value_end_idx = idx
text = (decoded_value if isinstance(decoded_value, str) else s[value_start_idx:value_end_idx]) parsed.append((decoded_key, _xtml_type(decoded_value), text))
_skip_whitespaces() c = _next_char() _skip_whitespaces()
if c == "}": break elif c == ",": continue else: raise ValueError(f"Expect '}}' or ',', got {c!r}")
return parsed
def normalize_tool_arguments( arguments: Any, ) -> tuple[list[XtmlArgument], Optional[str]]: """Normalize tool call arguments for XTML rendering.
Returns ``(argument_triples, raw_json_block)``. String arguments are parsed one level deep so non-string values keep their original JSON literal text, and anything after the closing ``}`` is discarded; dict arguments (already Python objects) are serialized on the spot. Any string that is not a well-formed JSON object -- unparsable, whitespace only, or valid non-object JSON -- falls back to the raw ``<json>`` block. """ if arguments is None: return [], None if isinstance(arguments, dict): return [(str(key), _xtml_type(value), _xtml_value(value)) for key, value in arguments.items()], None if isinstance(arguments, str): if arguments == "": return [], None try: return _parse_arguments_object(arguments), None except ValueError: return [], arguments 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")) # Only an empty string counts as no reasoning, so whitespace-only # reasoning is still rendered into the think channel. if reasoning_content is not None and str(reasoning_content) != "": _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")) else: for key, arg_type, arg_text in args: segments.extend( _open_tag("argument", [("key", key), ("type", arg_type)])) _append_text(segments, arg_text, 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): # Malformed messages are rejected instead of being silently skipped. if not isinstance(message, dict): raise ValueError( f"Kimi K3 messages must be dicts, got {type(message).__name__} " f"at index {message_index}.")
role = message.get("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()) else: raise ValueError( f"Unknown message role {role!r} at index {message_index}.")
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:7f60e41909fb16712100c311ca4402cc4e66ecc9dff9dad4ebc06f05106c58a1size 2341216112123version https://git-lfs.github.com/spec/v1oid sha256:3896d0f0d987abeb75f90ff0c047b9fb7faf3ff39a6e31cbd49a1358f48b7ffasize 16990911504123version https://git-lfs.github.com/spec/v1oid sha256:8db356979d0b5e4fdf16f13d56edee900261cc59d81395e498a52847518abf4csize 16990911504123version https://git-lfs.github.com/spec/v1oid sha256:01ca3a36220afc36a9f2891045c8c9d0e64fc2cd08fffe1b3851e24bd2a93a40size 16582379656123version https://git-lfs.github.com/spec/v1oid sha256:596fc235fe92c9656cbbd63eb719cd46f68b19e22d792224ef307c156f699682size 16990911504123version https://git-lfs.github.com/spec/v1oid sha256:a9f6a9d6682b2f5177553b9986bdc0774fe84a2181b76a6b7d7482de0ecf049bsize 16990911504123version https://git-lfs.github.com/spec/v1oid sha256:ea268a3cb5978f50079ffd111d78d785bdd313fb9c7dafda8df0d841daeba4absize 16990911504123version https://git-lfs.github.com/spec/v1oid sha256:e514e45c4a17a187657fbcd1d4f9eb6a0c33bcdbbe54049da391ed54ce57f60fsize 16582379656123version https://git-lfs.github.com/spec/v1oid sha256:c5f9adff3d853bcf1e14c27bca0f1a74de985e7afb3149acd00eb2de3732ca12size 16990911504123version https://git-lfs.github.com/spec/v1oid sha256:ee9b1762da09dad17d6f8a22732645b070149266c40c3ae1e8ee90f48fec6742size 16990911504123version https://git-lfs.github.com/spec/v1oid sha256:0bb52ff6b774c289888854203726e0cd955fc650dda2f5cf9e4f825037f4af72size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:2c2c9be2d6b722d75bec065e545826a88a8839b8100766442e7f476143e7ba44size 16582385056123version https://git-lfs.github.com/spec/v1oid sha256:bbf5db5833f4607cd201156229aa7f05183f70f2ffd2cf0ca8a6d781ee7f139csize 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:5f412b94c799903bc4b3694e662e6ef342bcc3712a3108a63b157bef16ec59dfsize 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:28e678ecfc2286eb86aa6dfe20df03bd7c8873b34d96f0b230d1aab64365a889size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:896fd658f4cddad15eaca16ed54471ad265ad73d48d291bb4bb792767dc4d617size 16582385056123version https://git-lfs.github.com/spec/v1oid sha256:4b82b33835679910ad9f87ec4662e38f8dc111421fb2a56f538cec5be6c55b74size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:db91d8251d9bc0f47e31fc18955e8428a6a1fa25460a5e54578e4b261660e3efsize 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:281ef055e54eff0c8ffacdf886e983ff27de43d002abf9aa97b663e9a3ae9ee7size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:783cbb7d6056c0ad3f32b8f1c10c20e6b2d7e5356e0cfd6ce6123f43d3648e60size 16582385056123version https://git-lfs.github.com/spec/v1oid sha256:9774e732cae20192427c8777f79bd9a9fb7c9ef3bc71c2784a2f72e891e1b51esize 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:5e3f0905780d988b0fcb974479731e751f8bed319e22224f5f9d0ec76b1b755esize 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:69940e5bde762834f2731401194a8fb2c2784274890bd6d23e0c0aca91383451size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:f48efe6ad27d75b51564a3de48ab312ee7c06969db35d7b2b764d9515c00b0a7size 16582385056123version https://git-lfs.github.com/spec/v1oid sha256:833a0f761b2944cde386def5bdb7dabbfdf30f2927dd26304d0f7723b4ff018csize 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:02bff688e36ec90942dcb3ece1bfc7f102fd3c78bffdabba79fd4ec4bedb9230size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:4fe3e6f06b9c341d06eee45c0add2c7f8aff48a4c48bdcd97130c48c91b93202size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:832b28d66ea0c9bca4b42c8b206463b3f8fa8cafd13d4118911604351c27dc22size 16582385056123version https://git-lfs.github.com/spec/v1oid sha256:bf8f4f4f10a3cbf72d95851232c17d20c58d44f024a8c4e421b344cb0f871659size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:a974612d9f6300e9a86eb882e2c6dbad2446d491e15289b576acd015f1f69928size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:aa227f8eddaf25975915e8a161446fb042e1db7bb176aafd29d4953f01a4e2ddsize 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:4520a3321b8fd7e3f7da7c29afc084802af2f1498f8c96e5103fe4476b204957size 16582385056123version https://git-lfs.github.com/spec/v1oid sha256:32a8f004afb58539f28fe5333fef3e1604c60f2113bbe2e173c99502a0f0cd89size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:4310c7808e7bf72506168fc1e521852ee95da94c6ee2f6ee6b8fa6b800c559c8size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:5ba50bc47a6b48c057208b7e2ea5aaccb6e8ce27041402e469cbb18661858ce2size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:5a64e3f0e0988dda1e568fcbf37d4f0a03493e536daff572a8d8378442ef26ecsize 16582385056123version https://git-lfs.github.com/spec/v1oid sha256:43ab18d28759e45ba316e03423b2c0d447ebc7f8ffea7972c4634a7630349262size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:a518377eff993b5b0b0337296072bb32a3ed249776b0c1459aaef20f9749fcf1size 16990916912123version https://git-lfs.github.com/spec/v1oid sha256:0c693043cdf7910af15e649039a7bfd8e924b923f7224cc1222e0d56edd36358size 16990916912.gitattributesAdded+36
LICENSEAdded+52
README.mdAdded+705
assets/kimi-logo.pngAdded

config.jsonAdded+330
configuration_kimi_k3.pyAdded+277
encoding_k3.pyAdded+735
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
model-00036-of-000096.safetensorsAdded+3
model-00037-of-000096.safetensorsAdded+3
model-00038-of-000096.safetensorsAdded+3
model-00039-of-000096.safetensorsAdded+3